File: dulparse.cc

package info (click to toggle)
dcmtk 3.6.9-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 95,648 kB
  • sloc: ansic: 426,874; cpp: 318,177; makefile: 6,401; sh: 4,341; yacc: 1,026; xml: 482; lex: 321; perl: 277
file content (967 lines) | stat: -rw-r--r-- 35,969 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
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
/*
 *
 *  Copyright (C) 1994-2024, OFFIS e.V.
 *  All rights reserved.  See COPYRIGHT file for details.
 *
 *  This software and supporting documentation were partly developed by
 *
 *    OFFIS e.V.
 *    R&D Division Health
 *    Escherweg 2
 *    D-26121 Oldenburg, Germany
 *
 *  For further copyrights, see the following paragraphs.
 *
 */

/*
          Copyright (C) 1993, 1994, RSNA and Washington University

          The software and supporting documentation for the Radiological
          Society of North America (RSNA) 1993, 1994 Digital Imaging and
          Communications in Medicine (DICOM) Demonstration were developed
          at the
                  Electronic Radiology Laboratory
                  Mallinckrodt Institute of Radiology
                  Washington University School of Medicine
                  510 S. Kingshighway Blvd.
                  St. Louis, MO 63110
          as part of the 1993, 1994 DICOM Central Test Node project for, and
          under contract with, the Radiological Society of North America.

          THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND NEITHER RSNA NOR
          WASHINGTON UNIVERSITY MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
          PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
          USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
          SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
          THE SOFTWARE IS WITH THE USER.

          Copyright of the software and supporting documentation is
          jointly owned by RSNA and Washington University, and free access
          is hereby granted as a license to use this software, copy this
          software and prepare derivative works based upon this software.
          However, any distribution of this software source code or
          supporting documentation or derivative works (source code and
          supporting documentation) must include the three paragraphs of
          the copyright notice.
*/

/*
**          DICOM 93
**        Electronic Radiology Laboratory
**      Mallinckrodt Institute of Radiology
**    Washington University School of Medicine
**
** Module Name(s):  parseAssociate
**                  parseDebug
** Author, Date:    Stephen M. Moore, 15-Apr-93
** Intent:          This file contains functions for parsing Dicom
**                  Upper Layer (DUL) Protocol Data Units (PDUs)
**                  into logical in-memory structures.
*/


#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/ofstd/ofstd.h"  // for OFStandard::safeSubtract() and safeAdd()
#include "dcmtk/dcmnet/dicom.h"
#include "dcmtk/dcmnet/cond.h"
#include "dcmtk/dcmnet/lst.h"
#include "dcmtk/dcmnet/dul.h"
#include "dcmtk/dcmnet/diutil.h"
#include "dcmtk/dcmnet/dulstruc.h"
#include "dcmtk/dcmnet/helpers.h"
#include "dulpriv.h"
#include "dcmtk/ofstd/ofconsol.h"

static OFCondition
parseSubItem(DUL_SUBITEM * subItem, unsigned char *buf,
             unsigned long *itemLength, unsigned long availData);
static OFCondition
parsePresentationContext(unsigned char type,
                         PRV_PRESENTATIONCONTEXTITEM * context,
                         unsigned char *buf, unsigned long *itemLength,
                         unsigned long availData);
static OFCondition
parseUserInfo(DUL_USERINFO * userInfo,
              unsigned char *buf, unsigned long *itemLength,
              unsigned char typeRQorAC, unsigned long availData);
static OFCondition
parseMaxPDU(DUL_MAXLENGTH * max, unsigned char *buf,
            unsigned long *itemLength, unsigned long availData);
static OFCondition
    parseDummy(unsigned char *buf, unsigned long *itemLength,
            unsigned long availData);
static OFCondition
parseSCUSCPRole(PRV_SCUSCPROLE * role, unsigned char *buf,
                unsigned long *length, unsigned long availData);
static void trim_trailing_spaces(char *s);


static OFCondition
parseExtNeg(SOPClassExtendedNegotiationSubItem* extNeg, unsigned char *buf,
            unsigned long *length, unsigned long availData);

static OFCondition
makeLengthError(const char *pdu, unsigned long bufSize, unsigned long minSize = 0,
        unsigned long length = 0);

static OFCondition
makeUnderflowError(const char *pdu, unsigned long minuend, unsigned long subtrahend);

