File: requests.c

package info (click to toggle)
ctn 3.2.0~dfsg-8
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 16,924 kB
  • sloc: ansic: 179,652; makefile: 7,006; java: 1,863; csh: 1,067; yacc: 523; sh: 424; cpp: 394; sql: 389; lex: 170
file content (999 lines) | stat: -rw-r--r-- 26,331 bytes parent folder | download
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
/*
          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.
*/
/* Copyright marker.  Copyright will be inserted above.  Do not remove */
/*
**				DICOM 94
**		     Electronic Radiology Laboratory
**		   Mallinckrodt Institute of Radiology
**		Washington University School of Medicine
**
** Module Name(s):
** Author, Date:	Stephen Moore, 11-Feb-94
** Intent:
** Last Update:		$Author: smm $, $Date: 2002-12-13 15:20:17 $
** Source File:		$RCSfile: requests.c,v $
** Revision:		$Revision: 1.16 $
** Status:		$State: Exp $
*/

static char rcsid[] = "$Revision: 1.16 $ $RCSfile: requests.c,v $";

#include "ctn_os.h"

#if 0
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#ifdef _MSC_VER
#include <windows.h>
#endif
#endif

#include "dicom.h"
#include "condition.h"
#include "lst.h"
#include "dicom_uids.h"
#include "dulprotocol.h"
#include "dicom_objects.h"
#include "dicom_ie.h"
#include "dicom_messages.h"
#include "dicom_services.h"
#ifdef CTN_MULTIBYTE
#include "tblmb.h"
#include "idbmb.h"
#else
#include "tbl.h"
#include "idb.h"
#endif
#include "manage.h"
#include "fis.h"
#include "copy.h"

#include "image_archive.h"
#include "find.h"
#include "move.h"
#include "cget.h"
#include "naction.h"
#include "gq.h"
#include "iqueues.h"

extern char *controlDatabase;
extern CTNBOOLEAN doVerification;
extern int queueNumber;
static char lastImageInAssociation[512] = "";
static char callingAPTitle[20] = "";
static int receivedImageCount = 0;

typedef struct {
    char *fileName;
    char *transferSyntax;
    char *owner;
    char *groupName;
    char *priv;
    DMAN_HANDLE **handle;
    int  imageCount;
}   STORAGE_PARAMS;

static IDB_HANDLE *IDBHandle;
static FIS_HANDLE *fisHandle;

static CONDITION
serviceThisCommand(DUL_NETWORKKEY ** network, DUL_ASSOCIATIONKEY ** association,
		   DUL_PRESENTATIONCONTEXT * ctx, MSG_TYPE messageType,
		   void **message, DUL_ASSOCIATESERVICEPARAMETERS * params,
		   DMAN_HANDLE ** handle);
static CONDITION
echoRequest(DUL_ASSOCIATIONKEY ** association,
	    DUL_PRESENTATIONCONTEXT * ctx, MSG_C_ECHO_REQ ** message);
static CONDITION
storeRequest(DUL_ASSOCIATESERVICEPARAMETERS * params,
	     DUL_ASSOCIATIONKEY ** association, DMAN_HANDLE ** handle,
	     DUL_PRESENTATIONCONTEXT * ctx, MSG_C_STORE_REQ ** message);
static CONDITION
echoCallback(MSG_C_ECHO_REQ * echoRequest,
	     MSG_C_ECHO_RESP * echoResponse, void *ctx,
	     DUL_PRESENTATIONCONTEXT * pc);
static CONDITION
storageCallback(MSG_C_STORE_REQ * request, MSG_C_STORE_RESP * response,
		unsigned long received, unsigned long estimate,
/*		DCM_OBJECT ** object, STORAGE_PARAMS * params, */
		DCM_OBJECT ** object, void *paramsPtr,
		DUL_PRESENTATIONCONTEXT * pc);
static CONDITION
storeImage(DMAN_HANDLE ** handle, char *origFileName,
	   char *transferSyntax, char *SOPClass,
	   char *owner, char *groupName, char *priv,
	   DCM_OBJECT ** object);

extern CTNBOOLEAN silent;

void
queueInitialize();
void
queueNewAssociation(const char* node);
void
queueNetworkNewAssociation(const char* node);
void
queueClosedAssociation(const char* node, int count);
void
queueDisplayImage(const char* node, const char* name);
void
queueNewImage(const char* node, int count);
void
networkqueuePartialImage(const char* node, int percentage);

