A
download daemon.c
Language: C
Copyright: (C) 2002 Ximian, Inc.
LOC: 961
Project Info
Mono
Server: Mono
Type: svn
...\m\mono\mono\mono\io‑layer\
   access.h
   atomic.c
   atomic.h
   collection.c
   collection.h
   context.c
   context.h
   critical-sections.c
   critical-sections.h
   daemon-messages.c
   daemon-messages.h
   daemon-private.h
   daemon.c
   error.c
   error.h
   event-private.h
   events.c
   events.h
   handles-private.h
   handles.c
   handles.h
   hppa_atomic.s
   io-layer-dummy.c
   io-layer.h
   io-portability.c
   io-portability.h
   io-private.h
   io.c
   io.h
   macros.h
   Makefile.am
   misc-private.h
   misc.c
   mono-mutex.c
   mono-mutex.h
   mono-spinlock.h
   mutex-private.h
   mutexes.c
   mutexes.h
   process-private.h
   processes.c
   processes.h
   security.c
   security.h
   semaphore-private.h
   semaphores.c
   semaphores.h
   shared.c
   shared.h
   socket-private.h
   socket-wrappers.h
   sockets.c
   sockets.h
   status.h
   system.c
   system.h
   thread-private.h
   threads.c
   threads.h
   timefuncs-private.h
   timefuncs.c
   timefuncs.h
   types.h
   uglify.h
   versioninfo.h
   wait.c
   wait.h
   wapi-private.h
   wapi.h

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
/*
 * daemon.c:  The handle daemon
 *
 * Author:
 *	Dick Porter (dick@ximian.com)
 *
 * (C) 2002 Ximian, Inc.
 */

#include <config.h>
#include <glib.h>

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/time.h>

#ifdef HAVE_POLL
#include <sys/poll.h>
#endif

#include <mono/io-layer/io-layer.h>
#include <mono/io-layer/handles-private.h>
#include <mono/io-layer/wapi-private.h>
#include <mono/io-layer/daemon-messages.h>
#include <mono/io-layer/timefuncs-private.h>
#include <mono/io-layer/daemon-private.h>
#include <mono/io-layer/socket-wrappers.h>

#undef DEBUG

/* The shared thread codepath doesn't seem to work yet... */
#undef _POSIX_THREAD_PROCESS_SHARED

/* Keep track of the number of clients */
static int nfds=0;

/* Arrays to keep track of channel data for the 
 * daemon and clients indexed by file descriptor
 * value.
 */

typedef struct _channel_data {
	int io_source; /* the ID given back by g_io_add_watch */
	guint32 *open_handles; /* array of open handles for this client */
} ChannelData;

static ChannelData *daemon_channel_data=NULL;
static ChannelData *channels=NULL;
static int channels_length=0;

/* The socket which we listen to new connections on */
static int main_sock;

/* Set to TRUE by the SIGCHLD signal handler */
static volatile gboolean check_processes=FALSE;

/* The file_share_hash is used to emulate the windows file sharing mode */
typedef struct _share_key
{
	dev_t device;
	ino_t inode;
} ShareKey;

typedef struct _share_data
{
	guint32 sharemode;
	guint32 access;
} ShareData;

static GHashTable *file_share_hash = NULL;

static gboolean fd_activity (GIOChannel *channel, GIOCondition condition,
			     gpointer data);
static void check_sharing (dev_t device, ino_t inode);

/* Deletes the shared memory segment.  If we're exiting on error,
 * clients will get EPIPEs.
 */
static void cleanup (void)
{
	int i;
	
#ifdef NEED_LINK_UNLINK
        unlink(_wapi_shared_data[0]->daemon);
#endif 
	for(i=1; i<_wapi_shared_data[0]->num_segments; i++) {
		unlink (_wapi_shm_file (WAPI_SHM_DATA, i));
	}
	unlink (_wapi_shm_file (WAPI_SHM_DATA, 0));
	
	/* There's only one scratch file */
	unlink (_wapi_shm_file (WAPI_SHM_SCRATCH, 0));
}

/* If there is only one socket, and no child processes, we can exit.
 * We test for child processes by counting handle references held by
 * the daemon.
 */
static void maybe_exit (void)
{
	guint32 i;

#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": Seeing if we should exit");
#endif

	if(nfds>1) {
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION ": Still got clients");
#endif
		return;
	}

	/* Prevent new clients from connecting... */
	_wapi_shared_data[0]->daemon_running=DAEMON_CLOSING;

	for(i=0;
	    i<_wapi_shared_data[0]->num_segments * _WAPI_HANDLES_PER_SEGMENT;
	    i++) {
		if(daemon_channel_data->open_handles[i]>0) {
#ifdef DEBUG
			g_message (G_GNUC_PRETTY_FUNCTION
				   ": Still got handle references");
#endif

			_wapi_shared_data[0]->daemon_running=DAEMON_RUNNING;
			return;
		}
	}
	
#ifdef HAVE_POLL
	/* Last check, make sure no client came along while we were
	 * checking the handle lists.
	 *
	 * Use poll() directly here, as glib doesn't seem to have any
	 * exposed way of seeing if a file descriptor is ready
	 * (g_io_channel_get_buffer_condition() isn't it.)
	 *
	 * Crappy systems that don't have poll() will just have to
	 * lump it (for them there is still the very slight chance
	 * that someone tried to connect just as the DAEMON_CLOSING
	 * flag was being set.)
	 */
	{
		struct pollfd fds[1];
		
		fds[0].fd=main_sock;
		fds[0].events=POLLIN;
		fds[0].revents=0;
		
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION ": Last connect check");
#endif

		if(poll (fds, 1, 0)>0) {
			/* Someone did connect, so carry on running */
#ifdef DEBUG
			g_message (G_GNUC_PRETTY_FUNCTION
				   ": Someone connected");
#endif

			_wapi_shared_data[0]->daemon_running=DAEMON_RUNNING;
			return;
		}
	}