/* parseAssociate
**
** Purpose:
**      Parse the buffer (read from the socket) and extract an Associate
**      PDU from it.
**
** Parameter Dictionary:
**      buf             Buffer holding the PDU in the stream format
**      pduLength       Length of the buffer
**      assoc           The Associate PDU to be extracted
**                      (returned to the caller)
**
** Return Values:
**
**      DUL_ILLEGALPDU
**      DUL_LISTERROR
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

OFCondition
parseAssociate(unsigned char *buf, unsigned long pduLength,
               PRV_ASSOCIATEPDU * assoc)
{
    OFCondition cond = EC_Normal;
    unsigned char
        type;
    unsigned long
        itemLength;
    PRV_PRESENTATIONCONTEXTITEM
        * context;

    (void) memset(assoc, 0, sizeof(*assoc));
    // Check if the PDU actually is long enough for the fields we read
    if (pduLength < 2 + 2 + 16 + 16 + 32)
        return makeLengthError("associate PDU", pduLength, 2 + 2 + 16 + 16 + 32);

    assoc->type = *buf++;
    assoc->rsv1 = *buf++;
    EXTRACT_LONG_BIG(buf, assoc->length);
    buf += 4;

    EXTRACT_SHORT_BIG(buf, assoc->protocol);
    buf += 2;
    pduLength -= 2;
    if ((assoc->protocol & DUL_PROTOCOL) == 0)
    {
        char buffer[256];
        OFStandard::snprintf(buffer, sizeof(buffer), "DUL Unsupported peer protocol %04x; expected %04x in %s", assoc->protocol, DUL_PROTOCOL, "parseAssociate");
        return makeDcmnetCondition(DULC_UNSUPPORTEDPEERPROTOCOL, OF_error, buffer);
    }
    assoc->rsv2[0] = *buf++;
    pduLength--;
    assoc->rsv2[1] = *buf++;
    pduLength--;
    (void) strncpy(assoc->calledAPTitle, (char *) buf, 16);
    assoc->calledAPTitle[16] = '\0';
    trim_trailing_spaces(assoc->calledAPTitle);

    buf += 16;
    pduLength -= 16;
    (void) strncpy(assoc->callingAPTitle, (char *) buf, 16);
    assoc->callingAPTitle[16] = '\0';
    trim_trailing_spaces(assoc->callingAPTitle);
    buf += 16;
    pduLength -= 16;
    (void) memcpy(assoc->rsv3, buf, 32);
    buf += 32;
    pduLength -= 32;

    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::DEBUG_LOG_LEVEL)) {
        const char *s;
        DCMNET_DEBUG("Parsing an A-ASSOCIATE PDU");
        if (assoc->type == DUL_TYPEASSOCIATERQ)
            s = "A-ASSOCIATE RQ";
        else if (assoc->type == DUL_TYPEASSOCIATEAC)
            s = "A-ASSOCIATE AC";
        else
            s = "Unknown: Programming bug in parseAssociate";

/*      If we hit the "Unknown type", there is a programming bug somewhere.
**      This function is only supposed to parse A-ASSOCIATE PDUs and
**      expects its input to have been properly screened.
*/
        DCMNET_TRACE("PDU type: "
            << STD_NAMESPACE hex << ((unsigned int)assoc->type)
            << STD_NAMESPACE dec << " (" << s << "), PDU Length: " << assoc->length << OFendl
            << "DICOM Protocol: "
            << STD_NAMESPACE hex << assoc->protocol
            << STD_NAMESPACE dec << OFendl
            << "Called AP Title:  " << assoc->calledAPTitle << OFendl
            << "Calling AP Title: " << assoc->callingAPTitle);
    }
    if ((assoc->presentationContextList = LST_Create()) == NULL) return EC_MemoryExhausted;
    if ((assoc->userInfo.SCUSCPRoleList = LST_Create()) == NULL) return EC_MemoryExhausted;
    while ((cond.good()) && (pduLength > 0))
    {
        type = *buf;
        DCMNET_TRACE("Parsing remaining " << pduLength << " bytes of A-ASSOCIATE PDU" << OFendl
                << "Next item type: "
                << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << ((unsigned int)type));
        switch (type) {
        case DUL_TYPEAPPLICATIONCONTEXT:
            cond = parseSubItem(&assoc->applicationContext,
                                buf, &itemLength, pduLength);
            if (cond.good())
            {
                buf += itemLength;
                if (!OFStandard::safeSubtract(pduLength, itemLength, pduLength))
                {
                    cond = makeUnderflowError("Application Context item", pduLength, itemLength);
                }
                else
                {
                    DCMNET_TRACE("Successfully parsed Application Context");
                }
            }
            break;
        case DUL_TYPEPRESENTATIONCONTEXTRQ:
        case DUL_TYPEPRESENTATIONCONTEXTAC:
            context = (PRV_PRESENTATIONCONTEXTITEM*)malloc(sizeof(PRV_PRESENTATIONCONTEXTITEM));
            if (context != NULL)
            {
                (void) memset(context, 0, sizeof(*context));
                cond = parsePresentationContext(type, context, buf, &itemLength, pduLength);
                if (cond.bad())
                {
                    free(context);
                }
                else
                {
                    buf += itemLength;
                    if (!OFStandard::safeSubtract(pduLength, itemLength, pduLength))
                    {
                        cond =  makeUnderflowError("Presentation Context item", pduLength, itemLength);
                    }
                    else
                    {
                        LST_Enqueue(&assoc->presentationContextList, (LST_NODE*)context);
                        DCMNET_TRACE("Successfully parsed Presentation Context");
                    }
                }
            }
            else
            {
                cond = EC_MemoryExhausted;
            }
            break;
        case DUL_TYPEUSERINFO:
            // parse user info, which can contain several sub-items like User
            // Identity Negotiation or SOP Class Extended Negotiation
            cond = parseUserInfo(&assoc->userInfo, buf, &itemLength, assoc->type, pduLength);
            if (cond.good())
            {
                buf += itemLength;
                if (!OFStandard::safeSubtract(pduLength, itemLength, pduLength))
                {
                    cond = makeUnderflowError("User Information item", pduLength, itemLength);
                }
                else
                {
                    DCMNET_TRACE("Successfully parsed User Information");
                }
            }
            break;
        default:
            cond = parseDummy(buf, &itemLength, pduLength);
            if (cond.good())
            {
                buf += itemLength;
                if (!OFStandard::safeSubtract(pduLength, itemLength, pduLength))
                {
                    cond = makeUnderflowError("unknown item type", pduLength, itemLength);
                }
            }
            break;
        }
    }
    if (cond.bad())
    {
      destroyAssociatePDUPresentationContextList(&assoc->presentationContextList);
      destroyUserInformationLists(&assoc->userInfo);
    }
    return cond;
}