/* serviceRequests
**
** Purpose:
**	This function reads requests from the network and services those
**	requests.
**
** Parameter Dictionary:
**	network		The key which is used to access the network.
**	association	They key which is used to access the association
**			on which requests are received.
**	service		The parameter list which describes the association.
**			This list includes the list of presentation contexts
**			for the association.
**	reducedCapability If true, we are operating with reduced capability.
**			This means we will not use FIS for anything.
**
** Return Values:
**
** Algorithm:
**	Description of the algorithm (optional) and any other notes.
*/

CONDITION
serviceRequests(DUL_NETWORKKEY ** network, DUL_ASSOCIATIONKEY ** association,
		DUL_ASSOCIATESERVICEPARAMETERS * service,
		CTNBOOLEAN reducedCapability)
{
    CONDITION
	cond;
    DUL_PRESENTATIONCONTEXT
	* ctx;
    DUL_PRESENTATIONCONTEXTID
	ctxID;
    void
       *message;
    MSG_TYPE
	messageType;
    CTNBOOLEAN
	networkLink = TRUE,
	commandServiced;
    DMAN_HANDLE
	* handle;
    DMAN_STORAGEACCESS
	storage;
    DMAN_FISACCESS fisAccess;

    receivedImageCount = 0;

    queueInitialize();
    strcpy(callingAPTitle, service->callingAPTitle);
    queueNewAssociation(service->callingAPTitle);
    queueNetworkNewAssociation(service->callingAPTitle);

    cond = DMAN_Open(controlDatabase, service->callingAPTitle,
		     service->calledAPTitle, &handle);

    if (cond != DMAN_NORMAL)
	fprintf(stderr, "Unable to open control database\n");

    if (cond == DMAN_NORMAL) {
	cond = DMAN_LookupStorage(&handle, service->calledAPTitle,
				  &storage);
    }
    if (cond != DMAN_NORMAL) {
	fprintf(stderr, "Unable to lookup storage\n");
	COND_DumpConditions();
    }
    if (cond == DMAN_NORMAL) {
	cond = IDB_Open(storage.DbKey, &IDBHandle);
#ifdef CTN_MULTIBYTE
	IDB_SetCharSet(&IDBHandle, storage.Comment);
#endif
    }

    if (cond != IDB_NORMAL)
	fprintf(stderr, "Unable to open IDB tables\n");

    if (!reducedCapability && !CTN_ERROR(cond)) {
	cond = DMAN_LookupFISAccess(&handle, service->calledAPTitle, &fisAccess);
	if (!CTN_ERROR(cond))
	    cond = FIS_Open(fisAccess.DbKey, &fisHandle);
    }
    while ((networkLink == TRUE) && !CTN_ERROR(cond)) {
	cond = SRV_ReceiveCommand(association, service, DUL_BLOCK, 0, &ctxID,
				  NULL, &messageType, &message);
	if (cond == SRV_PEERREQUESTEDRELEASE) {
	    networkLink = FALSE;
	    (void)COND_PopCondition(TRUE);
	    (void) DUL_AcknowledgeRelease(association);
	    (void) DUL_DropAssociation(association);
	} else if (cond == SRV_PEERABORTEDASSOCIATION) {
	    networkLink = FALSE;
	    (void) DUL_DropAssociation(association);
	} else if (cond != SRV_NORMAL) {
	    (void) DUL_DropAssociation(association);
	    COND_DumpConditions();
	    cond = 2;
	} else {
	    ctx = LST_Head(&service->acceptedPresentationContext);
	    if (ctx != NULL)
		(void) LST_Position(&service->acceptedPresentationContext, ctx);
	    commandServiced = FALSE;
	    while (ctx != NULL && !commandServiced) {
		if (ctx->presentationContextID == ctxID) {
		    if (commandServiced) {
			if (!silent)
			    fprintf(stderr,
			      "Context ID Repeat in serviceRequests (%d)\n",
				    ctxID);
		    } else {
			cond = serviceThisCommand(network, association, ctx,
					     messageType, &message, service,
						  &handle);
			if (cond == SRV_OPERATIONCANCELLED) {
			    if (!silent)
				printf("Operation cancelled\n");
			    (void) COND_PopCondition(TRUE);
			} else if (cond != SRV_NORMAL)
			    COND_DumpConditions();
			commandServiced = TRUE;
		    }
		}
		ctx = LST_Next(&service->acceptedPresentationContext);
	    }
	    if (!commandServiced) {
		fprintf(stderr, "In serviceRequests, context ID %d not found\n",
			ctxID);
		(void) DUL_DropAssociation(association);
		networkLink = FALSE;
	    }
	}
    }
    if (!silent)
	COND_DumpConditions();
    queueClosedAssociation(service->callingAPTitle, receivedImageCount);
    if (lastImageInAssociation[0] != '\0')
      queueDisplayImage(service->callingAPTitle, lastImageInAssociation);

    (void) DMAN_Close(&handle);
    (void) IDB_Close(&IDBHandle);
    if (!reducedCapability)
	(void) FIS_Close(&fisHandle);
    (void) DUL_ClearServiceParameters(service);
    free(service);
    return cond;
}