#endif
	
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": Byebye");
#endif
	
	cleanup ();
	exit (0);
}

/*
 * signal_handler:
 * @unused: unused
 *
 * Called if daemon receives a SIGTERM or SIGINT
 */
static void signal_handler (int signo)
{
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": daemon received signal %d", signo);
#endif
	cleanup ();
	exit (-1);
}

/*
 * sigchld_handler:
 * @unused: unused
 *
 * Called if daemon receives a SIGCHLD, and notes that a process needs
 * to be wait()ed for.
 */
static void sigchld_handler (int unused)
{
	/* Notice that a child process died */
	check_processes=TRUE;
}

static guint sharedata_hash (gconstpointer key)
{
	ShareKey *sharekey = (ShareKey *)key;
	
	return(g_int_hash (&(sharekey->inode)));
}

static gboolean sharedata_equal (gconstpointer a, gconstpointer b)
{
	ShareKey *share_a = (ShareKey *)a;
	ShareKey *share_b = (ShareKey *)b;
	
	return(share_a->device == share_b->device &&
	       share_a->inode == share_b->inode);
}

/*
 * startup:
 *
 * Bind signals, attach to shared memory and set up any internal data
 * structures needed.
 */
static void startup (void)
{
	struct sigaction sa;
	
	sa.sa_handler=signal_handler;
	sigemptyset (&sa.sa_mask);
	sa.sa_flags=0;
	sigaction (SIGINT, &sa, NULL);
	sigaction (SIGTERM, &sa, NULL);
	
#ifndef HAVE_MSG_NOSIGNAL
	sa.sa_handler=SIG_IGN;
	sigaction (SIGPIPE, &sa, NULL);
#endif

	sa.sa_handler=sigchld_handler;
	sa.sa_flags=SA_NOCLDSTOP;
	sigaction (SIGCHLD, &sa, NULL);
	
#ifdef NEED_LINK_UNLINK
	/* Here's a more portable method... */
	snprintf (_wapi_shared_data[0]->daemon, MONO_SIZEOF_SUNPATH-1,
		  "/tmp/mono-handle-daemon-%d-%ld-%ld", getuid (), random (),
		  time (NULL));
#else
	/* Leave the first byte NULL so we create the socket in the
	 * abstrace namespace, not on the filesystem.  (Lets see how
	 * portable _that_ is :)
	 *
	 * The name is intended to be unique, not cryptographically
	 * secure...
	 */
	snprintf (_wapi_shared_data[0]->daemon+1, MONO_SIZEOF_SUNPATH-2,
		  "mono-handle-daemon-%d-%d-%ld", getuid (), getpid (),
		  time (NULL));
#endif

	file_share_hash = g_hash_table_new_full (sharedata_hash,
						 sharedata_equal, g_free,
						 g_free);
}


/*
 * ref_handle:
 * @channel_data: Channel data for calling client
 * @handle: handle to inc refcnt
 *
 * Increase ref count of handle for the calling client.  Handle 0 is
 * ignored.
 */
static void ref_handle (ChannelData *channel_data, guint32 handle)
{
	guint32 segment, idx;
	
	if(handle==0) {
		return;
	}
	
	_wapi_handle_segment (GUINT_TO_POINTER (handle), &segment, &idx);
	
	_wapi_shared_data[segment]->handles[idx].ref++;
	channel_data->open_handles[handle]++;
	
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION
		   ": handle 0x%x ref now %d (%d this process)", handle,
		   _wapi_shared_data[segment]->handles[idx].ref,
		   channel_data->open_handles[handle]);
#endif
}

/*
 * unref_handle:
 * @channel_data: Channel data for calling client
 * @handle: handle to inc refcnt
 *
 * Decrease ref count of handle for the calling client. If global ref
 * count reaches 0 it is free'ed. Return TRUE if the local ref count
 * is 0. Handle 0 is ignored.
 */
static gboolean unref_handle (ChannelData *channel_data, guint32 handle)
{
	gboolean destroy=FALSE;
	guint32 segment, idx;
	
	if(handle==0) {
		return(FALSE);
	}
	
	if (channel_data->open_handles[handle] == 0) {
                g_warning(G_GNUC_PRETTY_FUNCTION
                          ": unref on %d called when ref was already 0", 
                          handle);
                return TRUE;
        }

	_wapi_handle_segment (GUINT_TO_POINTER (handle), &segment, &idx);
	
	_wapi_shared_data[segment]->handles[idx].ref--;
	channel_data->open_handles[handle]--;
	
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION
		   ": handle 0x%x ref now %d (%d this process)", handle,
		   _wapi_shared_data[segment]->handles[idx].ref,
		   channel_data->open_handles[handle]);
#endif

	if (_wapi_shared_data[segment]->handles[idx].ref == 0) {
		gboolean was_file;
		dev_t device = 0;
		ino_t inode = 0;
		
		/* This client has released the handle */
		destroy=TRUE;
	
		if (channel_data->open_handles[handle]!=0) {
			g_warning (G_GNUC_PRETTY_FUNCTION ": per-process open_handles mismatch, set to %d, should be 0", 
					channel_data->open_handles[handle]);
		}
		
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION ": Destroying handle 0x%x",
			   handle);
#endif

		/* if this was a file handle, save the device and
		 * inode numbers so we can scan the share info data
		 * later to see if the last handle to a file has been
		 * closed, and delete the data if so.
		 */
		was_file = (_wapi_shared_data[segment]->handles[idx].type == WAPI_HANDLE_FILE);
		if (was_file) {
			struct _WapiHandle_file *file_handle;
			gboolean ok;
			
			ok = _wapi_lookup_handle (GUINT_TO_POINTER (handle),
						  WAPI_HANDLE_FILE,
						  (gpointer *)&file_handle,
						  NULL);
			if (ok == FALSE) {
				g_warning (G_GNUC_PRETTY_FUNCTION
					   ": error looking up file handle %x",
					   handle);
			} else {
				device = file_handle->device;
				inode = file_handle->inode;
			}
		}
		
		_wapi_handle_ops_close_shared (GUINT_TO_POINTER (handle));
		