/* ============================================================
**  Private functions (to this module) defined below.
*/

/* parseSubItem
**
** Purpose:
**      Parse the buffer and extract the subitem structure
**
** Parameter Dictionary:
**      subItem         The subitem structure to be extracted
**      buf             Buffer to be parsed
**      itemLength      Length of the subitem extracted
**
** Return Values:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
parseSubItem(DUL_SUBITEM * subItem, unsigned char *buf,
             unsigned long *itemLength, unsigned long availData)
{
    // Need at least 4 bytes (type, rsv1, two bytes length field)
    if (availData < 4)
        return makeLengthError("subitem", availData, 4);

    subItem->type = *buf++;
    subItem->rsv1 = *buf++;
    EXTRACT_SHORT_BIG(buf, subItem->length);
    buf += 2;

    // Maximum allowed size and our buffer size is DICOM_UI_LENGTH
    if (subItem->length > DICOM_UI_LENGTH)
    {
        char buffer[256];
        OFStandard::snprintf(buffer, sizeof(buffer), "DUL illegal subitem length %d. Maximum allowed size is %d.",
               subItem->length, DICOM_UI_LENGTH);
        return makeDcmnetCondition(DULC_ILLEGALPDULENGTH, OF_error, buffer);
    }

    // Does the subitem claim to be larger than the containing PDU?
    if (availData - 4 < subItem->length)
        return makeLengthError("subitem", availData, 0, subItem->length);

    (void) memcpy(subItem->data, buf, subItem->length);
    subItem->data[subItem->length] = '\0';

    *itemLength = 2 + 2 + subItem->length;

    DCMNET_TRACE("Subitem parse: Type "
            << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << ((unsigned int)subItem->type)
            << STD_NAMESPACE dec << ", Length " << STD_NAMESPACE setw(4) << (int)subItem->length
            << ", Content: " << subItem->data);
    return EC_Normal;
}


/* parsePresentationContext
**
** Purpose:
**      Parse the buffer and extract the presentation context.
**
** Parameter Dictionary:
**      context         The presentation context that is to be extracted
**      buf             The buffer to be parsed
**      itemLength      Total length of the presentation context that is
**                      extracted
**
** Return Values:
**
**      DUL_ILLEGALPDU
**      DUL_LISTERROR
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
parsePresentationContext(unsigned char type,
                  PRV_PRESENTATIONCONTEXTITEM * context, unsigned char *buf,
                         unsigned long *itemLength, unsigned long availData)
{
    unsigned long
        length;
    unsigned long
        presentationLength;
    OFCondition cond = EC_Normal;
    DUL_SUBITEM
        * subItem;

    // We need at least 8 bytes, anything smaller would be reading past the end
    if (availData < 8)
        return makeLengthError("presentation context", availData, 8);

    if ((context->transferSyntaxList = LST_Create()) == NULL) return EC_MemoryExhausted;

    *itemLength = 0;
    context->type = *buf++;
    context->rsv1 = *buf++;
    EXTRACT_SHORT_BIG(buf, context->length);
    buf += 2;
    context->contextID = *buf++;
    context->rsv2 = *buf++;
    context->result = *buf++;
    context->rsv3 = *buf++;

    length = context->length;
    *itemLength = 2 + 2 + length;

    // Does the length field claim to be larger than the containing PDU?
    if (availData - 4 < length || length < 4)
        return makeLengthError("presentation context", availData, 4, length);

    DCMNET_TRACE("Parsing Presentation Context: ("
            << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << (unsigned int)context->type
            << STD_NAMESPACE dec << "), Length: " << (unsigned long)context->length << OFendl
            << "Presentation Context ID: "
            << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << (unsigned int)context->contextID
            << STD_NAMESPACE dec);
    presentationLength = length - 4;
    if (!((type == DUL_TYPEPRESENTATIONCONTEXTAC) &&
          (context->result != DUL_PRESENTATION_ACCEPT))) {
        while (presentationLength > 0) {
            DCMNET_TRACE("Parsing remaining " << presentationLength << " bytes of Presentation Context" << OFendl
                    << "Next item type: "
                    << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << (unsigned int)*buf);
            switch (*buf) {
            case DUL_TYPEABSTRACTSYNTAX:
                cond = parseSubItem(&context->abstractSyntax, buf, &length, presentationLength);
                if (cond.bad())
                    return cond;

                buf += length;
                if (!OFStandard::safeSubtract(presentationLength, length, presentationLength))
                  return makeUnderflowError("Abstract Syntax", presentationLength, length);
                DCMNET_TRACE("Successfully parsed Abstract Syntax");
                break;
            case DUL_TYPETRANSFERSYNTAX:
                subItem = (DUL_SUBITEM*)malloc(sizeof(DUL_SUBITEM));
                if (subItem == NULL) return EC_MemoryExhausted;
                cond = parseSubItem(subItem, buf, &length, presentationLength);
                if (cond.bad())
                {
                    free(subItem);
                    return cond;
                }
                LST_Enqueue(&context->transferSyntaxList, (LST_NODE*)subItem);
                buf += length;
                if (!OFStandard::safeSubtract(presentationLength, length, presentationLength))
                  return makeUnderflowError("Transfer Syntax", presentationLength, length);
                DCMNET_TRACE("Successfully parsed Transfer Syntax");
                break;
            default:
                cond = parseDummy(buf, &length, presentationLength);
                if (cond.bad())
                    return cond;
                buf += length;
                if (!OFStandard::safeSubtract(presentationLength, length, presentationLength))
                  return makeUnderflowError("unknown presentation context type", presentationLength, length);
                break;
            }
        }
    }
    return EC_Normal;
}



/* parseUserInfo
**
** Purpose:
**      Parse the buffer and extract the user info structure
**
** Parameter Dictionary:
**      userInfo        Structure to hold the extracted user info information
**      buf             The buffer that is to be parsed
**      itemLength      Length of structure extracted.
**
** Return Values:
**
**      DUL_ILLEGALPDU
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static OFCondition
parseUserInfo(DUL_USERINFO * userInfo,
              unsigned char *buf,
              unsigned long *itemLength,
              unsigned char typeRQorAC,
              unsigned long availData /* bytes left for in this PDU */)
{
    unsigned short userLength;
    unsigned long length;
    OFCondition cond = EC_Normal;
    PRV_SCUSCPROLE *role;
    SOPClassExtendedNegotiationSubItem *extNeg = NULL;
    UserIdentityNegotiationSubItem *usrIdent = NULL;

    // minimum allowed size is 4 byte (case where the length of the user data is 0),
    // else we read past the buffer end
    if (availData < 4)
        return makeLengthError("user info", availData, 4);

    // skip item type (50H) field
    userInfo->type = *buf++;
    // skip unused ("reserved") field
    userInfo->rsv1 = *buf++;
    // get and remember announced length of user data
    EXTRACT_SHORT_BIG(buf, userInfo->length);
    // .. and skip over the two length field bytes
    buf += 2;

    // userLength contains announced length of full user item structure,
    // will be used here to count down the available data later
    userLength = userInfo->length;
    // itemLength contains full length of the user item including the 4 bytes extra header (type, reserved + 2 for length)
    *itemLength = userLength + 4;

    // does this item claim to be larger than the available data?
    if (availData < *itemLength)
        return makeLengthError("user info", availData, 0, userLength);

    DCMNET_TRACE("Parsing user info field ("
            << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << (unsigned int)userInfo->type
            << STD_NAMESPACE dec << "), Length: " << (unsigned long)userInfo->length);
    // parse through different types of user items as long as we have data
    while (userLength > 0) {
        DCMNET_TRACE("Parsing remaining " << (long)userLength << " bytes of User Information" << OFendl
                << "Next item type: "
                << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << (unsigned int)*buf);
        switch (*buf) {
        case DUL_TYPEMAXLENGTH:
            cond = parseMaxPDU(&userInfo->maxLength, buf, &length, userLength);
            if (cond.bad())
                return cond;
            buf += length;
            if (!OFStandard::safeSubtract(userLength, OFstatic_cast(short unsigned int, length), userLength))
              return makeLengthError("maximum length sub-item", userLength, length);
            DCMNET_TRACE("Successfully parsed Maximum PDU Length");
            break;
        case DUL_TYPEIMPLEMENTATIONCLASSUID:
            cond = parseSubItem(&userInfo->implementationClassUID,
                                buf, &length, userLength);
            if (cond.bad())
                return cond;
            buf += length;
            if (!OFStandard::safeSubtract(userLength, OFstatic_cast(short unsigned int, length), userLength))
              return makeLengthError("Implementation Class UID sub-item", userLength, length);
            break;

        case DUL_TYPEASYNCOPERATIONS:
            cond = parseDummy(buf, &length, userLength);
            if (cond.bad())
                return cond;
            buf += length;
            if (!OFStandard::safeSubtract(userLength, OFstatic_cast(short unsigned int, length), userLength))
              return makeLengthError("asynchronous operation user item type", userLength, length);
            break;
        case DUL_TYPESCUSCPROLE:
            role = (PRV_SCUSCPROLE*)malloc(sizeof(PRV_SCUSCPROLE));
            if (role == NULL) return EC_MemoryExhausted;
            cond = parseSCUSCPRole(role, buf, &length, userLength);
            if (cond.bad())
            {
                free(role);
                return cond;
            }
            LST_Enqueue(&userInfo->SCUSCPRoleList, (LST_NODE*)role);
            buf += length;
            if (!OFStandard::safeSubtract(userLength, OFstatic_cast(short unsigned int, length), userLength))
              return makeLengthError("SCP/SCU Role Selection sub-item", userLength, length);
            break;
        case DUL_TYPEIMPLEMENTATIONVERSIONNAME:
            cond = parseSubItem(&userInfo->implementationVersionName,
                                buf, &length, userLength);
            if (cond.bad()) return cond;
            buf += length;
            if (!OFStandard::safeSubtract(userLength, OFstatic_cast(short unsigned int, length), userLength))
              return makeLengthError("Implementation Version Name structure", userLength, length);
            break;

        case DUL_TYPESOPCLASSEXTENDEDNEGOTIATION:
            /* parse an extended negotiation sub-item */
            extNeg = new SOPClassExtendedNegotiationSubItem;
            if (extNeg == NULL)  return EC_MemoryExhausted;
            cond = parseExtNeg(extNeg, buf, &length, userLength);
            if (cond.bad()) return cond;
            if (userInfo->extNegList == NULL)
            {
                userInfo->extNegList = new SOPClassExtendedNegotiationSubItemList;
                if (userInfo->extNegList == NULL)  return EC_MemoryExhausted;
            }
            userInfo->extNegList->push_back(extNeg);
            buf += length;
            if (!OFStandard::safeSubtract(userLength, OFstatic_cast(short unsigned int, length), userLength))
              return makeLengthError("SOP Class Extended Negotiation sub-item", userLength, length);
            break;

        case DUL_TYPENEGOTIATIONOFUSERIDENTITY_REQ:
        case DUL_TYPENEGOTIATIONOFUSERIDENTITY_ACK:
          if (typeRQorAC == DUL_TYPEASSOCIATERQ)
            usrIdent = new UserIdentityNegotiationSubItemRQ();
          else // assume DUL_TYPEASSOCIATEAC
            usrIdent = new UserIdentityNegotiationSubItemAC();
          if (usrIdent == NULL) return EC_MemoryExhausted;
          cond = usrIdent->parseFromBuffer(buf, length /*return value*/, userLength);
          if (cond.bad())
          {
            delete usrIdent;
            return cond;
          }
          userInfo->usrIdent = usrIdent;
          buf += length;
          if (!OFStandard::safeSubtract(userLength, OFstatic_cast(short unsigned int, length), userLength))
            return makeLengthError("User Identity sub-item", userLength, length);
          break;
        default:
            // we hit an unknown user item that is not defined in the standard
            // or still unknown to DCMTK
            cond = parseDummy(buf, &length /* returns bytes "handled" by parseDummy */, userLength /* data available in bytes for user item */);
            if (cond.bad())
              return cond;
            // skip the bytes read
            buf += length;
            // subtract bytes of parsed data from available data bytes
            if (OFstatic_cast(unsigned short, length) != length
                || !OFStandard::safeSubtract(userLength, OFstatic_cast(unsigned short, length), userLength))
              return makeUnderflowError("unknown user item", userLength, length);
            break;
        }
    }

    return EC_Normal;
}



