File: libith.cpp

package info (click to toggle)
ike 2.2.1%2Bdfsg-3
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 2,240 kB
  • ctags: 2,674
  • sloc: cpp: 28,690; yacc: 1,499; lex: 324; sh: 149; makefile: 33
file content (1546 lines) | stat: -rw-r--r-- 28,244 bytes parent folder | download | duplicates (3)
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
/*
 * Copyright (c) 2007
 *      Shrew Soft Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Redistributions in any form must be accompanied by information on
 *    how to obtain complete source code for the software and any
 *    accompanying software that uses the software.  The source code
 *    must either be included in the distribution or be available for no
 *    more than the cost of distribution plus a nominal fee, and must be
 *    freely redistributable under reasonable conditions.  For an
 *    executable file, complete source code means the source code for all
 *    modules it contains.  It does not include source code for modules or
 *    files that typically accompany the major components of the operating
 *    system on which the executable file runs.
 *
 * THIS SOFTWARE IS PROVIDED BY SHREW SOFT INC ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT, ARE DISCLAIMED.  IN NO EVENT SHALL SHREW SOFT INC
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 *
 * AUTHOR : Matthew Grooms
 *          mgrooms@shrew.net
 *
 */

#include "libith.h"

//==============================================================================
// mutex lock class
//==============================================================================

#ifdef WIN32

_ITH_LOCK::_ITH_LOCK()
{
	memset( obj_name, 0, 20 );
	hmutex = CreateMutex( NULL, false, NULL );
	strcpy_s( obj_name, 20, "unknown" );
}

_ITH_LOCK::~_ITH_LOCK()
{
	CloseHandle( hmutex );
}

void _ITH_LOCK::name( const char * set_name )
{
	strcpy_s( obj_name, 20, set_name );
}

bool _ITH_LOCK::lock()
{
	int result = WaitForSingleObject( hmutex, 3000 );

	assert( result != WAIT_FAILED );

	if( result != WAIT_FAILED )
		return true;

	result = GetLastError();

	printf( "XX : mutex lock failed, ERROR CODE %i\n", result );

	return false;
}

bool _ITH_LOCK::unlock()
{
	ReleaseMutex( hmutex );

	return true;
}

#endif

#ifdef UNIX

_ITH_LOCK::_ITH_LOCK()
{
	memset( obj_name, 0, 20 );
	pthread_mutexattr_init( &attr );
	pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
	pthread_mutex_init( &mutex, &attr );
}

_ITH_LOCK::~_ITH_LOCK()
{
	pthread_mutex_destroy( &mutex );
	pthread_mutexattr_destroy( &attr );
}

void _ITH_LOCK::name( const char * set_name )
{
	strcpy_s( obj_name, 20, set_name );
}

bool _ITH_LOCK::lock()
{

#ifdef OPT_TIMEDLOCK

        struct timespec ts;
        clock_gettime( CLOCK_REALTIME, &ts );
        ts.tv_sec += 3;

	int result = pthread_mutex_timedlock( &mutex, &ts );

#else

	int result = pthread_mutex_lock( &mutex );

#endif

	switch( result )
	{
		case 0:
			return true;

		case EINVAL:
			printf( "XX : mutex %s lock failed, invalid parameter\n", obj_name  );
			break;

		case ETIMEDOUT:
			printf( "XX : mutex %s lock failed, timeout expired\n", obj_name );
			break;

		case EAGAIN:
			printf( "XX : mutex %s lock failed, recursion error\n", obj_name );
			break;

		case EDEADLK:
			printf( "XX : mutex %s lock failed, mutex already owned\n", obj_name );
			break;
	}

	assert( result == 0 );

	return false;
}

bool _ITH_LOCK::unlock()
{

	int result = pthread_mutex_unlock( &mutex );

	switch( result )
	{
		case 0:
			return true;

		case EINVAL:
			printf( "XX : mutex %s unlock failed, mutex not owned\n", obj_name );
			break;
	}

	assert( result == 0 );

	return false;
}

#endif

//==============================================================================
// alertable wait condition
//==============================================================================

#ifdef WIN32

_ITH_COND::_ITH_COND()
{
	hevent = CreateEvent( NULL, TRUE, FALSE, NULL );
}

_ITH_COND::~_ITH_COND()
{
	CloseHandle( hevent );
}