#if defined(_POSIX_THREAD_PROCESS_SHARED) && _POSIX_THREAD_PROCESS_SHARED != -1
		mono_mutex_destroy (&_wapi_shared_data[segment]->handles[idx].signal_mutex);
		pthread_cond_destroy (&_wapi_shared_data[segment]->handles[idx].signal_cond);
#endif

		memset (&_wapi_shared_data[segment]->handles[idx].u, '\0', sizeof(_wapi_shared_data[segment]->handles[idx].u));
		_wapi_shared_data[segment]->handles[idx].type=WAPI_HANDLE_UNUSED;

		if (was_file) {
			check_sharing (device, inode);
		}
	}

	if(channel_data == daemon_channel_data) {
		/* The daemon released a reference, so see if it's
		 * ready to exit
		 */
		maybe_exit ();
	}
	
	return(destroy);
}

/*
 * add_fd:
 * @fd: Filehandle to add
 *
 * Create a new GIOChannel, and add it to the main loop event sources.
 */
static void add_fd(int fd, GMainContext *context)
{
	GIOChannel *io_channel;
	GSource *source;
	guint32 *refs;
	
	io_channel=g_io_channel_unix_new (fd);
	
	/* Turn off all encoding and buffering crap */
	g_io_channel_set_encoding (io_channel, NULL, NULL);
	g_io_channel_set_buffered (io_channel, FALSE);
	
	refs=g_new0 (guint32,_wapi_shared_data[0]->num_segments * _WAPI_HANDLES_PER_SEGMENT);

	if(fd>=channels_length) {
		/* Add a bit of padding, so we dont resize for _every_
		 * new connection
		 */
		int old_len=channels_length * sizeof(ChannelData);
		
		channels_length=fd+10;
		if(channels==NULL) {
			channels=g_new0 (ChannelData, channels_length);
			/* We rely on the daemon channel being created first.
			 * That's safe, because every other channel is the
			 * result of an accept() on the daemon channel.
			 */
			daemon_channel_data = &channels[fd];
		} else {
			int daemon_index=daemon_channel_data - channels;

			/* Can't use g_renew here, because the unused
			 * elements must be NULL and g_renew doesn't
			 * initialise the memory it returns
			 */
			channels=_wapi_g_renew0 (channels, old_len, channels_length * sizeof(ChannelData));
			daemon_channel_data = channels + daemon_index;
		}

	}

	channels[fd].open_handles=refs;

	source = g_io_create_watch (io_channel, 
				    G_IO_IN|G_IO_ERR|G_IO_HUP|G_IO_NVAL);
	g_source_set_callback (source, (GSourceFunc)fd_activity, 
			       context, NULL);
	channels[fd].io_source=g_source_attach (source, context);
	g_source_unref (source);

	nfds++;
}

/*
 * rem_fd:
 * @channel: GIOChannel to close
 *
 * Closes the IO channel. Closes all handles that it may have open. If
 * only main_sock is left, the daemon is shut down.
 */
static void rem_fd(GIOChannel *channel, ChannelData *channel_data)
{
	guint32 handle_count;
	int i, j, fd;
	
	fd=g_io_channel_unix_get_fd (channel);
	
	if(fd == main_sock) {
		/* We shouldn't be deleting the daemon's fd */
		g_warning (G_GNUC_PRETTY_FUNCTION ": Deleting daemon fd!");
		cleanup ();
		exit (-1);
	}
	
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": Removing client fd %d", fd);
#endif

	if (channel_data->io_source == 0) {
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION ": channel already closed for fd %d", fd);
#endif
		return;
	}


	g_io_channel_shutdown (channel, TRUE, NULL);
	g_source_remove (channel_data->io_source);
	g_io_channel_unref (channel);

	for(i=0;
	    i<_wapi_shared_data[0]->num_segments * _WAPI_HANDLES_PER_SEGMENT;
	    i++) {
		handle_count=channel_data->open_handles[i];
		
		for(j=0; j<handle_count; j++) {
#ifdef DEBUG
			g_message (G_GNUC_PRETTY_FUNCTION ": closing handle 0x%x for client at index %d", i, g_io_channel_unix_get_fd (channel));
#endif
			/* Ignore the hint to the client to destroy
			 * the handle private data
			 */
			unref_handle (channel_data, i);
		}
	}
	
	g_free (channel_data->open_handles);
	channel_data->open_handles=NULL;
	channel_data->io_source=0;
	
	nfds--;
	if(nfds==1) {
		/* Just the master socket left, so see if we can
		 * cleanup and exit
		 */
		maybe_exit ();
	}
}

static void sharemode_set (dev_t device, ino_t inode, guint32 sharemode,
			   guint32 access)
{
	ShareKey *sharekey;
	ShareData *sharedata;
	
	sharekey = g_new (ShareKey, 1);
	sharekey->device = device;
	sharekey->inode = inode;

	sharedata = g_new (ShareData, 1);
	sharedata->sharemode = sharemode;
	sharedata->access = access;
	
	/* Setting share mode to include all access bits is really
	 * removing the share info
	 */
	if (sharemode == (FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE)) {
		g_hash_table_remove (file_share_hash, sharekey);
	} else {
		g_hash_table_insert (file_share_hash, sharekey, sharedata);
	}
}

static gboolean sharemode_get (dev_t device, ino_t inode, guint32 *sharemode,
			       guint32 *access)
{
	ShareKey sharekey;
	ShareData *sharedata;
	
	sharekey.device = device;
	sharekey.inode = inode;
	
	sharedata = (ShareData *)g_hash_table_lookup (file_share_hash,
						       &sharekey);
	if (sharedata == NULL) {
		return(FALSE);
	}
	
	*sharemode = sharedata->sharemode;
	*access = sharedata->access;
	
	return(TRUE);
}

