comparison Resources/Orthanc/Core/Toolbox.cpp @ 200:03afbee0cc7b

integration of Orthanc core into Stone
author Sebastien Jodogne <s.jodogne@gmail.com>
date Fri, 23 Mar 2018 11:04:03 +0100
parents
children 795d71f66f31
comparison
equal deleted inserted replaced
199:dabe9982fca3 200:03afbee0cc7b
1 /**
2 * Orthanc - A Lightweight, RESTful DICOM Store
3 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
4 * Department, University Hospital of Liege, Belgium
5 * Copyright (C) 2017-2018 Osimis S.A., Belgium
6 *
7 * This program is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
11 *
12 * In addition, as a special exception, the copyright holders of this
13 * program give permission to link the code of its release with the
14 * OpenSSL project's "OpenSSL" library (or with modified versions of it
15 * that use the same license as the "OpenSSL" library), and distribute
16 * the linked executables. You must obey the GNU General Public License
17 * in all respects for all of the code used other than "OpenSSL". If you
18 * modify file(s) with this exception, you may extend this exception to
19 * your version of the file(s), but you are not obligated to do so. If
20 * you do not wish to do so, delete this exception statement from your
21 * version. If you delete this exception statement from all source files
22 * in the program, then also delete it here.
23 *
24 * This program is distributed in the hope that it will be useful, but
25 * WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27 * General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 **/
32
33
34 #include "PrecompiledHeaders.h"
35 #include "Toolbox.h"
36
37 #include "OrthancException.h"
38 #include "Logging.h"
39
40 #include <boost/algorithm/string/case_conv.hpp>
41 #include <boost/algorithm/string/replace.hpp>
42 #include <boost/lexical_cast.hpp>
43 #include <boost/regex.hpp>
44 #include <boost/uuid/sha1.hpp>
45
46 #include <string>
47 #include <stdint.h>
48 #include <string.h>
49 #include <algorithm>
50 #include <ctype.h>
51
52
53 #if ORTHANC_ENABLE_MD5 == 1
54 # include "../Resources/ThirdParty/md5/md5.h"
55 #endif
56
57 #if ORTHANC_ENABLE_BASE64 == 1
58 # include "../Resources/ThirdParty/base64/base64.h"
59 #endif
60
61 #if ORTHANC_ENABLE_LOCALE == 1
62 # include <boost/locale.hpp>
63 #endif
64
65
66 #if defined(_MSC_VER) && (_MSC_VER < 1800)
67 // Patch for the missing "_strtoll" symbol when compiling with Visual Studio < 2013
68 extern "C"
69 {
70 int64_t _strtoi64(const char *nptr, char **endptr, int base);
71 int64_t strtoll(const char *nptr, char **endptr, int base)
72 {
73 return _strtoi64(nptr, endptr, base);
74 }
75 }
76 #endif
77
78
79 #if defined(_WIN32)
80 # include <windows.h> // For ::Sleep
81 #endif
82
83
84 #if ORTHANC_ENABLE_PUGIXML == 1
85 # include "ChunkedBuffer.h"
86 # include <pugixml.hpp>
87 #endif
88
89
90 namespace Orthanc
91 {
92 void Toolbox::ToUpperCase(std::string& s)
93 {
94 std::transform(s.begin(), s.end(), s.begin(), toupper);
95 }
96
97
98 void Toolbox::ToLowerCase(std::string& s)
99 {
100 std::transform(s.begin(), s.end(), s.begin(), tolower);
101 }
102
103
104 void Toolbox::ToUpperCase(std::string& result,
105 const std::string& source)
106 {
107 result = source;
108 ToUpperCase(result);
109 }
110
111 void Toolbox::ToLowerCase(std::string& result,
112 const std::string& source)
113 {
114 result = source;
115 ToLowerCase(result);
116 }
117
118
119 void Toolbox::SplitUriComponents(UriComponents& components,
120 const std::string& uri)
121 {
122 static const char URI_SEPARATOR = '/';
123
124 components.clear();
125
126 if (uri.size() == 0 ||
127 uri[0] != URI_SEPARATOR)
128 {
129 throw OrthancException(ErrorCode_UriSyntax);
130 }
131
132 // Count the number of slashes in the URI to make an assumption
133 // about the number of components in the URI
134 unsigned int estimatedSize = 0;
135 for (unsigned int i = 0; i < uri.size(); i++)
136 {
137 if (uri[i] == URI_SEPARATOR)
138 estimatedSize++;
139 }
140
141 components.reserve(estimatedSize - 1);
142
143 unsigned int start = 1;
144 unsigned int end = 1;
145 while (end < uri.size())
146 {
147 // This is the loop invariant
148 assert(uri[start - 1] == '/' && (end >= start));
149
150 if (uri[end] == '/')
151 {
152 components.push_back(std::string(&uri[start], end - start));
153 end++;
154 start = end;
155 }
156 else
157 {
158 end++;
159 }
160 }
161
162 if (start < uri.size())
163 {
164 components.push_back(std::string(&uri[start], end - start));
165 }
166
167 for (size_t i = 0; i < components.size(); i++)
168 {
169 if (components[i].size() == 0)
170 {
171 // Empty component, as in: "/coucou//e"
172 throw OrthancException(ErrorCode_UriSyntax);
173 }
174 }
175 }
176
177
178 void Toolbox::TruncateUri(UriComponents& target,
179 const UriComponents& source,
180 size_t fromLevel)
181 {
182 target.clear();
183
184 if (source.size() > fromLevel)
185 {
186 target.resize(source.size() - fromLevel);
187
188 size_t j = 0;
189 for (size_t i = fromLevel; i < source.size(); i++, j++)
190 {
191 target[j] = source[i];
192 }
193
194 assert(j == target.size());
195 }
196 }
197
198
199
200 bool Toolbox::IsChildUri(const UriComponents& baseUri,
201 const UriComponents& testedUri)
202 {
203 if (testedUri.size() < baseUri.size())
204 {
205 return false;
206 }
207
208 for (size_t i = 0; i < baseUri.size(); i++)
209 {
210 if (baseUri[i] != testedUri[i])
211 return false;
212 }
213
214 return true;
215 }
216
217
218 std::string Toolbox::AutodetectMimeType(const std::string& path)
219 {
220 std::string contentType;
221 size_t lastDot = path.rfind('.');
222 size_t lastSlash = path.rfind('/');
223
224 if (lastDot == std::string::npos ||
225 (lastSlash != std::string::npos && lastDot < lastSlash))
226 {
227 // No trailing dot, unable to detect the content type
228 }
229 else
230 {
231 const char* extension = &path[lastDot + 1];
232
233 // http://en.wikipedia.org/wiki/Mime_types
234 // Text types
235 if (!strcmp(extension, "txt"))
236 contentType = "text/plain";
237 else if (!strcmp(extension, "html"))
238 contentType = "text/html";
239 else if (!strcmp(extension, "xml"))
240 contentType = "text/xml";
241 else if (!strcmp(extension, "css"))
242 contentType = "text/css";
243
244 // Application types
245 else if (!strcmp(extension, "js"))
246 contentType = "application/javascript";
247 else if (!strcmp(extension, "json"))
248 contentType = "application/json";
249 else if (!strcmp(extension, "pdf"))
250 contentType = "application/pdf";
251
252 // Images types
253 else if (!strcmp(extension, "jpg") || !strcmp(extension, "jpeg"))
254 contentType = "image/jpeg";
255 else if (!strcmp(extension, "gif"))
256 contentType = "image/gif";
257 else if (!strcmp(extension, "png"))
258 contentType = "image/png";
259 }
260
261 return contentType;
262 }
263
264
265 std::string Toolbox::FlattenUri(const UriComponents& components,
266 size_t fromLevel)
267 {
268 if (components.size() <= fromLevel)
269 {
270 return "/";
271 }
272 else
273 {
274 std::string r;
275
276 for (size_t i = fromLevel; i < components.size(); i++)
277 {
278 r += "/" + components[i];
279 }
280
281 return r;
282 }
283 }
284
285
286 #if ORTHANC_ENABLE_MD5 == 1
287 static char GetHexadecimalCharacter(uint8_t value)
288 {
289 assert(value < 16);
290
291 if (value < 10)
292 {
293 return value + '0';
294 }
295 else
296 {
297 return (value - 10) + 'a';
298 }
299 }
300
301
302 void Toolbox::ComputeMD5(std::string& result,
303 const std::string& data)
304 {
305 if (data.size() > 0)
306 {
307 ComputeMD5(result, &data[0], data.size());
308 }
309 else
310 {
311 ComputeMD5(result, NULL, 0);
312 }
313 }
314
315
316 void Toolbox::ComputeMD5(std::string& result,
317 const void* data,
318 size_t size)
319 {
320 md5_state_s state;
321 md5_init(&state);
322
323 if (size > 0)
324 {
325 md5_append(&state,
326 reinterpret_cast<const md5_byte_t*>(data),
327 static_cast<int>(size));
328 }
329
330 md5_byte_t actualHash[16];
331 md5_finish(&state, actualHash);
332
333 result.resize(32);
334 for (unsigned int i = 0; i < 16; i++)
335 {
336 result[2 * i] = GetHexadecimalCharacter(static_cast<uint8_t>(actualHash[i] / 16));
337 result[2 * i + 1] = GetHexadecimalCharacter(static_cast<uint8_t>(actualHash[i] % 16));
338 }
339 }
340 #endif
341
342
343 #if ORTHANC_ENABLE_BASE64 == 1
344 void Toolbox::EncodeBase64(std::string& result,
345 const std::string& data)
346 {
347 result = base64_encode(data);
348 }
349
350 void Toolbox::DecodeBase64(std::string& result,
351 const std::string& data)
352 {
353 for (size_t i = 0; i < data.length(); i++)
354 {
355 if (!isalnum(data[i]) &&
356 data[i] != '+' &&
357 data[i] != '/' &&
358 data[i] != '=')
359 {
360 // This is not a valid character for a Base64 string
361 throw OrthancException(ErrorCode_BadFileFormat);
362 }
363 }
364
365 result = base64_decode(data);
366 }
367
368
369 bool Toolbox::DecodeDataUriScheme(std::string& mime,
370 std::string& content,
371 const std::string& source)
372 {
373 boost::regex pattern("data:([^;]+);base64,([a-zA-Z0-9=+/]*)",
374 boost::regex::icase /* case insensitive search */);
375
376 boost::cmatch what;
377 if (regex_match(source.c_str(), what, pattern))
378 {
379 mime = what[1];
380 DecodeBase64(content, what[2]);
381 return true;
382 }
383 else
384 {
385 return false;
386 }
387 }
388
389
390 void Toolbox::EncodeDataUriScheme(std::string& result,
391 const std::string& mime,
392 const std::string& content)
393 {
394 result = "data:" + mime + ";base64," + base64_encode(content);
395 }
396
397 #endif
398
399
400 #if ORTHANC_ENABLE_LOCALE == 1
401 static const char* GetBoostLocaleEncoding(const Encoding sourceEncoding)
402 {
403 switch (sourceEncoding)
404 {
405 case Encoding_Utf8:
406 return "UTF-8";
407
408 case Encoding_Ascii:
409 return "ASCII";
410
411 case Encoding_Latin1:
412 return "ISO-8859-1";
413 break;
414
415 case Encoding_Latin2:
416 return "ISO-8859-2";
417 break;
418
419 case Encoding_Latin3:
420 return "ISO-8859-3";
421 break;
422
423 case Encoding_Latin4:
424 return "ISO-8859-4";
425 break;
426
427 case Encoding_Latin5:
428 return "ISO-8859-9";
429 break;
430
431 case Encoding_Cyrillic:
432 return "ISO-8859-5";
433 break;
434
435 case Encoding_Windows1251:
436 return "WINDOWS-1251";
437 break;
438
439 case Encoding_Arabic:
440 return "ISO-8859-6";
441 break;
442
443 case Encoding_Greek:
444 return "ISO-8859-7";
445 break;
446
447 case Encoding_Hebrew:
448 return "ISO-8859-8";
449 break;
450
451 case Encoding_Japanese:
452 return "SHIFT-JIS";
453 break;
454
455 case Encoding_Chinese:
456 return "GB18030";
457 break;
458
459 case Encoding_Thai:
460 return "TIS620.2533-0";
461 break;
462
463 default:
464 throw OrthancException(ErrorCode_NotImplemented);
465 }
466 }
467 #endif
468
469
470 #if ORTHANC_ENABLE_LOCALE == 1
471 std::string Toolbox::ConvertToUtf8(const std::string& source,
472 Encoding sourceEncoding)
473 {
474 if (sourceEncoding == Encoding_Utf8)
475 {
476 // Already in UTF-8: No conversion is required
477 return source;
478 }
479
480 if (sourceEncoding == Encoding_Ascii)
481 {
482 return ConvertToAscii(source);
483 }
484
485 const char* encoding = GetBoostLocaleEncoding(sourceEncoding);
486
487 try
488 {
489 return boost::locale::conv::to_utf<char>(source, encoding);
490 }
491 catch (std::runtime_error&)
492 {
493 // Bad input string or bad encoding
494 return ConvertToAscii(source);
495 }
496 }
497 #endif
498
499
500 #if ORTHANC_ENABLE_LOCALE == 1
501 std::string Toolbox::ConvertFromUtf8(const std::string& source,
502 Encoding targetEncoding)
503 {
504 if (targetEncoding == Encoding_Utf8)
505 {
506 // Already in UTF-8: No conversion is required
507 return source;
508 }
509
510 if (targetEncoding == Encoding_Ascii)
511 {
512 return ConvertToAscii(source);
513 }
514
515 const char* encoding = GetBoostLocaleEncoding(targetEncoding);
516
517 try
518 {
519 return boost::locale::conv::from_utf<char>(source, encoding);
520 }
521 catch (std::runtime_error&)
522 {
523 // Bad input string or bad encoding
524 return ConvertToAscii(source);
525 }
526 }
527 #endif
528
529
530 bool Toolbox::IsAsciiString(const void* data,
531 size_t size)
532 {
533 const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
534
535 for (size_t i = 0; i < size; i++, p++)
536 {
537 if (*p > 127 || *p == 0 || iscntrl(*p))
538 {
539 return false;
540 }
541 }
542
543 return true;
544 }
545
546
547 bool Toolbox::IsAsciiString(const std::string& s)
548 {
549 return IsAsciiString(s.c_str(), s.size());
550 }
551
552
553 std::string Toolbox::ConvertToAscii(const std::string& source)
554 {
555 std::string result;
556
557 result.reserve(source.size() + 1);
558 for (size_t i = 0; i < source.size(); i++)
559 {
560 if (source[i] <= 127 && source[i] >= 0 && !iscntrl(source[i]))
561 {
562 result.push_back(source[i]);
563 }
564 }
565
566 return result;
567 }
568
569
570 void Toolbox::ComputeSHA1(std::string& result,
571 const void* data,
572 size_t size)
573 {
574 boost::uuids::detail::sha1 sha1;
575
576 if (size > 0)
577 {
578 sha1.process_bytes(data, size);
579 }
580
581 unsigned int digest[5];
582
583 // Sanity check for the memory layout: A SHA-1 digest is 160 bits wide
584 assert(sizeof(unsigned int) == 4 && sizeof(digest) == (160 / 8));
585
586 sha1.get_digest(digest);
587
588 result.resize(8 * 5 + 4);
589 sprintf(&result[0], "%08x-%08x-%08x-%08x-%08x",
590 digest[0],
591 digest[1],
592 digest[2],
593 digest[3],
594 digest[4]);
595 }
596
597 void Toolbox::ComputeSHA1(std::string& result,
598 const std::string& data)
599 {
600 if (data.size() > 0)
601 {
602 ComputeSHA1(result, data.c_str(), data.size());
603 }
604 else
605 {
606 ComputeSHA1(result, NULL, 0);
607 }
608 }
609
610
611 bool Toolbox::IsSHA1(const char* str,
612 size_t size)
613 {
614 if (size == 0)
615 {
616 return false;
617 }
618
619 const char* start = str;
620 const char* end = str + size;
621
622 // Trim the beginning of the string
623 while (start < end)
624 {
625 if (*start == '\0' ||
626 isspace(*start))
627 {
628 start++;
629 }
630 else
631 {
632 break;
633 }
634 }
635
636 // Trim the trailing of the string
637 while (start < end)
638 {
639 if (*(end - 1) == '\0' ||
640 isspace(*(end - 1)))
641 {
642 end--;
643 }
644 else
645 {
646 break;
647 }
648 }
649
650 if (end - start != 44)
651 {
652 return false;
653 }
654
655 for (unsigned int i = 0; i < 44; i++)
656 {
657 if (i == 8 ||
658 i == 17 ||
659 i == 26 ||
660 i == 35)
661 {
662 if (start[i] != '-')
663 return false;
664 }
665 else
666 {
667 if (!isalnum(start[i]))
668 return false;
669 }
670 }
671
672 return true;
673 }
674
675
676 bool Toolbox::IsSHA1(const std::string& s)
677 {
678 if (s.size() == 0)
679 {
680 return false;
681 }
682 else
683 {
684 return IsSHA1(s.c_str(), s.size());
685 }
686 }
687
688
689 std::string Toolbox::StripSpaces(const std::string& source)
690 {
691 size_t first = 0;
692
693 while (first < source.length() &&
694 isspace(source[first]))
695 {
696 first++;
697 }
698
699 if (first == source.length())
700 {
701 // String containing only spaces
702 return "";
703 }
704
705 size_t last = source.length();
706 while (last > first &&
707 isspace(source[last - 1]))
708 {
709 last--;
710 }
711
712 assert(first <= last);
713 return source.substr(first, last - first);
714 }
715
716
717 static char Hex2Dec(char c)
718 {
719 return ((c >= '0' && c <= '9') ? c - '0' :
720 ((c >= 'a' && c <= 'f') ? c - 'a' + 10 : c - 'A' + 10));
721 }
722
723 void Toolbox::UrlDecode(std::string& s)
724 {
725 // http://en.wikipedia.org/wiki/Percent-encoding
726 // http://www.w3schools.com/tags/ref_urlencode.asp
727 // http://stackoverflow.com/questions/154536/encode-decode-urls-in-c
728
729 if (s.size() == 0)
730 {
731 return;
732 }
733
734 size_t source = 0;
735 size_t target = 0;
736
737 while (source < s.size())
738 {
739 if (s[source] == '%' &&
740 source + 2 < s.size() &&
741 isalnum(s[source + 1]) &&
742 isalnum(s[source + 2]))
743 {
744 s[target] = (Hex2Dec(s[source + 1]) << 4) | Hex2Dec(s[source + 2]);
745 source += 3;
746 target += 1;
747 }
748 else
749 {
750 if (s[source] == '+')
751 s[target] = ' ';
752 else
753 s[target] = s[source];
754
755 source++;
756 target++;
757 }
758 }
759
760 s.resize(target);
761 }
762
763
764 Endianness Toolbox::DetectEndianness()
765 {
766 // http://sourceforge.net/p/predef/wiki/Endianness/
767
768 uint8_t buffer[4];
769
770 buffer[0] = 0x00;
771 buffer[1] = 0x01;
772 buffer[2] = 0x02;
773 buffer[3] = 0x03;
774
775 switch (*((uint32_t *)buffer))
776 {
777 case 0x00010203:
778 return Endianness_Big;
779
780 case 0x03020100:
781 return Endianness_Little;
782
783 default:
784 throw OrthancException(ErrorCode_NotImplemented);
785 }
786 }
787
788
789 std::string Toolbox::WildcardToRegularExpression(const std::string& source)
790 {
791 // TODO - Speed up this with a regular expression
792
793 std::string result = source;
794
795 // Escape all special characters
796 boost::replace_all(result, "\\", "\\\\");
797 boost::replace_all(result, "^", "\\^");
798 boost::replace_all(result, ".", "\\.");
799 boost::replace_all(result, "$", "\\$");
800 boost::replace_all(result, "|", "\\|");
801 boost::replace_all(result, "(", "\\(");
802 boost::replace_all(result, ")", "\\)");
803 boost::replace_all(result, "[", "\\[");
804 boost::replace_all(result, "]", "\\]");
805 boost::replace_all(result, "+", "\\+");
806 boost::replace_all(result, "/", "\\/");
807 boost::replace_all(result, "{", "\\{");
808 boost::replace_all(result, "}", "\\}");
809
810 // Convert wildcards '*' and '?' to their regex equivalents
811 boost::replace_all(result, "?", ".");
812 boost::replace_all(result, "*", ".*");
813
814 return result;
815 }
816
817
818 void Toolbox::TokenizeString(std::vector<std::string>& result,
819 const std::string& value,
820 char separator)
821 {
822 result.clear();
823
824 std::string currentItem;
825
826 for (size_t i = 0; i < value.size(); i++)
827 {
828 if (value[i] == separator)
829 {
830 result.push_back(currentItem);
831 currentItem.clear();
832 }
833 else
834 {
835 currentItem.push_back(value[i]);
836 }
837 }
838
839 result.push_back(currentItem);
840 }
841
842
843 #if ORTHANC_ENABLE_PUGIXML == 1
844 class ChunkedBufferWriter : public pugi::xml_writer
845 {
846 private:
847 ChunkedBuffer buffer_;
848
849 public:
850 virtual void write(const void *data, size_t size)
851 {
852 if (size > 0)
853 {
854 buffer_.AddChunk(reinterpret_cast<const char*>(data), size);
855 }
856 }
857
858 void Flatten(std::string& s)
859 {
860 buffer_.Flatten(s);
861 }
862 };
863
864
865 static void JsonToXmlInternal(pugi::xml_node& target,
866 const Json::Value& source,
867 const std::string& arrayElement)
868 {
869 // http://jsoncpp.sourceforge.net/value_8h_source.html#l00030
870
871 switch (source.type())
872 {
873 case Json::nullValue:
874 {
875 target.append_child(pugi::node_pcdata).set_value("null");
876 break;
877 }
878
879 case Json::intValue:
880 {
881 std::string s = boost::lexical_cast<std::string>(source.asInt());
882 target.append_child(pugi::node_pcdata).set_value(s.c_str());
883 break;
884 }
885
886 case Json::uintValue:
887 {
888 std::string s = boost::lexical_cast<std::string>(source.asUInt());
889 target.append_child(pugi::node_pcdata).set_value(s.c_str());
890 break;
891 }
892
893 case Json::realValue:
894 {
895 std::string s = boost::lexical_cast<std::string>(source.asFloat());
896 target.append_child(pugi::node_pcdata).set_value(s.c_str());
897 break;
898 }
899
900 case Json::stringValue:
901 {
902 target.append_child(pugi::node_pcdata).set_value(source.asString().c_str());
903 break;
904 }
905
906 case Json::booleanValue:
907 {
908 target.append_child(pugi::node_pcdata).set_value(source.asBool() ? "true" : "false");
909 break;
910 }
911
912 case Json::arrayValue:
913 {
914 for (Json::Value::ArrayIndex i = 0; i < source.size(); i++)
915 {
916 pugi::xml_node node = target.append_child();
917 node.set_name(arrayElement.c_str());
918 JsonToXmlInternal(node, source[i], arrayElement);
919 }
920 break;
921 }
922
923 case Json::objectValue:
924 {
925 Json::Value::Members members = source.getMemberNames();
926
927 for (size_t i = 0; i < members.size(); i++)
928 {
929 pugi::xml_node node = target.append_child();
930 node.set_name(members[i].c_str());
931 JsonToXmlInternal(node, source[members[i]], arrayElement);
932 }
933
934 break;
935 }
936
937 default:
938 throw OrthancException(ErrorCode_NotImplemented);
939 }
940 }
941
942
943 void Toolbox::JsonToXml(std::string& target,
944 const Json::Value& source,
945 const std::string& rootElement,
946 const std::string& arrayElement)
947 {
948 pugi::xml_document doc;
949
950 pugi::xml_node n = doc.append_child(rootElement.c_str());
951 JsonToXmlInternal(n, source, arrayElement);
952
953 pugi::xml_node decl = doc.prepend_child(pugi::node_declaration);
954 decl.append_attribute("version").set_value("1.0");
955 decl.append_attribute("encoding").set_value("utf-8");
956
957 ChunkedBufferWriter writer;
958 doc.save(writer, " ", pugi::format_default, pugi::encoding_utf8);
959 writer.Flatten(target);
960 }
961
962 #endif
963
964
965
966 bool Toolbox::IsInteger(const std::string& str)
967 {
968 std::string s = StripSpaces(str);
969
970 if (s.size() == 0)
971 {
972 return false;
973 }
974
975 size_t pos = 0;
976 if (s[0] == '-')
977 {
978 if (s.size() == 1)
979 {
980 return false;
981 }
982
983 pos = 1;
984 }
985
986 while (pos < s.size())
987 {
988 if (!isdigit(s[pos]))
989 {
990 return false;
991 }
992
993 pos++;
994 }
995
996 return true;
997 }
998
999
1000 void Toolbox::CopyJsonWithoutComments(Json::Value& target,
1001 const Json::Value& source)
1002 {
1003 switch (source.type())
1004 {
1005 case Json::nullValue:
1006 target = Json::nullValue;
1007 break;
1008
1009 case Json::intValue:
1010 target = source.asInt64();
1011 break;
1012
1013 case Json::uintValue:
1014 target = source.asUInt64();
1015 break;
1016
1017 case Json::realValue:
1018 target = source.asDouble();
1019 break;
1020
1021 case Json::stringValue:
1022 target = source.asString();
1023 break;
1024
1025 case Json::booleanValue:
1026 target = source.asBool();
1027 break;
1028
1029 case Json::arrayValue:
1030 {
1031 target = Json::arrayValue;
1032 for (Json::Value::ArrayIndex i = 0; i < source.size(); i++)
1033 {
1034 Json::Value& item = target.append(Json::nullValue);
1035 CopyJsonWithoutComments(item, source[i]);
1036 }
1037
1038 break;
1039 }
1040
1041 case Json::objectValue:
1042 {
1043 target = Json::objectValue;
1044 Json::Value::Members members = source.getMemberNames();
1045 for (Json::Value::ArrayIndex i = 0; i < members.size(); i++)
1046 {
1047 const std::string item = members[i];
1048 CopyJsonWithoutComments(target[item], source[item]);
1049 }
1050
1051 break;
1052 }
1053
1054 default:
1055 break;
1056 }
1057 }
1058
1059
1060 bool Toolbox::StartsWith(const std::string& str,
1061 const std::string& prefix)
1062 {
1063 if (str.size() < prefix.size())
1064 {
1065 return false;
1066 }
1067 else
1068 {
1069 return str.compare(0, prefix.size(), prefix) == 0;
1070 }
1071 }
1072
1073
1074 static bool IsUnreservedCharacter(char c)
1075 {
1076 // This function checks whether "c" is an unserved character
1077 // wrt. an URI percent-encoding
1078 // https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding%5Fin%5Fa%5FURI
1079
1080 return ((c >= 'A' && c <= 'Z') ||
1081 (c >= 'a' && c <= 'z') ||
1082 (c >= '0' && c <= '9') ||
1083 c == '-' ||
1084 c == '_' ||
1085 c == '.' ||
1086 c == '~');
1087 }
1088
1089 void Toolbox::UriEncode(std::string& target,
1090 const std::string& source)
1091 {
1092 // Estimate the length of the percent-encoded URI
1093 size_t length = 0;
1094
1095 for (size_t i = 0; i < source.size(); i++)
1096 {
1097 if (IsUnreservedCharacter(source[i]))
1098 {
1099 length += 1;
1100 }
1101 else
1102 {
1103 // This character must be percent-encoded
1104 length += 3;
1105 }
1106 }
1107
1108 target.clear();
1109 target.reserve(length);
1110
1111 for (size_t i = 0; i < source.size(); i++)
1112 {
1113 if (IsUnreservedCharacter(source[i]))
1114 {
1115 target.push_back(source[i]);
1116 }
1117 else
1118 {
1119 // This character must be percent-encoded
1120 uint8_t byte = static_cast<uint8_t>(source[i]);
1121 uint8_t a = byte >> 4;
1122 uint8_t b = byte & 0x0f;
1123
1124 target.push_back('%');
1125 target.push_back(a < 10 ? a + '0' : a - 10 + 'A');
1126 target.push_back(b < 10 ? b + '0' : b - 10 + 'A');
1127 }
1128 }
1129 }
1130
1131
1132 static bool HasField(const Json::Value& json,
1133 const std::string& key,
1134 Json::ValueType expectedType)
1135 {
1136 if (json.type() != Json::objectValue ||
1137 !json.isMember(key))
1138 {
1139 return false;
1140 }
1141 else if (json[key].type() == expectedType)
1142 {
1143 return true;
1144 }
1145 else
1146 {
1147 throw OrthancException(ErrorCode_BadParameterType);
1148 }
1149 }
1150
1151
1152 std::string Toolbox::GetJsonStringField(const Json::Value& json,
1153 const std::string& key,
1154 const std::string& defaultValue)
1155 {
1156 if (HasField(json, key, Json::stringValue))
1157 {
1158 return json[key].asString();
1159 }
1160 else
1161 {
1162 return defaultValue;
1163 }
1164 }
1165
1166
1167 bool Toolbox::GetJsonBooleanField(const ::Json::Value& json,
1168 const std::string& key,
1169 bool defaultValue)
1170 {
1171 if (HasField(json, key, Json::booleanValue))
1172 {
1173 return json[key].asBool();
1174 }
1175 else
1176 {
1177 return defaultValue;
1178 }
1179 }
1180
1181
1182 int Toolbox::GetJsonIntegerField(const ::Json::Value& json,
1183 const std::string& key,
1184 int defaultValue)
1185 {
1186 if (HasField(json, key, Json::intValue))
1187 {
1188 return json[key].asInt();
1189 }
1190 else
1191 {
1192 return defaultValue;
1193 }
1194 }
1195
1196
1197 unsigned int Toolbox::GetJsonUnsignedIntegerField(const ::Json::Value& json,
1198 const std::string& key,
1199 unsigned int defaultValue)
1200 {
1201 int v = GetJsonIntegerField(json, key, defaultValue);
1202
1203 if (v < 0)
1204 {
1205 throw OrthancException(ErrorCode_ParameterOutOfRange);
1206 }
1207 else
1208 {
1209 return static_cast<unsigned int>(v);
1210 }
1211 }
1212
1213
1214 bool Toolbox::IsUuid(const std::string& str)
1215 {
1216 if (str.size() != 36)
1217 {
1218 return false;
1219 }
1220
1221 for (size_t i = 0; i < str.length(); i++)
1222 {
1223 if (i == 8 || i == 13 || i == 18 || i == 23)
1224 {
1225 if (str[i] != '-')
1226 return false;
1227 }
1228 else
1229 {
1230 if (!isalnum(str[i]))
1231 return false;
1232 }
1233 }
1234
1235 return true;
1236 }
1237
1238
1239 bool Toolbox::StartsWithUuid(const std::string& str)
1240 {
1241 if (str.size() < 36)
1242 {
1243 return false;
1244 }
1245
1246 if (str.size() == 36)
1247 {
1248 return IsUuid(str);
1249 }
1250
1251 assert(str.size() > 36);
1252 if (!isspace(str[36]))
1253 {
1254 return false;
1255 }
1256
1257 return IsUuid(str.substr(0, 36));
1258 }
1259
1260
1261 #if ORTHANC_ENABLE_LOCALE == 1
1262 static std::auto_ptr<std::locale> globalLocale_;
1263
1264 static bool SetGlobalLocale(const char* locale)
1265 {
1266 globalLocale_.reset(NULL);
1267
1268 try
1269 {
1270 if (locale == NULL)
1271 {
1272 LOG(WARNING) << "Falling back to system-wide default locale";
1273 globalLocale_.reset(new std::locale());
1274 }
1275 else
1276 {
1277 LOG(INFO) << "Using locale: \"" << locale << "\" for case-insensitive comparison of strings";
1278 globalLocale_.reset(new std::locale(locale));
1279 }
1280 }
1281 catch (std::runtime_error&)
1282 {
1283 }
1284
1285 return (globalLocale_.get() != NULL);
1286 }
1287
1288 void Toolbox::InitializeGlobalLocale(const char* locale)
1289 {
1290 // Make Orthanc use English, United States locale
1291 // Linux: use "en_US.UTF-8"
1292 // Windows: use ""
1293 // Wine: use NULL
1294
1295 #if defined(__MINGW32__)
1296 // Visibly, there is no support of locales in MinGW yet
1297 // http://mingw.5.n7.nabble.com/How-to-use-std-locale-global-with-MinGW-correct-td33048.html
1298 static const char* DEFAULT_LOCALE = NULL;
1299 #elif defined(_WIN32)
1300 // For Windows: use default locale (using "en_US" does not work)
1301 static const char* DEFAULT_LOCALE = "";
1302 #else
1303 // For Linux & cie
1304 static const char* DEFAULT_LOCALE = "en_US.UTF-8";
1305 #endif
1306
1307 bool ok;
1308
1309 if (locale == NULL)
1310 {
1311 ok = SetGlobalLocale(DEFAULT_LOCALE);
1312
1313 #if defined(__MINGW32__)
1314 LOG(WARNING) << "This is a MinGW build, case-insensitive comparison of "
1315 << "strings with accents will not work outside of Wine";
1316 #endif
1317 }
1318 else
1319 {
1320 ok = SetGlobalLocale(locale);
1321 }
1322
1323 if (!ok &&
1324 !SetGlobalLocale(NULL))
1325 {
1326 LOG(ERROR) << "Cannot initialize global locale";
1327 throw OrthancException(ErrorCode_InternalError);
1328 }
1329
1330 }
1331
1332
1333 void Toolbox::FinalizeGlobalLocale()
1334 {
1335 globalLocale_.reset();
1336 }
1337
1338
1339 std::string Toolbox::ToUpperCaseWithAccents(const std::string& source)
1340 {
1341 if (globalLocale_.get() == NULL)
1342 {
1343 LOG(ERROR) << "No global locale was set, call Toolbox::InitializeGlobalLocale()";
1344 throw OrthancException(ErrorCode_BadSequenceOfCalls);
1345 }
1346
1347 /**
1348 * A few notes about locales:
1349 *
1350 * (1) We don't use "case folding":
1351 * http://www.boost.org/doc/libs/1_64_0/libs/locale/doc/html/conversions.html
1352 *
1353 * Characters are made uppercase one by one. This is because, in
1354 * static builds, we are using iconv, which is visibly not
1355 * supported correctly (TODO: Understand why). Case folding seems
1356 * to be working correctly if using the default backend under
1357 * Linux (ICU or POSIX?). If one wishes to use case folding, one
1358 * would use:
1359 *
1360 * boost::locale::generator gen;
1361 * std::locale::global(gen(DEFAULT_LOCALE));
1362 * return boost::locale::to_upper(source);
1363 *
1364 * (2) The function "boost::algorithm::to_upper_copy" does not
1365 * make use of the "std::locale::global()". We therefore create a
1366 * global variable "globalLocale_".
1367 *
1368 * (3) The variant of "boost::algorithm::to_upper_copy()" that
1369 * uses std::string does not work properly. We need to apply it
1370 * one wide strings (std::wstring). This explains the two calls to
1371 * "utf_to_utf" in order to convert to/from std::wstring.
1372 **/
1373
1374 std::wstring w = boost::locale::conv::utf_to_utf<wchar_t>(source);
1375 w = boost::algorithm::to_upper_copy<std::wstring>(w, *globalLocale_);
1376 return boost::locale::conv::utf_to_utf<char>(w);
1377 }
1378 #endif
1379 }