void _ITH_COND::name( const char * set_name )
{
	strcpy_s( obj_name, 20, set_name );
}

bool _ITH_COND::wait( long msecs )
{
	if( msecs < 0 )
		msecs = INFINITE;

	if( WaitForSingleObject( hevent, msecs ) == WAIT_OBJECT_0 )
		return false;

	return true;
}

void _ITH_COND::alert()
{
	SetEvent( hevent );
}

void _ITH_COND::reset()
{
	ResetEvent( hevent );
}

#endif

#ifdef UNIX

_ITH_COND::_ITH_COND()
{
	socketpair( AF_UNIX, SOCK_STREAM, 0, conn_wake );
	fcntl( conn_wake[ 0 ], F_SETFL, O_NONBLOCK );
}

_ITH_COND::~_ITH_COND()
{
	if( conn_wake[ 0 ] != -1 )
	{
		close( conn_wake[ 0 ] );
		conn_wake[ 0 ] = -1;
	}

	if( conn_wake[ 1 ] != -1 )
	{
		close( conn_wake[ 1 ] );
		conn_wake[ 1 ] = -1;
	}

}

void _ITH_COND::name( const char * set_name )
{
	strcpy_s( obj_name, 20, set_name );
}

bool _ITH_COND::wait( long msecs )
{
	// timeval expressed as seconds and microseconds

	timeval	tval;
	timeval * ptval = NULL;

	if( msecs >= 0 )
	{
		tval.tv_sec = msecs / 1000;
		tval.tv_usec = msecs % 1000 * 1000;
		ptval = &tval;
	}

	fd_set fds;
	FD_ZERO( &fds );
	FD_SET( conn_wake[ 0 ], &fds );

	select( conn_wake[ 0 ] + 1, &fds, NULL, NULL, ptval );

	if( FD_ISSET( conn_wake[ 0 ], &fds ) )
		return false;

	return true;
}

void _ITH_COND::alert()
{
	char c = 0;
	long result = send( conn_wake[ 1 ], &c, 1, 0 );
}

void _ITH_COND::reset()
{
	char c = 0;
	long result = recv( conn_wake[ 0 ], &c, 1, 0 );
}

#endif

//==============================================================================
// thread execution class
//==============================================================================

typedef struct _ITH_PARAM
{
	ITH_EXEC *	exec;
	void *		arg;

}ITH_PARAM;

_ITH_EXEC::_ITH_EXEC()
{
}

#ifdef WIN32

unsigned long __stdcall help( void * arg )
{
	ITH_PARAM * param = ( ITH_PARAM * ) arg;

	long result = param->exec->func( param->arg );

	delete param;

	return result;
}

bool _ITH_EXEC::exec( void * arg )
{
	ITH_PARAM * param = new ITH_PARAM;
	if( param == NULL )
		return false;

	param->exec = this;
	param->arg = arg;

	DWORD tid;

	CreateThread(
		NULL,
		0,
		help,
		param,
		0,
		&tid );

	return true;
}

#endif

#ifdef UNIX

void * help( void * arg )
{
	ITH_PARAM * param = ( ITH_PARAM * ) arg;

	sigset_t signal_mask;
	sigemptyset( &signal_mask );
	sigaddset( &signal_mask, SIGINT );
	sigaddset( &signal_mask, SIGTERM );
	pthread_sigmask( SIG_BLOCK, &signal_mask, NULL );

	param->exec->func( param->arg );

	delete param;

	return NULL;
}

bool _ITH_EXEC::exec( void * arg )
{
	ITH_PARAM * param = new ITH_PARAM;
	if( param == NULL )
		return false;

	param->exec = this;
	param->arg = arg;

	pthread_create(
		&thread,
		NULL,
		&help,
		param );

	pthread_detach(
		thread );

	return true;
}

#endif

//==============================================================================
// event execution timer classes
//==============================================================================

_ITH_TIMER::_ITH_TIMER()
{
	head = NULL;

	stop = false;
	exit = false;
}

_ITH_TIMER::~_ITH_TIMER()
{
	while( head != NULL )
	{
		ITH_ENTRY * next = head->next;
		delete head;
		head = next;
	}
}

#ifdef WIN32