static gboolean share_compare (gpointer handle, gpointer user_data)
{
	struct _WapiHandle_file *file_handle;
	gboolean ok;
	ShareKey *sharekey = (ShareKey *)user_data;
	
	ok = _wapi_lookup_handle (handle, WAPI_HANDLE_FILE,
				  (gpointer *)&file_handle, NULL);
	if (ok == FALSE) {
		g_warning (G_GNUC_PRETTY_FUNCTION
			   ": error looking up file handle %p", handle);
		return(FALSE);
	}
	
	if (file_handle->device == sharekey->device &&
	    file_handle->inode == sharekey->inode) {
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION ": found one, handle %p",
			   handle);
#endif
		return(TRUE);
	} else {
		return(FALSE);
	}
}

static void check_sharing (dev_t device, ino_t inode)
{
	ShareKey sharekey;
	gpointer file_handle;
	
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": Checking if anything has (dev 0x%llx, inode %lld) still open", device, inode);
#endif

	sharekey.device = device;
	sharekey.inode = inode;
	
	file_handle = _wapi_search_handle (WAPI_HANDLE_FILE, share_compare,
					   &sharekey, NULL, NULL);

	if (file_handle == NULL) {
		/* Delete this share info, as the last handle to it
		 * has been closed
		 */
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION ": Deleting share data for (dev 0x%llx inode %lld)", device, inode);
#endif
		
		g_hash_table_remove (file_share_hash, &sharekey);
	}
}

static gboolean process_compare (gpointer handle, gpointer user_data)
{
	struct _WapiHandle_process *process_handle;
	gboolean ok;
	pid_t pid;
	guint32 segment, idx;
	
	ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
				(gpointer *)&process_handle, NULL);
	if(ok==FALSE) {
		g_warning (G_GNUC_PRETTY_FUNCTION
			   ": error looking up process handle %p", handle);
		return(FALSE);
	}

	_wapi_handle_segment (handle, &segment, &idx);
	if (_wapi_shared_data[segment]->handles[idx].signalled) {
		return(FALSE);
	}

	pid=GPOINTER_TO_UINT (user_data);
	if(process_handle->id==pid) {
		return(TRUE);
	} else {
		return(FALSE);
	}
}

static gboolean process_thread_compare (gpointer handle, gpointer user_data)
{
	struct _WapiHandle_thread *thread_handle;
	gboolean ok;
	guint32 segment, idx;
	
	ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
				(gpointer *)&thread_handle, NULL);
	if(ok==FALSE) {
		g_warning (G_GNUC_PRETTY_FUNCTION
			   ": error looking up thread handle %p", handle);
		return(FALSE);
	}

	if(thread_handle->process_handle==user_data) {
		/* Signal the handle.  Don't use
		 * _wapi_handle_set_signal_state() unless we have
		 * process-shared pthread support.
		 */
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION ": Set thread handle %p signalled, because its process died", handle);
#endif

		thread_handle->exitstatus=0;

#if defined(_POSIX_THREAD_PROCESS_SHARED) && _POSIX_THREAD_PROCESS_SHARED != -1
		_wapi_handle_lock_handle (handle);
		_wapi_handle_set_signal_state (handle, TRUE, TRUE);
		_wapi_handle_unlock_handle (handle);
#else
		/* Just tweak the signal state directly.  This is not
		 * recommended behaviour, but it works for threads
		 * because they can never become unsignalled.  There
		 * are some nasty kludges in the handle waiting code
		 * to cope with missing condition signals for when
		 * process-shared pthread support is missing.
		 */
		_wapi_handle_segment (handle, &segment, &idx);
		_wapi_shared_data[segment]->handles[idx].signalled=TRUE;
#endif /* _POSIX_THREAD_PROCESS_SHARED */
	}
	
	/* Return false to keep searching */
	return(FALSE);
}

/* Find the handle associated with pid, mark it dead and record exit
 * status.  Finds all thread handles associated with this process
 * handle, and marks those signalled too, with exitstatus '0'.  It
 * also drops the daemon's reference to the handle, and the thread
 * pointed at by main_thread.
 */
static void process_post_mortem (pid_t pid, int status)
{
	gpointer process_handle;
	struct _WapiHandle_process *process_handle_data;
	guint32 segment, idx;
	
	process_handle=_wapi_search_handle (WAPI_HANDLE_PROCESS,
					    process_compare,
					    GUINT_TO_POINTER (pid),
					    (gpointer *)&process_handle_data,
					    NULL);
	if(process_handle==0) {
#ifdef DEBUG
		/*
		 * This may happen if we use Process.EnableRaisingEvents +
		 * process.Exited event and the parent has finished.
		 */
		g_warning (G_GNUC_PRETTY_FUNCTION
			   ": Couldn't find handle for process %d!", pid);
#endif
	} else {
		/* Signal the handle.  Don't use
		 * _wapi_handle_set_signal_state() unless we have
		 * process-shared pthread support.
		 */
		struct timeval tv;
		
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION
			   ": Set process %d exitstatus to %d", pid,
			   WEXITSTATUS (status));
#endif
		
		/* If the child terminated due to the receipt of a signal,
		 * the exit status must be based on WTERMSIG, since WEXITSTATUS
		 * returns 0 in this case.
		 */
		if (WIFSIGNALED(status))
			process_handle_data->exitstatus=128 + WTERMSIG (status);
		else
			process_handle_data->exitstatus=WEXITSTATUS (status);

		/* Ignore errors */
		gettimeofday (&tv, NULL);
		_wapi_timeval_to_filetime (&tv,
					   &process_handle_data->exit_time);

#if defined(_POSIX_THREAD_PROCESS_SHARED) && _POSIX_THREAD_PROCESS_SHARED != -1
		_wapi_handle_lock_handle (process_handle);
		_wapi_handle_set_signal_state (process_handle, TRUE, TRUE);
		_wapi_handle_unlock_handle (process_handle);
#else
		/* Just tweak the signal state directly.  This is not
		 * recommended behaviour, but it works for processes
		 * because they can never become unsignalled.  There
		 * are some nasty kludges in the handle waiting code
		 * to cope with missing condition signals for when
		 * process-shared pthread support is missing.
		 */
		_wapi_handle_segment (process_handle, &segment, &idx);
		_wapi_shared_data[segment]->handles[idx].signalled=TRUE;
#endif /* _POSIX_THREAD_PROCESS_SHARED */
	}

	/* Find all threads that have their process
	 * handle==process_handle.  Ignore the return value, all the
	 * work will be done in the compare func
	 */
	(void)_wapi_search_handle (WAPI_HANDLE_THREAD, process_thread_compare,
				   process_handle, NULL, NULL);

	unref_handle (daemon_channel_data,
		      GPOINTER_TO_UINT (process_handle_data->main_thread));
	unref_handle (daemon_channel_data, GPOINTER_TO_UINT (process_handle));
}