/* serviceThisCommand
**
** Purpose:
**	This function serves as a dispatch routine for the commands
**	that can be received from the network.  It uses a case statement
**	to identify the command and call the function which will
**	respond to the request.
**
** Parameter Dictionary:
**	association	They key which is used to access the association
**			on which requests are received.
**	ctx		Pointer to the presentation context for this command
**	messageType	The type of message that we are to recognize.
**	message		Pointer to a structure which contains the message.
**			We will use "messageType" to get the proper type.
**
** Return Values:
**
** Algorithm:
**	Description of the algorithm (optional) and any other notes.
*/

static CONDITION
serviceThisCommand(DUL_NETWORKKEY ** network,
		   DUL_ASSOCIATIONKEY ** association,
		   DUL_PRESENTATIONCONTEXT * ctx, MSG_TYPE messageType,
		   void **message, DUL_ASSOCIATESERVICEPARAMETERS * params,
		   DMAN_HANDLE ** handle)
{
    CONDITION
    cond;
    MSG_GENERAL
	* general;

    general = *(MSG_GENERAL **) message;

    if (!silent)
	MSG_DumpMessage((void *) general, stdout);
    switch (messageType) {
    case MSG_K_C_ECHO_REQ:
	cond = echoRequest(association, ctx, (MSG_C_ECHO_REQ **) message);
	break;
    case MSG_K_C_STORE_REQ:
	cond = storeRequest(params, association, handle, ctx,
			    (MSG_C_STORE_REQ **) message);
	break;
    case MSG_K_C_FIND_REQ:
	cond = findRequest(association, params, ctx,
			   (MSG_C_FIND_REQ **) message, &IDBHandle);
	break;
    case MSG_K_C_MOVE_REQ:
	cond = moveRequest(network, association, ctx,
			   (MSG_C_MOVE_REQ **) message, params, &IDBHandle,
			   handle);
	break;
    case MSG_K_C_GET_REQ:
	cond = cgetRequest(network, association, ctx,
			   (MSG_C_GET_REQ **) message, params, &IDBHandle,
			   handle);
	break;
    case MSG_K_C_CANCEL_REQ:
	cond = SRV_NORMAL;	/* This must have happened after we were done */
	break;
    case MSG_K_N_ACTION_REQ:
	cond = nactionRequest(params, association, handle, ctx,
			      (MSG_N_ACTION_REQ **) message, &fisHandle,
			      &IDBHandle);
	break;
    default:
	fprintf(stderr, "Unimplemented message type: %d\n", messageType);
	cond = 1;
	break;
    }
    return cond;
}


/* echoRequest
**
** Purpose:
**	This function responds to an echo request from the network.
**	It creates an echo response message with a status of success
**	and sends the message to the peer application.
**
** Parameter Dictionary:
**	association	They key which is used to access the association
**			on which requests are received.
**	ctx		Pointer to the presentation context for this command
**	message		Pointer to the MSG_C_ECHO_REQ message that was
**			received by the server.
**
** Return Values:
**
**	SRV_CALLBACKABORTEDSERVICE
**	SRV_ILLEGALPARAMETER
**	SRV_NOCALLBACK
**	SRV_NORMAL
**	SRV_OBJECTBUILDFAILED
**	SRV_RESPONSEFAILED
**
** Algorithm:
**	Description of the algorithm (optional) and any other notes.
*/

static CONDITION
echoRequest(DUL_ASSOCIATIONKEY ** association,
	    DUL_PRESENTATIONCONTEXT * ctx, MSG_C_ECHO_REQ ** echoReq)
{
    MSG_C_ECHO_RESP
    echoResponse = {
	MSG_K_C_ECHO_RESP, 0, 0, DCM_CMDDATANULL, 0, ""
    };

    return SRV_CEchoResponse(association, ctx, echoReq,
			     &echoResponse, echoCallback, NULL, "");
}