void _ITH_TIMER::tval_cur( ITH_TIMEVAL & tval )
{
	SYSTEMTIME stime;
	memset( &stime, 0, sizeof( stime ) );
	GetSystemTime( &stime );

	FILETIME ftime;
	memset( &ftime, 0, sizeof( ftime ) );
	SystemTimeToFileTime( &stime, &ftime );

	memcpy( &tval, &ftime, sizeof( tval ) );
}

void _ITH_TIMER::tval_add( ITH_TIMEVAL & tval, long lval )
{
	// ftime expressed as 100 nanosecond units

	ITH_TIMEVAL dval;
	dval.QuadPart = lval;
	dval.QuadPart *= 10000;

	tval.QuadPart += dval.QuadPart;
}

long _ITH_TIMER::tval_sub( ITH_TIMEVAL & tval1, ITH_TIMEVAL & tval2 )
{
	ITH_TIMEVAL dval;
	dval.QuadPart = tval2.QuadPart - tval1.QuadPart;

	return long( dval.QuadPart / 10000 );
}

bool _ITH_TIMER::wait_time( long msecs )
{
	return cond.wait( msecs );
}

#endif

#ifdef UNIX

void _ITH_TIMER::tval_cur( ITH_TIMEVAL & tval )
{
	gettimeofday( &tval, NULL );
}

void _ITH_TIMER::tval_add( ITH_TIMEVAL & tval, long delay )
{
	// timeval expressed as seconds and microseconds

	tval.tv_sec += delay / 1000;
	tval.tv_usec += delay % 1000 * 1000;
}

long _ITH_TIMER::tval_sub( ITH_TIMEVAL & tval1, ITH_TIMEVAL & tval2 )
{
	long sec = tval2.tv_sec - tval1.tv_sec;
	sec *= 1000;

	long usec = tval2.tv_usec - tval1.tv_usec;
	usec /= 1000;

	return sec + usec;
}

bool _ITH_TIMER::wait_time( long msecs )
{
	return cond.wait( msecs );
}

#endif

void _ITH_TIMER::run()
{
	lock.lock();

	while( !stop )
	{
		//
		// determine the time we must
		// wait before the next event
		// should be executed
		//

		long delay = -1;

		if( head != NULL )
		{
			ITH_TIMEVAL current;
			tval_cur( current );
			delay = tval_sub( current, head->sched );

			if( delay < 0 )
				delay = 0;
		}

		//
		// wait for calculated delay
		//

		lock.unlock();

		bool result = wait_time( delay );

		lock.lock();

		//
		// if the wait returned false,
		// it returned before the time
		// period elapsed
		//

		if( !result )
		{
			cond.reset();
			continue;
		}

		//
		// check if we have an event
		// that needs to be enabled
		//

		if( head != NULL )
		{
			ITH_TIMEVAL current;
			tval_cur( current );

			//
			// make sure the head event
			// is ready to execute
			//

			if( tval_sub( current, head->sched ) > 0 )
				continue;

			ITH_ENTRY * entry = head;
			head = head->next;

			//
			// execute the event
			//

			lock.unlock();

			if( entry->event->func() )
				add( entry->event );

			delete entry;
			lock.lock();
		}
	}

	exit = true;

	lock.unlock();
}

void _ITH_TIMER::end()
{
	stop = true;

	cond.alert();
}

bool _ITH_TIMER::add( ITH_EVENT * event )
{
	ITH_ENTRY * entry = new ITH_ENTRY;
	if( entry == NULL )
		return false;

	entry->event = event;
	tval_cur( entry->sched );
	tval_add( entry->sched, event->delay );

	lock.lock();

	ITH_ENTRY * prev = NULL;
	ITH_ENTRY * next = head;

	while( next != NULL )
	{
		if( tval_sub( next->sched, entry->sched ) <= 0 )
			break;

		if( next == NULL )
			break;

		prev = next;
		next = prev->next;
	}

	entry->next = next;

	if( prev == NULL )
		head = entry;
	else
		prev->next = entry;

	cond.alert();

	lock.unlock();

	return true;
}

bool _ITH_TIMER::del( ITH_EVENT * event )
{
	ITH_ENTRY * prev = NULL;
	ITH_ENTRY * next = head;

	lock.lock();

	while( next != NULL )
	{
		if( next->event == event )
			break;

		if( next == NULL )
			break;

		prev = next;
		next = prev->next;
	}

	if( next != NULL )
	{
		if( prev == NULL )
			head = next->next;
		else
			prev->next = next->next;

		delete next;
	}

	lock.unlock();

	return ( next != NULL );
}