static void process_died (void)
{
	int status;
	pid_t pid;
	
	check_processes=FALSE;

#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": Reaping processes");
#endif

	while(TRUE) {
		pid=waitpid (-1, &status, WNOHANG);
		if(pid==0 || pid==-1) {
			/* Finished waiting.  I was checking pid==-1
			 * separately but was getting ECHILD when
			 * there were no more child processes (which
			 * doesnt seem to conform to the man page)
			 */
			return;
		} else {
			/* pid contains the ID of a dead process */
#ifdef DEBUG
			g_message (G_GNUC_PRETTY_FUNCTION ": process %d reaped", pid);
#endif
			process_post_mortem (pid, status);
		}
	}
}


/*
 * send_reply:
 * @channel: channel to send reply to
 * @resp: Package to send
 *
 * Send a package to a client
 */
static void send_reply (GIOChannel *channel, WapiHandleResponse *resp)
{
	/* send message */
	_wapi_daemon_response (g_io_channel_unix_get_fd (channel), resp);
}

static guint32 new_handle_with_shared_check (WapiHandleType type)
{
	guint32 handle = 0;

	while ((handle = _wapi_handle_new_internal (type)) == 0) {
		/* Try and allocate a new shared segment, and have
		 * another go
		 */
		guint32 segment=_wapi_shared_data[0]->num_segments;
		int i;
		
		_wapi_handle_ensure_mapped (segment);
		if(_wapi_shared_data[segment]!=NULL) {
			/* Got a new segment */
			gulong old_len, new_len;
			
			old_len=_wapi_shared_data[0]->num_segments * _WAPI_HANDLES_PER_SEGMENT * sizeof(guint32);
			_wapi_shared_data[0]->num_segments++;
			new_len=_wapi_shared_data[0]->num_segments * _WAPI_HANDLES_PER_SEGMENT * sizeof(guint32);

			/* Need to expand all the handle reference
			 * count arrays
			 */

			for(i=0; i<channels_length; i++) {
				if(channels[i].open_handles!=NULL) {
					channels[i].open_handles=_wapi_g_renew0 (channels[i].open_handles, old_len, new_len);
				}
			}
		} else {
			/* Map failed.  Just return 0 meaning "out of
			 * handles"
			 */
			break;
		}
	}
	
	return(handle);
}

/*
 * process_new:
 * @channel: The client making the request
 * @channel_data: Our data for this channel
 * @type: type to init handle to
 *
 * Find a free handle and initialize it to 'type', increase refcnt and
 * send back a reply to the client.
 */
static void process_new (GIOChannel *channel, ChannelData *channel_data,
			 WapiHandleType type)
{
	guint32 handle;
	WapiHandleResponse resp={0};
	
	handle = new_handle_with_shared_check (type);
	
	/* handle might still be set to 0.  This is handled at the
	 * client end
	 */

	ref_handle (channel_data, handle);

#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": returning new handle 0x%x",
		   handle);
#endif

	resp.type=WapiHandleResponseType_New;
	resp.u.new.type=type;
	resp.u.new.handle=handle;
			
	send_reply (channel, &resp);
}

/*
 * process_open:
 * @channel: The client making the request
 * @channel_data: Our data for this channel
 * @handle: handle no.
 *
 * Increase refcnt on a previously created handle and send back a
 * response to the client.
 */
static void process_open (GIOChannel *channel, ChannelData *channel_data,
			  guint32 handle)
{
	WapiHandleResponse resp={0};
	guint32 segment, idx;
	struct _WapiHandleShared *shared;

	_wapi_handle_segment (GUINT_TO_POINTER (handle), &segment, &idx);
	shared=&_wapi_shared_data[segment]->handles[idx];
		
	if(shared->type!=WAPI_HANDLE_UNUSED && handle!=0) {
		ref_handle (channel_data, handle);

#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION
			   ": returning new handle 0x%x", handle);
#endif

		resp.type=WapiHandleResponseType_Open;
		resp.u.new.type=shared->type;
		resp.u.new.handle=handle;
			
		send_reply (channel, &resp);

		return;
	}

	resp.type=WapiHandleResponseType_Open;
	resp.u.new.handle=0;
			
	send_reply (channel, &resp);
}

/*
 * process_close:
 * @channel: The client making the request
 * @channel_data: Our data for this channel
 * @handle: handle no.
 *
 * Decrease refcnt on a previously created handle and send back a
 * response to the client with notice of it being destroyed.
 */
static void process_close (GIOChannel *channel, ChannelData *channel_data,
			   guint32 handle)
{
	WapiHandleResponse resp={0};
	
	resp.type=WapiHandleResponseType_Close;
	resp.u.close.destroy=unref_handle (channel_data, handle);

#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": unreffing handle 0x%x", handle);
#endif
			
	send_reply (channel, &resp);
}

/*
 * process_scratch:
 * @channel: The client making the request
 * @length: allocate this much scratch space
 *
 * Allocate some scratch space and send a reply to the client.
 */
