comparison Framework/Orthanc/Core/Toolbox.cpp @ 1:2dbe613f6c93

add orthanc core
author Sebastien Jodogne <s.jodogne@gmail.com>
date Fri, 14 Oct 2016 15:39:01 +0200
parents
children 9220cf4a63d5
comparison
equal deleted inserted replaced
0:351ab0da0150 1:2dbe613f6c93
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 *
6 * This program is free software: you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * In addition, as a special exception, the copyright holders of this
12 * program give permission to link the code of its release with the
13 * OpenSSL project's "OpenSSL" library (or with modified versions of it
14 * that use the same license as the "OpenSSL" library), and distribute
15 * the linked executables. You must obey the GNU General Public License
16 * in all respects for all of the code used other than "OpenSSL". If you
17 * modify file(s) with this exception, you may extend this exception to
18 * your version of the file(s), but you are not obligated to do so. If
19 * you do not wish to do so, delete this exception statement from your
20 * version. If you delete this exception statement from all source files
21 * in the program, then also delete it here.
22 *
23 * This program is distributed in the hope that it will be useful, but
24 * WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 * General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 **/
31
32
33 #include "PrecompiledHeaders.h"
34 #include "Toolbox.h"
35
36 #include "OrthancException.h"
37 #include "Logging.h"
38
39 #include <string>
40 #include <stdint.h>
41 #include <string.h>
42 #include <boost/filesystem.hpp>
43 #include <boost/filesystem/fstream.hpp>
44 #include <boost/uuid/sha1.hpp>
45 #include <boost/lexical_cast.hpp>
46 #include <algorithm>
47 #include <ctype.h>
48
49 #if BOOST_HAS_DATE_TIME == 1
50 #include <boost/date_time/posix_time/posix_time.hpp>
51 #endif
52
53 #if BOOST_HAS_REGEX == 1
54 #include <boost/regex.hpp>
55 #endif
56
57 #if defined(_WIN32)
58 #include <windows.h>
59 #include <process.h> // For "_spawnvp()" and "_getpid()"
60 #else
61 #include <unistd.h> // For "execvp()"
62 #include <sys/wait.h> // For "waitpid()"
63 #endif
64
65 #if defined(__APPLE__) && defined(__MACH__)
66 #include <mach-o/dyld.h> /* _NSGetExecutablePath */
67 #include <limits.h> /* PATH_MAX */
68 #endif
69
70 #if defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
71 #include <limits.h> /* PATH_MAX */
72 #include <signal.h>
73 #include <unistd.h>
74 #endif
75
76 #if BOOST_HAS_LOCALE != 1
77 #error Since version 0.7.6, Orthanc entirely relies on boost::locale
78 #endif
79
80 #include <boost/locale.hpp>
81
82
83 #if !defined(ORTHANC_ENABLE_MD5) || ORTHANC_ENABLE_MD5 == 1
84 #include "../Resources/ThirdParty/md5/md5.h"
85 #endif
86
87
88 #if !defined(ORTHANC_ENABLE_BASE64) || ORTHANC_ENABLE_BASE64 == 1
89 #include "../Resources/ThirdParty/base64/base64.h"
90 #endif
91
92
93 #if defined(_MSC_VER) && (_MSC_VER < 1800)
94 // Patch for the missing "_strtoll" symbol when compiling with Visual Studio < 2013
95 extern "C"
96 {
97 int64_t _strtoi64(const char *nptr, char **endptr, int base);
98 int64_t strtoll(const char *nptr, char **endptr, int base)
99 {
100 return _strtoi64(nptr, endptr, base);
101 }
102 }
103 #endif
104
105
106 #if ORTHANC_PUGIXML_ENABLED == 1
107 #include "ChunkedBuffer.h"
108 #include <pugixml.hpp>
109 #endif
110
111
112 namespace Orthanc
113 {
114 void Toolbox::USleep(uint64_t microSeconds)
115 {
116 #if defined(_WIN32)
117 ::Sleep(static_cast<DWORD>(microSeconds / static_cast<uint64_t>(1000)));
118 #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__) || defined(__native_client__)
119 usleep(microSeconds);
120 #else
121 #error Support your platform here
122 #endif
123 }
124
125
126 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
127 static bool finish_;
128 static ServerBarrierEvent barrierEvent_;
129
130 #if defined(_WIN32)
131 static BOOL WINAPI ConsoleControlHandler(DWORD dwCtrlType)
132 {
133 // http://msdn.microsoft.com/en-us/library/ms683242(v=vs.85).aspx
134 finish_ = true;
135 return true;
136 }
137 #else
138 static void SignalHandler(int signal)
139 {
140 if (signal == SIGHUP)
141 {
142 barrierEvent_ = ServerBarrierEvent_Reload;
143 }
144
145 finish_ = true;
146 }
147 #endif
148
149
150 static ServerBarrierEvent ServerBarrierInternal(const bool* stopFlag)
151 {
152 #if defined(_WIN32)
153 SetConsoleCtrlHandler(ConsoleControlHandler, true);
154 #else
155 signal(SIGINT, SignalHandler);
156 signal(SIGQUIT, SignalHandler);
157 signal(SIGTERM, SignalHandler);
158 signal(SIGHUP, SignalHandler);
159 #endif
160
161 // Active loop that awakens every 100ms
162 finish_ = false;
163 barrierEvent_ = ServerBarrierEvent_Stop;
164 while (!(*stopFlag || finish_))
165 {
166 Toolbox::USleep(100 * 1000);
167 }
168
169 #if defined(_WIN32)
170 SetConsoleCtrlHandler(ConsoleControlHandler, false);
171 #else
172 signal(SIGINT, NULL);
173 signal(SIGQUIT, NULL);
174 signal(SIGTERM, NULL);
175 signal(SIGHUP, NULL);
176 #endif
177
178 return barrierEvent_;
179 }
180
181
182 ServerBarrierEvent Toolbox::ServerBarrier(const bool& stopFlag)
183 {
184 return ServerBarrierInternal(&stopFlag);
185 }
186
187 ServerBarrierEvent Toolbox::ServerBarrier()
188 {
189 const bool stopFlag = false;
190 return ServerBarrierInternal(&stopFlag);
191 }
192 #endif /* ORTHANC_SANDBOXED */
193
194
195 void Toolbox::ToUpperCase(std::string& s)
196 {
197 std::transform(s.begin(), s.end(), s.begin(), toupper);
198 }
199
200
201 void Toolbox::ToLowerCase(std::string& s)
202 {
203 std::transform(s.begin(), s.end(), s.begin(), tolower);
204 }
205
206
207 void Toolbox::ToUpperCase(std::string& result,
208 const std::string& source)
209 {
210 result = source;
211 ToUpperCase(result);
212 }
213
214 void Toolbox::ToLowerCase(std::string& result,
215 const std::string& source)
216 {
217 result = source;
218 ToLowerCase(result);
219 }
220
221
222 static std::streamsize GetStreamSize(std::istream& f)
223 {
224 // http://www.cplusplus.com/reference/iostream/istream/tellg/
225 f.seekg(0, std::ios::end);
226 std::streamsize size = f.tellg();
227 f.seekg(0, std::ios::beg);
228
229 return size;
230 }
231
232
233 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
234 void Toolbox::ReadFile(std::string& content,
235 const std::string& path)
236 {
237 if (!IsRegularFile(path))
238 {
239 LOG(ERROR) << std::string("The path does not point to a regular file: ") << path;
240 throw OrthancException(ErrorCode_RegularFileExpected);
241 }
242
243 boost::filesystem::ifstream f;
244 f.open(path, std::ifstream::in | std::ifstream::binary);
245 if (!f.good())
246 {
247 throw OrthancException(ErrorCode_InexistentFile);
248 }
249
250 std::streamsize size = GetStreamSize(f);
251 content.resize(size);
252 if (size != 0)
253 {
254 f.read(reinterpret_cast<char*>(&content[0]), size);
255 }
256
257 f.close();
258 }
259 #endif
260
261
262 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
263 bool Toolbox::ReadHeader(std::string& header,
264 const std::string& path,
265 size_t headerSize)
266 {
267 if (!IsRegularFile(path))
268 {
269 LOG(ERROR) << std::string("The path does not point to a regular file: ") << path;
270 throw OrthancException(ErrorCode_RegularFileExpected);
271 }
272
273 boost::filesystem::ifstream f;
274 f.open(path, std::ifstream::in | std::ifstream::binary);
275 if (!f.good())
276 {
277 throw OrthancException(ErrorCode_InexistentFile);
278 }
279
280 bool full = true;
281
282 {
283 std::streamsize size = GetStreamSize(f);
284 if (size <= 0)
285 {
286 headerSize = 0;
287 full = false;
288 }
289 else if (static_cast<size_t>(size) < headerSize)
290 {
291 headerSize = size; // Truncate to the size of the file
292 full = false;
293 }
294 }
295
296 header.resize(headerSize);
297 if (headerSize != 0)
298 {
299 f.read(reinterpret_cast<char*>(&header[0]), headerSize);
300 }
301
302 f.close();
303
304 return full;
305 }
306 #endif
307
308
309 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
310 void Toolbox::WriteFile(const void* content,
311 size_t size,
312 const std::string& path)
313 {
314 boost::filesystem::ofstream f;
315 f.open(path, std::ofstream::out | std::ofstream::binary);
316 if (!f.good())
317 {
318 throw OrthancException(ErrorCode_CannotWriteFile);
319 }
320
321 if (size != 0)
322 {
323 f.write(reinterpret_cast<const char*>(content), size);
324
325 if (!f.good())
326 {
327 f.close();
328 throw OrthancException(ErrorCode_FileStorageCannotWrite);
329 }
330 }
331
332 f.close();
333 }
334 #endif
335
336
337 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
338 void Toolbox::WriteFile(const std::string& content,
339 const std::string& path)
340 {
341 WriteFile(content.size() > 0 ? content.c_str() : NULL,
342 content.size(), path);
343 }
344 #endif
345
346
347 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
348 void Toolbox::RemoveFile(const std::string& path)
349 {
350 if (boost::filesystem::exists(path))
351 {
352 if (IsRegularFile(path))
353 {
354 boost::filesystem::remove(path);
355 }
356 else
357 {
358 throw OrthancException(ErrorCode_RegularFileExpected);
359 }
360 }
361 }
362 #endif
363
364
365 void Toolbox::SplitUriComponents(UriComponents& components,
366 const std::string& uri)
367 {
368 static const char URI_SEPARATOR = '/';
369
370 components.clear();
371
372 if (uri.size() == 0 ||
373 uri[0] != URI_SEPARATOR)
374 {
375 throw OrthancException(ErrorCode_UriSyntax);
376 }
377
378 // Count the number of slashes in the URI to make an assumption
379 // about the number of components in the URI
380 unsigned int estimatedSize = 0;
381 for (unsigned int i = 0; i < uri.size(); i++)
382 {
383 if (uri[i] == URI_SEPARATOR)
384 estimatedSize++;
385 }
386
387 components.reserve(estimatedSize - 1);
388
389 unsigned int start = 1;
390 unsigned int end = 1;
391 while (end < uri.size())
392 {
393 // This is the loop invariant
394 assert(uri[start - 1] == '/' && (end >= start));
395
396 if (uri[end] == '/')
397 {
398 components.push_back(std::string(&uri[start], end - start));
399 end++;
400 start = end;
401 }
402 else
403 {
404 end++;
405 }
406 }
407
408 if (start < uri.size())
409 {
410 components.push_back(std::string(&uri[start], end - start));
411 }
412
413 for (size_t i = 0; i < components.size(); i++)
414 {
415 if (components[i].size() == 0)
416 {
417 // Empty component, as in: "/coucou//e"
418 throw OrthancException(ErrorCode_UriSyntax);
419 }
420 }
421 }
422
423
424 void Toolbox::TruncateUri(UriComponents& target,
425 const UriComponents& source,
426 size_t fromLevel)
427 {
428 target.clear();
429
430 if (source.size() > fromLevel)
431 {
432 target.resize(source.size() - fromLevel);
433
434 size_t j = 0;
435 for (size_t i = fromLevel; i < source.size(); i++, j++)
436 {
437 target[j] = source[i];
438 }
439
440 assert(j == target.size());
441 }
442 }
443
444
445
446 bool Toolbox::IsChildUri(const UriComponents& baseUri,
447 const UriComponents& testedUri)
448 {
449 if (testedUri.size() < baseUri.size())
450 {
451 return false;
452 }
453
454 for (size_t i = 0; i < baseUri.size(); i++)
455 {
456 if (baseUri[i] != testedUri[i])
457 return false;
458 }
459
460 return true;
461 }
462
463
464 std::string Toolbox::AutodetectMimeType(const std::string& path)
465 {
466 std::string contentType;
467 size_t lastDot = path.rfind('.');
468 size_t lastSlash = path.rfind('/');
469
470 if (lastDot == std::string::npos ||
471 (lastSlash != std::string::npos && lastDot < lastSlash))
472 {
473 // No trailing dot, unable to detect the content type
474 }
475 else
476 {
477 const char* extension = &path[lastDot + 1];
478
479 // http://en.wikipedia.org/wiki/Mime_types
480 // Text types
481 if (!strcmp(extension, "txt"))
482 contentType = "text/plain";
483 else if (!strcmp(extension, "html"))
484 contentType = "text/html";
485 else if (!strcmp(extension, "xml"))
486 contentType = "text/xml";
487 else if (!strcmp(extension, "css"))
488 contentType = "text/css";
489
490 // Application types
491 else if (!strcmp(extension, "js"))
492 contentType = "application/javascript";
493 else if (!strcmp(extension, "json"))
494 contentType = "application/json";
495 else if (!strcmp(extension, "pdf"))
496 contentType = "application/pdf";
497
498 // Images types
499 else if (!strcmp(extension, "jpg") || !strcmp(extension, "jpeg"))
500 contentType = "image/jpeg";
501 else if (!strcmp(extension, "gif"))
502 contentType = "image/gif";
503 else if (!strcmp(extension, "png"))
504 contentType = "image/png";
505 }
506
507 return contentType;
508 }
509
510
511 std::string Toolbox::FlattenUri(const UriComponents& components,
512 size_t fromLevel)
513 {
514 if (components.size() <= fromLevel)
515 {
516 return "/";
517 }
518 else
519 {
520 std::string r;
521
522 for (size_t i = fromLevel; i < components.size(); i++)
523 {
524 r += "/" + components[i];
525 }
526
527 return r;
528 }
529 }
530
531
532
533 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
534 uint64_t Toolbox::GetFileSize(const std::string& path)
535 {
536 try
537 {
538 return static_cast<uint64_t>(boost::filesystem::file_size(path));
539 }
540 catch (boost::filesystem::filesystem_error&)
541 {
542 throw OrthancException(ErrorCode_InexistentFile);
543 }
544 }
545 #endif
546
547
548 #if !defined(ORTHANC_ENABLE_MD5) || ORTHANC_ENABLE_MD5 == 1
549 static char GetHexadecimalCharacter(uint8_t value)
550 {
551 assert(value < 16);
552
553 if (value < 10)
554 {
555 return value + '0';
556 }
557 else
558 {
559 return (value - 10) + 'a';
560 }
561 }
562
563
564 void Toolbox::ComputeMD5(std::string& result,
565 const std::string& data)
566 {
567 if (data.size() > 0)
568 {
569 ComputeMD5(result, &data[0], data.size());
570 }
571 else
572 {
573 ComputeMD5(result, NULL, 0);
574 }
575 }
576
577
578 void Toolbox::ComputeMD5(std::string& result,
579 const void* data,
580 size_t size)
581 {
582 md5_state_s state;
583 md5_init(&state);
584
585 if (size > 0)
586 {
587 md5_append(&state,
588 reinterpret_cast<const md5_byte_t*>(data),
589 static_cast<int>(size));
590 }
591
592 md5_byte_t actualHash[16];
593 md5_finish(&state, actualHash);
594
595 result.resize(32);
596 for (unsigned int i = 0; i < 16; i++)
597 {
598 result[2 * i] = GetHexadecimalCharacter(static_cast<uint8_t>(actualHash[i] / 16));
599 result[2 * i + 1] = GetHexadecimalCharacter(static_cast<uint8_t>(actualHash[i] % 16));
600 }
601 }
602 #endif
603
604
605 #if !defined(ORTHANC_ENABLE_BASE64) || ORTHANC_ENABLE_BASE64 == 1
606 void Toolbox::EncodeBase64(std::string& result,
607 const std::string& data)
608 {
609 result = base64_encode(data);
610 }
611
612 void Toolbox::DecodeBase64(std::string& result,
613 const std::string& data)
614 {
615 for (size_t i = 0; i < data.length(); i++)
616 {
617 if (!isalnum(data[i]) &&
618 data[i] != '+' &&
619 data[i] != '/' &&
620 data[i] != '=')
621 {
622 // This is not a valid character for a Base64 string
623 throw OrthancException(ErrorCode_BadFileFormat);
624 }
625 }
626
627 result = base64_decode(data);
628 }
629
630
631 # if BOOST_HAS_REGEX == 1
632 bool Toolbox::DecodeDataUriScheme(std::string& mime,
633 std::string& content,
634 const std::string& source)
635 {
636 boost::regex pattern("data:([^;]+);base64,([a-zA-Z0-9=+/]*)",
637 boost::regex::icase /* case insensitive search */);
638
639 boost::cmatch what;
640 if (regex_match(source.c_str(), what, pattern))
641 {
642 mime = what[1];
643 DecodeBase64(content, what[2]);
644 return true;
645 }
646 else
647 {
648 return false;
649 }
650 }
651 # endif
652
653
654 void Toolbox::EncodeDataUriScheme(std::string& result,
655 const std::string& mime,
656 const std::string& content)
657 {
658 result = "data:" + mime + ";base64," + base64_encode(content);
659 }
660
661 #endif
662
663
664
665 #if defined(_WIN32)
666 static std::string GetPathToExecutableInternal()
667 {
668 // Yes, this is ugly, but there is no simple way to get the
669 // required buffer size, so we use a big constant
670 std::vector<char> buffer(32768);
671 /*int bytes =*/ GetModuleFileNameA(NULL, &buffer[0], static_cast<DWORD>(buffer.size() - 1));
672 return std::string(&buffer[0]);
673 }
674
675 #elif defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
676 static std::string GetPathToExecutableInternal()
677 {
678 std::vector<char> buffer(PATH_MAX + 1);
679 ssize_t bytes = readlink("/proc/self/exe", &buffer[0], buffer.size() - 1);
680 if (bytes == 0)
681 {
682 throw OrthancException(ErrorCode_PathToExecutable);
683 }
684
685 return std::string(&buffer[0]);
686 }
687
688 #elif defined(__APPLE__) && defined(__MACH__)
689 static std::string GetPathToExecutableInternal()
690 {
691 char pathbuf[PATH_MAX + 1];
692 unsigned int bufsize = static_cast<int>(sizeof(pathbuf));
693
694 _NSGetExecutablePath( pathbuf, &bufsize);
695
696 return std::string(pathbuf);
697 }
698
699 #elif defined(ORTHANC_SANDBOXED) && ORTHANC_SANDBOXED == 1
700 // Sandboxed Orthanc, no access to the executable
701
702 #else
703 #error Support your platform here
704 #endif
705
706
707 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
708 std::string Toolbox::GetPathToExecutable()
709 {
710 boost::filesystem::path p(GetPathToExecutableInternal());
711 return boost::filesystem::absolute(p).string();
712 }
713
714
715 std::string Toolbox::GetDirectoryOfExecutable()
716 {
717 boost::filesystem::path p(GetPathToExecutableInternal());
718 return boost::filesystem::absolute(p.parent_path()).string();
719 }
720 #endif
721
722
723 static const char* GetBoostLocaleEncoding(const Encoding sourceEncoding)
724 {
725 switch (sourceEncoding)
726 {
727 case Encoding_Utf8:
728 return "UTF-8";
729
730 case Encoding_Ascii:
731 return "ASCII";
732
733 case Encoding_Latin1:
734 return "ISO-8859-1";
735 break;
736
737 case Encoding_Latin2:
738 return "ISO-8859-2";
739 break;
740
741 case Encoding_Latin3:
742 return "ISO-8859-3";
743 break;
744
745 case Encoding_Latin4:
746 return "ISO-8859-4";
747 break;
748
749 case Encoding_Latin5:
750 return "ISO-8859-9";
751 break;
752
753 case Encoding_Cyrillic:
754 return "ISO-8859-5";
755 break;
756
757 case Encoding_Windows1251:
758 return "WINDOWS-1251";
759 break;
760
761 case Encoding_Arabic:
762 return "ISO-8859-6";
763 break;
764
765 case Encoding_Greek:
766 return "ISO-8859-7";
767 break;
768
769 case Encoding_Hebrew:
770 return "ISO-8859-8";
771 break;
772
773 case Encoding_Japanese:
774 return "SHIFT-JIS";
775 break;
776
777 case Encoding_Chinese:
778 return "GB18030";
779 break;
780
781 case Encoding_Thai:
782 return "TIS620.2533-0";
783 break;
784
785 default:
786 throw OrthancException(ErrorCode_NotImplemented);
787 }
788 }
789
790
791 std::string Toolbox::ConvertToUtf8(const std::string& source,
792 Encoding sourceEncoding)
793 {
794 if (sourceEncoding == Encoding_Utf8)
795 {
796 // Already in UTF-8: No conversion is required
797 return source;
798 }
799
800 if (sourceEncoding == Encoding_Ascii)
801 {
802 return ConvertToAscii(source);
803 }
804
805 const char* encoding = GetBoostLocaleEncoding(sourceEncoding);
806
807 try
808 {
809 return boost::locale::conv::to_utf<char>(source, encoding);
810 }
811 catch (std::runtime_error&)
812 {
813 // Bad input string or bad encoding
814 return ConvertToAscii(source);
815 }
816 }
817
818
819 std::string Toolbox::ConvertFromUtf8(const std::string& source,
820 Encoding targetEncoding)
821 {
822 if (targetEncoding == Encoding_Utf8)
823 {
824 // Already in UTF-8: No conversion is required
825 return source;
826 }
827
828 if (targetEncoding == Encoding_Ascii)
829 {
830 return ConvertToAscii(source);
831 }
832
833 const char* encoding = GetBoostLocaleEncoding(targetEncoding);
834
835 try
836 {
837 return boost::locale::conv::from_utf<char>(source, encoding);
838 }
839 catch (std::runtime_error&)
840 {
841 // Bad input string or bad encoding
842 return ConvertToAscii(source);
843 }
844 }
845
846
847 std::string Toolbox::ConvertToAscii(const std::string& source)
848 {
849 std::string result;
850
851 result.reserve(source.size() + 1);
852 for (size_t i = 0; i < source.size(); i++)
853 {
854 if (source[i] <= 127 && source[i] >= 0 && !iscntrl(source[i]))
855 {
856 result.push_back(source[i]);
857 }
858 }
859
860 return result;
861 }
862
863
864 void Toolbox::ComputeSHA1(std::string& result,
865 const void* data,
866 size_t size)
867 {
868 boost::uuids::detail::sha1 sha1;
869
870 if (size > 0)
871 {
872 sha1.process_bytes(data, size);
873 }
874
875 unsigned int digest[5];
876
877 // Sanity check for the memory layout: A SHA-1 digest is 160 bits wide
878 assert(sizeof(unsigned int) == 4 && sizeof(digest) == (160 / 8));
879
880 sha1.get_digest(digest);
881
882 result.resize(8 * 5 + 4);
883 sprintf(&result[0], "%08x-%08x-%08x-%08x-%08x",
884 digest[0],
885 digest[1],
886 digest[2],
887 digest[3],
888 digest[4]);
889 }
890
891 void Toolbox::ComputeSHA1(std::string& result,
892 const std::string& data)
893 {
894 if (data.size() > 0)
895 {
896 ComputeSHA1(result, data.c_str(), data.size());
897 }
898 else
899 {
900 ComputeSHA1(result, NULL, 0);
901 }
902 }
903
904
905 bool Toolbox::IsSHA1(const char* str,
906 size_t size)
907 {
908 if (size == 0)
909 {
910 return false;
911 }
912
913 const char* start = str;
914 const char* end = str + size;
915
916 // Trim the beginning of the string
917 while (start < end)
918 {
919 if (*start == '\0' ||
920 isspace(*start))
921 {
922 start++;
923 }
924 else
925 {
926 break;
927 }
928 }
929
930 // Trim the trailing of the string
931 while (start < end)
932 {
933 if (*(end - 1) == '\0' ||
934 isspace(*(end - 1)))
935 {
936 end--;
937 }
938 else
939 {
940 break;
941 }
942 }
943
944 if (end - start != 44)
945 {
946 return false;
947 }
948
949 for (unsigned int i = 0; i < 44; i++)
950 {
951 if (i == 8 ||
952 i == 17 ||
953 i == 26 ||
954 i == 35)
955 {
956 if (start[i] != '-')
957 return false;
958 }
959 else
960 {
961 if (!isalnum(start[i]))
962 return false;
963 }
964 }
965
966 return true;
967 }
968
969
970 bool Toolbox::IsSHA1(const std::string& s)
971 {
972 if (s.size() == 0)
973 {
974 return false;
975 }
976 else
977 {
978 return IsSHA1(s.c_str(), s.size());
979 }
980 }
981
982
983 #if BOOST_HAS_DATE_TIME == 1
984 std::string Toolbox::GetNowIsoString()
985 {
986 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
987 return boost::posix_time::to_iso_string(now);
988 }
989
990 void Toolbox::GetNowDicom(std::string& date,
991 std::string& time)
992 {
993 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
994 tm tm = boost::posix_time::to_tm(now);
995
996 char s[32];
997 sprintf(s, "%04d%02d%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
998 date.assign(s);
999
1000 // TODO milliseconds
1001 sprintf(s, "%02d%02d%02d.%06d", tm.tm_hour, tm.tm_min, tm.tm_sec, 0);
1002 time.assign(s);
1003 }
1004 #endif
1005
1006
1007 std::string Toolbox::StripSpaces(const std::string& source)
1008 {
1009 size_t first = 0;
1010
1011 while (first < source.length() &&
1012 isspace(source[first]))
1013 {
1014 first++;
1015 }
1016
1017 if (first == source.length())
1018 {
1019 // String containing only spaces
1020 return "";
1021 }
1022
1023 size_t last = source.length();
1024 while (last > first &&
1025 isspace(source[last - 1]))
1026 {
1027 last--;
1028 }
1029
1030 assert(first <= last);
1031 return source.substr(first, last - first);
1032 }
1033
1034
1035 static char Hex2Dec(char c)
1036 {
1037 return ((c >= '0' && c <= '9') ? c - '0' :
1038 ((c >= 'a' && c <= 'f') ? c - 'a' + 10 : c - 'A' + 10));
1039 }
1040
1041 void Toolbox::UrlDecode(std::string& s)
1042 {
1043 // http://en.wikipedia.org/wiki/Percent-encoding
1044 // http://www.w3schools.com/tags/ref_urlencode.asp
1045 // http://stackoverflow.com/questions/154536/encode-decode-urls-in-c
1046
1047 if (s.size() == 0)
1048 {
1049 return;
1050 }
1051
1052 size_t source = 0;
1053 size_t target = 0;
1054
1055 while (source < s.size())
1056 {
1057 if (s[source] == '%' &&
1058 source + 2 < s.size() &&
1059 isalnum(s[source + 1]) &&
1060 isalnum(s[source + 2]))
1061 {
1062 s[target] = (Hex2Dec(s[source + 1]) << 4) | Hex2Dec(s[source + 2]);
1063 source += 3;
1064 target += 1;
1065 }
1066 else
1067 {
1068 if (s[source] == '+')
1069 s[target] = ' ';
1070 else
1071 s[target] = s[source];
1072
1073 source++;
1074 target++;
1075 }
1076 }
1077
1078 s.resize(target);
1079 }
1080
1081
1082 Endianness Toolbox::DetectEndianness()
1083 {
1084 // http://sourceforge.net/p/predef/wiki/Endianness/
1085
1086 uint8_t buffer[4];
1087
1088 buffer[0] = 0x00;
1089 buffer[1] = 0x01;
1090 buffer[2] = 0x02;
1091 buffer[3] = 0x03;
1092
1093 switch (*((uint32_t *)buffer))
1094 {
1095 case 0x00010203:
1096 return Endianness_Big;
1097
1098 case 0x03020100:
1099 return Endianness_Little;
1100
1101 default:
1102 throw OrthancException(ErrorCode_NotImplemented);
1103 }
1104 }
1105
1106
1107 #if BOOST_HAS_REGEX == 1
1108 std::string Toolbox::WildcardToRegularExpression(const std::string& source)
1109 {
1110 // TODO - Speed up this with a regular expression
1111
1112 std::string result = source;
1113
1114 // Escape all special characters
1115 boost::replace_all(result, "\\", "\\\\");
1116 boost::replace_all(result, "^", "\\^");
1117 boost::replace_all(result, ".", "\\.");
1118 boost::replace_all(result, "$", "\\$");
1119 boost::replace_all(result, "|", "\\|");
1120 boost::replace_all(result, "(", "\\(");
1121 boost::replace_all(result, ")", "\\)");
1122 boost::replace_all(result, "[", "\\[");
1123 boost::replace_all(result, "]", "\\]");
1124 boost::replace_all(result, "+", "\\+");
1125 boost::replace_all(result, "/", "\\/");
1126 boost::replace_all(result, "{", "\\{");
1127 boost::replace_all(result, "}", "\\}");
1128
1129 // Convert wildcards '*' and '?' to their regex equivalents
1130 boost::replace_all(result, "?", ".");
1131 boost::replace_all(result, "*", ".*");
1132
1133 return result;
1134 }
1135 #endif
1136
1137
1138
1139 void Toolbox::TokenizeString(std::vector<std::string>& result,
1140 const std::string& value,
1141 char separator)
1142 {
1143 result.clear();
1144
1145 std::string currentItem;
1146
1147 for (size_t i = 0; i < value.size(); i++)
1148 {
1149 if (value[i] == separator)
1150 {
1151 result.push_back(currentItem);
1152 currentItem.clear();
1153 }
1154 else
1155 {
1156 currentItem.push_back(value[i]);
1157 }
1158 }
1159
1160 result.push_back(currentItem);
1161 }
1162
1163
1164 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
1165 void Toolbox::MakeDirectory(const std::string& path)
1166 {
1167 if (boost::filesystem::exists(path))
1168 {
1169 if (!boost::filesystem::is_directory(path))
1170 {
1171 throw OrthancException(ErrorCode_DirectoryOverFile);
1172 }
1173 }
1174 else
1175 {
1176 if (!boost::filesystem::create_directories(path))
1177 {
1178 throw OrthancException(ErrorCode_MakeDirectory);
1179 }
1180 }
1181 }
1182 #endif
1183
1184
1185 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
1186 bool Toolbox::IsExistingFile(const std::string& path)
1187 {
1188 return boost::filesystem::exists(path);
1189 }
1190 #endif
1191
1192
1193 #if ORTHANC_PUGIXML_ENABLED == 1
1194 class ChunkedBufferWriter : public pugi::xml_writer
1195 {
1196 private:
1197 ChunkedBuffer buffer_;
1198
1199 public:
1200 virtual void write(const void *data, size_t size)
1201 {
1202 if (size > 0)
1203 {
1204 buffer_.AddChunk(reinterpret_cast<const char*>(data), size);
1205 }
1206 }
1207
1208 void Flatten(std::string& s)
1209 {
1210 buffer_.Flatten(s);
1211 }
1212 };
1213
1214
1215 static void JsonToXmlInternal(pugi::xml_node& target,
1216 const Json::Value& source,
1217 const std::string& arrayElement)
1218 {
1219 // http://jsoncpp.sourceforge.net/value_8h_source.html#l00030
1220
1221 switch (source.type())
1222 {
1223 case Json::nullValue:
1224 {
1225 target.append_child(pugi::node_pcdata).set_value("null");
1226 break;
1227 }
1228
1229 case Json::intValue:
1230 {
1231 std::string s = boost::lexical_cast<std::string>(source.asInt());
1232 target.append_child(pugi::node_pcdata).set_value(s.c_str());
1233 break;
1234 }
1235
1236 case Json::uintValue:
1237 {
1238 std::string s = boost::lexical_cast<std::string>(source.asUInt());
1239 target.append_child(pugi::node_pcdata).set_value(s.c_str());
1240 break;
1241 }
1242
1243 case Json::realValue:
1244 {
1245 std::string s = boost::lexical_cast<std::string>(source.asFloat());
1246 target.append_child(pugi::node_pcdata).set_value(s.c_str());
1247 break;
1248 }
1249
1250 case Json::stringValue:
1251 {
1252 target.append_child(pugi::node_pcdata).set_value(source.asString().c_str());
1253 break;
1254 }
1255
1256 case Json::booleanValue:
1257 {
1258 target.append_child(pugi::node_pcdata).set_value(source.asBool() ? "true" : "false");
1259 break;
1260 }
1261
1262 case Json::arrayValue:
1263 {
1264 for (Json::Value::ArrayIndex i = 0; i < source.size(); i++)
1265 {
1266 pugi::xml_node node = target.append_child();
1267 node.set_name(arrayElement.c_str());
1268 JsonToXmlInternal(node, source[i], arrayElement);
1269 }
1270 break;
1271 }
1272
1273 case Json::objectValue:
1274 {
1275 Json::Value::Members members = source.getMemberNames();
1276
1277 for (size_t i = 0; i < members.size(); i++)
1278 {
1279 pugi::xml_node node = target.append_child();
1280 node.set_name(members[i].c_str());
1281 JsonToXmlInternal(node, source[members[i]], arrayElement);
1282 }
1283
1284 break;
1285 }
1286
1287 default:
1288 throw OrthancException(ErrorCode_NotImplemented);
1289 }
1290 }
1291
1292
1293 void Toolbox::JsonToXml(std::string& target,
1294 const Json::Value& source,
1295 const std::string& rootElement,
1296 const std::string& arrayElement)
1297 {
1298 pugi::xml_document doc;
1299
1300 pugi::xml_node n = doc.append_child(rootElement.c_str());
1301 JsonToXmlInternal(n, source, arrayElement);
1302
1303 pugi::xml_node decl = doc.prepend_child(pugi::node_declaration);
1304 decl.append_attribute("version").set_value("1.0");
1305 decl.append_attribute("encoding").set_value("utf-8");
1306
1307 ChunkedBufferWriter writer;
1308 doc.save(writer, " ", pugi::format_default, pugi::encoding_utf8);
1309 writer.Flatten(target);
1310 }
1311
1312 #endif
1313
1314
1315 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
1316 void Toolbox::ExecuteSystemCommand(const std::string& command,
1317 const std::vector<std::string>& arguments)
1318 {
1319 // Convert the arguments as a C array
1320 std::vector<char*> args(arguments.size() + 2);
1321
1322 args.front() = const_cast<char*>(command.c_str());
1323
1324 for (size_t i = 0; i < arguments.size(); i++)
1325 {
1326 args[i + 1] = const_cast<char*>(arguments[i].c_str());
1327 }
1328
1329 args.back() = NULL;
1330
1331 int status;
1332
1333 #if defined(_WIN32)
1334 // http://msdn.microsoft.com/en-us/library/275khfab.aspx
1335 status = static_cast<int>(_spawnvp(_P_OVERLAY, command.c_str(), &args[0]));
1336
1337 #else
1338 int pid = fork();
1339
1340 if (pid == -1)
1341 {
1342 // Error in fork()
1343 #if ORTHANC_ENABLE_LOGGING == 1
1344 LOG(ERROR) << "Cannot fork a child process";
1345 #endif
1346
1347 throw OrthancException(ErrorCode_SystemCommand);
1348 }
1349 else if (pid == 0)
1350 {
1351 // Execute the system command in the child process
1352 execvp(command.c_str(), &args[0]);
1353
1354 // We should never get here
1355 _exit(1);
1356 }
1357 else
1358 {
1359 // Wait for the system command to exit
1360 waitpid(pid, &status, 0);
1361 }
1362 #endif
1363
1364 if (status != 0)
1365 {
1366 #if ORTHANC_ENABLE_LOGGING == 1
1367 LOG(ERROR) << "System command failed with status code " << status;
1368 #endif
1369
1370 throw OrthancException(ErrorCode_SystemCommand);
1371 }
1372 }
1373 #endif
1374
1375
1376 bool Toolbox::IsInteger(const std::string& str)
1377 {
1378 std::string s = StripSpaces(str);
1379
1380 if (s.size() == 0)
1381 {
1382 return false;
1383 }
1384
1385 size_t pos = 0;
1386 if (s[0] == '-')
1387 {
1388 if (s.size() == 1)
1389 {
1390 return false;
1391 }
1392
1393 pos = 1;
1394 }
1395
1396 while (pos < s.size())
1397 {
1398 if (!isdigit(s[pos]))
1399 {
1400 return false;
1401 }
1402
1403 pos++;
1404 }
1405
1406 return true;
1407 }
1408
1409
1410 void Toolbox::CopyJsonWithoutComments(Json::Value& target,
1411 const Json::Value& source)
1412 {
1413 switch (source.type())
1414 {
1415 case Json::nullValue:
1416 target = Json::nullValue;
1417 break;
1418
1419 case Json::intValue:
1420 target = source.asInt64();
1421 break;
1422
1423 case Json::uintValue:
1424 target = source.asUInt64();
1425 break;
1426
1427 case Json::realValue:
1428 target = source.asDouble();
1429 break;
1430
1431 case Json::stringValue:
1432 target = source.asString();
1433 break;
1434
1435 case Json::booleanValue:
1436 target = source.asBool();
1437 break;
1438
1439 case Json::arrayValue:
1440 {
1441 target = Json::arrayValue;
1442 for (Json::Value::ArrayIndex i = 0; i < source.size(); i++)
1443 {
1444 Json::Value& item = target.append(Json::nullValue);
1445 CopyJsonWithoutComments(item, source[i]);
1446 }
1447
1448 break;
1449 }
1450
1451 case Json::objectValue:
1452 {
1453 target = Json::objectValue;
1454 Json::Value::Members members = source.getMemberNames();
1455 for (Json::Value::ArrayIndex i = 0; i < members.size(); i++)
1456 {
1457 const std::string item = members[i];
1458 CopyJsonWithoutComments(target[item], source[item]);
1459 }
1460
1461 break;
1462 }
1463
1464 default:
1465 break;
1466 }
1467 }
1468
1469
1470 bool Toolbox::StartsWith(const std::string& str,
1471 const std::string& prefix)
1472 {
1473 if (str.size() < prefix.size())
1474 {
1475 return false;
1476 }
1477 else
1478 {
1479 return str.compare(0, prefix.size(), prefix) == 0;
1480 }
1481 }
1482
1483
1484 int Toolbox::GetProcessId()
1485 {
1486 #if defined(_WIN32)
1487 return static_cast<int>(_getpid());
1488 #else
1489 return static_cast<int>(getpid());
1490 #endif
1491 }
1492
1493
1494 #if !defined(ORTHANC_SANDBOXED) || ORTHANC_SANDBOXED != 1
1495 bool Toolbox::IsRegularFile(const std::string& path)
1496 {
1497 namespace fs = boost::filesystem;
1498
1499 try
1500 {
1501 if (fs::exists(path))
1502 {
1503 fs::file_status status = fs::status(path);
1504 return (status.type() == boost::filesystem::regular_file ||
1505 status.type() == boost::filesystem::reparse_file); // Fix BitBucket issue #11
1506 }
1507 }
1508 catch (fs::filesystem_error&)
1509 {
1510 }
1511
1512 return false;
1513 }
1514 #endif
1515
1516
1517 FILE* Toolbox::OpenFile(const std::string& path,
1518 FileMode mode)
1519 {
1520 #if defined(_WIN32)
1521 // TODO Deal with special characters by converting to the current locale
1522 #endif
1523
1524 const char* m;
1525 switch (mode)
1526 {
1527 case FileMode_ReadBinary:
1528 m = "rb";
1529 break;
1530
1531 case FileMode_WriteBinary:
1532 m = "wb";
1533 break;
1534
1535 default:
1536 throw OrthancException(ErrorCode_ParameterOutOfRange);
1537 }
1538
1539 return fopen(path.c_str(), m);
1540 }
1541
1542
1543
1544 static bool IsUnreservedCharacter(char c)
1545 {
1546 // This function checks whether "c" is an unserved character
1547 // wrt. an URI percent-encoding
1548 // https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding%5Fin%5Fa%5FURI
1549
1550 return ((c >= 'A' && c <= 'Z') ||
1551 (c >= 'a' && c <= 'z') ||
1552 (c >= '0' && c <= '9') ||
1553 c == '-' ||
1554 c == '_' ||
1555 c == '.' ||
1556 c == '~');
1557 }
1558
1559 void Toolbox::UriEncode(std::string& target,
1560 const std::string& source)
1561 {
1562 // Estimate the length of the percent-encoded URI
1563 size_t length = 0;
1564
1565 for (size_t i = 0; i < source.size(); i++)
1566 {
1567 if (IsUnreservedCharacter(source[i]))
1568 {
1569 length += 1;
1570 }
1571 else
1572 {
1573 // This character must be percent-encoded
1574 length += 3;
1575 }
1576 }
1577
1578 target.clear();
1579 target.reserve(length);
1580
1581 for (size_t i = 0; i < source.size(); i++)
1582 {
1583 if (IsUnreservedCharacter(source[i]))
1584 {
1585 target.push_back(source[i]);
1586 }
1587 else
1588 {
1589 // This character must be percent-encoded
1590 uint8_t byte = static_cast<uint8_t>(source[i]);
1591 uint8_t a = byte >> 4;
1592 uint8_t b = byte & 0x0f;
1593
1594 target.push_back('%');
1595 target.push_back(a < 10 ? a + '0' : a - 10 + 'A');
1596 target.push_back(b < 10 ? b + '0' : b - 10 + 'A');
1597 }
1598 }
1599 }
1600
1601
1602 static bool HasField(const Json::Value& json,
1603 const std::string& key,
1604 Json::ValueType expectedType)
1605 {
1606 if (json.type() != Json::objectValue ||
1607 !json.isMember(key))
1608 {
1609 return false;
1610 }
1611 else if (json[key].type() == expectedType)
1612 {
1613 return true;
1614 }
1615 else
1616 {
1617 throw OrthancException(ErrorCode_BadParameterType);
1618 }
1619 }
1620
1621
1622 std::string Toolbox::GetJsonStringField(const Json::Value& json,
1623 const std::string& key,
1624 const std::string& defaultValue)
1625 {
1626 if (HasField(json, key, Json::stringValue))
1627 {
1628 return json[key].asString();
1629 }
1630 else
1631 {
1632 return defaultValue;
1633 }
1634 }
1635
1636
1637 bool Toolbox::GetJsonBooleanField(const ::Json::Value& json,
1638 const std::string& key,
1639 bool defaultValue)
1640 {
1641 if (HasField(json, key, Json::booleanValue))
1642 {
1643 return json[key].asBool();
1644 }
1645 else
1646 {
1647 return defaultValue;
1648 }
1649 }
1650
1651
1652 int Toolbox::GetJsonIntegerField(const ::Json::Value& json,
1653 const std::string& key,
1654 int defaultValue)
1655 {
1656 if (HasField(json, key, Json::intValue))
1657 {
1658 return json[key].asInt();
1659 }
1660 else
1661 {
1662 return defaultValue;
1663 }
1664 }
1665
1666
1667 unsigned int Toolbox::GetJsonUnsignedIntegerField(const ::Json::Value& json,
1668 const std::string& key,
1669 unsigned int defaultValue)
1670 {
1671 int v = GetJsonIntegerField(json, key, defaultValue);
1672
1673 if (v < 0)
1674 {
1675 throw OrthancException(ErrorCode_ParameterOutOfRange);
1676 }
1677 else
1678 {
1679 return static_cast<unsigned int>(v);
1680 }
1681 }
1682 }