//==============================================================================
// inter process communication classes
//==============================================================================

//
// shared platform functions
//

long _ITH_IPCC::io_send( void *data, size_t size )
{
	char * buff = ( char * ) data;
	size_t sent = 0;
	size_t temp = 0;

	while( size > sent )
	{
		temp = size - sent;
		long result = io_send( buff + sent, temp, temp );

		switch( result )
		{
			case IPCERR_OK:
			case IPCERR_BUFFER:
				break;

			default:
				return result;
		}


		sent += temp;
	}

	return IPCERR_OK;
}

long _ITH_IPCC::io_recv( void *data, size_t size )
{
	char * buff = ( char * ) data;
	size_t rcvd = 0;
	size_t temp = 0;

	while( size > rcvd )
	{
		temp = size - rcvd;
		long result = io_recv( buff + rcvd, temp, temp );

		switch( result )
		{
			case IPCERR_OK:
			case IPCERR_BUFFER:
				break;

			default:
				return result;
		}

		rcvd += temp;
	}

	return IPCERR_OK;
}

#ifdef WIN32

//
// inter process communication client
//

_ITH_IPCC::_ITH_IPCC()
{
	hmutex_recv = CreateMutex( NULL, false, NULL );
	hmutex_send = CreateMutex( NULL, false, NULL );

	hevent_wake = CreateEvent( NULL, true, false, NULL );

	conn = INVALID_HANDLE_VALUE;
}

_ITH_IPCC::~_ITH_IPCC()
{
	detach();

	if( hevent_wake != NULL )
	{
		CloseHandle( hevent_wake );
		hevent_wake = NULL;
	}

	if( hmutex_send != NULL )
	{
		CloseHandle( hmutex_send );
		hmutex_send = NULL;
	}

	if( hmutex_recv != NULL )
	{
		CloseHandle( hmutex_recv );
		hmutex_recv = NULL;
	}
}


void _ITH_IPCC::io_conf( IPCCONN sconn )
{
	conn = sconn;
}

VOID WINAPI io_send_complete( DWORD result, DWORD size, LPOVERLAPPED olapp )
{
	// nothing to do
}

long _ITH_IPCC::io_send( void * data, size_t size, size_t & sent )
{
//	if( conn == INVALID_HANDLE_VALUE )
//		return IPCERR_CLOSED;

	DWORD dwsize = ( DWORD ) sent;

	WaitForSingleObject( hmutex_send, INFINITE );

	// windows does not always set
	// the GetLastError value to
	// success after ReadFileEx but
	// the documentation says you
	// should check it for errors

	SetLastError( ERROR_SUCCESS );

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

	long result = WriteFileEx(
					conn,
					data,
					dwsize,
					&olapp_send,
					io_send_complete );

	if( !result )
	{
		result = WaitForSingleObject( hevent_wake, 0 );
//		if( result == WAIT_OBJECT_0 )
//			ResetEvent( hevent_wake );

		ReleaseMutex( hmutex_send );

		if( result == WAIT_OBJECT_0 )
			return IPCERR_WAKEUP;

		return IPCERR_CLOSED;
	}

	result = GetLastError();

	switch( result )
	{
		case ERROR_SUCCESS:

			//
			// wait in an alertable state until
			// the operation completes or until
			// the wake event is signaled
			//

			result = WaitForSingleObjectEx(
				hevent_wake,
				INFINITE,
				true );

			if( result == WAIT_OBJECT_0 )
			{
//				ResetEvent( hevent_wake );

				// cancel the current overlaped
				// request and give it a chance
				// to complete in a wait state

				CancelIo( conn );

				ReleaseMutex( hmutex_recv );

				return IPCERR_WAKEUP;
			}

			GetOverlappedResult(
				conn,
				&olapp_send,
				&dwsize,
				true );

			result = GetLastError();
			break;
	}

	switch( result )
	{
		case ERROR_SUCCESS:
			result = IPCERR_OK;
			break;

		case ERROR_MORE_DATA:
			result = IPCERR_BUFFER;
			break;

		case ERROR_OPERATION_ABORTED:
//			ResetEvent( hevent_wake );
//			result = IPCERR_WAKEUP;
//			break;

		case ERROR_BROKEN_PIPE:
		case ERROR_INVALID_HANDLE:
			result = IPCERR_CLOSED;
			break;

		default:
			result = IPCERR_NODATA;
			break;
	}

	sent = dwsize;

	ReleaseMutex( hmutex_send );

	return result;
}