static void process_scratch (GIOChannel *channel, guint32 length)
{
	WapiHandleResponse resp={0};
	
	resp.type=WapiHandleResponseType_Scratch;
	resp.u.scratch.idx=_wapi_handle_scratch_store_internal (length, &resp.u.scratch.remap);
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": allocating scratch index 0x%x",
		   resp.u.scratch.idx);
#endif
			
	send_reply (channel, &resp);
}

/*
 * process_scratch_free:
 * @channel: The client making the request
 * @scratch_idx: deallocate this scratch space
 *
 * Deallocate scratch space and send a reply to the client.
 */
static void process_scratch_free (GIOChannel *channel, guint32 scratch_idx)
{
	WapiHandleResponse resp={0};
	
	resp.type=WapiHandleResponseType_ScratchFree;
	_wapi_handle_scratch_delete_internal (scratch_idx);

#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": deleting scratch index 0x%x",
		   scratch_idx);
#endif
			
	send_reply (channel, &resp);
}

/*
 * process_process_kill:
 * @channel: The client making the request
 * @process_kill: pid and signal to send to the pid.
 *
 * Sends the specified signal to the process.
 */
static void
process_process_kill (GIOChannel *channel,
		      WapiHandleRequest_ProcessKill process_kill)
{
	WapiHandleResponse resp = {0};

	resp.type = WapiHandleResponseType_ProcessKill;

#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": kill (%d, %d)",
		   process_kill.pid, process_kill.signo);
#endif
	if (kill (process_kill.pid, process_kill.signo) == -1) {
		resp.u.process_kill.err = errno;
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": kill (%d, %d) failed: %d",
		   process_kill.pid, process_kill.signo, resp.u.process_kill.err);
#endif
	}

	send_reply (channel, &resp);
}

/*
 * process_process_fork:
 * @channel: The client making the request
 * @process_fork: Describes the process to fork
 * @fds: stdin, stdout, and stderr for the new process
 *
 * Forks a new process, and returns the process and thread data to the
 * client.
 */
static void process_process_fork (GIOChannel *channel, ChannelData *channel_data,
				  WapiHandleRequest_ProcessFork process_fork,
				  int *fds)
{
	WapiHandleResponse resp={0};
	guint32 process_handle, thread_handle;
	struct _WapiHandle_process *process_handle_data;
	struct _WapiHandle_thread *thread_handle_data;
	pid_t pid = 0;
	
	resp.type=WapiHandleResponseType_ProcessFork;
	
	/* Create handles first, so the child process can store exec
	 * errors.  Either handle might be set to 0, if this happens
	 * just reply to the client without bothering to fork.  The
	 * client must check if either handle is 0 and take
	 * appropriate error handling action.
	 */
	process_handle = new_handle_with_shared_check (WAPI_HANDLE_PROCESS);
	ref_handle (daemon_channel_data, process_handle);
	ref_handle (channel_data, process_handle);
	
	thread_handle = new_handle_with_shared_check (WAPI_HANDLE_THREAD);
	ref_handle (daemon_channel_data, thread_handle);
	ref_handle (channel_data, thread_handle);
	
	if(process_handle==0 || thread_handle==0) {
		/* unref_handle() copes with the handle being 0 */
		unref_handle (daemon_channel_data, process_handle);
		unref_handle (channel_data, process_handle);
		unref_handle (daemon_channel_data, thread_handle);
		unref_handle (channel_data, thread_handle);
		process_handle=0;
		thread_handle=0;
	} else {
		char *cmd=NULL, *dir=NULL, **argv, **env;
		GError *gerr=NULL;
		gboolean ret;
		struct timeval tv;
		
		/* Get usable copies of the cmd, dir and env now
		 * rather than in the child process.  This is to
		 * prevent the race condition where the parent can
		 * return the reply to the client, which then promptly
		 * deletes the scratch data before the new process
		 * gets to see it.  Also explode argv here so we can
		 * use it to set the process name.
		 */
		cmd=_wapi_handle_scratch_lookup (process_fork.cmd);
		dir=_wapi_handle_scratch_lookup (process_fork.dir);
		env=_wapi_handle_scratch_lookup_string_array (process_fork.env);

		_wapi_lookup_handle (GUINT_TO_POINTER (process_handle),
				     WAPI_HANDLE_PROCESS,
				     (gpointer *)&process_handle_data,
				     NULL);

		_wapi_lookup_handle (GUINT_TO_POINTER (thread_handle),
				     WAPI_HANDLE_THREAD,
				     (gpointer *)&thread_handle_data,
				     NULL);
		
		ret=g_shell_parse_argv (cmd, NULL, &argv, &gerr);
		if(ret==FALSE) {
			/* FIXME: Could do something with the
			 * GError here
			 */
			process_handle_data->exec_errno=gerr->code;
		} else {
#ifdef DEBUG
			g_message (G_GNUC_PRETTY_FUNCTION ": forking");
#endif

			/* Fork, exec cmd with args and optional env,
			 * and return the handles with pid and blank
			 * thread id
			 */
			pid=fork ();
			if(pid==-1) {
				process_handle_data->exec_errno=errno;
			} else if (pid==0) {
				/* child */
				int i;
				
				/* should we detach from the process
				 * group? We're already running
				 * without a controlling tty...
				 */

				/* Connect stdin, stdout and stderr */
				dup2 (fds[0], 0);
				dup2 (fds[1], 1);
				dup2 (fds[2], 2);

				if(process_fork.inherit!=TRUE) {
					/* FIXME: do something here */
				}
				
				/* Close all file descriptors */
				for (i = getdtablesize () - 1; i > 2; i--) {
					close (i);
				}
			
				/* pass process and thread handle info
				 * to the child, so it doesn't have to
				 * do an expensive search over the
				 * whole list
				 */
				{
					guint env_count=0;
					
					while(env[env_count]!=NULL) {
						env_count++;
					}

					env=(char **)g_renew (char **, env, env_count+3);
					
					env[env_count]=g_strdup_printf ("_WAPI_PROCESS_HANDLE=%d", process_handle);
					env[env_count+1]=g_strdup_printf ("_WAPI_THREAD_HANDLE=%d", thread_handle);
					env[env_count+2]=NULL;
				}

#ifdef DEBUG
				g_message (G_GNUC_PRETTY_FUNCTION
					   ": exec()ing [%s] in dir [%s]",
					   cmd, dir);
				{
					i=0;
					while(argv[i]!=NULL) {
						g_message ("arg %d: [%s]",
							   i, argv[i]);
						i++;
					}

					i=0;
					while(env[i]!=NULL) {
						g_message ("env %d: [%s]",
							   i, env[i]);
						i++;
					}
				}
#endif
			
				/* set cwd */
				if(chdir (dir)==-1) {
					process_handle_data->exec_errno=errno;
					exit (-1);
				}
				
				/* exec */
				execve (argv[0], argv, env);
		
				/* bummer! */
				process_handle_data->exec_errno=errno;
				exit (-1);
			}
		}
		/* parent */

		/* store process name, based on the last section of the cmd */
		{
			char *slash;
			
			/* This should never fail, but it seems it can...
			 */
			if (argv[0] != NULL) {
				slash=strrchr (argv[0], '/');
			
				if(slash!=NULL) {
					process_handle_data->proc_name=_wapi_handle_scratch_store (slash+1, strlen (slash+1));
				} else {
					process_handle_data->proc_name=_wapi_handle_scratch_store (argv[0], strlen (argv[0]));
				}
			} else {
				process_handle_data->proc_name = _wapi_handle_scratch_store (cmd, strlen(cmd));
			}
		}
		
		/* These seem to be the defaults on w2k */
		process_handle_data->min_working_set=204800;
		process_handle_data->max_working_set=1413120;
		
		if(cmd!=NULL) {
			g_free (cmd);
		}
		if(dir!=NULL) {
			g_free (dir);
		}
		g_strfreev (argv);
		g_strfreev (env);
		
		/* store pid */
		process_handle_data->id=pid;
		process_handle_data->main_thread=GUINT_TO_POINTER (thread_handle);
		/* Ignore errors */
		gettimeofday (&tv, NULL);
		_wapi_timeval_to_filetime (&tv,
					   &process_handle_data->create_time);
		
		/* FIXME: if env==0, inherit the env from the current
		 * process
		 */
		process_handle_data->env=process_fork.env;

		thread_handle_data->process_handle=GUINT_TO_POINTER (process_handle);

		resp.u.process_fork.pid=pid;
	}

	resp.u.process_fork.process_handle=process_handle;
	resp.u.process_fork.thread_handle=thread_handle;

	send_reply (channel, &resp);
}

