-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathprintscp.cpp
More file actions
1556 lines (1378 loc) · 50.7 KB
/
printscp.cpp
File metadata and controls
1556 lines (1378 loc) · 50.7 KB
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2014-2018 Softus Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; version 2.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "product.h"
#include "printscp.h"
#include "storescp.h"
#include "transcyrillic.h"
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#endif
#include <QRect>
#include <QUtf8Settings>
#include <QStringList>
#include <QXmlStreamReader>
#include <locale.h> // Required for tesseract
#ifdef UNICODE
#define DCMTK_UNICODE_BUG_WORKAROUND
#undef UNICODE
#endif
#include <dcmtk/dcmdata/dcdeftag.h>
#include <dcmtk/dcmdata/dcfilefo.h>
#include <dcmtk/dcmdata/dcsequen.h>
#include <dcmtk/dcmdata/dcvrui.h>
#include <dcmtk/dcmpstat/dvpsdef.h> /* for constants */
#include <dcmtk/dcmimgle/dcmimage.h> /* for DicomImage */
#ifdef DCMTK_UNICODE_BUG_WORKAROUND
#define UNICODE
#undef DCMTK_UNICODE_BUG_WORKAROUND
#endif
#ifndef DCM_RETIRED_DestinationAE
#define DCM_RETIRED_DestinationAE DcmTagKey(0x2100, 0x0140)
#endif
bool saveToDisk(const QString& spoolPath, DcmDataset* rqDataset)
{
if (!QDir::root().mkpath(spoolPath))
{
qDebug() << "Failed to create folder " << spoolPath << ": " << QString::fromLocal8Bit(strerror(errno));
}
const char* uId = nullptr;
rqDataset->findAndGetString(DCM_SOPInstanceUID, uId);
QString fileName = QString(spoolPath).append(QDir::separator()).append(uId).append(".dcm");
if (QFile::exists(fileName))
{
int cnt = 1;
QString alt;
do
{
alt = QString(fileName).append(" (").append(QString::number(++cnt)).append(')');
}
while (QFile::exists(alt));
fileName = alt;
}
DcmFileFormat ff(rqDataset);
OFCondition cond = ff.saveFile((const char*)fileName.toUtf8(),
EXS_LittleEndianExplicit, EET_ExplicitLength, EGL_recalcGL, EPD_withoutPadding);
if (cond.bad())
{
qDebug() << "Failed to save " << fileName << ": " << QString::fromLocal8Bit(cond.text());
}
else
{
qDebug() << "Dataset saved to " << fileName;
}
return cond.good();
}
static OFCondition putAndInsertVariant(DcmDataset* dataset, const DcmTag& tag, const QVariant& value)
{
switch (tag.getEVR())
{
case EVR_FL:
case EVR_OF:
return dataset->putAndInsertFloat32(tag, value.toFloat());
case EVR_FD:
return dataset->putAndInsertFloat64(tag, value.toDouble());
case EVR_SL:
return dataset->putAndInsertSint32(tag, value.toInt());
case EVR_UL:
return dataset->putAndInsertUint32(tag, value.toUInt());
case EVR_SS:
return dataset->putAndInsertSint16(tag, (Sint16)value.toInt());
case EVR_US:
return dataset->putAndInsertUint16(tag, (Uint16)value.toUInt());
case EVR_DA:
return dataset->putAndInsertString(tag, value.toDate().toString("yyyyMMdd").toUtf8());
case EVR_DT:
return dataset->putAndInsertString(tag, value.toDateTime().toString("yyyyMMddHHmmss").toUtf8());
case EVR_TM:
return dataset->putAndInsertString(tag, value.toTime().toString("HHmmss").toUtf8());
default:
if (tag.getVR().isaString())
{
return dataset->putAndInsertString(tag, value.toString().toUtf8());
}
break;
}
qDebug() << "VR" << tag.getVRName() << "not implemented";
return EC_IllegalParameter;
}
static OFCondition findAndGetVariant(DcmDataset* dataset, const DcmTag& tag, QVariant& value)
{
OFCondition cond;
switch (tag.getEVR())
{
case EVR_FL:
case EVR_OF:
{
float f = 0.0f;
cond = dataset->findAndGetFloat32(tag, f);
if (cond.good()) { value.setValue(f); }
break;
}
case EVR_FD:
{
double d = 0.0;
cond = dataset->findAndGetFloat64(tag, d);
if (cond.good()) { value.setValue(d); }
break;
}
case EVR_SL:
{
Sint32 i = 0;
cond = dataset->findAndGetSint32(tag, i);
if (cond.good()) { value.setValue(i); }
break;
}
case EVR_UL:
{
Uint32 u = 0;
cond = dataset->findAndGetUint32(tag, u);
if (cond.good()) { value.setValue(u); }
break;
}
case EVR_SS:
{
Sint16 i = 0;
cond = dataset->findAndGetSint16(tag, i);
if (cond.good()) { value.setValue(i); }
break;
}
case EVR_US:
{
Uint16 u = 0;
cond = dataset->findAndGetUint16(tag, u);
if (cond.good()) { value.setValue(u); }
break;
}
case EVR_DA:
{
const char* str = nullptr;
cond = dataset->findAndGetString(tag, str);
if (cond.good())
{
value.setValue(QDate::fromString(str, "yyyyMMdd"));
}
break;
}
case EVR_DT:
{
const char* str = nullptr;
cond = dataset->findAndGetString(tag, str);
if (cond.good())
{
value.setValue(QDateTime::fromString(str, "yyyyMMddHHmmss"));
}
break;
}
case EVR_TM:
{
const char* str = nullptr;
cond = dataset->findAndGetString(tag, str);
if (cond.good())
{
value.setValue(QTime::fromString(str, "HHmmss"));
}
break;
}
default:
if (tag.getVR().isaString())
{
const char* str = nullptr;
cond = dataset->findAndGetString(tag, str);
if (cond.good())
{
value.setValue(QString::fromUtf8(str));
}
}
else
{
qDebug() << "VR" << tag.getVRName() << "not implemented";
cond = EC_IllegalParameter;
break;
}
}
return cond;
}
static bool isDatasetPresent(T_DIMSE_Message &msg)
{
switch (msg.CommandField)
{
case DIMSE_C_STORE_RQ: return msg.msg.CStoreRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_STORE_RSP: return msg.msg.CStoreRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_GET_RQ: return msg.msg.CGetRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_GET_RSP: return msg.msg.CGetRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_FIND_RQ: return msg.msg.CFindRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_FIND_RSP: return msg.msg.CFindRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_MOVE_RQ: return msg.msg.CMoveRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_MOVE_RSP: return msg.msg.CMoveRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_ECHO_RQ: return msg.msg.CEchoRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_ECHO_RSP: return msg.msg.CEchoRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_C_CANCEL_RQ: return msg.msg.CCancelRQ.DataSetType != DIMSE_DATASET_NULL;
/* there is no DIMSE_C_CANCEL_RSP */
case DIMSE_N_EVENT_REPORT_RQ: return msg.msg.NEventReportRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_EVENT_REPORT_RSP: return msg.msg.NEventReportRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_GET_RQ: return msg.msg.NGetRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_GET_RSP: return msg.msg.NGetRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_SET_RQ: return msg.msg.NSetRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_SET_RSP: return msg.msg.NSetRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_ACTION_RQ: return msg.msg.NActionRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_ACTION_RSP: return msg.msg.NActionRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_CREATE_RQ: return msg.msg.NCreateRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_CREATE_RSP: return msg.msg.NCreateRSP.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_DELETE_RQ: return msg.msg.NDeleteRQ.DataSetType != DIMSE_DATASET_NULL;
case DIMSE_N_DELETE_RSP: return msg.msg.NDeleteRSP.DataSetType != DIMSE_DATASET_NULL;
default:
qDebug() << "Unhandled command field" << msg.CommandField;
break;
}
return false;
}
static void copyItems(DcmItem* src, DcmItem *dst)
{
// The source dataset is optional
//
if (!src)
{
return;
}
DcmObject* obj = nullptr;
while (obj = src->nextInContainer(obj), obj != nullptr)
{
if (obj->getVR() == EVR_SQ)
{
// Ignore ReferencedFilmSessionSequence
//
continue;
}
// Insert with overwrite
//
dst->insert(dynamic_cast<DcmElement*>(obj->clone()), true);
}
}
PrintSCP::PrintSCP(T_ASC_Association *assoc, QObject *parent, const QString &printer)
: QObject(parent)
, blockMode(DIMSE_BLOCKING)
, timeout(DEFAULT_TIMEOUT)
, forceUniqueSeries(false)
, forceUniqueStudy(false)
, sessionDataset(nullptr)
, printer(printer)
, upstreamNet(nullptr)
, assoc(assoc)
, upstream(nullptr)
, debugUpstream(false)
{
QUtf8Settings settings;
auto ocrLang = settings.value("ocr-lang", DEFAULT_OCR_LANG).toString();
#ifdef WITH_TESSERACT
// Set locale to "C" to avoid tesseract crash. Then revert to the system default
//
auto oldLocale = setlocale(LC_NUMERIC, "C");
tess.Init(nullptr, ocrLang.toUtf8(), tesseract::OEM_TESSERACT_ONLY);
setlocale(LC_NUMERIC, oldLocale);
#endif
blockMode = (T_DIMSE_BlockingMode)settings.value("block-mode", blockMode).toInt();
timeout = settings.value("timeout", timeout).toInt();
debugUpstream = settings.value("debug-upstream", debugUpstream).toBool();
reBadSymbols.setPattern(settings.value("bad-symbols").toString());
}
PrintSCP::~PrintSCP()
{
dropAssociations();
ASC_dropNetwork(&upstreamNet);
qDebug() << __func__ << "pid" << getpid();
}
void PrintSCP::dump(const char* desc, DcmItem *dataset)
{
if (!dataset || !debugUpstream)
return;
std::stringstream ss;
dataset->print(ss);
qDebug() << desc << QString::fromLocal8Bit(ss.str().c_str());
}
void PrintSCP::dumpIn(T_DIMSE_Message &msg, DcmItem *dataset)
{
if (!dataset || !debugUpstream)
return;
OFString str;
DIMSE_dumpMessage(str, msg, DIMSE_INCOMING, dataset);
qDebug() << QString::fromLocal8Bit(str.c_str());
}
void PrintSCP::dumpOut(T_DIMSE_Message &msg, DcmItem *dataset)
{
if (!dataset || !debugUpstream)
return;
OFString str;
DIMSE_dumpMessage(str, msg, DIMSE_OUTGOING, dataset);
qDebug() << QString::fromLocal8Bit(str.c_str());
}
bool PrintSCP::negotiateAssociation()
{
QUtf8Settings settings;
char buf[BUFSIZ];
bool dropAssoc = false;
const char *abstractSyntaxes[] =
{
UID_BasicGrayscalePrintManagementMetaSOPClass,
UID_PresentationLUTSOPClass,
UID_VerificationSOPClass,
};
const char* transferSyntaxes[] =
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
UID_LittleEndianExplicitTransferSyntax, UID_BigEndianExplicitTransferSyntax,
#elif __BYTE_ORDER == __BIG_ENDIAN
UID_BigEndianExplicitTransferSyntax, UID_LittleEndianExplicitTransferSyntax,
#else
#error "Unsupported byte order"
#endif
UID_LittleEndianImplicitTransferSyntax
};
printer = QString::fromUtf8(assoc->params->DULparams.calledAPTitle);
qDebug() << "\n\n\nClient association received (max send PDV: " << assoc->sendPDVLength << ")"
<< assoc->params->DULparams.callingPresentationAddress << ":"
<< assoc->params->DULparams.callingAPTitle << "=>"
<< assoc->params->DULparams.calledPresentationAddress << ":"
<< assoc->params->DULparams.calledAPTitle
<< QDateTime::currentDateTime().toString(Qt::ISODate)
;
ASC_setAPTitles(assoc->params, nullptr, nullptr, printer.toUtf8());
/* Application Context Name */
auto cond = ASC_getApplicationContextName(assoc->params, buf);
if (cond.bad() || strcmp(buf, DICOM_STDAPPLICATIONCONTEXT) != 0)
{
/* reject: the application context name is not supported */
qDebug() << "Bad AppContextName: " << buf;
cond = refuseAssociation(ASC_RESULT_REJECTEDTRANSIENT, ASC_REASON_SU_APPCONTEXTNAMENOTSUPPORTED);
dropAssoc = true;
}
else if (!settings.childGroups().contains(printer))
{
cond = refuseAssociation(ASC_RESULT_REJECTEDTRANSIENT, ASC_REASON_SU_CALLEDAETITLENOTRECOGNIZED);
dropAssoc = true;
}
else
{
/* accept presentation contexts */
cond = ASC_acceptContextsWithPreferredTransferSyntaxes(assoc->params,
abstractSyntaxes, sizeof(abstractSyntaxes)/sizeof(abstractSyntaxes[0]),
transferSyntaxes, sizeof(transferSyntaxes)/sizeof(transferSyntaxes[0]));
}
if (dropAssoc)
{
printer.clear();
dropAssociations();
}
else
{
// Initialize connection to upstream printer, if one is configured
//
settings.beginGroup(printer);
auto printerAETitle = settings.value("upstream-aetitle").toString();
auto printerAddress = settings.value("upstream-address").toString();
auto calleeAETitle = settings.value("aetitle", assoc->params->DULparams.callingAPTitle).toString().toUpper();
forceUniqueSeries = settings.value("force-unique-series", forceUniqueSeries).toBool();
forceUniqueStudy = settings.value("force-unique-study", forceUniqueStudy).toBool();
debugUpstream = settings.value("debug-upstream", debugUpstream).toBool();
reBadSymbols.setPattern(settings.value("bad-symbols", reBadSymbols.pattern()).toString());
settings.endGroup();
if (printerAETitle.isEmpty())
{
qDebug() << "No upstream connection for" << printer;
}
else
{
DIC_NODENAME localHost;
T_ASC_Parameters* params = nullptr;
auto port = settings.value("print-port", 0).toInt();
auto cond = ASC_initializeNetwork(NET_REQUESTOR, port, timeout, &upstreamNet);
qDebug() << "Creating upstream connection to" << printer;
cond = ASC_createAssociationParameters(¶ms, settings.value("pdu-size", ASC_DEFAULTMAXPDU).toInt());
if (cond.good())
{
ASC_setAPTitles(params, calleeAETitle.toUtf8(), printerAETitle.toUtf8(), nullptr);
// Figure out the presentation addresses and copy the
// corresponding values into the DcmAssoc parameters.
//
gethostname(localHost, sizeof(localHost) - 1);
ASC_setPresentationAddresses(params, localHost, printerAddress.toUtf8());
for (size_t i = 0; cond.good() && i < sizeof(abstractSyntaxes)/sizeof(abstractSyntaxes[0]); ++i)
{
cond = ASC_addPresentationContext(params, i*2+1, abstractSyntaxes[i],
transferSyntaxes, sizeof(transferSyntaxes)/sizeof(transferSyntaxes[0]));
}
}
if (cond.good())
{
cond = ASC_requestAssociation(upstreamNet, params, &upstream);
}
if (cond.bad())
{
qDebug() << "Failed to create association to" << printerAETitle << QString::fromLocal8Bit(cond.text());
ASC_destroyAssociation(&upstream);
}
else
{
// Dump general information concerning the establishment of the network connection if required
//
qDebug() << "Connection to upstream printer" << printer
<< "accepted (max send PDV: " << upstream->sendPDVLength << ")"
<< upstream->params->DULparams.callingPresentationAddress << ":"
<< upstream->params->DULparams.callingAPTitle << "=>"
<< upstream->params->DULparams.calledPresentationAddress << ":"
<< upstream->params->DULparams.calledAPTitle;
}
}
// First of all, store the calee AE title.
// Later we will add all attributes comes from client/server to the
// final message. And store the message to the storage server.
//
sessionDataset = new DcmDataset;
sessionDataset->putAndInsertString(DCM_RETIRED_DestinationAE, calleeAETitle.toUtf8());
// Fill in with some defaults
//
sessionDataset->putAndInsertString(DCM_PatientID, "0", false);
sessionDataset->putAndInsertString(DCM_PatientName, "^", false);
}
return !dropAssoc;
}
OFCondition PrintSCP::refuseAssociation(T_ASC_RejectParametersResult result, T_ASC_RejectParametersReason reason)
{
qDebug() << __FUNCTION__ << result << reason;
T_ASC_RejectParameters rej = { result, ASC_SOURCE_SERVICEUSER, reason };
void *associatePDU = nullptr;
unsigned long associatePDUlength=0;
OFCondition cond = ASC_rejectAssociation(assoc, &rej, &associatePDU, &associatePDUlength);
delete[] (char *)associatePDU;
return cond;
}
void PrintSCP::dropAssociations()
{
if (assoc)
{
if (assoc->params)
{
qDebug() << "Client association with"
<< assoc->params->DULparams.callingPresentationAddress << ":"
<< assoc->params->DULparams.callingAPTitle << "closed" << "pid" << getpid();
}
else
{
qDebug() << "Client association with unknown params closed" << "pid" << getpid();
}
ASC_dropSCPAssociation(assoc);
ASC_destroyAssociation(&assoc);
}
if (upstream)
{
if (upstream->params)
{
qDebug() << "Upstream association with"
<< upstream->params->DULparams.callingPresentationAddress << ":"
<< upstream->params->DULparams.callingAPTitle << "closed" << "pid" << getpid();
}
else
{
qDebug() << "Upstream association with unknown params closed" << "pid" << getpid();
}
ASC_dropSCPAssociation(upstream);
ASC_destroyAssociation(&upstream);
ASC_dropNetwork(&upstreamNet);
}
delete sessionDataset;
sessionDataset = nullptr;
qDebug() << "Drop association completed. pid" << getpid();
}
void PrintSCP::handleClient()
{
void *associatePDU = nullptr;
unsigned long associatePDUlength = 0;
OFCondition cond = ASC_acknowledgeAssociation(assoc, &associatePDU, &associatePDUlength);
delete[] (char *)associatePDU;
// Do the real work
//
while (cond.good())
{
T_DIMSE_Message rq;
T_DIMSE_Message rsp;
T_ASC_PresentationContextID presId;
T_ASC_PresentationContextID upstreamPresId = 0;
DcmDataset *rawCommandSet = nullptr;
DcmDataset *statusDetail = nullptr;
DcmDataset *rqDataset = nullptr;
DcmDataset *rspDataset = nullptr;
cond = DIMSE_receiveCommand(assoc, DIMSE_BLOCKING, 0, &presId, &rq, &statusDetail, &rawCommandSet);
if (cond.bad())
{
qDebug() << "DIMSE_receiveCommand" << QString::fromLocal8Bit(cond.text());
break;
}
dump("statusDetail", statusDetail);
dump("rawCommandSet", rawCommandSet);
delete rawCommandSet;
rawCommandSet = nullptr;
if (isDatasetPresent(rq))
{
cond = DIMSE_receiveDataSetInMemory(assoc, blockMode, timeout, &presId, &rqDataset, nullptr, nullptr);
if (cond.bad())
{
qDebug() << "DIMSE_receiveDataSetInMemory" << QString::fromLocal8Bit(cond.text());
break;
}
}
dumpIn(rq, rqDataset);
if (upstream)
{
cond = DIMSE_sendMessageUsingMemoryData(upstream, presId, &rq, statusDetail, rqDataset, nullptr, nullptr, &rawCommandSet);
dump("rawCommandSet", rawCommandSet);
delete rawCommandSet;
rawCommandSet = nullptr;
delete statusDetail;
statusDetail = nullptr;
if (cond.bad())
{
qDebug() << "DIMSE_sendMessageUsingMemoryData(upstream) failed" << QString::fromLocal8Bit(cond.text())
<< "presId" << presId;
break;
}
cond = DIMSE_receiveCommand(upstream, blockMode, timeout, &upstreamPresId, &rsp, &statusDetail, &rawCommandSet);
dump("rawCommandSet", rawCommandSet);
delete rawCommandSet;
rawCommandSet = nullptr;
dump("statusDetail", statusDetail);
if (cond.bad())
{
qDebug() << "DIMSE_recv(upstream) failed" << QString::fromLocal8Bit(cond.text());
break;
}
if (rq.CommandField != (rsp.CommandField & ~0x8000))
{
qDebug() << "Mismatched response: rq" << rq.CommandField << "rsp" << rsp.CommandField;
}
if (isDatasetPresent(rsp))
{
cond = DIMSE_receiveDataSetInMemory(upstream, blockMode, timeout, &upstreamPresId, &rspDataset, nullptr, nullptr);
if (cond.bad())
{
qDebug() << "DIMSE_receiveDataSetInMemory(upstream)" << QString::fromLocal8Bit(cond.text());
break;
}
}
}
else
{
/* process command */
switch (rq.CommandField)
{
case DIMSE_C_ECHO_RQ:
cond = handleCEcho(rq, rqDataset, rsp, rspDataset);
break;
case DIMSE_N_GET_RQ:
cond = handleNGet(rq, rqDataset, rsp, rspDataset);
break;
case DIMSE_N_SET_RQ:
cond = handleNSet(rq, rqDataset, rsp, rspDataset);
break;
case DIMSE_N_ACTION_RQ:
cond = handleNAction(rq, rqDataset, rsp, rspDataset);
break;
case DIMSE_N_CREATE_RQ:
cond = handleNCreate(rq, rqDataset, rsp, rspDataset);
break;
case DIMSE_N_DELETE_RQ:
cond = handleNDelete(rq, rqDataset, rsp, rspDataset);
break;
default:
cond = DIMSE_BADCOMMANDTYPE; /* unsupported command */
qDebug() << "Cannot handle command: 0x" << QString::number((unsigned)rq.CommandField, 16);
break;
}
}
if (DIMSE_N_SET_RQ == rq.CommandField
&& QString(rq.msg.NSetRQ.RequestedSOPClassUID).startsWith(UID_BasicGrayscaleImageBoxSOPClass))
{
SOPInstanceUID = QString::fromUtf8(rq.msg.NSetRQ.RequestedSOPInstanceUID);
char uid[100] = {0};
if (forceUniqueStudy)
{
studyInstanceUID = QString::fromUtf8(dcmGenerateUniqueIdentifier(uid, SITE_STUDY_UID_ROOT));
}
if (forceUniqueSeries)
{
seriesInstanceUID = QString::fromUtf8(dcmGenerateUniqueIdentifier(uid, SITE_SERIES_UID_ROOT));
}
storeImage(rqDataset);
}
else
{
if (DIMSE_N_CREATE_RQ == rq.CommandField)
{
if (0 == strcmp(rq.msg.NCreateRQ.AffectedSOPClassUID, UID_BasicFilmSessionSOPClass))
{
studyInstanceUID = QString::fromUtf8(rsp.msg.NCreateRSP.AffectedSOPInstanceUID);
}
else if (0 == strcmp(rq.msg.NCreateRQ.AffectedSOPClassUID, UID_BasicFilmBoxSOPClass))
{
seriesInstanceUID = QString::fromUtf8(rsp.msg.NCreateRSP.AffectedSOPInstanceUID);
}
}
copyItems(rqDataset, sessionDataset);
copyItems(rspDataset, sessionDataset);
}
delete rqDataset;
rqDataset = nullptr;
dumpOut(rsp, rspDataset);
cond = DIMSE_sendMessageUsingMemoryData(assoc, presId, &rsp, statusDetail, rspDataset, nullptr, nullptr, &rawCommandSet);
dump("rawCommandSet", rawCommandSet);
delete rawCommandSet;
rawCommandSet = nullptr;
delete statusDetail;
statusDetail = nullptr;
delete rspDataset;
rspDataset = nullptr;
if (cond.bad())
{
qDebug() << "DIMSE_sendMessageUsingMemoryData" << QString::fromLocal8Bit(cond.text());
break;
}
} /* while */
qDebug() << "Print session is done";
// Close client association
//
if (cond == DUL_PEERREQUESTEDRELEASE)
{
qDebug() << "Association Release";
cond = ASC_acknowledgeRelease(assoc);
}
else if (cond == DUL_PEERABORTEDASSOCIATION)
{
qDebug() << "Association Aborted" << (assoc->params? assoc->params->DULparams.callingPresentationAddress: "");
}
else
{
qDebug() << "DIMSE Failure (aborting association)" << (assoc->params? assoc->params->DULparams.callingPresentationAddress: "");
cond = ASC_abortAssociation(assoc);
}
// close upstream printer association
//
if (upstream)
{
ASC_releaseAssociation(upstream);
}
dropAssociations();
}
OFCondition PrintSCP::handleCEcho(T_DIMSE_Message& rq, DcmDataset *, T_DIMSE_Message& rsp, DcmDataset *&)
{
rsp.CommandField = DIMSE_C_ECHO_RSP;
rsp.msg.CEchoRSP.MessageIDBeingRespondedTo = rq.msg.CEchoRQ.MessageID;
rsp.msg.CEchoRSP.AffectedSOPClassUID[0] = 0;
rsp.msg.CEchoRSP.DataSetType = DIMSE_DATASET_NULL;
rsp.msg.CEchoRSP.DimseStatus = STATUS_Success;
rsp.msg.CEchoRSP.opts = 0;
OFCondition cond = EC_Normal;
return cond;
}
OFCondition PrintSCP::handleNGet(T_DIMSE_Message& rq, DcmDataset *, T_DIMSE_Message& rsp, DcmDataset *& rspDataset)
{
// initialize response message
rsp.CommandField = DIMSE_N_GET_RSP;
rsp.msg.NGetRSP.MessageIDBeingRespondedTo = rq.msg.NGetRQ.MessageID;
rsp.msg.NGetRSP.AffectedSOPClassUID[0] = 0;
rsp.msg.NGetRSP.DimseStatus = STATUS_Success;
rsp.msg.NGetRSP.AffectedSOPInstanceUID[0] = 0;
rsp.msg.NGetRSP.DataSetType = DIMSE_DATASET_NULL;
rsp.msg.NGetRSP.opts = 0;
OFCondition cond = EC_Normal;
QString sopClass(rq.msg.NGetRQ.RequestedSOPClassUID);
if (sopClass == UID_PrinterSOPClass)
{
// Print N-GET
printerNGet(rq, rsp, rspDataset);
}
else
{
qDebug() << "N-GET unsupported for SOP class '" << sopClass << "'";
rsp.msg.NGetRSP.DimseStatus = STATUS_N_NoSuchSOPClass;
}
return cond;
}
OFCondition PrintSCP::handleNSet(T_DIMSE_Message& rq, DcmDataset *, T_DIMSE_Message& rsp, DcmDataset *&)
{
// initialize response message
rsp.CommandField = DIMSE_N_SET_RSP;
rsp.msg.NSetRSP.MessageIDBeingRespondedTo = rq.msg.NSetRQ.MessageID;
rsp.msg.NSetRSP.AffectedSOPClassUID[0] = 0;
rsp.msg.NSetRSP.DimseStatus = STATUS_Success;
rsp.msg.NSetRSP.AffectedSOPInstanceUID[0] = 0;
rsp.msg.NSetRSP.DataSetType = DIMSE_DATASET_NULL;
rsp.msg.NSetRSP.opts = 0;
OFCondition cond = EC_Normal;
return cond;
}
OFCondition PrintSCP::handleNAction(T_DIMSE_Message& rq, DcmDataset *, T_DIMSE_Message& rsp, DcmDataset *&)
{
// initialize response message
rsp.CommandField = DIMSE_N_ACTION_RSP;
rsp.msg.NActionRSP.MessageIDBeingRespondedTo = rq.msg.NActionRQ.MessageID;
rsp.msg.NActionRSP.AffectedSOPClassUID[0] = 0;
rsp.msg.NActionRSP.DimseStatus = STATUS_Success;
rsp.msg.NActionRSP.AffectedSOPInstanceUID[0] = 0;
rsp.msg.NActionRSP.ActionTypeID = rq.msg.NActionRQ.ActionTypeID;
rsp.msg.NActionRSP.DataSetType = DIMSE_DATASET_NULL;
rsp.msg.NActionRSP.opts = O_NACTION_ACTIONTYPEID;
OFCondition cond = EC_Normal;
return cond;
}
OFCondition PrintSCP::handleNCreate(T_DIMSE_Message& rq, DcmDataset *rqDataset, T_DIMSE_Message& rsp, DcmDataset *& rspDataset)
{
// initialize response message
rsp.CommandField = DIMSE_N_CREATE_RSP;
rsp.msg.NCreateRSP.MessageIDBeingRespondedTo = rq.msg.NCreateRQ.MessageID;
rsp.msg.NCreateRSP.AffectedSOPClassUID[0] = 0;
rsp.msg.NCreateRSP.DimseStatus = STATUS_Success;
if (rq.msg.NCreateRQ.opts & O_NCREATE_AFFECTEDSOPINSTANCEUID)
{
// instance UID is provided by SCU
strncpy(rsp.msg.NCreateRSP.AffectedSOPInstanceUID, rq.msg.NCreateRQ.AffectedSOPInstanceUID, sizeof(DIC_UI));
}
else
{
// we generate our own instance UID
dcmGenerateUniqueIdentifier(rsp.msg.NCreateRSP.AffectedSOPInstanceUID);
}
rsp.msg.NCreateRSP.DataSetType = DIMSE_DATASET_NULL;
rsp.msg.NCreateRSP.opts = O_NCREATE_AFFECTEDSOPINSTANCEUID | O_NCREATE_AFFECTEDSOPCLASSUID;
strncpy(rsp.msg.NCreateRSP.AffectedSOPClassUID, rq.msg.NCreateRQ.AffectedSOPClassUID, sizeof(DIC_UI));
OFCondition cond = EC_Normal;
QString sopClass(rq.msg.NCreateRQ.AffectedSOPClassUID);
if (sopClass == UID_BasicFilmSessionSOPClass)
{
// BFS N-CREATE
filmSessionNCreate(rqDataset, rsp, rspDataset);
}
else if (sopClass == UID_BasicFilmBoxSOPClass)
{
// BFB N-CREATE
filmBoxNCreate(rqDataset, rsp, rspDataset);
}
else if (sopClass == UID_PresentationLUTSOPClass)
{
// P-LUT N-CREATE
presentationLUTNCreate(rqDataset, rsp, rspDataset);
}
else
{
qDebug() << "N-CREATE unsupported for SOP class '" << sopClass << "'";
rsp.msg.NCreateRSP.DimseStatus = STATUS_N_NoSuchSOPClass;
rsp.msg.NCreateRSP.opts = 0; // don't include affected SOP instance UID
}
return cond;
}
OFCondition PrintSCP::handleNDelete(T_DIMSE_Message& rq, DcmDataset *, T_DIMSE_Message& rsp, DcmDataset *&)
{
// initialize response message
rsp.CommandField = DIMSE_N_DELETE_RSP;
rsp.msg.NDeleteRSP.MessageIDBeingRespondedTo = rq.msg.NDeleteRQ.MessageID;
rsp.msg.NDeleteRSP.AffectedSOPClassUID[0] = 0;
rsp.msg.NDeleteRSP.DimseStatus = STATUS_Success;
rsp.msg.NDeleteRSP.AffectedSOPInstanceUID[0] = 0;
rsp.msg.NDeleteRSP.DataSetType = DIMSE_DATASET_NULL;
rsp.msg.NDeleteRSP.opts = 0;
OFCondition cond = EC_Normal;
QString sopClass(rq.msg.NDeleteRQ.RequestedSOPClassUID);
if (sopClass == UID_BasicFilmSessionSOPClass)
{
// BFS N-DELETE
filmSessionNDelete(rq, rsp);
}
else if (sopClass == UID_BasicFilmBoxSOPClass)
{
// BFB N-DELETE
filmBoxNDelete(rq, rsp);
}
else if (sopClass == UID_PresentationLUTSOPClass)
{
// P-LUT N-DELETE
presentationLUTNDelete(rq, rsp);
}
else
{
qDebug() << "N-DELETE unsupported for SOP class '" << sopClass << "'";
rsp.msg.NDeleteRSP.DimseStatus = STATUS_N_NoSuchSOPClass;
}
return cond;
}
void PrintSCP::printerNGet(T_DIMSE_Message& rq, T_DIMSE_Message& rsp, DcmDataset *& rspDataset)
{
QString printerInstance(UID_PrinterSOPInstance);
if (printerInstance == rq.msg.NGetRQ.RequestedSOPInstanceUID)
{
rsp.msg.NSetRSP.DataSetType = DIMSE_DATASET_PRESENT;
rspDataset = new DcmDataset;
// By default, send only PrinterStatus & PrinterStatusInfo
//
if (rq.msg.NGetRQ.ListCount == 0)
{
rspDataset->putAndInsertString(DCM_PrinterStatus, DEFAULT_printerStatus);
rspDataset->putAndInsertString(DCM_PrinterStatusInfo, DEFAULT_printerStatusInfo);
}
else
{
QUtf8Settings settings;
settings.beginGroup(printer);
QMap<DcmTag, QVariant> info;
auto size = settings.beginReadArray("info");
for (int idx = 0; idx < size; ++idx)
{
settings.setArrayIndex(idx);
auto key = settings.value("key").toString();
DcmTag tag;
if (DcmTag::findTagFromName(key.toUtf8(), tag).good())
{
info[tag] = settings.value("value");
}
else
{
qDebug() << "Bad DICOM tag" << key << "in" << printer << "info" << idx;
}
}
settings.endArray();
settings.endGroup();
for (int i = 0; i < rq.msg.NGetRQ.ListCount / 2; ++i)
{
auto group = rq.msg.NGetRQ.AttributeIdentifierList[i*2];
auto element = rq.msg.NGetRQ.AttributeIdentifierList[i*2 + 1];
if (element == 0x0000)
{
// Group length
//
continue;
}
if (group == DCM_PrinterStatus.getGroup())
{
if (element == DCM_PrinterStatus.getElement())
{
rspDataset->putAndInsertString(DCM_PrinterStatus, DEFAULT_printerStatus);
continue;
}
if (element == DCM_PrinterStatusInfo.getElement())
{
rspDataset->putAndInsertString(DCM_PrinterStatusInfo, DEFAULT_printerStatusInfo);
continue;
}
}
// Some unknown element was requested.
//
DcmTag tag(group, element);
if (!info.contains(tag))
{