/* echoCallback
**
** Purpose:
**	Call back routine provided by the service provider. It is invoked
**	by the SRV Echo Response function.
**
** Parameter Dictionary:
**	request		Pointer to C-Echo Request Message
**	response	Pointer to C-Echo Response Message
**	ctx		Context information that we ignore
**	pc		Presentation context pointer that we ignore
**
** Return Values:
**	SRV_NORMAL
**
** Notes:
**
** Algorithm:
**	Description of the algorithm (optional) and any other notes.
*/
static CONDITION
echoCallback(MSG_C_ECHO_REQ * request,
	     MSG_C_ECHO_RESP * response, void *ctx,
	     DUL_PRESENTATIONCONTEXT * pc)
{
    if (!silent)
	printf("Echo Request Received/Acknowledged\n");

    response->dataSetType = DCM_CMDDATANULL;
    response->messageIDRespondedTo = request->messageID;
    response->status = MSG_K_SUCCESS;
    strcpy(response->classUID, request->classUID);

    return SRV_NORMAL;
}


/* storeRequest
**
** Purpose:
**	This function responds to a request to store an image.
**
** Parameter Dictionary:
**	association	They key which is used to access the association
**			on which requests are received.
**	ctx		Pointer to the presentation context for this command
**	message		Pointer to the MSG_C_STORE_REQ message that was
**			received by the server.
**
** Return Values:
**
**	SRV_FILECREATEFAILED
**	SRV_NORMAL
**	SRV_OBJECTBUILDFAILED
**	SRV_RESPONSEFAILED
**	SRV_UNEXPECTEDPDVTYPE
**
** Algorithm:
**	Description of the algorithm (optional) and any other notes.
*/


static CONDITION
storeRequest(DUL_ASSOCIATESERVICEPARAMETERS * params,
	     DUL_ASSOCIATIONKEY ** association, DMAN_HANDLE ** handle,
	     DUL_PRESENTATIONCONTEXT * ctx, MSG_C_STORE_REQ ** request)
{
    char
        fileName[1024];
    MSG_C_STORE_RESP
	response;
    CONDITION
	cond;
    STORAGE_PARAMS
	storageParams;
    static int imageCount = 0;

    imageCount++;

    cond = DMAN_TempImageFile(handle, (*request)->classUID,
			      fileName, sizeof(fileName));
    if (cond != DMAN_NORMAL) {
	COND_DumpConditions();
	fileName[0] = '\0';
    } else {
#ifdef DEBUG
	fprintf(stderr, "Temp file: %s\n", fileName);
#endif
    }


    storageParams.fileName = fileName;
    storageParams.transferSyntax = ctx->acceptedTransferSyntax;
    storageParams.handle = handle;
    storageParams.owner = params->callingAPTitle;
    storageParams.groupName = "";
    storageParams.priv = "";
    storageParams.imageCount = imageCount;

    queueNewImage(params->callingAPTitle, imageCount);

    cond = SRV_CStoreResponse(association, ctx, request, &response,
			      fileName, storageCallback, &storageParams, "");

#ifdef _MSC_VER
    _unlink(fileName);
#endif
    return cond;
}


/* storageCallback
**
** Purpose:
**	Call back routine provided by the service provider and invoked by
**	the C-STORE response routine
**
** Parameter Dictionary:
**	request		Pointer to C-STORE request message
**	response	Pointer to C-STORE response message
**	received	Number of bytes received so far
**	estimate	Estimated number of bytes in the data set
**	object		Handle to DICOM object
**	params		Context information which is a set of pointers we
**			use for storing the image and data in the database.
**	pc		Presentation context which describes this SOP class.
**
** Return Values:
**	SRV_NORMAL
**
** Notes:
**	We pass the hand
** Algorithm:
**	Description of the algorithm (optional) and any other notes.
*/