VOID WINAPI io_recv_complete( DWORD result, DWORD size, LPOVERLAPPED olapp )
{
	// nothing to do
}

long _ITH_IPCC::io_recv( void * data, size_t size, size_t & rcvd )
{
//	if( conn == INVALID_HANDLE_VALUE )
//		return IPCERR_CLOSED;

	DWORD dwsize = ( DWORD ) size;

	WaitForSingleObject( hmutex_recv, INFINITE );

	// windows does not always set
	// the GetLastError value to
	// success after ReadFileEx but
	// the documentation says you
	// should check it for errors

	SetLastError( ERROR_SUCCESS );

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

	long result = ReadFileEx(
					conn,
					data,
					dwsize,
					&olapp_recv,
					io_recv_complete );

	if( !result )
	{
		result = WaitForSingleObject( hevent_wake, 0 );
		if( result == WAIT_OBJECT_0 )
			ResetEvent( hevent_wake );

		ReleaseMutex( hmutex_recv );

		if( result == WAIT_OBJECT_0 )
			return IPCERR_WAKEUP;

		return IPCERR_CLOSED;
	}

	result = GetLastError();

	switch( result )
	{
		case ERROR_SUCCESS:

			//
			// wait in an alertable state until
			// the operation completes or until
			// the wake event is signaled
			//

			result = WaitForSingleObjectEx(
				hevent_wake,
				INFINITE,
				true );

			if( result == WAIT_OBJECT_0 )
			{
				ResetEvent( hevent_wake );

				// cancel the current overlaped
				// request and give it a chance
				// to complete in a wait state

				CancelIo( conn );

				ReleaseMutex( hmutex_recv );

				return IPCERR_WAKEUP;
			}

			GetOverlappedResult(
				conn,
				&olapp_recv,
				&dwsize,
				true );

			result = GetLastError();
			break;
	}

	switch( result )
	{
		case ERROR_SUCCESS:
			result = IPCERR_OK;
			break;

		case ERROR_MORE_DATA:
			result = IPCERR_BUFFER;
			break;

		case ERROR_OPERATION_ABORTED:
//			ResetEvent( hevent_wake );
//			result = IPCERR_WAKEUP;
//			break;

		case ERROR_BROKEN_PIPE:
		case ERROR_INVALID_HANDLE:
			result = IPCERR_CLOSED;
			break;

		default:
			result = IPCERR_NODATA;
			break;
	}

	rcvd = dwsize;

	ReleaseMutex( hmutex_recv );

	return result;
}

long _ITH_IPCC::attach( const char * path, long timeout )
{
	if( !WaitNamedPipe( path, timeout ) )
		return IPCERR_FAILED;

	conn = CreateFile(
				path,
				GENERIC_READ | GENERIC_WRITE,
				FILE_SHARE_READ | FILE_SHARE_WRITE,
				NULL,
				OPEN_EXISTING,
				FILE_FLAG_OVERLAPPED,
				NULL );

	if( conn == INVALID_HANDLE_VALUE )
	{
		long result = GetLastError();
		return IPCERR_FAILED;
	}

	return IPCERR_OK;
}

void _ITH_IPCC::wakeup()
{
	if( hevent_wake != NULL )
		SetEvent( hevent_wake );
}

void _ITH_IPCC::detach()
{
	if( conn != INVALID_HANDLE_VALUE )
	{
		CancelIo( conn );
		FlushFileBuffers( conn );

		CloseHandle( conn );
		conn = INVALID_HANDLE_VALUE;
	}
}

//
// inter process communication server
//

_ITH_IPCS::_ITH_IPCS()
{
	hevent_wake = CreateEvent( NULL, true, false, NULL );
	hevent_conn = CreateEvent( NULL, true, false, NULL );

	sid_server = NULL;
	sid_client = NULL;

	acl = NULL;
	psa	= NULL;

	conn = INVALID_HANDLE_VALUE;
}

