libdap Updated for version 3.20.5
libdap4 is an implementation of OPeNDAP's DAP protocol.
util.cc
1// -*- mode: c++; c-basic-offset:4 -*-
2
3// This file is part of libdap, A C++ implementation of the OPeNDAP Data
4// Access Protocol.
5
6// Copyright (c) 2002,2003 OPeNDAP, Inc.
7// Author: James Gallagher <jgallagher@opendap.org>
8//
9// This library is free software; you can redistribute it and/or
10// modify it under the terms of the GNU Lesser General Public
11// License as published by the Free Software Foundation; either
12// version 2.1 of the License, or (at your option) any later version.
13//
14// This library is distributed in the hope that it will be useful,
15// but WITHOUT ANY WARRANTY; without even the implied warranty of
16// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17// Lesser General Public License for more details.
18//
19// You should have received a copy of the GNU Lesser General Public
20// License along with this library; if not, write to the Free Software
21// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22//
23// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
24
25// (c) COPYRIGHT URI/MIT 1994-1999
26// Please read the full copyright statement in the file COPYRIGHT_URI.
27//
28// Authors:
29// jhrg,jimg James Gallagher <jgallagher@gso.uri.edu>
30
31// Utility functions used by the api.
32//
33// jhrg 9/21/94
34
35#include "config.h"
36
37#include <fstream>
38
39#include <cassert>
40#include <cstring>
41#include <climits>
42#include <cstdlib>
43
44#include <ctype.h>
45#ifndef TM_IN_SYS_TIME
46#include <time.h>
47#else
48#include <sys/time.h>
49#endif
50
51#ifndef WIN32
52#include <unistd.h> // for stat
53#else
54#include <io.h>
55#include <fcntl.h>
56#include <process.h>
57#endif
58
59#include <sys/types.h>
60#include <sys/stat.h>
61
62#include <string>
63#include <sstream>
64#include <vector>
65#include <algorithm>
66#include <stdexcept>
67
68#include "BaseType.h"
69#include "Byte.h"
70#include "Int16.h"
71#include "Int32.h"
72#include "UInt16.h"
73#include "UInt32.h"
74#include "Float32.h"
75#include "Float64.h"
76#include "Str.h"
77#include "Array.h"
78
79#include "Int64.h"
80#include "UInt64.h"
81#include "Int8.h"
82
83#include "Error.h"
84
85#include "util.h"
86#include "GNURegex.h"
87#include "debug.h"
88
89using namespace std;
90
91namespace libdap {
92
95{
96#ifdef COMPUTE_ENDIAN_AT_RUNTIME
97
98 dods_int16 i = 0x0100;
99 char *c = reinterpret_cast<char*>(&i);
100 return *c;
101
102#else
103
104#if WORDS_BIGENDIAN
105 return true;
106#else
107 return false;
108#endif
109
110#endif
111}
112
120{
121 assert(arg);
122
123 if (arg->type() != dods_str_c) throw Error(malformed_expr, "The function requires a string argument.");
124
125 if (!arg->read_p())
126 throw InternalErr(__FILE__, __LINE__,
127 "The CE Evaluator built an argument list where some constants held no values.");
128
129 return static_cast<Str*>(arg)->value();
130}
131
132template<class T> static void set_array_using_double_helper(Array *a, double *src, int src_len)
133{
134 assert(a);
135 assert(src);
136 assert(src_len > 0);
137
138 vector<T> values(src_len);
139 for (int i = 0; i < src_len; ++i)
140 values[i] = (T) src[i];
141
142 // This copies the values
143 a->set_value(values, src_len);
144}
145
166void set_array_using_double(Array *dest, double *src, int src_len)
167{
168 assert(dest);
169 assert(src);
170 assert(src_len > 0);
171
172 // Simple types are Byte, ..., Float64, String and Url.
173 if ((dest->type() == dods_array_c && !dest->var()->is_simple_type()) || dest->var()->type() == dods_str_c
174 || dest->var()->type() == dods_url_c)
175 throw InternalErr(__FILE__, __LINE__, "The function requires a numeric-type array argument.");
176
177 // Test sizes. Note that Array::length() takes any constraint into account
178 // when it returns the length. Even if this was removed, the 'helper'
179 // function this uses calls Vector::val2buf() which uses Vector::width()
180 // which in turn uses length().
181 if (dest->length() != src_len)
182 throw InternalErr(__FILE__, __LINE__,
183 "The source and destination array sizes don't match (" + long_to_string(src_len) + " versus "
184 + long_to_string(dest->length()) + ").");
185
186 // The types of arguments that the CE Parser will build for numeric
187 // constants are limited to Uint32, Int32 and Float64. See ce_expr.y.
188 // Expanded to work for any numeric type so it can be used for more than
189 // just arguments.
190 switch (dest->var()->type()) {
191 case dods_byte_c:
192 set_array_using_double_helper<dods_byte>(dest, src, src_len);
193 break;
194 case dods_uint16_c:
195 set_array_using_double_helper<dods_uint16>(dest, src, src_len);
196 break;
197 case dods_int16_c:
198 set_array_using_double_helper<dods_int16>(dest, src, src_len);
199 break;
200 case dods_uint32_c:
201 set_array_using_double_helper<dods_uint32>(dest, src, src_len);
202 break;
203 case dods_int32_c:
204 set_array_using_double_helper<dods_int32>(dest, src, src_len);
205 break;
206 case dods_float32_c:
207 set_array_using_double_helper<dods_float32>(dest, src, src_len);
208 break;
209 case dods_float64_c:
210 set_array_using_double_helper<dods_float64>(dest, src, src_len);
211 break;
212
213 // DAP4 support
214 case dods_uint8_c:
215 set_array_using_double_helper<dods_byte>(dest, src, src_len);
216 break;
217 case dods_int8_c:
218 set_array_using_double_helper<dods_int8>(dest, src, src_len);
219 break;
220 case dods_uint64_c:
221 set_array_using_double_helper<dods_uint64>(dest, src, src_len);
222 break;
223 case dods_int64_c:
224 set_array_using_double_helper<dods_int64>(dest, src, src_len);
225 break;
226 default:
227 throw InternalErr(__FILE__, __LINE__,
228 "The argument list built by the CE parser contained an unsupported numeric type.");
229 }
230
231 // Set the read_p property.
232 dest->set_read_p(true);
233}
234
235template<class T> static double *extract_double_array_helper(Array * a)
236{
237 assert(a);
238
239 int length = a->length();
240
241 vector<T> b(length);
242 a->value(&b[0]); // Extract the values of 'a' to 'b'
243
244 double *dest = new double[length];
245 for (int i = 0; i < length; ++i)
246 dest[i] = (double) b[i];
247
248 return dest;
249}
250
262{
263 assert(a);
264
265 // Simple types are Byte, ..., Float64, String and Url.
266 if ((a->type() == dods_array_c && !a->var()->is_simple_type()) || a->var()->type() == dods_str_c
267 || a->var()->type() == dods_url_c)
268 throw Error(malformed_expr, "The function requires a DAP numeric-type array argument.");
269
270 if (!a->read_p())
271 throw InternalErr(__FILE__, __LINE__, string("The Array '") + a->name() + "'does not contain values.");
272
273 // The types of arguments that the CE Parser will build for numeric
274 // constants are limited to Uint32, Int32 and Float64. See ce_expr.y.
275 // Expanded to work for any numeric type so it can be used for more than
276 // just arguments.
277 switch (a->var()->type()) {
278 case dods_byte_c:
279 return extract_double_array_helper<dods_byte>(a);
280 case dods_uint16_c:
281 return extract_double_array_helper<dods_uint16>(a);
282 case dods_int16_c:
283 return extract_double_array_helper<dods_int16>(a);
284 case dods_uint32_c:
285 return extract_double_array_helper<dods_uint32>(a);
286 case dods_int32_c:
287 return extract_double_array_helper<dods_int32>(a);
288 case dods_float32_c:
289 return extract_double_array_helper<dods_float32>(a);
290 case dods_float64_c:
291 // Should not be copying these values, just read them,
292 // but older code may depend on the return of this function
293 // being something that should be deleted, so leave this
294 // alone. jhrg 2/24/15
295 return extract_double_array_helper<dods_float64>(a);
296
297 // Support for DAP4
298 case dods_uint8_c:
299 return extract_double_array_helper<dods_byte>(a);
300 case dods_int8_c:
301 return extract_double_array_helper<dods_int8>(a);
302 case dods_uint64_c:
303 return extract_double_array_helper<dods_uint64>(a);
304 case dods_int64_c:
305 return extract_double_array_helper<dods_int64>(a);
306 default:
307 throw InternalErr(__FILE__, __LINE__,
308 "The argument list built by the CE parser contained an unsupported numeric type.");
309 }
310}
311
312// This helper function assumes 'dest' is the correct size. This should not
313// be called when the Array 'a' is a Float64, since the values are already
314// in a double array!
315template<class T> static void extract_double_array_helper(Array * a, vector<double> &dest)
316{
317 assert(a);
318 assert(dest.size() == (unsigned long )a->length());
319
320 int length = a->length();
321
322 vector<T> b(length);
323 a->value(&b[0]); // Extract the values of 'a' to 'b'
324
325 for (int i = 0; i < length; ++i)
326 dest[i] = (double) b[i];
327}
328
343void extract_double_array(Array *a, vector<double> &dest)
344{
345 assert(a);
346
347 // Simple types are Byte, ..., Float64, String and Url.
348 if ((a->type() == dods_array_c && !a->var()->is_simple_type()) || a->var()->type() == dods_str_c
349 || a->var()->type() == dods_url_c)
350 throw Error(malformed_expr, "The function requires a DAP numeric-type array argument.");
351
352 if (!a->read_p())
353 throw InternalErr(__FILE__, __LINE__, string("The Array '") + a->name() + "' does not contain values.");
354
355 dest.resize(a->length());
356
357 // The types of arguments that the CE Parser will build for numeric
358 // constants are limited to Uint32, Int32 and Float64. See ce_expr.y.
359 // Expanded to work for any numeric type so it can be used for more than
360 // just arguments.
361 switch (a->var()->type()) {
362 case dods_byte_c:
363 return extract_double_array_helper<dods_byte>(a, dest);
364 case dods_uint16_c:
365 return extract_double_array_helper<dods_uint16>(a, dest);
366 case dods_int16_c:
367 return extract_double_array_helper<dods_int16>(a, dest);
368 case dods_uint32_c:
369 return extract_double_array_helper<dods_uint32>(a, dest);
370 case dods_int32_c:
371 return extract_double_array_helper<dods_int32>(a, dest);
372 case dods_float32_c:
373 return extract_double_array_helper<dods_float32>(a, dest);
374 case dods_float64_c:
375 return a->value(&dest[0]); // no need to copy the values
376 // return extract_double_array_helper<dods_float64>(a, dest);
377
378 // Support for DAP4
379 case dods_uint8_c:
380 return extract_double_array_helper<dods_byte>(a, dest);
381 case dods_int8_c:
382 return extract_double_array_helper<dods_int8>(a, dest);
383 case dods_uint64_c:
384 return extract_double_array_helper<dods_uint64>(a, dest);
385 case dods_int64_c:
386 return extract_double_array_helper<dods_int64>(a, dest);
387 default:
388 throw InternalErr(__FILE__, __LINE__,
389 "The argument list built by the CE parser contained an unsupported numeric type.");
390 }
391}
392
403{
404 assert(arg);
405
406 // Simple types are Byte, ..., Float64, String and Url.
407 if (!arg->is_simple_type() || arg->type() == dods_str_c || arg->type() == dods_url_c)
408 throw Error(malformed_expr, "The function requires a numeric-type argument.");
409
410 if (!arg->read_p())
411 throw InternalErr(__FILE__, __LINE__,
412 "The Evaluator built an argument list where some constants held no values.");
413
414 // The types of arguments that the CE Parser will build for numeric
415 // constants are limited to Uint32, Int32 and Float64. See ce_expr.y.
416 // Expanded to work for any numeric type so it can be used for more than
417 // just arguments.
418 switch (arg->type()) {
419 case dods_byte_c:
420 return (double) (static_cast<Byte*>(arg)->value());
421 case dods_uint16_c:
422 return (double) (static_cast<UInt16*>(arg)->value());
423 case dods_int16_c:
424 return (double) (static_cast<Int16*>(arg)->value());
425 case dods_uint32_c:
426 return (double) (static_cast<UInt32*>(arg)->value());
427 case dods_int32_c:
428 return (double) (static_cast<Int32*>(arg)->value());
429 case dods_float32_c:
430 return (double) (static_cast<Float32*>(arg)->value());
431 case dods_float64_c:
432 return static_cast<Float64*>(arg)->value();
433
434 // Support for DAP4 types.
435 case dods_uint8_c:
436 return (double) (static_cast<Byte*>(arg)->value());
437 case dods_int8_c:
438 return (double) (static_cast<Int8*>(arg)->value());
439 case dods_uint64_c:
440 return (double) (static_cast<UInt64*>(arg)->value());
441 case dods_int64_c:
442 return (double) (static_cast<Int64*>(arg)->value());
443
444 default:
445 throw InternalErr(__FILE__, __LINE__,
446 "The argument list built by the parser contained an unsupported numeric type.");
447 }
448}
449
450// Remove spaces from the start of a URL and from the start of any constraint
451// expression it contains. 4/7/98 jhrg
452
459string prune_spaces(const string &name)
460{
461 // If the URL does not even have white space return.
462 if (name.find_first_of(' ') == name.npos)
463 return name;
464 else {
465 // Strip leading spaces from http://...
466 unsigned int i = name.find_first_not_of(' ');
467 string tmp_name = name.substr(i);
468
469 // Strip leading spaces from constraint part (following `?').
470 unsigned int j = tmp_name.find('?') + 1;
471 i = tmp_name.find_first_not_of(' ', j);
472 tmp_name.erase(j, i - j);
473
474 return tmp_name;
475 }
476}
477
478// Compare elements in a list of (BaseType *)s and return true if there are
479// no duplicate elements, otherwise return false.
480
481bool unique_names(vector<BaseType *> l, const string &var_name, const string &type_name, string &msg)
482{
483 // copy the identifier names to a vector
484 vector<string> names(l.size());
485
486 int nelem = 0;
487 typedef std::vector<BaseType *>::const_iterator citer;
488 for (citer i = l.begin(); i != l.end(); i++) {
489 assert(*i);
490 names[nelem++] = (*i)->name();
491 DBG(cerr << "NAMES[" << nelem - 1 << "]=" << names[nelem-1] << endl);
492 }
493
494 // sort the array of names
495 sort(names.begin(), names.end());
496
497 // sort the array of names
498 sort(names.begin(), names.end());
499
500 // look for any instance of consecutive names that are ==
501 for (int j = 1; j < nelem; ++j) {
502 if (names[j - 1] == names[j]) {
503 ostringstream oss;
504 oss << "The variable `" << names[j] << "' is used more than once in " << type_name << " `" << var_name
505 << "'";
506 msg = oss.str();
507
508 return false;
509 }
510 }
511
512 return true;
513}
514
515const char *
516libdap_root()
517{
518 return LIBDAP_ROOT;
519}
520
525extern "C" const char *
527{
528 return PACKAGE_VERSION;
529}
530
531extern "C" const char *
532libdap_name()
533{
534 return PACKAGE_NAME;
535}
536
542string systime()
543{
544 time_t TimBin;
545
546 if (time(&TimBin) == (time_t) -1)
547 return string("time() error");
548 else {
549 char *ctime_value = ctime(&TimBin);
550 if (ctime_value) {
551 string TimStr = ctime_value;
552 return TimStr.substr(0, TimStr.size() - 2); // remove the \n
553 }
554 else
555 return "Unknown";
556 }
557}
558
563void downcase(string &s)
564{
565 for (unsigned int i = 0; i < s.length(); i++)
566 s[i] = tolower(s[i]);
567}
568
574bool is_quoted(const string &s)
575{
576 return (!s.empty() && s[0] == '\"' && s[s.length() - 1] == '\"');
577}
578
585string remove_quotes(const string &s)
586{
587 if (is_quoted(s))
588 return s.substr(1, s.length() - 2);
589 else
590 return s;
591}
592
594Type get_type(const char *name)
595{
596 if (strcmp(name, "Byte") == 0) return dods_byte_c;
597
598 if (strcmp(name, "Char") == 0) return dods_char_c;
599
600 if (strcmp(name, "Int8") == 0) return dods_int8_c;
601
602 if (strcmp(name, "UInt8") == 0) return dods_uint8_c;
603
604 if (strcmp(name, "Int16") == 0) return dods_int16_c;
605
606 if (strcmp(name, "UInt16") == 0) return dods_uint16_c;
607
608 if (strcmp(name, "Int32") == 0) return dods_int32_c;
609
610 if (strcmp(name, "UInt32") == 0) return dods_uint32_c;
611
612 if (strcmp(name, "Int64") == 0) return dods_int64_c;
613
614 if (strcmp(name, "UInt64") == 0) return dods_uint64_c;
615
616 if (strcmp(name, "Float32") == 0) return dods_float32_c;
617
618 if (strcmp(name, "Float64") == 0) return dods_float64_c;
619
620 if (strcmp(name, "String") == 0) return dods_str_c;
621
622 // accept both spellings; this might be confusing since URL
623 // could be filtered through code and come out Url. Don't know...
624 // jhrg 8/15/13
625 if (strcmp(name, "Url") == 0 || strcmp(name, "URL") == 0) return dods_url_c;
626
627 if (strcmp(name, "Enum") == 0) return dods_enum_c;
628
629 if (strcmp(name, "Opaque") == 0) return dods_opaque_c;
630
631 if (strcmp(name, "Array") == 0) return dods_array_c;
632
633 if (strcmp(name, "Structure") == 0) return dods_structure_c;
634
635 if (strcmp(name, "Sequence") == 0) return dods_sequence_c;
636
637 if (strcmp(name, "Grid") == 0) return dods_grid_c;
638
639 return dods_null_c;
640}
641
650{
651 switch (t) {
652 case dods_null_c:
653 return string("Null");
654 case dods_byte_c:
655 return string("Byte");
656 case dods_int16_c:
657 return string("Int16");
658 case dods_uint16_c:
659 return string("UInt16");
660 case dods_int32_c:
661 return string("Int32");
662 case dods_uint32_c:
663 return string("UInt32");
664 case dods_float32_c:
665 return string("Float32");
666 case dods_float64_c:
667 return string("Float64");
668 case dods_str_c:
669 return string("String");
670 case dods_url_c:
671 return string("Url");
672
673 case dods_array_c:
674 return string("Array");
675 case dods_structure_c:
676 return string("Structure");
677 case dods_sequence_c:
678 return string("Sequence");
679 case dods_grid_c:
680 return string("Grid");
681
682 default:
683 throw InternalErr(__FILE__, __LINE__, "Unknown type.");
684 }
685}
686
695{
696 switch (t) {
697 case dods_null_c:
698 return string("Null");
699 case dods_byte_c:
700 return string("Byte");
701 case dods_char_c:
702 return string("Char");
703 case dods_int8_c:
704 return string("Int8");
705 case dods_uint8_c:
706 return string("UInt8");
707 case dods_int16_c:
708 return string("Int16");
709 case dods_uint16_c:
710 return string("UInt16");
711 case dods_int32_c:
712 return string("Int32");
713 case dods_uint32_c:
714 return string("UInt32");
715 case dods_int64_c:
716 return string("Int64");
717 case dods_uint64_c:
718 return string("UInt64");
719 case dods_enum_c:
720 return string("Enum");
721
722 case dods_float32_c:
723 return string("Float32");
724 case dods_float64_c:
725 return string("Float64");
726
727 case dods_str_c:
728 return string("String");
729 case dods_url_c:
730 return string("URL");
731
732 case dods_opaque_c:
733 return string("Opaque");
734
735 case dods_array_c:
736 return string("Array");
737
738 case dods_structure_c:
739 return string("Structure");
740 case dods_sequence_c:
741 return string("Sequence");
742 case dods_group_c:
743 return string("Group");
744
745 default:
746 throw InternalErr(__FILE__, __LINE__, "Unknown type.");
747 }
748}
749
761{
762 try {
763 return D4type_name(t);
764 }
765 catch (...) {
766 return D2type_name(t);
767 }
768}
769
776{
777 switch (t) {
778
779 case dods_byte_c:
780 case dods_char_c:
781
782 case dods_int8_c:
783 case dods_uint8_c:
784
785 case dods_int16_c:
786 case dods_uint16_c:
787 case dods_int32_c:
788 case dods_uint32_c:
789
790 case dods_int64_c:
791 case dods_uint64_c:
792
793 case dods_float32_c:
794 case dods_float64_c:
795 case dods_str_c:
796 case dods_url_c:
797 case dods_enum_c:
798 case dods_opaque_c:
799 return true;
800
801 case dods_null_c:
802 case dods_array_c:
803 case dods_structure_c:
804 case dods_sequence_c:
805 case dods_grid_c:
806 case dods_group_c:
807 default:
808 return false;
809 }
810}
811
816{
817 switch (t) {
818 case dods_null_c:
819 case dods_byte_c:
820 case dods_char_c:
821
822 case dods_int8_c:
823 case dods_uint8_c:
824
825 case dods_int16_c:
826 case dods_uint16_c:
827
828 case dods_int32_c:
829 case dods_uint32_c:
830
831 case dods_int64_c:
832 case dods_uint64_c:
833
834 case dods_float32_c:
835 case dods_float64_c:
836
837 case dods_str_c:
838 case dods_url_c:
839 case dods_enum_c:
840 case dods_opaque_c:
841 return false;
842
843 case dods_array_c:
844 return true;
845
846 case dods_structure_c:
847 case dods_sequence_c:
848 case dods_grid_c:
849 case dods_group_c:
850 default:
851 return false;
852 }
853}
854
860{
861 switch (t) {
862 case dods_null_c:
863 case dods_byte_c:
864 case dods_char_c:
865
866 case dods_int8_c:
867 case dods_uint8_c:
868
869 case dods_int16_c:
870 case dods_uint16_c:
871 case dods_int32_c:
872 case dods_uint32_c:
873
874 case dods_int64_c:
875 case dods_uint64_c:
876
877 case dods_float32_c:
878 case dods_float64_c:
879 case dods_str_c:
880 case dods_url_c:
881 case dods_enum_c:
882 case dods_opaque_c:
883
884 case dods_array_c:
885 return false;
886
887 case dods_structure_c:
888 case dods_sequence_c:
889 case dods_grid_c:
890 case dods_group_c:
891 default:
892 return true;
893 }
894}
895
901{
902 switch (t) {
903 case dods_byte_c:
904 case dods_char_c:
905 case dods_int8_c:
906 case dods_uint8_c:
907 case dods_int16_c:
908 case dods_uint16_c:
909 case dods_int32_c:
910 case dods_uint32_c:
911 case dods_int64_c:
912 case dods_uint64_c:
913 return true;
914 default:
915 return false;
916 }
917}
918
925bool dir_exists(const string &dir)
926{
927 struct stat buf;
928
929 return (stat(dir.c_str(), &buf) == 0) && (buf.st_mode & S_IFDIR);
930}
931
932// Jose Garcia
933void append_long_to_string(long val, int base, string &str_val)
934{
935 // The array digits contains 36 elements which are the
936 // posible valid digits for out bases in the range
937 // [2,36]
938 char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
939 // result of val / base
940 ldiv_t r;
941
942 if (base > 36 || base < 2) {
943 // no conversion if wrong base
944 std::invalid_argument ex("The parameter base has an invalid value.");
945 throw ex;
946 }
947 if (val < 0) str_val += '-';
948 r = ldiv(labs(val), base);
949
950 // output digits of val/base first
951 if (r.quot > 0) append_long_to_string(r.quot, base, str_val);
952
953 // output last digit
954
955 str_val += digits[(int) r.rem];
956}
957
958// base defaults to 10
959string long_to_string(long val, int base)
960{
961 string s;
962 append_long_to_string(val, base, s);
963 return s;
964}
965
966// Jose Garcia
967void append_double_to_string(const double &num, string &str)
968{
969 // s having 100 characters should be enough for sprintf to do its job.
970 // I want to banish all instances of sprintf. 10/5/2001 jhrg
971 ostringstream oss;
972 oss.precision(9);
973 oss << num;
974 str += oss.str();
975}
976
977string double_to_string(const double &num)
978{
979 string s;
980 append_double_to_string(num, s);
981 return s;
982}
983
984// Given a pathname, return the file at the end of the path. This is used
985// when reporting errors (maybe other times, too) to keep the server from
986// revealing too much about its organization when sending error responses
987// back to clients. 10/11/2000 jhrg
988// MT-safe. 08/05/02 jhrg
989
990#ifdef WIN32
991static const char path_sep[] =
992{ "\\"
993};
994#else
995static const char path_sep[] = { "/" };
996#endif
997
1006string path_to_filename(string path)
1007{
1008 string::size_type pos = path.rfind(path_sep);
1009
1010 return (pos == string::npos) ? path : path.substr(++pos);
1011}
1012
1013#define CHECK_BIT( tab, bit ) ( tab[ (bit)/8 ] & (1<<( (bit)%8 )) )
1014#define BITLISTSIZE 16 /* bytes used for [chars] in compiled expr */
1015
1016/*
1017 * globchars() - build a bitlist to check for character group match
1018 */
1019
1020static void globchars(const char *s, const char *e, char *b)
1021{
1022 int neg = 0;
1023
1024 memset(b, '\0', BITLISTSIZE);
1025
1026 if (*s == '^') neg++, s++;
1027
1028 while (s < e) {
1029 int c;
1030
1031 if (s + 2 < e && s[1] == '-') {
1032 for (c = s[0]; c <= s[2]; c++)
1033 b[c / 8] |= (1 << (c % 8));
1034 s += 3;
1035 }
1036 else {
1037 c = *s++;
1038 b[c / 8] |= (1 << (c % 8));
1039 }
1040 }
1041
1042 if (neg) {
1043 int i;
1044 for (i = 0; i < BITLISTSIZE; i++)
1045 b[i] ^= 0377;
1046 }
1047
1048 /* Don't include \0 in either $[chars] or $[^chars] */
1049
1050 b[0] &= 0376;
1051}
1052
1069int glob(const char *c, const char *s)
1070{
1071 if (!c || !s) return 1;
1072
1073 char bitlist[BITLISTSIZE];
1074 int i = 0;
1075 for (;;) {
1076 ++i;
1077 switch (*c++) {
1078 case '\0':
1079 return *s ? -1 : 0;
1080
1081 case '?':
1082 if (!*s++) return i/*1*/;
1083 break;
1084
1085 case '[': {
1086 /* scan for matching ] */
1087
1088 const char *here = c;
1089 do {
1090 if (!*c++) return i/*1*/;
1091 } while (here == c || *c != ']');
1092 c++;
1093
1094 /* build character class bitlist */
1095
1096 globchars(here, c, bitlist);
1097
1098 if (!CHECK_BIT(bitlist, *(unsigned char * )s)) return i/*1*/;
1099 s++;
1100 break;
1101 }
1102
1103 case '*': {
1104 const char *here = s;
1105
1106 while (*s)
1107 s++;
1108
1109 /* Try to match the rest of the pattern in a recursive */
1110 /* call. If the match fails we'll back up chars, retrying. */
1111
1112 while (s != here) {
1113 int r;
1114
1115 /* A fast path for the last token in a pattern */
1116
1117 r = *c ? glob(c, s) : *s ? -1 : 0;
1118
1119 if (!r)
1120 return 0;
1121 else if (r < 0) return i/*1*/;
1122
1123 --s;
1124 }
1125 break;
1126 }
1127
1128 case '\\':
1129 /* Force literal match of next char. */
1130
1131 if (!*c || *s++ != *c++) return i/*1*/;
1132 break;
1133
1134 default:
1135 if (*s++ != c[-1]) return i/*1*/;
1136 break;
1137 }
1138 }
1139}
1140
1148bool size_ok(unsigned int sz, unsigned int nelem)
1149{
1150 return (sz > 0 && nelem < UINT_MAX / sz);
1151}
1152
1169bool pathname_ok(const string &path, bool strict)
1170{
1171 if (path.length() > 255) return false;
1172
1173 Regex name("[-0-9A-z_./]+");
1174 if (!strict) name = "[:print:]+";
1175
1176 string::size_type len = path.length();
1177 int result = name.match(path.c_str(), len);
1178 // Protect against casting too big an uint to int
1179 // if LEN is bigger than the max int32, the second test can't work
1180 if (len > INT_MAX || result != static_cast<int>(len)) return false;
1181
1182 return true;
1183}
1184
1186
1192{
1193 return (string) "OPeNDAP DAP/" + libdap_version() + ": compiled on " + __DATE__ + ":" + __TIME__;
1194}
1195
1208string open_temp_fstream(ofstream &f, const string &name_template, const string &suffix /* = "" */)
1209{
1210 vector<char> name;
1211 copy(name_template.begin(), name_template.end(), back_inserter(name));
1212 if (!suffix.empty())
1213 copy(suffix.begin(), suffix.end(), back_inserter(name));
1214 name.push_back('\0');
1215
1216 // Use mkstemp to make and open the temp file atomically
1217 int tmpfile = mkstemps(&name[0], suffix.length());
1218 if (tmpfile == -1)
1219 throw Error(internal_error, "Could not make a temporary file.");
1220 // Open the file using C++ ofstream; get a C++ fstream object
1221 f.open(&name[0]);
1222 // Close the file descriptor; the file stays open because of the fstream object
1223 close(tmpfile);
1224 // Now test that the fstream object is valid
1225 if (f.fail())
1226 throw Error(internal_error, "Could not make a temporary file.");
1227
1228 return string(&name[0]);
1229}
1230
1231
1232} // namespace libdap
1233
A multidimensional array of identical data types.
Definition Array.h:113
The basic data type for the DODS DAP types.
Definition BaseType.h:118
virtual string name() const
Returns the name of the class instance.
Definition BaseType.cc:320
virtual bool read_p()
Has this variable been read?
Definition BaseType.cc:480
virtual bool is_simple_type() const
Returns true if the instance is a numeric, string or URL type variable.
Definition BaseType.cc:393
virtual Type type() const
Returns the type of the class instance.
Definition BaseType.cc:365
Holds a single byte.
Definition Byte.h:61
A class for error processing.
Definition Error.h:93
Holds a 32-bit floating point value.
Definition Float32.h:62
Holds a 64-bit (double precision) floating point value.
Definition Float64.h:61
Holds a 16-bit signed integer value.
Definition Int16.h:60
Holds a 32-bit signed integer.
Definition Int32.h:66
Holds a64-bit signed integer.
Definition Int64.h:50
Holds an 8-bit signed integer value.
Definition Int8.h:43
A class for software fault reporting.
Definition InternalErr.h:65
int match(const char *s, int len, int pos=0)
Does the pattern match.
Definition GNURegex.cc:115
Holds character string data.
Definition Str.h:63
Holds an unsigned 16-bit integer.
Definition UInt16.h:58
Holds a 32-bit unsigned integer.
Definition UInt32.h:60
Holds a 64-bit unsigned integer.
Definition UInt64.h:50
virtual int length() const
Definition Vector.cc:548
virtual void set_read_p(bool state)
Indicates that the data is ready to send.
Definition Vector.cc:391
virtual BaseType * var(const string &name="", bool exact_match=true, btp_stack *s=0)
Definition Vector.cc:433
top level DAP object to house generic methods
Type
Identifies the data type.
Definition Type.h:94
string open_temp_fstream(ofstream &f, const string &name_template, const string &suffix)
Definition util.cc:1208
bool size_ok(unsigned int sz, unsigned int nelem)
sanitize the size of an array. Test for integer overflow when dynamically allocating an array.
Definition util.cc:1148
string remove_quotes(const string &s)
Definition util.cc:585
string path_to_filename(string path)
Definition util.cc:1006
bool is_host_big_endian()
Does this host use big-endian byte order?
Definition util.cc:94
const char * libdap_version()
Definition util.cc:526
double extract_double_value(BaseType *arg)
Definition util.cc:402
string prune_spaces(const string &name)
Definition util.cc:459
string type_name(Type t)
Definition util.cc:760
void set_array_using_double(Array *dest, double *src, int src_len)
Definition util.cc:166
bool is_simple_type(Type t)
Returns true if the instance is a numeric, string or URL type variable.
Definition util.cc:775
bool dir_exists(const string &dir)
Definition util.cc:925
bool pathname_ok(const string &path, bool strict)
Does the string name a potentially valid pathname? Test the given pathname to verify that it is a val...
Definition util.cc:1169
void downcase(string &s)
Definition util.cc:563
string D2type_name(Type t)
Returns the type of the class instance as a string. Supports all DAP2 types and not the DAP4-only typ...
Definition util.cc:649
string D4type_name(Type t)
Returns the type of the class instance as a string. Supports all DAP4 types and not the DAP2-only typ...
Definition util.cc:694
string systime()
Definition util.cc:542
bool is_constructor_type(Type t)
Returns true if the instance is a constructor (i.e., Structure, Sequence or Grid) type variable.
Definition util.cc:859
bool is_vector_type(Type t)
Returns true if the instance is a vector (i.e., array) type variable.
Definition util.cc:815
bool is_integer_type(Type t)
Definition util.cc:900
int glob(const char *c, const char *s)
Definition util.cc:1069
string extract_string_argument(BaseType *arg)
Definition util.cc:119
ObjectType get_type(const string &value)
Definition mime_util.cc:326
double * extract_double_array(Array *a)
Definition util.cc:261
bool is_quoted(const string &s)
Definition util.cc:574
string dap_version()
Definition util.cc:1191