static CONDITION
storageCallback(MSG_C_STORE_REQ * request, MSG_C_STORE_RESP * response,
		unsigned long received, unsigned long estimate,
/*		DCM_OBJECT ** object, STORAGE_PARAMS * params, */
		DCM_OBJECT ** object, void *paramsPtr,
		DUL_PRESENTATIONCONTEXT * pc)
{
    CONDITION
    cond = 0;
    IE_OBJECT
	* ieObject;
/*  The definition and assignment help satisfy prototypes for this callback
**  function (defined by dicom_services.h)
*/
    STORAGE_PARAMS *params;
    int percentage;

    params = (STORAGE_PARAMS *) paramsPtr;

    percentage = (100 * received) / estimate;
    if (percentage > 100)
      percentage = 100;

    networkqueuePartialImage(callingAPTitle, percentage);

    if (!silent)
	printf("%8d bytes received of %8d estimated \n", received, estimate);
    if (!silent && (object != NULL))
	(void) DCM_DumpElements(object, 0);

    if (object != NULL) {
	if (doVerification) {
	    cond = IE_ExamineObject(object, &ieObject);
	    (void) IE_Free((void **) &ieObject);
	    if (cond != IE_NORMAL) {	/* The image does not satisfy */
		/* Part 3 requirements */
		response->status = MSG_K_C_STORE_DATASETNOTMATCHSOPCLASSERROR;
		return SRV_NORMAL;
	    }
	}
	cond = storeImage(params->handle, params->fileName,
			  params->transferSyntax, request->classUID,
			  params->owner, params->groupName, params->priv,
			  object);
    }
    if (response != NULL) {
	if (cond == APP_NORMAL)
	    response->status = MSG_K_SUCCESS;
	else
	    response->status = MSG_K_C_STORE_OUTOFRESOURCES;
    }
    return SRV_NORMAL;
}

static void
logImageError(const char *msg, const char *fileName)
{
    FILE *log;
    time_t t;
    char *timeString;

    t = time(0);
    timeString = ctime(&t);

    log = fopen("archive_logfile", "a");
    if (log == NULL)
	fprintf(stderr, "%s %s %s\n", timeString, msg, fileName);
    else {
	fprintf(log, "%s %s %s\n", timeString, msg, fileName);
	fclose(log);
    }
}

#ifdef CTN_IDBV2
typedef struct {
    void *reserved[2];
    IDB_Query query;
}   STUDY_NODE;

CONDITION LST_Sort(LST_HEAD ** list, size_t nodeSize, int (*compare) ());
static int
compareStudyInsertTimes(STUDY_NODE * p1, STUDY_NODE * p2)
{
    long d1,
        d2;
    double t1,
        t2;

    d1 = UTL_ConvertDatetoLong(p1->query.study.InsertDate);
    d2 = UTL_ConvertDatetoLong(p2->query.study.InsertDate);

    if (d1 > d2)
	return 1;
    else if (d1 < d2)
	return -1;

    t1 = UTL_ConvertTimetoFloat(p1->query.study.InsertTime);
    t2 = UTL_ConvertTimetoFloat(p2->query.study.InsertTime);
    if (t1 > t2)
	return 1;
    else if (t1 < t2)
	return -1;

    return 0;
}

static CONDITION
selectCallback(IDB_Query * query, long count, LST_HEAD * lst)
{

    STUDY_NODE *node;

    node = malloc(sizeof(*node));
    node->query = *query;
    (void) LST_Enqueue(&lst, node);
    return IDB_NORMAL;
}

static void
purgeIDB(IDB_HANDLE ** handle, long size, long limit)
{
    CONDITION cond;
    IDB_Query pssi;
    LST_HEAD *lst;
    STUDY_NODE *node;
    long count = 0;
    IDB_Limits limitStructure;

    memset(&pssi, 0, sizeof(pssi));
    lst = LST_Create();

    cond = IDB_Select(handle, STUDY_ROOT, IDB_STUDY_LEVEL, IDB_STUDY_LEVEL,
		      &pssi, &count, selectCallback, lst);

    if (cond != IDB_NORMAL) {
	COND_DumpConditions();
	return;
    }
    LST_Sort(&lst, sizeof(*node), compareStudyInsertTimes);

    node = LST_Dequeue(&lst);
    while (size > limit && (node != NULL)) {
#ifdef DEBUG
	printf("Deleting study: %s\n", node->query.study.StuInsUID);
#endif

	cond = IDB_Delete(handle,
			  IDB_STUDY_LEVEL,
			  node->query.study.StuInsUID,
			  TRUE);
	free(node);
	memset(&limitStructure, 0, sizeof(limitStructure));
	cond = IDB_SelectLimits(handle, &limitStructure);
	size = limitStructure.DBSize;
	limit = limitStructure.DBLimit;

	if (size > limit)
	    node = LST_Dequeue(&lst);
    }
    while ((node = LST_Dequeue(&lst)) != NULL)
	free(node);

    LST_Destroy(&lst);
}