/*
 * process_set_share:
 * @channel: The client making the request
 * @channel_data: The channel data
 * @set_share: Set share data passed from the client
 *
 * Sets file share info
 */
static void process_set_share (GIOChannel *channel, ChannelData *channel_data,
			       WapiHandleRequest_SetShare set_share)
{
	WapiHandleResponse resp = {0};

	resp.type = WapiHandleResponseType_SetShare;
	
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION ": Setting share for file (dev:0x%llx, ino:%lld) mode 0x%x access 0x%x", set_share.device, set_share.inode, set_share.sharemode, set_share.access);
#endif
	
	sharemode_set (set_share.device, set_share.inode, set_share.sharemode,
		       set_share.access);
	
	send_reply (channel, &resp);
}

/*
 * process_get_or_set_share:
 * @channel: The client making the request
 * @channel_data: The channel data
 * @get_share: GetOrSetShare data passed from the client
 *
 * Gets a file share status, and sets the status if it doesn't already
 * exist
 */
static void process_get_or_set_share (GIOChannel *channel,
				      ChannelData *channel_data,
				      WapiHandleRequest_GetOrSetShare get_share)
{
	WapiHandleResponse resp = {0};
	
	resp.type = WapiHandleResponseType_GetOrSetShare;
	
#ifdef DEBUG
	g_message (G_GNUC_PRETTY_FUNCTION
		   ": Getting share status for file (dev:0x%llx, ino:%lld)",
		   get_share.device, get_share.inode);
#endif

	resp.u.get_or_set_share.exists = sharemode_get (get_share.device, get_share.inode, &resp.u.get_or_set_share.sharemode, &resp.u.get_or_set_share.access);
	
	if (resp.u.get_or_set_share.exists) {
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION ": Share mode: 0x%x",
			   resp.u.get_or_set_share.sharemode);
#endif
	} else {
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION
			   ": file share info not already known, setting");
#endif
		sharemode_set (get_share.device, get_share.inode,
			       get_share.new_sharemode, get_share.new_access);
	}
	
	send_reply (channel, &resp);
}

/*
 * read_message:
 * @channel: The client to read the request from
 * @open_handles: An array of handles referenced by this client
 *
 * Read a message (A WapiHandleRequest) from a client and dispatch
 * whatever it wants to the process_* calls.  Return TRUE if the message
 * was read successfully, FALSE otherwise.
 */
