File: Configuration.cpp

package info (click to toggle)
orthanc-dicomweb 1.7%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 5,592 kB
  • sloc: javascript: 34,006; cpp: 14,041; python: 418; sh: 127; makefile: 31
file content (781 lines) | stat: -rw-r--r-- 20,671 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
/**
 * Orthanc - A Lightweight, RESTful DICOM Store
 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
 * Department, University Hospital of Liege, Belgium
 * Copyright (C) 2017-2021 Osimis S.A., Belgium
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 **/


#include "Configuration.h"

#include "../Resources/Orthanc/Plugins/OrthancPluginCppWrapper.h"
#include "DicomWebServers.h"

#include <Compatibility.h>
#include <Logging.h>
#include <Toolbox.h>

#include <fstream>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/predicate.hpp>


// Assume Latin-1 encoding by default (as in the Orthanc core)
static Orthanc::Encoding defaultEncoding_ = Orthanc::Encoding_Latin1;
static std::unique_ptr<OrthancPlugins::OrthancConfiguration> configuration_;
static bool serversInDatabase_ = false;
static const int32_t GLOBAL_PROPERTY_SERVERS = 5468;


namespace OrthancPlugins
{
  bool LookupHttpHeader(std::string& value,
                        const OrthancPluginHttpRequest* request,
                        const std::string& header)
  {
    value.clear();

    for (uint32_t i = 0; i < request->headersCount; i++)
    {
      std::string s = request->headersKeys[i];
      Orthanc::Toolbox::ToLowerCase(s);
      if (s == header)
      {
        value = request->headersValues[i];
        return true;
      }
    }

    return false;
  }


  void ParseContentType(std::string& application,
                        std::map<std::string, std::string>& attributes,
                        const std::string& header)
  {
    application.clear();
    attributes.clear();

    std::vector<std::string> tokens;
    Orthanc::Toolbox::TokenizeString(tokens, header, ';');

    assert(tokens.size() > 0);
    application = tokens[0];
    Orthanc::Toolbox::StripSpaces(application);
    Orthanc::Toolbox::ToLowerCase(application);

    boost::regex pattern("\\s*([^=]+)\\s*=\\s*(([^=\"]+)|\"([^=\"]+)\")\\s*");
    
    for (size_t i = 1; i < tokens.size(); i++)
    {
      boost::cmatch what;
      if (boost::regex_match(tokens[i].c_str(), what, pattern))
      {
        std::string key(what[1]);
        std::string value(what.length(3) != 0 ? what[3] : what[4]);
        Orthanc::Toolbox::ToLowerCase(key);
        attributes[key] = value;
      }
    }
  }


  void ParseAssociativeArray(std::map<std::string, std::string>& target,
                             const Json::Value& value)
  {
    if (value.type() != Json::objectValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat,
                                      "The JSON object is not a JSON associative array as expected");
    }

    Json::Value::Members names = value.getMemberNames();