_ITH_IPCS::~_ITH_IPCS()
{
	done();

	if( hevent_conn != NULL )
	{
		CloseHandle( hevent_conn );
		hevent_conn = NULL;
	}

	if( hevent_wake != NULL )
	{
		CloseHandle( hevent_wake );
		hevent_wake = NULL;
	}
}

long _ITH_IPCS::init( const char * path, bool admin )
{
	// when creating a named pipe with explicit access,
	// you must specify FILE_CREATE_PIPE_INSTANCE for
	// an SID that is appropriate for the account that
	// owns your process. otherwise, after creating the
	// initial pipe instance and assigning the access
	// control, your process will loose its ability to
	// create more than one pipe instance ... really.

	long ea_count = 0;

	// admin sid

	SID_IDENTIFIER_AUTHORITY sia_nt = SECURITY_NT_AUTHORITY;

	if( !AllocateAndInitializeSid(
			&sia_nt,
			2,
			SECURITY_BUILTIN_DOMAIN_RID,
			DOMAIN_ALIAS_RID_ADMINS,
			0, 0, 0, 0, 0, 0,
			&sid_server ) )
		return IPCERR_FAILED;

	// initialize the explicit access info

	memset( &ea[ 0 ], sizeof( EXPLICIT_ACCESS ), 0 );
	ea[ 0 ].grfAccessPermissions = GENERIC_READ | GENERIC_WRITE | FILE_CREATE_PIPE_INSTANCE;
	ea[ 0 ].grfAccessMode = SET_ACCESS;
	ea[ 0 ].grfInheritance= NO_INHERITANCE;
	ea[ 0 ].Trustee.TrusteeForm = TRUSTEE_IS_SID;
	ea[ 0 ].Trustee.TrusteeType = TRUSTEE_IS_GROUP;
	ea[ 0 ].Trustee.ptstrName  = ( LPTSTR ) sid_server;

	ea_count++;

	if( !admin )
	{
		// user sid

		if( !AllocateAndInitializeSid(
				&sia_nt,
				2,
				SECURITY_BUILTIN_DOMAIN_RID,
				DOMAIN_ALIAS_RID_USERS,
				0, 0, 0, 0, 0, 0,
				&sid_client ) )
			return IPCERR_FAILED;

		// initialize the explicit access info

		memset( &ea[ 1 ], sizeof( EXPLICIT_ACCESS ), 0 );
		ea[ 1 ].grfAccessPermissions = GENERIC_READ | GENERIC_WRITE;
		ea[ 1 ].grfAccessMode = SET_ACCESS;
		ea[ 1 ].grfInheritance= NO_INHERITANCE;
		ea[ 1 ].Trustee.TrusteeForm = TRUSTEE_IS_SID;
		ea[ 1 ].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
		ea[ 1 ].Trustee.ptstrName  = ( LPTSTR ) sid_client;

		ea_count++;
	}

	// create a new ACL for the access

	if( SetEntriesInAcl( ea_count, ea, NULL, &acl ) != ERROR_SUCCESS )
		return IPCERR_FAILED;

	// Initialize a security descriptor

	if( !InitializeSecurityDescriptor( &sd, SECURITY_DESCRIPTOR_REVISION ) ) 
		return IPCERR_FAILED;
 
	// Add the ACL to the security descriptor.

	if( !SetSecurityDescriptorDacl(
			&sd,
			TRUE,
			acl,
			FALSE ) )
		return IPCERR_FAILED;

	// Initialize a security attributes structure.

	sa.nLength = sizeof ( SECURITY_ATTRIBUTES );
	sa.lpSecurityDescriptor = &sd;
	sa.bInheritHandle = FALSE;

	conn = CreateNamedPipe(
			path,
			FILE_FLAG_FIRST_PIPE_INSTANCE |
			FILE_FLAG_OVERLAPPED |
			PIPE_ACCESS_DUPLEX,
		    PIPE_TYPE_MESSAGE |
			PIPE_READMODE_MESSAGE |
			PIPE_WAIT,
			PIPE_UNLIMITED_INSTANCES,
			8192,
			8192,
		    10,
			&sa );

	if( conn == INVALID_HANDLE_VALUE )
		return IPCERR_FAILED;

	return IPCERR_OK;
}

