Codebase list orthanc-dicomweb / lintian-fixes/main Plugin / DicomWebServers.cpp
lintian-fixes/main

Tree @lintian-fixes/main (Download .tar.gz)

DicomWebServers.cpp @lintian-fixes/mainraw · history · blame

  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
/**
 * 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 "DicomWebServers.h"

#include "Configuration.h"

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

#include <boost/algorithm/string/predicate.hpp>

namespace OrthancPlugins
{
  void DicomWebServers::Clear()
  {
    for (Servers::iterator it = servers_.begin(); it != servers_.end(); ++it)
    {
      assert(it->second != NULL);
      delete it->second;
    }

    servers_.clear();
  }


  void DicomWebServers::LoadGlobalConfiguration(const Json::Value& servers)
  {
    boost::mutex::scoped_lock lock(mutex_);

    Clear();

    bool ok = true;

    try
    {
      if (servers.type() != Json::objectValue)
      {
        ok = false;
      }
      else
      {
        Json::Value::Members members = servers.getMemberNames();

        for (size_t i = 0; i < members.size(); i++)
        {
          std::unique_ptr<Orthanc::WebServiceParameters> parameters
            (new Orthanc::WebServiceParameters(servers[members[i]]));

          servers_[members[i]] = parameters.release();
        }
      }
    }
    catch (Orthanc::OrthancException& e)
    {
      LogError("Exception while parsing the \"DicomWeb.Servers\" section "
               "of the configuration file: " + std::string(e.What()));
      throw;
    }

    if (!ok)
    {
      throw Orthanc::OrthancException(
        Orthanc::ErrorCode_BadFileFormat,
        "Cannot parse the \"DicomWeb.Servers\" section of the configuration file");
    }
  }


  DicomWebServers& DicomWebServers::GetInstance()
  {
    static DicomWebServers singleton;
    return singleton;
  }


  Orthanc::WebServiceParameters DicomWebServers::GetServer(const std::string& name)
  {
    boost::mutex::scoped_lock lock(mutex_);
    Servers::const_iterator server = servers_.find(name);

    if (server == servers_.end() ||
        server->second == NULL)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_InexistentItem,
                                      "Inexistent server: " + name);
    }
    else
    {
      return *server->second;
    }
  }


  void DicomWebServers::ListServers(std::list<std::string>& servers)
  {
    boost::mutex::scoped_lock lock(mutex_);

    servers.clear();
    for (Servers::const_iterator it = servers_.begin(); it != servers_.end(); ++it)
    {
      assert(it->second != NULL);
      servers.push_back(it->first);
    }
  }


  void DicomWebServers::ConfigureHttpClient(HttpClient& client,
                                            std::map<std::string, std::string>& userProperties,
                                            const std::string& name,
                                            const std::string& uri)
  {
    static const char* HAS_CHUNKED_TRANSFERS = "ChunkedTransfers";
    
    const Orthanc::WebServiceParameters parameters = GetServer(name);

    client.SetUrl(RemoveMultipleSlashes(parameters.GetUrl() + "/" + uri));
    client.SetHeaders(parameters.GetHttpHeaders());

    if (!parameters.GetUsername().empty())
    {
      client.SetCredentials(parameters.GetUsername(), parameters.GetPassword());
    }

    if (!parameters.GetCertificateFile().empty())
    {
      client.SetCertificate(
        parameters.GetCertificateFile(),
        parameters.GetCertificateKeyFile(),
        parameters.GetCertificateKeyPassword());
    }

    client.SetPkcs11(parameters.IsPkcs11Enabled());

    // By default, enable chunked transfers
    client.SetChunkedTransfersAllowed(
      parameters.GetBooleanUserProperty(HAS_CHUNKED_TRANSFERS, true));

    userProperties = parameters.GetUserProperties();

    if (parameters.HasTimeout())
    {
      client.SetTimeout(parameters.GetTimeout());
    }
  }


  void DicomWebServers::DeleteServer(const std::string& name)
  {
    boost::mutex::scoped_lock lock(mutex_);

    Servers::iterator found = servers_.find(name);

    if (found == servers_.end())
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange,
                                      "Unknown DICOMweb server: " + name);
    }
    else
    {
      assert(found->second != NULL);
      delete found->second;
      servers_.erase(found);
    }
  }


  void DicomWebServers::SetServer(const std::string& name,
                                  const Orthanc::WebServiceParameters& parameters)
  {
    boost::mutex::scoped_lock lock(mutex_);

    Servers::iterator found = servers_.find(name);

    if (found != servers_.end())
    {
      assert(found->second != NULL);
      delete found->second;
      servers_.erase(found);
    }

    servers_[name] = new Orthanc::WebServiceParameters(parameters);
  }

  

  static const char* ConvertToCString(const std::string& s)
  {
    if (s.empty())
    {
      return NULL;
    }
    else
    {
      return s.c_str();
    }
  }



  void CallServer(MemoryBuffer& answerBody /* out */,
                  std::map<std::string, std::string>& answerHeaders /* out */,
                  const Orthanc::WebServiceParameters& server,
                  OrthancPluginHttpMethod method,
                  const std::map<std::string, std::string>& httpHeaders,
                  const std::string& uri,
                  const std::string& body)
  {
    answerBody.Clear();
    answerHeaders.clear();

    std::string url = server.GetUrl();
    assert(!url.empty() && url[url.size() - 1] == '/');

    // Remove the leading "/" in the URI if need be
    if (!uri.empty() &&
        uri[0] == '/')
    {
      url += uri.substr(1);
    }
    else
    {
      url += uri;
    }

    std::map<std::string, std::string> allHttpHeaders = server.GetHttpHeaders();
    
    {
      // Add the user-specified HTTP headers to the HTTP headers
      // coming from the Orthanc configuration file
      for (std::map<std::string, std::string>::const_iterator
             it = httpHeaders.begin(); it != httpHeaders.end(); ++it)
      {
        allHttpHeaders[it->first] = it->second;
      }
    }

    std::vector<const char*> httpHeadersKeys(allHttpHeaders.size());
    std::vector<const char*> httpHeadersValues(allHttpHeaders.size());

    {
      size_t pos = 0;
      for (std::map<std::string, std::string>::const_iterator
             it = allHttpHeaders.begin(); it != allHttpHeaders.end(); ++it)
      {
        httpHeadersKeys[pos] = it->first.c_str();
        httpHeadersValues[pos] = it->second.c_str();
        pos += 1;
      }

      assert(pos == allHttpHeaders.size());
    }

    const char* bodyContent = NULL;
    size_t bodySize = 0;

    if ((method == OrthancPluginHttpMethod_Put ||
         method == OrthancPluginHttpMethod_Post) &&
        !body.empty())
    {
      bodyContent = body.c_str();
      bodySize = body.size();
    }

    OrthancPluginContext* context = GetGlobalContext();

    uint16_t status = 0;
    MemoryBuffer answerHeadersTmp;
    OrthancPluginErrorCode code = OrthancPluginHttpClient(
      context, 
      /* Outputs */
      *answerBody, *answerHeadersTmp, &status, 
      method,
      url.c_str(), 
      /* HTTP headers*/
      allHttpHeaders.size(),
      httpHeadersKeys.empty() ? NULL : &httpHeadersKeys[0],
      httpHeadersValues.empty() ? NULL : &httpHeadersValues[0],
      bodyContent, bodySize,
      ConvertToCString(server.GetUsername()), /* Authentication */
      ConvertToCString(server.GetPassword()), 
      0,                                      /* Timeout */
      ConvertToCString(server.GetCertificateFile()),
      ConvertToCString(server.GetCertificateKeyFile()),
      ConvertToCString(server.GetCertificateKeyPassword()),
      server.IsPkcs11Enabled() ? 1 : 0);

    if (code != OrthancPluginErrorCode_Success ||
        (status < 200 || status >= 300))
    {
      throw Orthanc::OrthancException(
        static_cast<Orthanc::ErrorCode>(code),
        "Cannot issue an HTTP query to " + url + 
        " (HTTP status: " + boost::lexical_cast<std::string>(status) + ")");
    }

    Json::Value json;
    answerHeadersTmp.ToJson(json);
    answerHeadersTmp.Clear();

    if (json.type() != Json::objectValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
    }

    Json::Value::Members members = json.getMemberNames();
    for (size_t i = 0; i < members.size(); i++)
    {
      const std::string& key = members[i];

      if (json[key].type() != Json::stringValue)
      {
        throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError);
      }
      else
      {
        answerHeaders[key] = json[key].asString();        
      }
    }
  }


  void DicomWebServers::UriEncode(std::string& uri,
                                  const std::string& resource,
                                  const std::map<std::string, std::string>& getArguments)
  {
    if (resource.find('?') != std::string::npos)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat,
                                      "The GET arguments must be provided in a separate field "
                                      "(explicit \"?\" is disallowed): " + resource);
    }

    uri = resource;

    bool isFirst = true;
    for (std::map<std::string, std::string>::const_iterator
           it = getArguments.begin(); it != getArguments.end(); ++it)
    {
      if (isFirst)
      {
        uri += '?';
        isFirst = false;
      }
      else
      {
        uri += '&';
      }

      std::string key, value;
      Orthanc::Toolbox::UriEncode(key, it->first);
      Orthanc::Toolbox::UriEncode(value, it->second);

      if (value.empty())
      {
        uri += key;
      }
      else
      {
        uri += key + "=" + value;
      }
    }
  }


  void DicomWebServers::SerializeGlobalProperty(std::string& target)
  {
    boost::mutex::scoped_lock lock(mutex_);

    Json::Value json = Json::objectValue;

    for (Servers::const_iterator it = servers_.begin(); it != servers_.end(); ++it)
    {
      assert(it->second != NULL);

      Json::Value server;
      it->second->Serialize(server, true /* advanced format */, true /* store passwords */);
      json[it->first] = server;
    }

    OrthancPlugins::WriteFastJson(target, json);
  }


  void DicomWebServers::UnserializeGlobalProperty(const std::string& source)
  {
    Json::Value json;
    
    if (!OrthancPlugins::ReadJson(json, source) ||
        json.type() != Json::objectValue)
    {
      throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat, "Cannot unserialize "
                                      "the list of DICOMweb servers from global properties");
    }

    Clear();

    std::vector<std::string> members = json.getMemberNames();
    
    for (size_t i = 0; i < members.size(); i++)
    {
      const std::string& name = members[i];
      
      std::unique_ptr<Orthanc::WebServiceParameters> server(new Orthanc::WebServiceParameters);
      server->Unserialize(json[name]);

      assert(servers_.find(name) == servers_.end());
      servers_[name] = server.release();
    }
  }
}