static void
checkStorageLimits(IDB_HANDLE ** handle)
{
    IDB_Limits limits;
    CONDITION cond;
    long l1,
        l2,
        l3;

    memset(&limits, 0, sizeof(limits));
    cond = IDB_SelectLimits(handle, &limits);
    if (cond != IDB_NORMAL) {
	COND_DumpConditions();
	return;
    }
    if (limits.DBSize > limits.DBLimit) {
#ifdef DEBUG
	printf("Need to purge DB, Size: %10d, limit: %10d\n",
	       limits.DBSize,
	       limits.DBLimit);
#endif
	purgeIDB(handle, limits.DBSize, limits.DBLimit);
    }
}
#endif

typedef struct {
  char* c1;
  char* c2;
} STRING_MATRIX;

#ifdef CTN_MULTIBYTE
static CONDITION
checkCharacterSets(DCM_OBJECT** object)
{
  char imageCharSet[1024];
  CONDITION cond;
  U32 length = 0;
  void* ctx = 0;
  char databaseCharSet[1024];
  int nullSpecificCharSet = 0;
  int index;
  CONDITION returnValue = 0;

  STRING_MATRIX firstElement[] = {
    { "EUCJP", "" },
    { "EUCJP", "ISO_IR 100" },
    { "EUCJP", "ISO_IR 100 " },
    { "EUCJP", "ISO 2022 IR 6" },
    { "EUCJP", "ISO 2022 IR 6 " },
    { "EUCJP", "ISO 2022 IR 100" },
    { "EUCJP", "ISO 2022 IR 100 " },
    { "EUCJPROMAJI", "ISO_IR 13"},
    { "EUCJPROMAJI", "ISO_IR 13 "},
    { "EUCJPROMAJI", "ISO 2022 IR 13"},
    { "EUCJPROMAJI", "ISO 2022 IR 13 "},
    { "EUCKR", "" }
  };
  STRING_MATRIX secondaryElements[] = {
    { "EUCJP", "ISO 2022 IR 87" },
    { "EUCJP", "ISO 2022 IR 87 " },
    { "EUCJP", "ISO 2022 IR 159" },
    { "EUCJP", "ISO 2022 IR 159 " },
    { "EUCJPROMAJI", "ISO 2022 IR 87" },
    { "EUCJPROMAJI", "ISO 2022 IR 87 " },
    { "EUCJPROMAJI", "ISO 2022 IR 159" },
    { "EUCJPROMAJI", "ISO 2022 IR 159 " },
    { "EUCKR", "ISO 2022 IR 149" },
    { "EUCKR", "ISO 2022 IR 149 " }
  };
  char* tok1;
  char* tok2;

  DCM_ELEMENT e = { DCM_IDSPECIFICCHARACTER, DCM_CS, "", 1,
	sizeof(imageCharSet), NULL};

  /* Get the Default Character Set.  If the attribute is not there,
  ** treat as if the attribute is there but empty.
  */

  e.d.string = imageCharSet;
  cond = DCM_GetElementValue(object, &e, &length, &ctx);
  if (cond == DCM_ELEMENTNOTFOUND) {
    (void)COND_PopCondition(TRUE);
    strcpy(imageCharSet, "");
  } else if (cond != DCM_NORMAL) {
    COND_DumpConditions();
    return 0;
  } else {
    imageCharSet[length] = '\0';
    if (imageCharSet[length-1] == ' ')
      imageCharSet[length-1] = '\0';
  }

  IDB_GetCharSet(&IDBHandle, databaseCharSet);

  if (imageCharSet[0] == '\\') {
    tok1 = "";
    tok2 = strtok(imageCharSet, "\\");
  } else if (imageCharSet[0] == '\0') {
    tok1 = "";
    tok2 = NULL;
  } else {
    tok1 = strtok(imageCharSet, "\\");
    tok2 = strtok(NULL, "\\");
  }

  returnValue = 0;
  for (index = 0;
	index < (int)DIM_OF(firstElement) && returnValue == 0;
	index++) {

    if ((strcmp(firstElement[index].c1, databaseCharSet) == 0) &&
	(strcmp(firstElement[index].c2, tok1) == 0) ) {
      returnValue = APP_NORMAL;
    }
  }
  if (returnValue != APP_NORMAL)
    return 0;

  while(tok2 != NULL) {
    returnValue = 0;
    for (index = 0;
	index < (int)DIM_OF(secondaryElements) && returnValue == 0;
	index++) {

      if ((strcmp(secondaryElements[index].c1, databaseCharSet) == 0) &&
	  (strcmp(secondaryElements[index].c2, tok2) == 0) ) {
	returnValue = APP_NORMAL;
      }
    }

    if (returnValue != APP_NORMAL)
      return 0;

      tok2 = strtok(NULL, "\\");
  }

  return APP_NORMAL;
}
#endif