void _ITH_IPCS::done()
{
	if( acl != NULL )
	{
		LocalFree( acl );
		acl = NULL;
	}

	if( sid_client != NULL )
	{
		FreeSid( sid_client );
		sid_client = NULL;
	}

	if( sid_server != NULL )
	{
		FreeSid( sid_server );
		sid_server = NULL;
	}

	if( conn != INVALID_HANDLE_VALUE )
	{
		CloseHandle( conn );
		conn = INVALID_HANDLE_VALUE;
	}
}

long _ITH_IPCS::inbound( const char * path, IPCCONN & ipcconn )
{
	DWORD	dwundef;
	long	result;

	if( conn == INVALID_HANDLE_VALUE )
	{
		conn = CreateNamedPipe(
				path,
				FILE_FLAG_OVERLAPPED |
				PIPE_ACCESS_DUPLEX,
				PIPE_TYPE_MESSAGE |
				PIPE_READMODE_MESSAGE |
				PIPE_WAIT,
				PIPE_UNLIMITED_INSTANCES,
				8192,
				8192,
				10,
				&sa );

		if( conn == INVALID_HANDLE_VALUE )
		{
			result = GetLastError();
			return IPCERR_FAILED;
		}
	}

	ipcconn = INVALID_HANDLE_VALUE;

	OVERLAPPED olapp;
	memset( &olapp, 0, sizeof( olapp ) );
	olapp.hEvent = hevent_conn;

	SetLastError( ERROR_SUCCESS );

	result = ConnectNamedPipe( conn, &olapp );
	if( !result )
		result = GetLastError();

	switch( result )
	{
		case ERROR_IO_PENDING:
		{
			HANDLE events[ 2 ] = { hevent_conn, hevent_wake };

			result = WaitForMultipleObjects(
						2,
						events,
						false,
						INFINITE );

			if( result == WAIT_OBJECT_0 + 1 )
			{
				// cancel the current overlaped
				// request and give it a chance
				// to complete in a wait state

				CancelIo( conn );
				SleepEx( 0, true );
			}

			result = GetOverlappedResult(
						conn,
						&olapp,
						&dwundef,
						false );

			result = GetLastError();

			break;
		}
	}

	switch( result )
	{
		case ERROR_SUCCESS:
		case ERROR_PIPE_CONNECTED:
			ipcconn = conn;
			conn = INVALID_HANDLE_VALUE;
			result = IPCERR_OK;
			break;

		case ERROR_OPERATION_ABORTED:
			ResetEvent( hevent_wake );
			result = IPCERR_WAKEUP;
			break;

		case ERROR_GEN_FAILURE:
		case ERROR_BROKEN_PIPE:
		case ERROR_INVALID_HANDLE:
			result = IPCERR_CLOSED;
			break;

		default:
			result = IPCERR_NODATA;
			break;
	}

	return result;
}

void _ITH_IPCS::wakeup()
{
	SetEvent( hevent_wake );
}

#endif

#ifdef UNIX

//
// inter process communication client
//

_ITH_IPCC::_ITH_IPCC()
{
	socketpair( AF_UNIX, SOCK_STREAM, 0, conn_wake );

	conn = -1;
}

_ITH_IPCC::~_ITH_IPCC()
{
	detach();

	if( conn_wake[ 0 ] != -1 )
	{
		close( conn_wake[ 0 ] );
		conn_wake[ 0 ] = -1;
	}

	if( conn_wake[ 1 ] != -1 )
	{
		close( conn_wake[ 1 ] );
		conn_wake[ 1 ] = -1;
	}
}


void _ITH_IPCC::io_conf( IPCCONN sconn )
{
	conn = sconn;
}

long _ITH_IPCC::io_send( void * data, size_t size, size_t & sent )
{
	long result = send( conn, data, size, 0 );
	if( result < 0 )
		return IPCERR_FAILED;

	sent = result;

	return IPCERR_OK;
}