    for (size_t i = 0; i < names.size(); i++)
    {
      if (value[names[i]].type() != Json::stringValue)
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat,
                                        "Value \"" + names[i] + "\" in the associative array "
                                        "is not a string as expected");
      }
      else
      {
        target[names[i]] = value[names[i]].asString();
      }
    }
  }
  

  void ParseAssociativeArray(std::map<std::string, std::string>& target,
                             const Json::Value& value,
                             const std::string& key)
  {
    if (value.type() != Json::objectValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat,
                                      "This is not a JSON object");
    }

    if (value.isMember(key))
    {
      ParseAssociativeArray(target, value[key]);
    }
    else
    {
      target.clear();
    }
  }


  bool ParseTag(Orthanc::DicomTag& target,
                const std::string& name)
  {
    OrthancPluginDictionaryEntry entry;
    
    if (OrthancPluginLookupDictionary(GetGlobalContext(), &entry, name.c_str()) == OrthancPluginErrorCode_Success)
    {
      target = Orthanc::DicomTag(entry.group, entry.element);
      return true;
    }
    else
    {
      return false;
    }
  }


  void ParseJsonBody(Json::Value& target,
                     const OrthancPluginHttpRequest* request)
  {
    if (!OrthancPlugins::ReadJson(target, request->body, request->bodySize))
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat,
                                      "A JSON file was expected");
    }
  }


  std::string RemoveMultipleSlashes(const std::string& source)
  {
    std::string target;
    target.reserve(source.size());

    size_t prefix = 0;
  
    if (boost::starts_with(source, "https://"))
    {
      prefix = 8;
    }
    else if (boost::starts_with(source, "http://"))
    {
      prefix = 7;
    }

    for (size_t i = 0; i < prefix; i++)
    {
      target.push_back(source[i]);
    }

    bool isLastSlash = false;

    for (size_t i = prefix; i < source.size(); i++)
    {
      if (source[i] == '/')
      {
        if (!isLastSlash)
        {
          target.push_back('/');
          isLastSlash = true;
        }
      }
      else
      {
        target.push_back(source[i]);
        isLastSlash = false;
      }
    }

    return target;
  }


  bool LookupStringValue(std::string& target,
                         const Json::Value& json,
                         const std::string& key)
  {
    if (json.type() != Json::objectValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
    }
    else if (!json.isMember(key))
    {
      return false;
    }
    else if (json[key].type() != Json::stringValue)
    {
      throw Orthanc::OrthancException(
        Orthanc::ErrorCode_BadFileFormat,
        "The field \"" + key + "\" in a JSON object should be a string");
    }
    else
    {
      target = json[key].asString();
      return true;
    }
  }


  bool LookupIntegerValue(int& target,
                          const Json::Value& json,
                          const std::string& key)
  {
    if (json.type() != Json::objectValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
    }
    else if (!json.isMember(key))
    {
      return false;
    }
    else if (json[key].type() != Json::intValue &&
             json[key].type() != Json::uintValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);      
    }
    else
    {
      target = json[key].asInt();
      return true;
    }
  }


  bool LookupBooleanValue(bool& target,
                          const Json::Value& json,
                          const std::string& key)
  {
    if (json.type() != Json::objectValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
    }
    else if (!json.isMember(key))
    {
      return false;
    }
    else if (json[key].type() != Json::booleanValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);      
    }
    else
    {
      target = json[key].asBool();
      return true;
    }
  }


  namespace Configuration
  {
    void Initialize()
    {
      configuration_.reset(new OrthancConfiguration);
      
      OrthancConfiguration global;
      global.GetSection(*configuration_, "DicomWeb");

      std::string s;
      if (global.LookupStringValue(s, "DefaultEncoding"))
      {
        defaultEncoding_ = Orthanc::StringToEncoding(s.c_str());
      }

      if (!configuration_->LookupBooleanValue(serversInDatabase_, "ServersInDatabase"))
      {
        serversInDatabase_ = false;
      }

      if (serversInDatabase_)
      {
        LOG(INFO) << "The DICOMweb plugin stores the DICOMweb servers in the Orthanc database";
      }
      else
      {
        LOG(INFO) << "The DICOMweb plugin reads the DICOMweb servers from the configuration file";
      }

      DicomWebServers::GetInstance().Clear();
        
      // Check configuration during initialization
      GetMetadataMode(Orthanc::ResourceType_Study);
      GetMetadataMode(Orthanc::ResourceType_Series);

      std::set<Orthanc::DicomTag> tags;
      GetExtrapolatedMetadataTags(tags, Orthanc::ResourceType_Study);
      GetExtrapolatedMetadataTags(tags, Orthanc::ResourceType_Series);
    }


    std::string GetStringValue(const std::string& key,
                               const std::string& defaultValue)
    {
      assert(configuration_.get() != NULL);
      return configuration_->GetStringValue(key, defaultValue);
    }


    bool GetBooleanValue(const std::string& key,
                         bool defaultValue)
    {
      assert(configuration_.get() != NULL);
      return configuration_->GetBooleanValue(key, defaultValue);
    }


    bool LookupBooleanValue(bool& target,
                            const std::string& key)
    {
      assert(configuration_.get() != NULL);
      return configuration_->LookupBooleanValue(target, key);
    }


    unsigned int GetUnsignedIntegerValue(const std::string& key,
                                         unsigned int defaultValue)
    {
      assert(configuration_.get() != NULL);
      return configuration_->GetUnsignedIntegerValue(key, defaultValue);
    }


    std::string GetDicomWebRoot()
    {
      assert(configuration_.get() != NULL);
      std::string root = configuration_->GetStringValue("Root", "/dicom-web/");

      // Make sure the root URI starts and ends with a slash
      if (root.size() == 0 ||
          root[0] != '/')
      {
        root = "/" + root;
      }
    
      if (root[root.length() - 1] != '/')
      {
        root += "/";
      }

      return root;
    }

    
    std::string GetOrthancApiRoot()
    {
      std::string root = Configuration::GetDicomWebRoot();
      std::vector<std::string> tokens;
      Orthanc::Toolbox::TokenizeString(tokens, root, '/');

      int depth = 0;
      for (size_t i = 0; i < tokens.size(); i++)
      {
        if (tokens[i].empty() ||
            tokens[i] == ".")
        {
          // Don't change the depth
        }
        else if (tokens[i] == "..")
        {
          depth--;
        }
        else
        {
          depth++;
        }
      }

      std::string orthancRoot = "./";
      for (int i = 0; i < depth; i++)
      {
        orthancRoot += "../";
      }

      return orthancRoot;
    }


    std::string GetWadoRoot()
    {
      assert(configuration_.get() != NULL);
      std::string root = configuration_->GetStringValue("WadoRoot", "/wado/");

      // Make sure the root URI starts with a slash
      if (root.size() == 0 ||
          root[0] != '/')
      {
        root = "/" + root;
      }

      // Remove the trailing slash, if any
      if (root[root.length() - 1] == '/')
      {
        root = root.substr(0, root.length() - 1);
      }

      return root;
    }


    static bool IsHttpsProto(const std::string& proto,
                             bool defaultValue)
    {
      if (proto == "http")
      {
        return false;
      }
      else if (proto == "https")
      {
        return true;
      }
      else
      {
        return defaultValue;
      }
    }


    static bool LookupHttpHeader2(std::string& value,
                                  const HttpClient::HttpHeaders& headers,
                                  const std::string& name)
    {
      for (HttpClient::HttpHeaders::const_iterator
             it = headers.begin(); it != headers.end(); ++it)
      {
        if (boost::iequals(it->first, name))
        {
          value = it->second;
          return true;
        }
      }

      return false;
    }


    std::string GetBaseUrl(const HttpClient::HttpHeaders& headers)
    {
      assert(configuration_.get() != NULL);
      std::string host = configuration_->GetStringValue("Host", "");
      bool https = configuration_->GetBooleanValue("Ssl", false);

      std::string forwarded;
      if (host.empty() &&
          LookupHttpHeader2(forwarded, headers, "forwarded"))
      {
        // There is a "Forwarded" HTTP header in the query
        // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
        
        std::vector<std::string> forwarders;
        Orthanc::Toolbox::TokenizeString(forwarders, forwarded, ',');

        // Only consider the first forwarder, if any
        if (!forwarders.empty())
        {
          std::vector<std::string> tokens;
          Orthanc::Toolbox::TokenizeString(tokens, forwarders[0], ';');

          for (size_t j = 0; j < tokens.size(); j++)
          {
            std::vector<std::string> args;
            Orthanc::Toolbox::TokenizeString(args, tokens[j], '=');
            
            if (args.size() == 2)
            {
              std::string key = Orthanc::Toolbox::StripSpaces(args[0]);
              std::string value = Orthanc::Toolbox::StripSpaces(args[1]);

              Orthanc::Toolbox::ToLowerCase(key);
              if (key == "host")
              {
                host = value;
              }
              else if (key == "proto")
              {
                https = IsHttpsProto(value, https);
              }
            }
          }
        }
      }

      if (host.empty() &&
          !LookupHttpHeader2(host, headers, "host"))
      {
        // Should never happen: The "host" header should always be present
        // in HTTP requests. Provide a default value anyway.
        host = "localhost:8042";
      }

      return (https ? "https://" : "http://") + host + GetDicomWebRoot();
    }


    std::string GetBaseUrl(const OrthancPluginHttpRequest* request)
    {
      HttpClient::HttpHeaders headers;

      std::string value;
      if (LookupHttpHeader(value, request, "forwarded"))
      {
        headers["Forwarded"] = value;
      }

      if (LookupHttpHeader(value, request, "host"))
      {
        headers["Host"] = value;
      }

      return GetBaseUrl(headers);
    }


    std::string GetWadoUrl(const std::string& wadoBase,
                           const std::string& studyInstanceUid,
                           const std::string& seriesInstanceUid,
                           const std::string& sopInstanceUid)
    {
      if (studyInstanceUid.empty() ||
          seriesInstanceUid.empty() ||
          sopInstanceUid.empty())
      {
        return "";
      }
      else
      {
        return (wadoBase + 
                "studies/" + studyInstanceUid + 
                "/series/" + seriesInstanceUid + 
                "/instances/" + sopInstanceUid + "/");
      }
    }


    Orthanc::Encoding GetDefaultEncoding()
    {
      return defaultEncoding_;
    }


    static bool IsXmlExpected(const std::string& acceptHeader)
    {
      std::string accept;
      Orthanc::Toolbox::ToLowerCase(accept, acceptHeader);
  
      if (accept == "application/dicom+json" ||
          accept == "application/json" ||
          accept == "*/*")
      {
        return false;
      }
      else if (accept == "application/dicom+xml" ||
               accept == "application/xml" ||
               accept == "text/xml")
      {
        return true;
      }
      else
      {
        LogError("Unsupported return MIME type: " + accept +
                 ", will return DICOM+JSON");
        return false;
      }
    }


    bool IsXmlExpected(const std::map<std::string, std::string>& headers)
    {
      std::map<std::string, std::string>::const_iterator found = headers.find("accept");

      if (found == headers.end())
      {
        return false;   // By default, return DICOM+JSON
      }
      else
      {
        return IsXmlExpected(found->second);
      }
    }


    bool IsXmlExpected(const OrthancPluginHttpRequest* request)
    {
      std::string accept;

      if (LookupHttpHeader(accept, request, "accept"))
      {
        return IsXmlExpected(accept);
      }
      else
      {
        return false;   // By default, return DICOM+JSON
      }
    }

    
    MetadataMode GetMetadataMode(Orthanc::ResourceType level)
    {
      static const std::string FULL = "Full";
      static const std::string MAIN_DICOM_TAGS = "MainDicomTags";
      static const std::string EXTRAPOLATE = "Extrapolate";
      
      std::string key;
      switch (level)
      {
        case Orthanc::ResourceType_Study:
          key = "StudiesMetadata";
          break;

        case Orthanc::ResourceType_Series:
          key = "SeriesMetadata";
          break;

        default:
          throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange);
      }

      std::string value = GetStringValue(key, FULL);

      if (value == FULL)
      {
        return MetadataMode_Full;
      }
      else if (value == MAIN_DICOM_TAGS)
      {
        return MetadataMode_MainDicomTags;
      }
      else if (value == EXTRAPOLATE)
      {
        return MetadataMode_Extrapolate;
      }
      else
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange,
                                        "Bad value for option \"" + key +
                                        "\": Should be either \"" + FULL + "\" or \"" +
                                        MAIN_DICOM_TAGS + "\" or \"" + EXTRAPOLATE + "\"");
      }
    }


    void GetSetOfTags(std::set<Orthanc::DicomTag>& tags,
                      const std::string& key)
    {
      tags.clear();

      std::list<std::string> s;
      
      if (configuration_->LookupListOfStrings(s, key, false))
      {
        for (std::list<std::string>::const_iterator it = s.begin(); it != s.end(); ++it)
        {
          OrthancPluginDictionaryEntry entry;
          if (OrthancPluginLookupDictionary(GetGlobalContext(), &entry, it->c_str()) == OrthancPluginErrorCode_Success)
          {
            tags.insert(Orthanc::DicomTag(entry.group, entry.element));
          }
          else
          {
            throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange,
                                            "Unknown DICOM tag in option \"" + key + "\" of DICOMweb: " + *it);
          }
        }
      }
    }


    void GetExtrapolatedMetadataTags(std::set<Orthanc::DicomTag>& tags,
                                     Orthanc::ResourceType level)
    {
      switch (level)
      {
        case Orthanc::ResourceType_Study:
          GetSetOfTags(tags, "StudiesMetadataExtrapolatedTags");
          break;

        case Orthanc::ResourceType_Series:
          GetSetOfTags(tags, "SeriesMetadataExtrapolatedTags");
          break;

        default:
          throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange);
      }
    }


    void LoadDicomWebServers()
    {
      if (serversInDatabase_)
      {
        // New in DICOMweb 1.5
        OrthancString property;
        property.Assign(OrthancPluginGetGlobalProperty(
                          GetGlobalContext(), GLOBAL_PROPERTY_SERVERS, "{}"));

        if (property.GetContent() == NULL)
        {
          DicomWebServers::GetInstance().Clear();
        }
        else
        {
          try
          {
            DicomWebServers::GetInstance().UnserializeGlobalProperty(property.GetContent());
          }
          catch (Orthanc::OrthancException&)
          {
            DicomWebServers::GetInstance().Clear();
            LOG(ERROR) << "Cannot read the DICOMweb servers from the database, no server will be defined";
          }
        }
      }
      else
      {
        OrthancConfiguration servers;
        configuration_->GetSection(servers, "Servers");
        DicomWebServers::GetInstance().LoadGlobalConfiguration(servers.GetJson());
      }
    }

    
    void SaveDicomWebServers()
    {
      if (serversInDatabase_)
      {
        // New in DICOMweb 1.5
        std::string property;
        DicomWebServers::GetInstance().SerializeGlobalProperty(property);

        if (OrthancPluginSetGlobalProperty(
              OrthancPlugins::GetGlobalContext(), GLOBAL_PROPERTY_SERVERS, property.c_str()) !=
            OrthancPluginErrorCode_Success)
        {
          LOG(ERROR) << "Cannot write the DICOMweb servers into the database";
        }
      }
    }
  }
}