static CONDITION
storeImage(DMAN_HANDLE ** handle, char *origFileName,
	   char *transferSyntax, char *SOPClass,
	   char *owner, char *groupName, char *priv, DCM_OBJECT ** object)
{
    IDB_Insertion Insertion;

    CONDITION cond;
    char fileName[256];
    char *accession;
    unsigned long objectSize = 0;
    int i = 0;
    static char displayedImage[512] = "";

#ifdef CTN_MULTIBYTE
    cond = checkCharacterSets(object);
    if (cond != APP_NORMAL) {
	fprintf(stderr, "Error on image character sets\n");
	return 0;
    }
#endif

    memset(&Insertion, 0, sizeof(Insertion));

#ifdef CTN_MULTIBYTE
    cond = parseImageForInsertMB(object, &Insertion);
#else
    cond = parseImageForInsert(object, &Insertion);
#endif
    if (cond != APP_NORMAL) {
	fprintf(stderr, "Could not parse image for insertion into database\n");
	COND_DumpConditions();
	return 0;
    }
    strcpy(Insertion.patient.Owner, owner);
    strcpy(Insertion.patient.GroupName, groupName);
    strcpy(Insertion.patient.Priv, priv);

    if (strlen(Insertion.study.AccNum) != 0)
	accession = Insertion.study.AccNum;
    else
	accession = Insertion.study.StuInsUID;

    cond = DMAN_PermImageFile(handle, SOPClass, accession,
			      Insertion.series.SerInsUID,
			      fileName, sizeof(fileName));
    if (cond != DMAN_NORMAL) {
	COND_DumpConditions();
	return 0;
    } else {
#ifdef DEBUG
	fprintf(stderr, "Perm file name: %s\n", fileName);
#endif
    }

#ifdef _MSC_VER
    if (!CopyFile(origFileName, fileName, FALSE)) {

	DWORD er;

	LPVOID lpMsgBuf;

	fprintf(stderr, "Unable to move file from %s to %s\n", 
		origFileName, fileName);

	er = GetLastError();

	FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
		      NULL,
		      er,
		      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		      (LPTSTR) & lpMsgBuf,
		      0, NULL);

	printf("%s\n", lpMsgBuf);

	return 0;

    }
#else
    i = rename(origFileName, fileName);
    if (i != 0) {
	fprintf(stderr, "Unable to rename file from %s to %s\n",
		origFileName, fileName);

	i = errno;
	return 0;
    }
#endif
    strcpy(Insertion.image.Path, fileName);
    strcpy(Insertion.image.Transfer, transferSyntax);

#if 0
    if (strlen(Insertion.patient.PatNam) == 0) {
	logImageError("Zero length patient name", fileName);
	(void) COND_PopCondition(TRUE);
	return APP_NORMAL;
    }
    if (strlen(Insertion.patient.PatID) == 0) {
	logImageError("Zero length patient ID", fileName);
	(void) COND_PopCondition(TRUE);
	return APP_NORMAL;
    }
#endif

    if (displayedImage[0] == '\0') {
      strcpy(displayedImage, fileName);
      queueDisplayImage(callingAPTitle , displayedImage);
    } else {
      strcpy(lastImageInAssociation, fileName);
    }
    receivedImageCount++;

    (void) DCM_GetObjectSize(object, &objectSize);
    Insertion.image.Size = objectSize;

    cond = IDB_InsertImage(&IDBHandle, &Insertion);
    if (cond != IDB_NORMAL) {
#ifdef _MSC_VER
	_unlink(fileName);
#else
	unlink(fileName);
#endif
	COND_DumpConditions();
	return 0;
    }
    (void) COND_PopCondition(TRUE);
#ifdef CTN_IDBV2
    checkStorageLimits(&IDBHandle);
#endif



    return APP_NORMAL;
}