libdap  Updated for version 3.19.1
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 
89 using namespace std;
90 
91 namespace 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 
132 template<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 
166 void 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 
235 template<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!
315 template<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 
343 void 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 
459 string 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 
481 bool 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 
515 const char *
516 libdap_root()
517 {
518  return LIBDAP_ROOT;
519 }
520 
525 extern "C" const char *
527 {
528  return PACKAGE_VERSION;
529 }
530 
531 extern "C" const char *
532 libdap_name()
533 {
534  return PACKAGE_NAME;
535 }
536 
542 string 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 
563 void downcase(string &s)
564 {
565  for (unsigned int i = 0; i < s.length(); i++)
566  s[i] = tolower(s[i]);
567 }
568 
574 bool is_quoted(const string &s)
575 {
576  return (!s.empty() && s[0] == '\"' && s[s.length() - 1] == '\"');
577 }
578 
585 string 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 
594 Type 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 
649 string D2type_name(Type t)
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 
694 string D4type_name(Type t)
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 
760 string type_name(Type t)
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  return false;
812 }
813 
818 {
819  switch (t) {
820  case dods_null_c:
821  case dods_byte_c:
822  case dods_char_c:
823 
824  case dods_int8_c:
825  case dods_uint8_c:
826 
827  case dods_int16_c:
828  case dods_uint16_c:
829 
830  case dods_int32_c:
831  case dods_uint32_c:
832 
833  case dods_int64_c:
834  case dods_uint64_c:
835 
836  case dods_float32_c:
837  case dods_float64_c:
838 
839  case dods_str_c:
840  case dods_url_c:
841  case dods_enum_c:
842  case dods_opaque_c:
843  return false;
844 
845  case dods_array_c:
846  return true;
847 
848  case dods_structure_c:
849  case dods_sequence_c:
850  case dods_grid_c:
851  case dods_group_c:
852  default:
853  return false;
854  }
855 
856  return false;
857 }
858 
864 {
865  switch (t) {
866  case dods_null_c:
867  case dods_byte_c:
868  case dods_char_c:
869 
870  case dods_int8_c:
871  case dods_uint8_c:
872 
873  case dods_int16_c:
874  case dods_uint16_c:
875  case dods_int32_c:
876  case dods_uint32_c:
877 
878  case dods_int64_c:
879  case dods_uint64_c:
880 
881  case dods_float32_c:
882  case dods_float64_c:
883  case dods_str_c:
884  case dods_url_c:
885  case dods_enum_c:
886  case dods_opaque_c:
887 
888  case dods_array_c:
889  return false;
890 
891  case dods_structure_c:
892  case dods_sequence_c:
893  case dods_grid_c:
894  case dods_group_c:
895  default:
896  return true;
897  }
898 
899  return false;
900 }
901 
907 {
908  switch (t) {
909  case dods_byte_c:
910  case dods_char_c:
911  case dods_int8_c:
912  case dods_uint8_c:
913  case dods_int16_c:
914  case dods_uint16_c:
915  case dods_int32_c:
916  case dods_uint32_c:
917  case dods_int64_c:
918  case dods_uint64_c:
919  return true;
920  default:
921  return false;
922  }
923 }
924 
931 bool dir_exists(const string &dir)
932 {
933  struct stat buf;
934 
935  return (stat(dir.c_str(), &buf) == 0) && (buf.st_mode & S_IFDIR);
936 }
937 
938 // Jose Garcia
939 void append_long_to_string(long val, int base, string &str_val)
940 {
941  // The array digits contains 36 elements which are the
942  // posible valid digits for out bases in the range
943  // [2,36]
944  char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
945  // result of val / base
946  ldiv_t r;
947 
948  if (base > 36 || base < 2) {
949  // no conversion if wrong base
950  std::invalid_argument ex("The parameter base has an invalid value.");
951  throw ex;
952  }
953  if (val < 0) str_val += '-';
954  r = ldiv(labs(val), base);
955 
956  // output digits of val/base first
957  if (r.quot > 0) append_long_to_string(r.quot, base, str_val);
958 
959  // output last digit
960 
961  str_val += digits[(int) r.rem];
962 }
963 
964 // base defaults to 10
965 string long_to_string(long val, int base)
966 {
967  string s;
968  append_long_to_string(val, base, s);
969  return s;
970 }
971 
972 // Jose Garcia
973 void append_double_to_string(const double &num, string &str)
974 {
975  // s having 100 characters should be enough for sprintf to do its job.
976  // I want to banish all instances of sprintf. 10/5/2001 jhrg
977  ostringstream oss;
978  oss.precision(9);
979  oss << num;
980  str += oss.str();
981 }
982 
983 string double_to_string(const double &num)
984 {
985  string s;
986  append_double_to_string(num, s);
987  return s;
988 }
989 
990 // Given a pathname, return the file at the end of the path. This is used
991 // when reporting errors (maybe other times, too) to keep the server from
992 // revealing too much about its organization when sending error responses
993 // back to clients. 10/11/2000 jhrg
994 // MT-safe. 08/05/02 jhrg
995 
996 #ifdef WIN32
997 static const char path_sep[] =
998 { "\\"
999 };
1000 #else
1001 static const char path_sep[] = { "/" };
1002 #endif
1003 
1012 string path_to_filename(string path)
1013 {
1014  string::size_type pos = path.rfind(path_sep);
1015 
1016  return (pos == string::npos) ? path : path.substr(++pos);
1017 }
1018 
1019 #define CHECK_BIT( tab, bit ) ( tab[ (bit)/8 ] & (1<<( (bit)%8 )) )
1020 #define BITLISTSIZE 16 /* bytes used for [chars] in compiled expr */
1021 
1022 /*
1023  * globchars() - build a bitlist to check for character group match
1024  */
1025 
1026 static void globchars(const char *s, const char *e, char *b)
1027 {
1028  int neg = 0;
1029 
1030  memset(b, '\0', BITLISTSIZE);
1031 
1032  if (*s == '^') neg++, s++;
1033 
1034  while (s < e) {
1035  int c;
1036 
1037  if (s + 2 < e && s[1] == '-') {
1038  for (c = s[0]; c <= s[2]; c++)
1039  b[c / 8] |= (1 << (c % 8));
1040  s += 3;
1041  }
1042  else {
1043  c = *s++;
1044  b[c / 8] |= (1 << (c % 8));
1045  }
1046  }
1047 
1048  if (neg) {
1049  int i;
1050  for (i = 0; i < BITLISTSIZE; i++)
1051  b[i] ^= 0377;
1052  }
1053 
1054  /* Don't include \0 in either $[chars] or $[^chars] */
1055 
1056  b[0] &= 0376;
1057 }
1058 
1075 int glob(const char *c, const char *s)
1076 {
1077  if (!c || !s) return 1;
1078 
1079  char bitlist[BITLISTSIZE];
1080  int i = 0;
1081  for (;;) {
1082  ++i;
1083  switch (*c++) {
1084  case '\0':
1085  return *s ? -1 : 0;
1086 
1087  case '?':
1088  if (!*s++) return i/*1*/;
1089  break;
1090 
1091  case '[': {
1092  /* scan for matching ] */
1093 
1094  const char *here = c;
1095  do {
1096  if (!*c++) return i/*1*/;
1097  } while (here == c || *c != ']');
1098  c++;
1099 
1100  /* build character class bitlist */
1101 
1102  globchars(here, c, bitlist);
1103 
1104  if (!CHECK_BIT(bitlist, *(unsigned char * )s)) return i/*1*/;
1105  s++;
1106  break;
1107  }
1108 
1109  case '*': {
1110  const char *here = s;
1111 
1112  while (*s)
1113  s++;
1114 
1115  /* Try to match the rest of the pattern in a recursive */
1116  /* call. If the match fails we'll back up chars, retrying. */
1117 
1118  while (s != here) {
1119  int r;
1120 
1121  /* A fast path for the last token in a pattern */
1122 
1123  r = *c ? glob(c, s) : *s ? -1 : 0;
1124 
1125  if (!r)
1126  return 0;
1127  else if (r < 0) return i/*1*/;
1128 
1129  --s;
1130  }
1131  break;
1132  }
1133 
1134  case '\\':
1135  /* Force literal match of next char. */
1136 
1137  if (!*c || *s++ != *c++) return i/*1*/;
1138  break;
1139 
1140  default:
1141  if (*s++ != c[-1]) return i/*1*/;
1142  break;
1143  }
1144  }
1145 
1146  return 1; // Should never get here; this quiets gcc's warning
1147 }
1148 
1156 bool size_ok(unsigned int sz, unsigned int nelem)
1157 {
1158  return (sz > 0 && nelem < UINT_MAX / sz);
1159 }
1160 
1177 bool pathname_ok(const string &path, bool strict)
1178 {
1179  if (path.length() > 255) return false;
1180 
1181  Regex name("[-0-9A-z_./]+");
1182  if (!strict) name = "[:print:]+";
1183 
1184  string::size_type len = path.length();
1185  int result = name.match(path.c_str(), len);
1186  // Protect against casting too big an uint to int
1187  // if LEN is bigger than the max int32, the second test can't work
1188  if (len > INT_MAX || result != static_cast<int>(len)) return false;
1189 
1190  return true;
1191 }
1192 
1194 
1199 string dap_version()
1200 {
1201  return (string) "OPeNDAP DAP/" + libdap_version() + ": compiled on " + __DATE__ + ":" + __TIME__;
1202 }
1203 
1216 string open_temp_fstream(ofstream &f, const string &name_template, const string &suffix /* = "" */)
1217 {
1218  vector<char> name;
1219  copy(name_template.begin(), name_template.end(), back_inserter(name));
1220  if (!suffix.empty())
1221  copy(suffix.begin(), suffix.end(), back_inserter(name));
1222  name.push_back('\0');
1223 
1224  // Use mkstemp to make and open the temp file atomically
1225  int tmpfile = mkstemps(&name[0], suffix.length());
1226  if (tmpfile == -1)
1227  throw Error(internal_error, "Could not make a temporary file.");
1228  // Open the file using C++ ofstream; get a C++ fstream object
1229  f.open(&name[0]);
1230  // Close the file descriptor; the file stays open because of the fstream object
1231  close(tmpfile);
1232  // Now test that the fstream object is valid
1233  if (f.fail())
1234  throw Error(internal_error, "Could not make a temporary file.");
1235 
1236  return string(&name[0]);
1237 }
1238 
1239 
1240 } // namespace libdap
1241 
Holds an 8-bit signed integer value.
Definition: Int8.h:42
Holds a64-bit signed integer.
Definition: Int64.h:49
virtual bool read_p()
Has this variable been read?
Definition: BaseType.cc:471
virtual string name() const
Returns the name of the class instance.
Definition: BaseType.cc:311
void downcase(string &s)
Definition: util.cc:563
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:863
string prune_spaces(const string &name)
Definition: util.cc:459
string open_temp_fstream(ofstream &f, const string &name_template, const string &suffix)
Definition: util.cc:1216
Holds an unsigned 16-bit integer.
Definition: UInt16.h:57
virtual void set_read_p(bool state)
Indicates that the data is ready to send.
Definition: Vector.cc:392
string extract_string_argument(BaseType *arg)
Definition: util.cc:119
bool dir_exists(const string &dir)
Definition: util.cc:931
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:1156
STL namespace.
bool is_vector_type(Type t)
Returns true if the instance is a vector (i.e., array) type variable.
Definition: util.cc:817
virtual bool is_simple_type() const
Returns true if the instance is a numeric, string or URL type variable.
Definition: BaseType.cc:384
Type
Identifies the data type.
Definition: Type.h:94
Holds a 32-bit floating point value.
Definition: Float32.h:61
A class for software fault reporting.
Definition: InternalErr.h:64
int match(const char *s, int len, int pos=0)
Does the pattern match.
Definition: GNURegex.cc:115
virtual BaseType * var(const string &name="", bool exact_match=true, btp_stack *s=0)
Definition: Vector.cc:434
Holds character string data.
Definition: Str.h:62
void set_array_using_double(Array *dest, double *src, int src_len)
Definition: util.cc:166
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:1177
double * extract_double_array(Array *a)
Definition: util.cc:261
Holds a 16-bit signed integer value.
Definition: Int16.h:59
virtual Type type() const
Returns the type of the class instance.
Definition: BaseType.cc:356
ObjectType get_type(const string &value)
Definition: mime_util.cc:326
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 path_to_filename(string path)
Definition: util.cc:1012
bool is_quoted(const string &s)
Definition: util.cc:574
bool is_simple_type(Type t)
Returns true if the instance is a numeric, string or URL type variable.
Definition: util.cc:775
string systime()
Definition: util.cc:542
Holds a 64-bit unsigned integer.
Definition: UInt64.h:49
double extract_double_value(BaseType *arg)
Definition: util.cc:402
string dap_version()
Definition: util.cc:1199
string remove_quotes(const string &s)
Definition: util.cc:585
The basic data type for the DODS DAP types.
Definition: BaseType.h:117
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
Holds a 64-bit (double precision) floating point value.
Definition: Float64.h:60
virtual int length() const
Definition: Vector.cc:555
Holds a single byte.
Definition: Byte.h:60
A class for error processing.
Definition: Error.h:90
bool is_host_big_endian()
Does this host use big-endian byte order?
Definition: util.cc:94
Holds a 32-bit unsigned integer.
Definition: UInt32.h:59
string type_name(Type t)
Definition: util.cc:760
const char * libdap_version()
Definition: util.cc:526
A multidimensional array of identical data types.
Definition: Array.h:112
int glob(const char *c, const char *s)
Definition: util.cc:1075
bool is_integer_type(Type t)
Definition: util.cc:906
Holds a 32-bit signed integer.
Definition: Int32.h:65