/* parseMaxPDU
**
** Purpose:
**      Parse the buffer and extract the Max PDU structure.
**
** Parameter Dictionary:
**      max             The structure to hold the Max PDU item
**      buf             The buffer that is to be parsed (input/output value)
**      itemLength      Length of structure extracted (output value)
**      availData       Number of bytes announced to be available for this sub item (input value)
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
parseMaxPDU(DUL_MAXLENGTH * max, unsigned char *buf,
            unsigned long *itemLength, unsigned long availData)
{
    // We want to read 8 bytes of data, is there enough data?
    if (availData < 8)
        return makeLengthError("Max PDU", availData, 8);

    max->type = *buf++;
    max->rsv1 = *buf++;
    EXTRACT_SHORT_BIG(buf, max->length);
    buf += 2;
    EXTRACT_LONG_BIG(buf, max->maxLength);
    *itemLength = 2 + 2 + max->length;

    if (max->length != 4)
        DCMNET_WARN("Invalid length (" << max->length << ") for maximum length item, must be 4");

    // Is there less data than the length field claims there is?
    if (availData - 4 < max->length)
        return makeLengthError("Max PDU", availData, 0, max->length);

    DCMNET_TRACE("Maximum PDU Length: " << (unsigned long)max->maxLength);

    return EC_Normal;
}

/* parseDummy
**
** Purpose:
**      Parse the buffer to extract just a dummy structure of length
**      User Length
**
** Parameter Dictionary:
**      buf             The buffer that is to be parsed (input/output value)
**      itemLength      Length of structure extracted (output value)
*       availData       Number of bytes announced to be available for this sub item (input value)
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
parseDummy(unsigned char *buf, unsigned long *itemLength, unsigned long availData)
{
    // Is there enough data for the length field?
    if (availData < 4)
        return makeLengthError("dummy item", availData, 4);

    // Get announced length of this sub-item and skip over the bytes read
    // 1 byte item-type (e.g. 58H for User Identity Negotiation), 1 byte reserved,
    // and 2 bytes length field
    unsigned short userLength;
    buf++;
    buf++;
    EXTRACT_SHORT_BIG(buf, userLength);
    buf += 2;

    // Return full length (announced + 4 extra bytes)
    *itemLength = userLength + 4;

    // Is there less data than the length field claims there is?
    if (availData - 4 < userLength)
        return makeLengthError("dummy item", availData, 0, userLength);

    return EC_Normal;
}

/* parseSCUSCPRole
**
** Purpose:
**      Parse the buffer and extract the SCU-SCP role list
**
** Parameter Dictionary:
**      role            The structure to hold the SCU-SCP role list
**      buf             The buffer that is to be parsed (input/output value)
**      itemLength      Length of structure extracted (output value)
**      availData       Number of bytes announced to be available for this sub item (input value)
**
** Return Values:
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/
static OFCondition
parseSCUSCPRole(PRV_SCUSCPROLE * role, unsigned char *buf,
                unsigned long *length, unsigned long availData)
{
    unsigned short
        UIDLength;

    // We need at least 8 bytes of data, else we read past the end of buf
    if (availData < 8)
        return makeLengthError("SCU-SCP role list", availData, 8);

    role->type = *buf++;
    role->rsv1 = *buf++;
    EXTRACT_SHORT_BIG(buf, role->length);
    buf += 2;

    EXTRACT_SHORT_BIG(buf, UIDLength);
    buf += 2;

    // Check if all the length fields are valid (we have the minimum needed
    // number of bytes, no field is larger than its surrounding field).
    if (availData - 4 < role->length)
        return makeLengthError("SCU-SCP role list", availData, 0, role->length);
    if (role->length < 4)
        return makeLengthError("SCU-SCP role list UID", role->length, 4);
    if (role->length - 4 < UIDLength)
        return makeLengthError("SCU-SCP role list UID", role->length, 0, UIDLength);

    if (UIDLength > DICOM_UI_LENGTH)
    {
      DCMNET_WARN("Provided role SOP Class UID length " << UIDLength
            << " is larger than maximum allowed UID length " << DICOM_UI_LENGTH << " (will use 64 bytes max)");
      UIDLength = DICOM_UI_LENGTH;
    }

    // The UID in the source buffer is not necessarily null terminated. Copy with memcpy
    // and add a zero byte. We have already checked that there is enough data available
    // in the source source buffer and enough space in the target buffer.
    (void) memcpy(role->SOPClassUID, buf, UIDLength);
    role->SOPClassUID[UIDLength] = '\0';

    buf += UIDLength;
    role->SCURole = *buf++;
    role->SCPRole = *buf++;

    *length = 2 + 2 + role->length;

    DCMNET_TRACE("Subitem parse: Type "
            << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << (unsigned int)role->type
            << STD_NAMESPACE dec << ", Length " << STD_NAMESPACE setw(4) << (int)role->length
            << ", Content: SOP Class: " << role->SOPClassUID << " SCU: " << (int)role->SCURole << " SCP: " << (int)role->SCPRole);
    return EC_Normal;
}

/* parseExtNeg
**
** Purpose:
**      Parse the buffer and extract the extended negotiation item
**
** Parameter Dictionary:
**      extNeg          The structure to hold the extended negotiation item
**      buf             The buffer that is to be parsed (input/output value)
**      itemLength      Length of structure extracted (output value)
**      availData       Number of bytes announced to be available for this sub item (input value)
**
** Return Values:
**
*/
static OFCondition
parseExtNeg(SOPClassExtendedNegotiationSubItem* extNeg, unsigned char *buf,
            unsigned long *length, unsigned long availData)
{
    unsigned char *bufStart = buf;

    // An extended negotiation item has to be at least 6 bytes large
    if (availData < 6)
        return makeLengthError("extended negotiation", availData, 6);

    extNeg->itemType = *buf++;
    extNeg->reserved1 = *buf++;
    EXTRACT_SHORT_BIG(buf, extNeg->itemLength);
    buf += 2;

    EXTRACT_SHORT_BIG(buf, extNeg->sopClassUIDLength);
    buf += 2;

    // Check if all the length fields are valid (we have the minimum needed
    // number of bytes, no field is larger than its surrounding field).
    if (availData - 4 < extNeg->itemLength)
        return makeLengthError("extended negotiation", availData, 0, extNeg->itemLength);
    if (extNeg->itemLength < 2)
        return makeLengthError("extended negotiation item", availData, 2);
    if (extNeg->itemLength - 2 < extNeg->sopClassUIDLength)
        return makeLengthError("extended negotiation item", extNeg->itemLength, 0, extNeg->sopClassUIDLength);

    extNeg->sopClassUID.append((const char*)buf, extNeg->sopClassUIDLength);
    buf += extNeg->sopClassUIDLength;

    *length = 2 + 2 + extNeg->itemLength;

    int remain = (int)(*length - (buf - bufStart));

    extNeg->serviceClassAppInfoLength = OFstatic_cast(unsigned short, remain);
    extNeg->serviceClassAppInfo = new unsigned char[remain];
    for (int i=0; i<remain; i++) {
        extNeg->serviceClassAppInfo[i] = *buf++;
    }

    if (DCM_dcmnetLogger.isEnabledFor(OFLogger::TRACE_LOG_LEVEL)) {
        DCMNET_TRACE("ExtNeg Subitem parse: Type "
            << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << OFstatic_cast(unsigned int, extNeg->itemType)
            << STD_NAMESPACE dec << ", Length " << STD_NAMESPACE setw(4) << (int)extNeg->itemLength
            << ", SOP Class: " << extNeg->sopClassUID.c_str());

        OFOStringStream str;
        str << "   values: ";
        for (int j=0; j<extNeg->serviceClassAppInfoLength; j++) {
            str << STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(2) << extNeg->serviceClassAppInfo[j]
                << STD_NAMESPACE dec << " ";
        }
        str << OFStringStream_ends;
        OFSTRINGSTREAM_GETOFSTRING(str, res)
        DCMNET_TRACE(res);
    }

    return EC_Normal;
}

