-
Notifications
You must be signed in to change notification settings - Fork 217
/
BonjourPublisher.m
1099 lines (877 loc) · 47.7 KB
/
BonjourPublisher.m
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
/*=========================================================================
Program: OsiriX
Copyright (c) OsiriX Team
All rights reserved.
Distributed under GNU - LGPL
See http://www.osirix-viewer.com/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#import "BonjourPublisher.h"
#import "BonjourBrowser.h"
#import "DCMPix.h"
#import "DCMTKStoreSCU.h"
#import "SendController.h"
#import "DicomStudy.h"
#import "NSUserDefaultsController+OsiriX.h"
#import "NSUserDefaultsController+N2.h"
#import "N2Debug.h"
#import "DicomDatabase.h"
#import "DicomImage.h"
#import "AppController.h"
// imports required for socket initialization
#import <sys/socket.h>
#import <netinet/in.h>
#import <unistd.h>
// BY DEFAULT OSIRIX USES 8780 PORT
#include <netdb.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static BonjourPublisher *currentPublisher = nil;
extern const char *GetPrivateIP();
@interface BonjourPublisher ()
@property(retain, readwrite) NSNetService* netService;
@end
@implementation BonjourPublisher
//@synthesize serviceName;
@synthesize netService;
+ (BonjourPublisher*) currentPublisher
{
return currentPublisher;
}
- (id) initWithBrowserController: (BrowserController*) bC
{
self = [super init];
if (self != nil)
{
currentPublisher = self;
// self.serviceName = [NSUserDefaultsController defaultServiceName];
fdForListening = 0;
listeningSocket = nil;
self.netService = nil;
connectionLock = [[NSLock alloc] init];
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forValuesKey:OsirixBonjourSharingActiveFlagDefaultsKey options:NSKeyValueObservingOptionInitial context:NULL];
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forValuesKey:OsirixBonjourSharingNameDefaultsKey options:NSKeyValueObservingOptionInitial context:NULL];
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forValuesKey:OsirixBonjourSharingPasswordFlagDefaultsKey options:NSKeyValueObservingOptionInitial context:NULL];
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forValuesKey:OsirixBonjourSharingPasswordDefaultsKey options:NSKeyValueObservingOptionInitial context:NULL];
}
return self;
}
- (void) dealloc
{
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forValuesKey:OsirixBonjourSharingActiveFlagDefaultsKey];
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forValuesKey:OsirixBonjourSharingNameDefaultsKey];
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forValuesKey:OsirixBonjourSharingPasswordFlagDefaultsKey];
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forValuesKey:OsirixBonjourSharingPasswordDefaultsKey];
[dicomSendLock release];
// self.serviceName = NULL;
[connectionLock release];
[super dealloc];
}
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
if (object == [NSUserDefaultsController sharedUserDefaultsController]) {
keyPath = [keyPath substringFromIndex:7];
if ([keyPath isEqual:OsirixBonjourSharingActiveFlagDefaultsKey]) {
[self toggleSharing:[NSUserDefaultsController IsBonjourSharingActive]];
return;
} else
if ([keyPath isEqual:OsirixBonjourSharingNameDefaultsKey]) {
// [self ];
return;
} else
if ([keyPath isEqual:OsirixBonjourSharingPasswordFlagDefaultsKey]) {
return;
} else
if ([keyPath isEqual:OsirixBonjourSharingPasswordDefaultsKey]) {
return;
}
}
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
- (int) OsiriXDBCurrentPort
{
return OsiriXDBCurrentPort;
}
- (void) toggleSharing:(BOOL) activated
{
@try
{
uint16_t chosenPort = 0;
if( !listeningSocket)
{
// Here, create the socket from traditional BSD socket calls, and then set up an NSFileHandle with
//that to listen for incoming connections.
if( fdForListening)
close( fdForListening);
fdForListening = 0;
struct sockaddr_in serverAddress;
socklen_t namelen = sizeof(serverAddress);
// In order to use NSFileHandle's acceptConnectionInBackgroundAndNotify method, we need to create a
// file descriptor that is itself a socket, bind that socket, and then set it up for listening. At this
// point, it's ready to be handed off to acceptConnectionInBackgroundAndNotify.
if((fdForListening = socket(AF_INET, SOCK_STREAM, 0)) > 0)
{
// int sock_buf_size = 10000;
//
// setsockopt( fdForListening, SOL_SOCKET, SO_SNDBUF, (char *)&sock_buf_size, sizeof(sock_buf_size) );
// setsockopt( fdForListening, SOL_SOCKET, SO_RCVBUF, (char *)&sock_buf_size, sizeof(sock_buf_size) );
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddress.sin_port = htons(8780); //make it endian independent
// Allow the kernel to choose a random port number by passing in 0 for the port.
if (bind(fdForListening, (struct sockaddr *)&serverAddress, namelen) < 0)
{
NSLog(@"bind failed... select another port than 8780");
serverAddress.sin_port = htons(0);
if (bind(fdForListening, (struct sockaddr *)&serverAddress, namelen) < 0)
{
close (fdForListening);
fdForListening = 0;
return;
}
}
// Find out what port number was chosen.
if (getsockname(fdForListening, (struct sockaddr *)&serverAddress, &namelen) < 0)
{
close(fdForListening);
fdForListening = 0;
return;
}
chosenPort = ntohs(serverAddress.sin_port);
if( chosenPort != 8780)
{
NSString *exampleAlertSuppress = @"Bonjour Port";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:exampleAlertSuppress])
{
}
else
{
NSAlert* alert = [[NSAlert new] autorelease];
[alert setMessageText: NSLocalizedString(@"Bonjour Port", nil)];
[alert setInformativeText : NSLocalizedString(@"Cannot use port 8780 for Bonjour sharing. It is already used, another port will be selected.", nil)];
[alert setShowsSuppressionButton:YES];
[alert runModal];
if ([[alert suppressionButton] state] == NSOnState)
{
[defaults setBool:YES forKey:exampleAlertSuppress];
}
}
}
NSLog(@"Chosen port for DB sharing: %d", chosenPort);
OsiriXDBCurrentPort = chosenPort;
// Once we're here, we know bind must have returned, so we can start the listen
if(listen(fdForListening, 1) == 0)
{
listeningSocket = [[NSFileHandle alloc] initWithFileDescriptor:fdForListening closeOnDealloc: NO];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectionReceived:) name:NSFileHandleConnectionAcceptedNotification object:listeningSocket];
[listeningSocket acceptConnectionInBackgroundAndNotify];
}
}
}
if (!netService)
{
// lazily instantiate the NSNetService object that will advertise on our behalf. Passing in "" for the domain causes the service
// to be registered in the default registration domain, which will currently always be "local"
netService = [[NSNetService alloc] initWithDomain:@"" type:@"_osirixdb._tcp." name:[NSUserDefaultsController BonjourSharingName] port:chosenPort];
[netService setDelegate:self];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
if( [[NSUserDefaults standardUserDefaults] stringForKey: @"AETITLE"].length == 0)
[[NSUserDefaults standardUserDefaults] setObject: @"OSIRIX" forKey: @"AETITLE"];
if( [[NSUserDefaults standardUserDefaults] stringForKey: @"AEPORT"].length == 0)
[[NSUserDefaults standardUserDefaults] setObject: @"11112" forKey: @"AEPORT"];
if( [[NSUserDefaults standardUserDefaults] stringForKey: @"AETITLE"])
[params setObject: [[NSUserDefaults standardUserDefaults] stringForKey: @"AETITLE"] forKey: @"AETitle"];
if( [[NSUserDefaults standardUserDefaults] stringForKey: @"AEPORT"])
[params setObject: [[NSUserDefaults standardUserDefaults] stringForKey: @"AEPORT"] forKey: @"port"];
if( [AppController UID])
[params setObject: [AppController UID] forKey: @"UID"];
if( [netService setTXTRecordData: [NSNetService dataFromTXTRecordDictionary: params]] == NO)
{
NSLog( @"ERROR - NSNetService setTXTRecordData FAILED");
}
}
if (netService && listeningSocket)
{
if( activated)
[netService publish];
else
[netService stop];
}
}
@catch (NSException *e) {
N2LogException( e);
}
dbPublished = activated;
}
+(NSDictionary*)dictionaryFromXTRecordData:(NSData*)data {
NSMutableDictionary* d = [NSMutableDictionary dictionary];
NSDictionary* dict = [NSNetService dictionaryFromTXTRecordData:data];
for (NSString* key in dict) {
NSData* data = [dict objectForKey:key];
if ([key isEqualToString:@"AETitle"])
[d setObject:[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease] forKey:key];
else if ([key isEqualToString:@"port"])
[d setObject:[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease] forKey:key];
else if ([key isEqualToString:@"UID"])
[d setObject:[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease] forKey:key];
else [d setObject:data forKey:key];
}
return d;
}
//- (NSData *)dataByZippingLocalPath:(NSString *)_path
//{
// NSFileHandle *nullHandle = nil;
// NSFileHandle *zipHandle = nil;
// NSPipe *zipPipe = nil;
// NSTask *zipTask = nil;
// NSData *result = nil;
// NSString *compression = nil;
//
// int _level = 6;
//
// // man zip writes, 6 is the default value
// compression = [NSString stringWithFormat: @"-%d", (_level < 0 || _level > 9) ? 6 : _level];
//
// zipPipe = [NSPipe pipe];
// zipHandle = [zipPipe fileHandleForReading];
// nullHandle = [NSFileHandle fileHandleForWritingAtPath:@"/dev/null"];
// zipTask = [[NSTask alloc] init];
// [zipTask setLaunchPath:@"/usr/bin/zip"];
// [zipTask setCurrentDirectoryPath: [_path stringByDeletingLastPathComponent]];
// [zipTask setArguments: [NSArray arrayWithObjects:@"-qr", compression, @"-", [_path lastPathComponent], nil]];
// [zipTask setStandardOutput:zipPipe];
// [zipTask setStandardError:nullHandle];
// [zipTask launch];
//
// result = [zipHandle readDataToEndOfFile];
//
// [zipTask release];
// return result;
//}
- (void) sendDICOMFilesToOsiriXNode:(NSDictionary*) todo
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if( dicomSendLock == nil) dicomSendLock = [[NSLock alloc] init];
[dicomSendLock lock];
DCMTKStoreSCU *storeSCU = [[DCMTKStoreSCU alloc] initWithCallingAET: [[NSUserDefaults standardUserDefaults] stringForKey: @"AETITLE"]
calledAET: [todo objectForKey:@"AETitle"]
hostname: [todo objectForKey:@"Address"]
port: [[todo objectForKey:@"Port"] intValue]
filesToSend: [todo valueForKey: @"Files"]
transferSyntax: [[todo objectForKey:@"TransferSyntax"] intValue]
compression: 1.0
extraParameters: [NSDictionary dictionaryWithObject:[DicomDatabase defaultDatabase] forKey:@"DicomDatabase"]]; // nil == TLS not supported !
@try
{
[storeSCU run:self];
}
@catch (NSException *ne)
{
NSLog( @"Bonjour DICOM Send FAILED");
NSLog( @"%@", [ne name]);
NSLog( @"%@", [ne reason]);
}
[storeSCU release];
storeSCU = nil;
[dicomSendLock unlock];
[pool release];
}
- (void) subConnectionReceived:(NSFileHandle *)incomingConnection
{
NSAutoreleasePool *mPool = [[NSAutoreleasePool alloc] init];
// BOOL saveDB = NO;
BOOL refreshDB = NO;
[incomingConnection retain];
if( dbPublished)
{
@try
{
NSData *readData;
NSMutableData *data = [NSMutableData dataWithCapacity: 512*512*2*2];
NSMutableData *representationToSend = nil;
if( incomingConnection)
{
// Waiting for incomming message (6 first bytes)
while ( [data length] < 6 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"DATAB" length: 6]])
{
DicomDatabase *database = [DicomDatabase defaultDatabase];
[[[database managedObjectContext] persistentStoreCoordinator] lock];
@try
{
[database save];
// we send the database SQL file
NSString *databasePath = [database sqlFilePath];
#if __LP64__
representationToSend = [NSMutableData dataWithContentsOfMappedFile: databasePath];
[incomingConnection writeData:representationToSend];
#else
NSDictionary *fattrs = [[NSFileManager defaultManager] fileAttributesAtPath: databasePath traverseLink: YES];
long long fileSize = [[fattrs objectForKey:NSFileSize] longLongValue];
fileSize /= 1024; // Kb
fileSize /= 1024; // Mb
#define DATA_READ_SIZE 200L
if( fileSize > DATA_READ_SIZE)
{
NSFileHandle *dbFileHandle = [NSFileHandle fileHandleForReadingAtPath: databasePath];
NSLog( @"split DB file reading");
int length = 0;
do
{
NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init];
NSData *chunk = [dbFileHandle readDataOfLength: DATA_READ_SIZE * 1024L*1024L];
[incomingConnection writeData: chunk];
length = [chunk length];
[arp release];
}
while( length > 0);
}
else
{
representationToSend = [NSMutableData dataWithContentsOfMappedFile: databasePath];
[incomingConnection writeData:representationToSend];
}
#endif
}
@catch (NSException *e) {
N2LogException( e);
}
@finally {
[[[database managedObjectContext] persistentStoreCoordinator] unlock];
}
struct sockaddr serverAddress;
socklen_t namelen = sizeof(serverAddress);
if (getsockname( [incomingConnection fileDescriptor], (struct sockaddr *)&serverAddress, &namelen) >= 0)
{
char client_ip_address[20];
sprintf(client_ip_address, "%-d.%-d.%-d.%-d", ((int) serverAddress.sa_data[2]) & 0xff, ((int) serverAddress.sa_data[3]) & 0xff, ((int) serverAddress.sa_data[4]) & 0xff, ((int) serverAddress.sa_data[5]) & 0xff);
NSLog( @"Bonjour Connection Received from: %s", client_ip_address);
}
}
else
{
if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"DBSIZ" length: 6]])
{
DicomDatabase *database = [DicomDatabase defaultDatabase];
[[[database managedObjectContext] persistentStoreCoordinator] lock];
int size, fileSize;
@try
{
[database save];
NSString *databasePath = [database sqlFilePath];
NSDictionary *fattrs = [[NSFileManager defaultManager] fileAttributesAtPath: databasePath traverseLink: YES];
fileSize = [[fattrs objectForKey:NSFileSize] longLongValue];
}
@catch (NSException *e) {
N2LogException( e);
}
@finally {
[[[database managedObjectContext] persistentStoreCoordinator] unlock];
}
representationToSend = [NSMutableData data];
NSLog( @"DB fileSize = %d", fileSize);
size = NSSwapHostIntToBig( fileSize);
[representationToSend appendBytes: &size length: 4];
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"GETDI" length: 6]])
{
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: [[NSUserDefaults standardUserDefaults] stringForKey: @"AETITLE"], @"AETitle", [[NSUserDefaults standardUserDefaults] stringForKey: @"AEPORT"], @"Port", [NSString stringWithFormat: @"%d", [DCMTKStoreSCU sendSyntaxForListenerSyntax: [[NSUserDefaults standardUserDefaults] integerForKey: @"preferredSyntaxForIncoming"]]], @"TransferSyntax", nil];
representationToSend = [NSMutableData dataWithData: [NSArchiver archivedDataWithRootObject: dictionary]];
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"VERSI" length: 6]])
{
NSTimeInterval val = [[DicomDatabase defaultDatabase] timeOfLastModification];
NSSwappedDouble swappedValue = NSSwapHostDoubleToBig( val);
if( sizeof( swappedValue.v) != 8) NSLog(@"********** warning sizeof( swappedValue) != 8");
representationToSend = [NSMutableData dataWithBytes: &swappedValue.v length:sizeof(NSTimeInterval)];
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"DBVER" length: 6]])
{
NSString *versString = [[NSUserDefaults standardUserDefaults] stringForKey: @"DATABASEVERSION"];
representationToSend = [NSMutableData dataWithData: [versString dataUsingEncoding: NSASCIIStringEncoding]];
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"ISPWD" length: 6]])
{
// is this database protected by a password
NSString* pswd = [NSUserDefaultsController BonjourSharingPassword];
int val = 0;
if (pswd) val = NSSwapHostIntToBig(1);
else val = 0;
representationToSend = [NSMutableData dataWithBytes: &val length:sizeof(int)];
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"PASWD" length: 6]])
{
int pos = 6, stringSize;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *incomingPswd = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
int val = 0;
if (![NSUserDefaultsController BonjourSharingPassword] || [incomingPswd isEqualToString: [NSUserDefaultsController BonjourSharingPassword]])
{
val = NSSwapHostIntToBig(1);
}
representationToSend = [NSMutableData dataWithBytes: &val length:sizeof(int)];
}
else if ([[data subdataWithRange: NSMakeRange(0,4)] isEqualToData: [NSData dataWithBytes:"SEND" length: 4]]) // SENDD & SENDG
{
int pos = 6, i;
NSString *order = [NSString stringWithCString: [[data subdataWithRange: NSMakeRange(0,6)] bytes]];
// We read 4 bytes that contain the no of file
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
int fileNo;
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &fileNo];
fileNo = NSSwapBigIntToHost( fileNo);
pos += 4;
NSMutableArray *savedFiles = [NSMutableArray array];
for( i = 0 ; i < fileNo; i++)
{
// We read 4 bytes that contain the file size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
int fileSize;
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &fileSize];
fileSize = NSSwapBigIntToHost( fileSize);
pos += 4;
while ( [data length] < pos + fileSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *dstPath = [[BrowserController currentBrowser] getNewFileDatabasePath: @"dcm"];
NSData *dcmData = [NSData dataWithBytesNoCopy: (char*)[data bytes] + pos length: fileSize freeWhenDone: NO];
[dcmData writeToFile: dstPath atomically: YES];
[savedFiles addObject: dstPath];
pos += fileSize;
}
BOOL generatedByOsiriX = NO;
if( [order isEqualToString: @"SENDD"]) generatedByOsiriX = NO;
else if( [order isEqualToString: @"SENDG"]) generatedByOsiriX = YES;
else
NSLog( @"******* unknown order: %@", order);
DicomDatabase *idatabase = [[DicomDatabase defaultDatabase] independentDatabase];
NSArray *objects = [idatabase addFilesAtPaths: savedFiles postNotifications: YES dicomOnly: NO rereadExistingItems: YES generatedByOsiriX: generatedByOsiriX];
objects = [idatabase objectsWithIDs: objects];
representationToSend = [NSMutableData data];
unsigned int temp = NSSwapHostIntToBig([objects count]);
[representationToSend appendBytes:&temp length:4];
for (DicomImage* image in objects) {
unsigned int temp = NSSwapHostIntToBig(image.pathNumber.intValue);
[representationToSend appendBytes:&temp length:4];
}
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"NEWMS" length: 6]]) // New Messaging System
{
int pos = 6, stringSize;
// We read 4 bytes that contain the data size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the data
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSDictionary *d = [NSPropertyListSerialization propertyListFromData: [data subdataWithRange: NSMakeRange(pos,stringSize)] mutabilityOption: NSPropertyListImmutable format: nil errorDescription: nil];
pos += stringSize;
if( d)
{
NSString *message = [d objectForKey:@"message"];
}
representationToSend = nil;
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"ADDAL" length: 6]])
{
int pos = 6, stringSize;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *object = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
if( [object writeToFile:@"/tmp/ADDAL" atomically: YES])
{
NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile: @"/tmp/ADDAL"];
NSArray *studies = [d objectForKey:@"albumStudies"];
NSString *albumUID = [d objectForKey:@"albumUID"];
DicomDatabase *idatabase = [[DicomDatabase defaultDatabase] independentDatabase];
@try
{
DicomAlbum* album = [idatabase objectWithID:albumUID]; // [context objectWithID: [[context persistentStoreCoordinator] managedObjectIDForURIRepresentation: [NSURL URLWithString: albumUID]]];
NSMutableSet* albumStudies = [album mutableSetValueForKey:@"studies"];
for (NSString* uri in studies)
{
DicomStudy* study = [idatabase objectWithID:uri]; // (DicomStudy*) [context objectWithID: [[context persistentStoreCoordinator] managedObjectIDForURIRepresentation: [NSURL URLWithString: uri]]];
[albumStudies addObject:study];
[study archiveAnnotationsAsDICOMSR];
}
refreshDB = YES;
[idatabase save:nil];
}
@catch (NSException * e)
{
NSLog(@"Exception in BonjourPublisher ADDAL");
}
@finally {
}
}
representationToSend = nil;
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"REMAL" length: 6]])
{
int pos = 6, stringSize;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *object = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
if( [object writeToFile:@"/tmp/REMAL" atomically: YES])
{
NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile: @"/tmp/REMAL"];
NSArray *studies = [d objectForKey:@"albumStudies"];
NSString *albumUID = [d objectForKey:@"albumUID"];
DicomDatabase *idatabase = [[DicomDatabase defaultDatabase] independentDatabase];
@try
{
DicomAlbum* album = [idatabase objectWithID:albumUID]; // [context objectWithID: [[context persistentStoreCoordinator] managedObjectIDForURIRepresentation: [NSURL URLWithString: albumUID]]];
NSMutableSet* albumStudies = [album mutableSetValueForKey: @"studies"];
for (NSString* uri in studies)
{
DicomStudy* study = [idatabase objectWithID:uri]; // (DicomStudy*) [context objectWithID: [[context persistentStoreCoordinator] managedObjectIDForURIRepresentation: [NSURL URLWithString: uri]]];
[albumStudies removeObject:study];
[study archiveAnnotationsAsDICOMSR];
}
refreshDB = YES;
[idatabase save:nil];
}
@catch (NSException * e)
{
NSLog(@"Exception in BonjourPublisher REMAL");
}
@finally {
}
}
representationToSend = nil;
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"SETVA" length: 6]])
{
int pos = 6, stringSize;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *objectId = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
NSString *value;
if( stringSize == 0)
{
value = nil;
}
else
{
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
value = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
}
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *key = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
DicomDatabase *idatabase = [[DicomDatabase defaultDatabase] independentDatabase];
@try
{
NSManagedObject* item = [idatabase objectWithID:objectId]; // [context objectWithID: [[context persistentStoreCoordinator] managedObjectIDForURIRepresentation: [NSURL URLWithString: object]]];
//NSLog(@"URL:%@", object);
if( item)
{
if( [[item valueForKeyPath: key] isKindOfClass: [NSNumber class]]) [item setValue: [NSNumber numberWithInt: [value intValue]] forKeyPath: key];
else
{
if( [key isEqualToString: @"reportURL"] == YES)
{
if( value == nil)
{
[[NSFileManager defaultManager] removeFileAtPath:[item valueForKeyPath: key] handler:nil];
}
else if( [[key pathComponents] count] == 1)
{
value = [[idatabase.baseDirPath stringByAppendingPathComponent: @"/REPORTS/"] stringByAppendingPathComponent: [value lastPathComponent]];
}
}
[item setValue: value forKeyPath: key];
}
}
[idatabase save:NULL];
}
@catch (NSException *e)
{
NSLog(@"***** BonjourPublisher Exception: %@", e);
}
@finally {
}
refreshDB = YES;
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"MFILE" length: 6]])
{
int pos = 6, stringSize;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *path = [[[NSString alloc] initWithData: [data subdataWithRange: NSMakeRange(pos,stringSize)] encoding: NSUnicodeStringEncoding] autorelease];
pos += stringSize;
if( [path length])
{
if( [path characterAtIndex: 0] != '/')
path = [[[DicomDatabase defaultDatabase] baseDirPath] stringByAppendingPathComponent: path];
}
NSDictionary *fattrs = [[NSFileManager defaultManager] fileAttributesAtPath:path traverseLink:YES];
NSData *content = [[[fattrs objectForKey:NSFileModificationDate] description] dataUsingEncoding: NSUnicodeStringEncoding];
representationToSend = [NSMutableData dataWithData: content];
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"DCMSE" length: 6]])
{
NSMutableArray *localPaths = [NSMutableArray array];
int pos = 6, noOfFiles = 0, stringSize, i;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *AETitle = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *Address = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *Port = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *TransferSyntax = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &noOfFiles]; noOfFiles = NSSwapBigIntToHost( noOfFiles);
pos += 4;
representationToSend = [NSMutableData dataWithCapacity: 0];
for( i = 0; i < noOfFiles; i++)
{
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *path = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
if( [path UTF8String] [ 0] != '/')
{
int val = [[path stringByDeletingPathExtension] intValue];
NSString *dbLocation = [[DicomDatabase defaultDatabase] sqlFilePath];
val /= [BrowserController DefaultFolderSizeForDB];
val++;
val *= [BrowserController DefaultFolderSizeForDB];
path = [[dbLocation stringByDeletingLastPathComponent] stringByAppendingFormat:@"/DATABASE.noindex/%d/%@", val, path];
}
[localPaths addObject: path];
}
if( [Address isEqualToString: @"127.0.0.1"])
{
struct sockaddr serverAddress;
socklen_t namelen = sizeof( serverAddress);
if (getsockname( [incomingConnection fileDescriptor], (struct sockaddr *)&serverAddress, &namelen) >= 0)
{
char client_ip_address[ 64];
sprintf( client_ip_address, "%-d.%-d.%-d.%-d", ((int) serverAddress.sa_data[2]) & 0xff, ((int) serverAddress.sa_data[3]) & 0xff, ((int) serverAddress.sa_data[4]) & 0xff, ((int) serverAddress.sa_data[5]) & 0xff);
Address = [NSString stringWithCString: client_ip_address encoding: NSUTF8StringEncoding];
}
}
NSDictionary *todo = [NSDictionary dictionaryWithObjectsAndKeys: Address, @"Address", TransferSyntax, @"TransferSyntax", Port, @"Port", AETitle, @"AETitle", localPaths, @"Files", nil];
[NSThread detachNewThreadSelector:@selector(sendDICOMFilesToOsiriXNode:) toTarget:self withObject: todo];
}
else if ([[data subdataWithRange: NSMakeRange(0,6)] isEqualToData: [NSData dataWithBytes:"DICOM" length: 6]])
{
NSMutableArray *localPaths = [NSMutableArray array];
NSMutableArray *dstPaths = [NSMutableArray array];
// We read now the path for the DICOM file(s)
int pos = 6, size, noOfFiles = 0, stringSize, i;
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &noOfFiles]; noOfFiles = NSSwapBigIntToHost( noOfFiles);
pos += 4;
representationToSend = [NSMutableData dataWithCapacity: 512*512*2*(noOfFiles+1)];
for( i = 0; i < noOfFiles; i++)
{
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *path = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
if( [path UTF8String] [ 0] != '/')
{
if( [[[path pathComponents] objectAtIndex: 0] isEqualToString:@"ROIs"])
{
//It's a ROI !
NSString *local = [[[DicomDatabase defaultDatabase] sqlFilePath] stringByDeletingLastPathComponent];
path = [[local stringByAppendingPathComponent:@"/ROIs/"] stringByAppendingPathComponent: [path lastPathComponent]];
}
else
{
int val = [[path stringByDeletingPathExtension] intValue];
val /= [BrowserController DefaultFolderSizeForDB];
val++;
val *= [BrowserController DefaultFolderSizeForDB];
NSString *local = [[[DicomDatabase defaultDatabase] sqlFilePath] stringByDeletingLastPathComponent];
path = [[[local stringByAppendingPathComponent:@"/DATABASE.noindex/"] stringByAppendingPathComponent: [NSString stringWithFormat:@"%d", val]] stringByAppendingPathComponent: path];
}
}
[localPaths addObject: path];
// if([[path pathExtension] isEqualToString:@"zip"])
// {
// // it is a ZIP
// NSLog(@"BONJOUR ZIP");
// NSString *xmlPath = [[path stringByDeletingPathExtension] stringByAppendingPathExtension:@"xml"];
// NSLog(@"xmlPath : %@", xmlPath);
// if([[NSFileManager defaultManager] fileExistsAtPath:xmlPath])
// {
// // it has an XML descriptor with it
// NSLog(@"BONJOUR XML");
// [localPaths addObject:xmlPath];
// }
// }
}
for( i = 0; i < noOfFiles; i++)
{
// We read 4 bytes that contain the string size
while ( [data length] < pos + 4 && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
[[data subdataWithRange: NSMakeRange(pos, 4)] getBytes: &stringSize]; stringSize = NSSwapBigIntToHost( stringSize);
pos += 4;
// We read the string
while ( [data length] < pos + stringSize && (readData = [incomingConnection availableData]) && [readData length]) [data appendData: readData];
NSString *path = [NSString stringWithUTF8String: [[data subdataWithRange: NSMakeRange(pos,stringSize)] bytes]];
pos += stringSize;
[dstPaths addObject: path];
// if([[path pathExtension] isEqualToString:@"zip"])
// {
// // it is a ZIP
// NSLog(@"BONJOUR ZIP");
// NSString *xmlPath = [[path stringByDeletingPathExtension] stringByAppendingPathExtension:@"xml"];
// NSLog(@"xmlPath : %@", xmlPath);
// if([[NSFileManager defaultManager] fileExistsAtPath:xmlPath])
// {
// // it has an XML descriptor with it
// NSLog(@"BONJOUR XML");
// [dstPaths addObject:xmlPath];
// }
// }