static gboolean read_message (GIOChannel *channel, ChannelData *channel_data)
{
	WapiHandleRequest req;
	int fds[3]={0, 1, 2};
	int ret;
	gboolean has_fds=FALSE;
	
	/* Reading data */
	ret=_wapi_daemon_request (g_io_channel_unix_get_fd (channel), &req,
				  fds, &has_fds);
	if(ret==0) {
		/* Other end went away */
#ifdef DEBUG
		g_message ("Read 0 bytes on fd %d, closing it",
			   g_io_channel_unix_get_fd (channel));
#endif
		rem_fd (channel, channel_data);
		return(FALSE);
	}
	
#ifdef DEBUG
	g_message ("Process request %d", req.type);
#endif
	switch(req.type) {
	case WapiHandleRequestType_New:
		process_new (channel, channel_data, req.u.new.type);
		break;
	case WapiHandleRequestType_Open:
#ifdef DEBUG
		g_assert(req.u.open.handle < _wapi_shared_data[0]->num_segments * _WAPI_HANDLES_PER_SEGMENT);
#endif
		process_open (channel, channel_data, req.u.open.handle);
		break;
	case WapiHandleRequestType_Close:
#ifdef DEBUG
		g_assert(req.u.close.handle < _wapi_shared_data[0]->num_segments * _WAPI_HANDLES_PER_SEGMENT);
#endif
		process_close (channel, channel_data, req.u.close.handle);
		break;
	case WapiHandleRequestType_Scratch:
		process_scratch (channel, req.u.scratch.length);
		break;
	case WapiHandleRequestType_ScratchFree:
		process_scratch_free (channel, req.u.scratch_free.idx);
		break;
	case WapiHandleRequestType_ProcessFork:
		process_process_fork (channel, channel_data,
				      req.u.process_fork, fds);
		break;
	case WapiHandleRequestType_ProcessKill:
		process_process_kill (channel, req.u.process_kill);
		break;
	case WapiHandleRequestType_SetShare:
		process_set_share (channel, channel_data, req.u.set_share);
		break;
	case WapiHandleRequestType_GetOrSetShare:
		process_get_or_set_share (channel, channel_data,
					  req.u.get_or_set_share);
		break;
	case WapiHandleRequestType_Error:
		/* fall through */
	default:
		/* Catch bogus requests */
		/* FIXME: call rem_fd? */
		break;
	}

	if(has_fds==TRUE) {
#ifdef DEBUG
		g_message (G_GNUC_PRETTY_FUNCTION ": closing %d", fds[0]);
		g_message (G_GNUC_PRETTY_FUNCTION ": closing %d", fds[1]);
		g_message (G_GNUC_PRETTY_FUNCTION ": closing %d", fds[2]);
#endif
		
		close (fds[0]);
		close (fds[1]);
		close (fds[2]);
	}

	return(TRUE);
}

/*
 * fd_activity:
 * @channel: The IO channel that is active
 * @condition: The condition that has been satisfied
 * @data: A pointer to an array of handles referenced by this client
 *
 * The callback called by the main loop when there is activity on an
 * IO channel.
 */
static gboolean fd_activity (GIOChannel *channel, GIOCondition condition,
			     gpointer data)
{
	int fd=g_io_channel_unix_get_fd (channel);
	ChannelData *channel_data=&channels[fd];
	GMainContext *context=data;
	
	if(condition & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
#ifdef DEBUG
		g_message ("fd %d error", fd);
#endif

		rem_fd (channel, channel_data);
		return(FALSE);
	}

	if(condition & (G_IO_IN | G_IO_PRI)) {
		if(fd==main_sock) {
			int newsock;
			struct sockaddr addr;
			socklen_t addrlen=sizeof(struct sockaddr);
			
			newsock=accept (main_sock, &addr, &addrlen);
			if(newsock==-1) {
				g_critical ("accept error: %s",
					    g_strerror (errno));
				cleanup ();
				exit (-1);
			}

#ifdef DEBUG
			g_message ("accept returning %d", newsock);
#endif

			add_fd (newsock, context);
		} else {
#ifdef DEBUG
			g_message ("reading data on fd %d", fd);
#endif

			return(read_message (channel, channel_data));
		}
		return(TRUE);
	}
	
	return(FALSE);	/* remove source */
}

/*
 * _wapi_daemon_main:
 *
 * Open socket, create shared mem segment and begin listening for
 * clients.
 */
void _wapi_daemon_main(gpointer data, gpointer scratch)
{
	struct sockaddr_un main_socket_address;
	int ret;
	GMainContext *context;

#ifdef DEBUG
	g_message ("Starting up...");
#endif

	_wapi_shared_data[0]=data;
	_wapi_shared_scratch=scratch;
	_wapi_shared_scratch->is_shared=TRUE;
	
	/* Note that we've got the starting segment already */
	_wapi_shared_data[0]->num_segments=1;
	_wapi_shm_mapped_segments=1;

	_wapi_fd_offset_table_size=getdtablesize ();
	_wapi_shared_data[0]->fd_offset_table_size = _wapi_fd_offset_table_size;
	
	startup ();
	
	main_sock=socket(PF_UNIX, SOCK_STREAM, 0);

	main_socket_address.sun_family=AF_UNIX;
	memcpy(main_socket_address.sun_path, _wapi_shared_data[0]->daemon,
	       MONO_SIZEOF_SUNPATH);

	ret=bind(main_sock, (struct sockaddr *)&main_socket_address,
		 sizeof(struct sockaddr_un));
	if(ret==-1) {
		g_critical ("bind failed: %s", g_strerror (errno));
		_wapi_shared_data[0]->daemon_running=DAEMON_DIED_AT_STARTUP;
		exit(-1);
	}

#ifdef DEBUG
	g_message("bound");
#endif

	ret=listen(main_sock, 5);
	if(ret==-1) {
		g_critical ("listen failed: %s", g_strerror (errno));
		_wapi_shared_data[0]->daemon_running=DAEMON_DIED_AT_STARTUP;
		exit(-1);
	}

#ifdef DEBUG
	g_message("listening");
#endif

	context = g_main_context_new ();

	add_fd(main_sock, context);

	/* We're finished setting up, let everyone else know we're
	 * ready.  From now on, it's up to us to delete the shared
	 * memory segment when appropriate.
	 */
	_wapi_shared_data[0]->daemon_running=DAEMON_RUNNING;

	while(TRUE) {
		if(check_processes==TRUE) {
			process_died ();
		}
		
#ifdef DEBUG
		g_message ("polling");
#endif

		/* Block until something happens. We don't use
		 * g_main_loop_run() because we rely on the SIGCHLD
		 * signal interrupting poll() so we can reap child
		 * processes as soon as they die, without burning cpu
		 * time by polling the flag.
		 */
		g_main_context_iteration (context, TRUE);
	}
}

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us