/* makeLengthError
 *
 * This function is used to generate the OFCondition code for an invalid field
 * length in a PDU.
 *
 * @param pdu The name of the field or PDU which got an invalid length field.
 * @param bufSize The size of the buffer that we received.
 * @param minSize The minimum size that a 'pdu' has to have.
 * @param length The length as given by the length field.
 */
static OFCondition
makeLengthError(const char *pdu, unsigned long bufSize, unsigned long minSize,
        unsigned long length)
{
    OFStringStream stream;
    stream << "DUL Illegal " << pdu << ". Got " << bufSize << " bytes of data";
    if (length != 0)
        stream << " with a length field of " << length << " (data before length field is not included in length field)";
    if (minSize != 0)
        stream << ". The minimum allowed size is " << minSize;
    stream << "." << OFStringStream_ends;

    OFCondition ret;
    OFSTRINGSTREAM_GETSTR(stream, tmpString)
    ret = makeDcmnetCondition(DULC_ILLEGALPDULENGTH, OF_error, tmpString);
    OFSTRINGSTREAM_FREESTR(tmpString)
    return ret;
}

/* makeUnderflowError
 *
 * This function is used to generate the OFCondition code if an underflow
 * computation has been detected.
 *
 * @param pdu The name of the field or PDU which caused the invalid computation
 * @param minuend The field (probably length) subtracted from
 * @param subtrahend The number subtracted from minuend
 */
static OFCondition
makeUnderflowError(const char *pdu, unsigned long minuend,
        unsigned long subtrahend)
{
  OFStringStream stream;
  stream << "DUL Illegal " << pdu << ". Got " << minuend << " bytes of data and told to subtract " << subtrahend << " bytes of data";
  stream << "." << OFStringStream_ends;

  OFCondition ret;
  OFSTRINGSTREAM_GETSTR(stream, tmpString)
  ret = makeDcmnetCondition(DULC_INCORRECTBUFFERLENGTH, OF_error, tmpString);
  OFSTRINGSTREAM_FREESTR(tmpString)
  return ret;
}


/* trim_trailing_spaces
**
** Purpose:
**      trim trailing spaces
**
** Parameter Dictionary:
**      s       The character string from which the trailing spaces are to be
**              removed.
**
** Return Values:
**      None
**
** Notes:
**
** Algorithm:
**      Description of the algorithm (optional) and any other notes.
*/

static void
trim_trailing_spaces(char *s)
{
    char
       *p;

    p = s;
    while (*p != '\0')
        p++;

    if (p == s)
        return;

    p--;
    while (p >= s && *p == ' ')
        *p-- = '\0';
}