long _ITH_IPCC::io_recv( void * data, size_t size, size_t & rcvd )
{
	fd_set fds;
	FD_ZERO( &fds );
	FD_SET( conn, &fds );
	FD_SET( conn_wake[ 0 ], &fds );

	int max = conn_wake[ 0 ];
	if( max < conn )
		max = conn;

	if( select( max + 1, &fds, NULL, NULL, NULL ) <= 0 )
		return IPCERR_FAILED;

	if( FD_ISSET( conn, &fds ) )
	{
		long result = recv( conn, data, size, 0 );
		if( result < 0 )
			return IPCERR_FAILED;

		if( result == 0 )
			return IPCERR_CLOSED;

		rcvd = result;

		return IPCERR_OK;
	}

	if( FD_ISSET( conn_wake[ 0 ], &fds ) )
	{
		char c;
		recv( conn_wake[ 0 ], &c, 1, 0 );

		return IPCERR_WAKEUP;
	}

	return IPCERR_NODATA;
}

long _ITH_IPCC::attach( const char * path, long timeout )
{
	conn = socket( AF_UNIX, SOCK_STREAM, 0 );
	if( conn == -1 )
		return IPCERR_FAILED;

	if( socketpair( AF_UNIX, SOCK_STREAM, 0, conn_wake ) < 0 )
		return IPCERR_FAILED;

	struct sockaddr_un saddr;
	saddr.sun_family = AF_UNIX;

	long sun_len =  strlen( path ) + sizeof( saddr.sun_family );

#ifndef __linux__
	sun_len += sizeof( saddr.sun_len );
	saddr.sun_len = sun_len;
#endif

	strcpy( saddr.sun_path, path );

	if( connect( conn, ( struct sockaddr * ) &saddr, sun_len ) < 0 )
		return IPCERR_FAILED;

	return IPCERR_OK;
}

void _ITH_IPCC::wakeup()
{
	char c = 0;
	send( conn_wake[ 1 ], &c, 1, 0 );
}

void _ITH_IPCC::detach()
{
	if( conn != -1 )
		close( conn );
}

//
// inter process communication server
//

_ITH_IPCS::_ITH_IPCS()
{
	conn = -1;

	socketpair( AF_UNIX, SOCK_STREAM, 0, conn_wake );
}

_ITH_IPCS::~_ITH_IPCS()
{
	done();

	if( conn_wake[ 0 ] != -1 )
	{
		close( conn_wake[ 0 ] );
		conn_wake[ 0 ] = -1;
	}

	if( conn_wake[ 1 ] != -1 )
	{
		close( conn_wake[ 1 ] );
		conn_wake[ 1 ] = -1;
	}
}

long _ITH_IPCS::init( const char * path, bool admin )
{
	unlink( path );

	conn = socket( AF_UNIX, SOCK_STREAM, 0 );
	if( conn == -1 )
		return IPCERR_FAILED;

	struct sockaddr_un saddr;
	saddr.sun_family = AF_UNIX;

	long sun_len =  strlen( path ) + sizeof( saddr.sun_family );

#ifndef __linux__
        sun_len += sizeof( saddr.sun_len );
        saddr.sun_len = sun_len;
#endif

	strcpy( saddr.sun_path, path );

	if( bind( conn, ( struct sockaddr * ) &saddr, sun_len ) < 0 )
		return IPCERR_FAILED;

	if( !admin )
		if( chmod( path, S_IRWXU | S_IRWXG | S_IRWXO ) < 0 )
			return IPCERR_FAILED;

	if( listen( conn, 5 ) < 0 )
		return IPCERR_FAILED;

	return IPCERR_OK;
}

void _ITH_IPCS::done()
{
	if( conn != -1 )
		close( conn );
}

long _ITH_IPCS::inbound( const char * path, IPCCONN & ipcconn )
{
	fd_set fds;
	FD_ZERO( &fds );
	FD_SET( conn, &fds );
	FD_SET( conn_wake[ 0 ], &fds );

	int max = conn_wake[ 0 ];
	if( max < conn )
		max = conn;

	if( select( max + 1, &fds, NULL, NULL, NULL ) <= 0 )
		return IPCERR_FAILED;

	if( FD_ISSET( conn, &fds ) )
	{
		ipcconn = accept( conn, NULL, NULL );
		if( ipcconn < 0 )
			return IPCERR_FAILED;

		return IPCERR_OK;
	}

	if( FD_ISSET( conn_wake[ 0 ], &fds ) )
	{
		char c;
		recv( conn_wake[ 0 ], &c, 1, 0 );

		return IPCERR_WAKEUP;
	}

	return IPCERR_NODATA;
}

void _ITH_IPCS::wakeup()
{
	char c = 0;
	send( conn_wake[ 1 ], &c, 1, 0 );
}

#endif