summaryrefslogtreecommitdiff
path: root/Ivy/Ivy.cs
blob: 9344ca9fc003d442c4423d84bed17af6443cc47e (plain)
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
/// François-Régis Colin
/// http://www.tls.cena.fr/products/ivy/
/// *
/// (C) CENA
/// *
/// 
[assembly: System.CLSCompliant(true)]
namespace IvyBus
{
	using System;
	using System.IO;
	using System.Collections;
	using System.Collections.Specialized;
	using System.Collections.Generic;
	using System.Net;
	using System.Net.Sockets;
	using System.Threading;
	using System.Configuration;
	using System.Globalization;
	using System.Text.RegularExpressions;
	using System.Text;
	using System.Reflection;
	using System.Diagnostics;
	using System.Collections.ObjectModel;
	using IvyBus.Properties;

	/// <summary> The Main bus Class
	/// </summary>
	/// 
	public class Ivy    : IDisposable 
	{
		/* Event */
		/// <summary>
		/// raise when an new IvyClient is connected
		/// </summary>
		public event EventHandler<IvyEventArgs> ClientConnected;
		/// <summary>
		/// raise when an new IvyClient is disconnected
		/// </summary>
		public event EventHandler<IvyEventArgs> ClientDisconnected;
		/// <summary>
		/// raise when a direct message is received
		/// </summary>
		public event EventHandler<IvyEventArgs> DirectMessageReceived;
		/// <summary>
		/// raise when some IvyClient  ask me to die
		/// </summary>
		public event EventHandler<IvyDieEventArgs> DieReceived;
		/// <summary>
		/// raise when an IvyClient register a binding
		/// </summary>
		public event EventHandler<IvyEventArgs> BindingAdd;
		/// <summary>
		/// raise when an IvyClient unregister a binding
		/// </summary>
		public event EventHandler<IvyEventArgs> BindingRemove;
		/// <summary>
		/// raise when an IvyClient  binding is filteredout
		/// </summary>
		public event EventHandler<IvyEventArgs> BindingFilter;
		/// <summary>
		/// raise when an IvyClient changer a binding
		/// </summary>
		public event EventHandler<IvyEventArgs> BindingChange;
		/// <summary>
		/// raise when an error message is received
		/// </summary>
		public event EventHandler<IvyEventArgs> ErrorMessage;

		/// <summary>
		/// Flag for displaying internal debug message of the protocol intrinsics
		/// </summary>
		public static bool DebugProtocol
		{
			get
			{
				return debugProtocol;
			}
			set
			{
				debugProtocol = value;
			}

		}
		/// <summary>
		/// Language for the Ivy SendMsg formating default en-US 
		/// ie: send point on float value sent
		/// </summary>
		public CultureInfo Culture
		{
			get
			{
				return culture;
			}
			set
			{
				culture = value;
			}

		}

		/// <summary>IvyClients accesses the list of the connected clients</summary>

		public ReadOnlyCollection<IvyClient> IvyClients
		{
			get
			{
				return new ReadOnlyCollection<IvyClient>(clients);
			}

		}
		
		/// <summary>AppName the application name</summary>

		public string AppName
		{
			set
			{
				appName = value;
			}
			get
			{
				return appName;
			}

		}
		/// <summary>
		/// AppId the Application Unique ID
		/// </summary>

		public string AppId
		{
			get
			{
				return applicationUniqueId;
			}

		}
		
		/// <summary>
		/// the Ivy Protocol version 
		/// </summary>
		public int ProtocolVersion
		{
			get
			{
				return protocolVersion;
			}

		}
		/// <summary>
        /// IsSynchronous is the bus Synchronous of the main thread ( ie callback running in the main thread) ?
		/// </summary>
		private bool synchronous = true;
		public bool Synchronous
		{
			set
			{
				synchronous = value && syncContext != null;
			}
			get
			{
				return synchronous;
			}

		}

		/// <summary>
		/// IsRunning is the bus Started and connected ?
		/// </summary>
		public bool IsRunning
		{
			get
			{
				return !stopped;
			}

		}
		///<summary>SentMessageClasses the first word token of sent messages
		///<remarks> optimise the parsing process when sending messages </remarks>
		///</summary>

		public Collection<string> SentMessageFilter
		{
			get
			{
				return sent_messageFilter;
			}
		}
		/// <summary>ReadyMessage message send when Application receive all the regexp at the connection of the client</summary>

		public string ReadyMessage
		{
			get { return ready_message; }
			set { ready_message = value; }
		}

		internal class MyTcpListener : TcpListener
		{
			public MyTcpListener(IPAddress address, int port)
				: base(address, port)
			{
			}
			public bool IsActive()
			{
				return this.Active;
			}
		}
		///  the name of the application on the bus
		internal string appName;
		/// the port for the UDP rendez vous, if none is supplied
		internal const ushort DefaultPort = 2010;
		/// the domain for the UDP rendez vous
		private static readonly string DefaultDomain = "127.0.0.1:" + DefaultPort;
		internal int protocolVersion = 3;
		private static bool debugProtocol;      // false by default runtime
		private static int serial = -1; /* an unique ID for each regexp */ // -1 to start numbering at 0
		private MyTcpListener app;
		private List<IvyWatcher> watchers;
		private Thread serverThread; // to ensure quick communication of the end
		private AutoResetEvent tcplistener_running;
		private bool ipv6;

		/// <summary>
		/// the Ivy IP version to use 
		/// </summary>
		public bool IpV6
		{
			get { return ipv6; }
		}

		/// <summary>
		/// the Ivy Assembly version
		/// </summary>
		static public Version Version
		{
			get { return Assembly.GetExecutingAssembly().GetName().Version; }
		}
		// Class representing Ivy Binding receive from client
		internal class IvyClientBinding
		{
			internal IvyBindingBase binding;
			internal Dictionary<IvyClient, List<int>> client_bindind_ids;
		}
		// The Application bindings
		internal Dictionary<int, IvyApplicationBinding> bindings;
		// the clients bindings
		private Dictionary<string, IvyClientBinding > client_bindings;
		private List<IvyClient> clients;
		private Collection<string> sent_messageFilter;
		private bool stopped = true;
		internal int applicationPort; /* Application port number */
		internal IPAddress applicationHost; /* Application host number */
		internal string applicationUniqueId;  /* identifier Application unique timestamp-ipaddress-port */
		private string ready_message;
		private CultureInfo culture = new CultureInfo("en-us");
		internal static Encoding ivyEncoding = Encoding.GetEncoding("iso-8859-15"); // ASCII 8 bits  iso-8859-2 
 
		// for synchronous event 
#if (PocketPC)
		private System.Windows.Forms.ContainerControl parentControl;
#else
		private readonly SynchronizationContext syncContext;
#endif


		/// <summary>
		/// Initializes a new instance of the Ivy Bus.
		/// Readies the structures for the software bus connexion.
		/// </summary>
		public Ivy()
		{
			this.ipv6 = false;
			clients = new List<IvyClient>();
			bindings = new Dictionary<int, IvyApplicationBinding>();
			client_bindings = new Dictionary<string, IvyClientBinding>();
			sent_messageFilter = new Collection<string>();
#if (!PocketPC)
			syncContext = SynchronizationContext.Current;
            if (syncContext == null)
                synchronous = false;
			debugProtocol = Properties.Settings.Default.IvyDebug;
			protocolVersion = Properties.Settings.Default.IvyProtocolVersion;
#endif
			// get binding from Attribute IvyBinding
			//TODO Autobinding attribute
#if (PocketPC)
			if (parentControl != null)
				BindAttibute(parentControl);
#endif
			Assembly assembly = Assembly.GetCallingAssembly();
			if ( assembly != this.GetType().Assembly )
				BindAttribute(assembly);
		}
		
		/// <summary>
		/// Readies the structures for the software bus connexion.
		/// </summary>
		/// <example> This sample shows how to start working with Ivy.
		/// <code>
		/// Ivy bus = new Ivy("Dummy agent","ready");
		/// bus.bindMsg("(.*)",myMessageListener);
		/// bus.start(null);
		/// </code>
		/// How to send & receive:
		/// the Ivy agent A performs <c>b.bindMsg("^Hello (*)",cb);</c>
		/// the Ivy agent B performs <c>b2.sendMsg("Hello world");</c>
		/// a thread in A will run the callback cb with its second argument set
		/// to a array of string, with one single element, "world"
		/// </example>
		/// <remarks>
		/// the real work begin in the start() method
		/// </remarks>
		/// <seealso cref=" Ivy.start"/>
		/// <param name='name'>The name of your Ivy agent on the software bus
		/// </param>
		/// <param name='message'>The hellow message you will send once ready
		/// </param>
		public Ivy(string name, string readyMessage)
			: this()
		{
			appName = name;
			this.ready_message = readyMessage;
			
			// get binding from Attribute IvyBinding
			//TODO Autobinding attribute
			Assembly assembly = Assembly.GetCallingAssembly();
			if (assembly != this.GetType().Assembly)
				BindAttribute(assembly);
		}
		

		internal void AddBinding(int id, IvyClient clnt, IvyBindingBase bindexp)
		{
			bool change = false;
			IvyClientBinding clientbind;
			lock (client_bindings)
			{
				if (client_bindings.ContainsKey(bindexp.Expression))
				{
					// check if id exits to remove it

					clientbind = client_bindings[bindexp.Expression];

					foreach (IvyClientBinding clbind in client_bindings.Values)
					{
						lock (clbind.client_bindind_ids)
						{
							if (clbind.client_bindind_ids.ContainsKey(clnt))
							{
								if (clbind.client_bindind_ids[clnt].Contains(id))
								{
									// remove from old
									clbind.client_bindind_ids[clnt].Remove(id);
									// add to new later
									change = true; //mark to call right handler
									break;
								}
							}
						}

					}

				}
				else
				{
					clientbind = new IvyClientBinding();
					clientbind.binding = bindexp;
					clientbind.client_bindind_ids = new Dictionary<IvyClient, List<int>>();
					clientbind.client_bindind_ids[clnt] = new List<int>();
					client_bindings[bindexp.Expression] = clientbind;

				}
			}
			
			lock (clientbind.client_bindind_ids)
			{
				if (!clientbind.client_bindind_ids.ContainsKey(clnt))
				{
					clientbind.client_bindind_ids[clnt] = new List<int>();
				}
				clientbind.client_bindind_ids[clnt].Add(id);
			}
			if (change)
			{
				OnClientChangeBinding(new IvyEventArgs(clnt, id, bindexp.Expression));
			}
			else
			{
				OnClientAddBinding(new IvyEventArgs(clnt, id, bindexp.Expression));
			}
		}
		internal void DelBinding(int id, IvyClient clnt)
		{
			IvyClientBinding clientbind = null;
			lock (client_bindings)
			{
				foreach (IvyClientBinding clbind in client_bindings.Values)
				{
					lock (clbind.client_bindind_ids)
					{
						if (clbind.client_bindind_ids.ContainsKey(clnt))
						{
							clbind.client_bindind_ids[clnt].Remove(id);
							clientbind = clbind;
							break;
						}
					}
				}
				if (clientbind != null)
				{
					lock (clientbind.client_bindind_ids)
					{
						if (clientbind.client_bindind_ids.Count == 0)
						{
							client_bindings.Remove(clientbind.binding.Expression);
						}
					}
				}
			}
			if (clientbind != null )
				OnClientRemoveBinding(new IvyEventArgs(clnt, id, clientbind.binding.Expression));
						
		}
		/// <summary>
		/// Automatic binding on static method of a Type 
		/// </summary>
		/// <param name="type"></param>
		public void BindAttribute(Type type)
		{
			if (type == null) return;
			//Get instance of the IvyBindingAttribute. 
			foreach (MethodInfo m in type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic))
			{
				foreach (IvyBindingAttribute attr in Attribute.GetCustomAttributes(m, typeof(IvyBindingAttribute)))
				{
					//TODO check paramater type MessageHandler 
					Debug.WriteLine("IvyBinding '" + attr.GetFormattedExpression(null) + "' to Method " + m.Name);
					EventHandler<IvyMessageEventArgs> handler;
#if (PocketPC)
					//Createdelegate mydlg = new Createdelegate(m, null, EventArgs.Empty);
					//bindMsg(attr.GetExpression(null), mydlg);
					handler = null;
#else
					handler = (EventHandler<IvyMessageEventArgs>)Delegate.CreateDelegate(typeof(EventHandler<IvyMessageEventArgs>), m);
#endif
					BindMsg(attr.GetFormattedExpression(null), handler);
				}
			}
		}
		
		
		/// <summary>
		/// Autobinding on instance method
		/// </summary>
		/// <param name="target"></param>
		public void BindAttribute(object target)
		{
			if (target == null) return;
			Type type = target.GetType();
			//Get instance of the IvyBindingAttribute. 
			foreach (MethodInfo m in type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic))
			{
				foreach (IvyBindingAttribute attr in Attribute.GetCustomAttributes(m, typeof(IvyBindingAttribute)))
				{
					//TODO check paramater type MessageHandler 
					Ivy.traceProtocol(Resources.Ivy, "BindAttibute " + attr.GetFormattedExpression(target) + "' to Method " + m.Name);
					EventHandler<IvyMessageEventArgs> handler;
#if (PocketPC)
					handler = null; // TODO
#else
					handler = (EventHandler<IvyMessageEventArgs>)Delegate.CreateDelegate(typeof(EventHandler<IvyMessageEventArgs>), target, m);
#endif
					BindMsg(attr.GetFormattedExpression(target), handler);
				}
			}

		}
		// Autobinding on IvyBindingAttribute method
		/// <summary>
		/// Automatic binding of IvyBindAttribute in an assembly
		/// </summary>
		/// <param name="target"></param>
		public void BindAttribute(Assembly target)
		{
			if (target != null)
			{
				foreach (Type typ in target.GetTypes())
				{
					BindAttribute(typ);
				}
			}
		}
		/// <summary>
		/// connects the Ivy bus to a domain or list of domains.
		/// </summary>
		/// <param name="domainbus">a domain of the form 10.0.0:1234, it is similar to the
		/// netmask without the trailing .255. This will determine the meeting point
		/// of the different applications. Right now, this is done with an UDP
		/// broadcast. Beware of routing problems ! You can also use a comma
		/// separated list of domains.</param>
		/// <remarks>
		/// One thread (IvyWatcher) for each traffic rendezvous (either UDP broadcast or TCP Multicast).
		/// One thread (serverThread/Ivy) to accept incoming connexions on server socket.
		/// a thread for each IvyClient when the connexion has been done.
		/// </remarks>
		public void Start(string domainBus)
		{
            if (string.IsNullOrEmpty(AppName))
            {
                AppName = "LazyDevelopper";
            }
            // check for ReadyMessage empty
            if (string.IsNullOrEmpty(ready_message))
            {
                if ( string.IsNullOrEmpty ( Properties.Settings.Default.ReadyMessage ) )
                    ready_message = AppName + " READY";
                else
                    ready_message = Properties.Settings.Default.ReadyMessage;
                
            }
			domainBus = GetDomain(domainBus);
			// check for IPV6 mode
			Domain[] d = parseDomains(domainBus);
			IPAddress group = IPAddress.Parse(d[0].Domainaddr);
			ipv6 = group.IsIPv6Multicast;

			try
			{
				long seed = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
				Random rand = new Random( (int)seed );

				app = new MyTcpListener(ipv6 ? IPAddress.IPv6Any :IPAddress.Any, 0);
				app.Start(); // should be started before getting port
				applicationHost = LocalIP;
				applicationPort = ((IPEndPoint)app.LocalEndpoint).Port;
				applicationUniqueId = string.Format(culture,"{0}:{1}:{2}",
					rand.Next(),
					seed,
					//applicationHost.ToString().Replace(".", ""),
					applicationPort);

			}
			catch (IOException e)
			{
				throw new IvyException("can't open TCP service socket " + e);
			}
			Ivy.traceProtocol("BindAttibute", "Ivy protocol: " + ProtocolVersion + " TCP service open on port " + applicationPort);
			watchers = new List<IvyWatcher>();

			// readies the rendezvous : an IvyWatcher (thread) per domain bus
			for (int index = 0; index < d.Length; index++)
			{
				IvyWatcher watcher = new IvyWatcher(this, d[index].Domainaddr, d[index].Port, ipv6 );
				watchers.Add(watcher);
			}
			serverThread = new Thread(new ThreadStart(this.TcpListener));
			serverThread.Name = "Ivy Tcp Server Thread";
			stopped = false;
			tcplistener_running = new AutoResetEvent(false);
			serverThread.Start();

			// Wait for readyness
			tcplistener_running.WaitOne();
 
			// sends the broadcasts and listen to incoming connexions
			for (int i = 0; i < watchers.Count; i++)
			{
				watchers[i].start();
			}
		}
		internal void SortClients()
		{
			lock (clients)
			{
				//clients.Sort(new IvyClient.IvyClientPriority());
				clients.Sort();
			}
		}
		

		internal static Domain[] parseDomains(string domainbus)
		{
			string[] st = domainbus.Split(',');
			Domain[] d = new Domain[st.Length];
			for (int i = 0; i < st.Length; i++)
			{
				d[i] = new Domain(st[i]);
			}
			return d;
		}

		/// <summary>
		/// disconnects from the Ivy bus
		/// </summary>
		public void Stop()
		{
			if (stopped)
				return;
			lock (app)
			{
				stopped = true;
				Ivy.traceProtocol(Resources.Ivy, "beginning stopping the bus");
				try
				{
					// stopping the serverThread
					if (serverThread != null)
					{
						app.Stop();
						// Wait for Thread to end.
						bool term = serverThread.Join(10000);
						if (!term && (serverThread != null)) serverThread.Abort();
						serverThread = null;
					}
					// The serverThread might be stopped even before having been created
					if (app != null)
						app.Stop();
					// stopping the IvyWatchers
					if (watchers != null)
						for (int i = 0; i < watchers.Count; i++)
						{
							((IvyWatcher)watchers[i]).stop();
						}
					// stopping the remaining IvyClients
					// copy the values in temporary variable to eliminate Thread modifying collection
					if (clients.Count != 0)
					{
						IvyClient[] copyClient;
						lock (clients)
						{
							copyClient = new IvyClient[clients.Count];
							clients.CopyTo(copyClient);
						}
						foreach (IvyClient client in copyClient)
						{
							client.close(true); // will notify the reading thread
							//removeClient(client); already donne in the thread
						}
					}
				}
				catch (IOException e)
				{
					Ivy.traceError(Resources.Ivy, "IOexception Stop " + e.Message);
				}
				Ivy.traceProtocol(Resources.Ivy, "the bus should have stopped so far");
			}
		}
		/// <summary> 
		/// join the main thread of Ivy ( ie wait until stopped )
		/// </summary>
		/// <remarks>
		/// Performs a join on the Principal Thread.
		/// </remarks>
		/// <param name='millisecondsTimeout'>Number of millisecondes to wait before the Thread Stop.</param>
		/// <returns>
		/// true if the thread stopped; false if it did not stop after the expiry of the period specified by the parameter millisecondsTimeout
		/// </returns>
		public bool Join(int millisecondsTimeout)
		{
			return serverThread.Join(millisecondsTimeout);
		}
		/// <summary> 
		/// Block the calling Thread until Ivy Stop
		/// </summary>
		/// <remarks>
		/// Performs a join on the Principal Thread.
		/// </remarks>
		public void MainLoop()
		{
			this.Join(Timeout.Infinite);
		}

		/// <summary> 
		/// Send a formated message to someone on the bus
		/// </summary>
		/// <remarks>
		/// Performs a pattern matching according to everyone's regexps, and sends
		/// the results to the relevant ivy agents.
		/// There is one thread for each client connected, we could also
		/// create another thread each time we send a message.
		/// </remarks>
		/// <param name='format'>A string message format to build  the message</param>
		/// <param name='args'>args used in message format</param>
		/// <returns>
		/// the number of messages actually sent
		/// </returns>
		public int SendMsg(string format, params object[] args)
		{
			// send to everybody
			string msg = string.Format(culture, format, args);
			int count = 0;
			// hash message in V4 protocol only
			if (ProtocolVersion == 4)
				IvyBindingSimple.Prepare(msg);
			// an alternate implementation would one sender thread per client
			// instead of one for all the clients. It might be a performance issue
			// Tentative of using BeginInvoke EndInvoke is slower 
			lock (client_bindings)
			{
				foreach (IvyClientBinding clbind in client_bindings.Values)
				{
					string[] matches = clbind.binding.Match(msg);
					if (matches != null)
					{
						lock (clbind.client_bindind_ids)
						{

							foreach (KeyValuePair<IvyClient, List<int>> assoc in clbind.client_bindind_ids)
							{
								foreach (ushort id in assoc.Value)
								{
									count += assoc.Key.sendMsg(id, matches);
								}

							}

						}
					}
					
				}
				
			}

			return count;
		}

		internal int SendMsgToClient(IvyClient clnt, string format, params object[] args)
		{
			string msg = string.Format(culture, format, args);
			int count = 0;
			// hash message in V4 protocol only
			if (ProtocolVersion == 4)
				IvyBindingSimple.Prepare(msg);
			// an alternate implementation would one sender thread per client
			// instead of one for all the clients. It might be a performance issue
			lock (client_bindings)
			{

				foreach (IvyClientBinding clbind in client_bindings.Values)
				{
					string[] matches = clbind.binding.Match(msg);
					if (matches != null)
					{
						lock (clbind.client_bindind_ids)
						{
								if (clbind.client_bindind_ids.ContainsKey(clnt))
								{
									List<int> ids = clbind.client_bindind_ids[clnt];
									foreach (ushort id in ids)
									{
										count += clnt.sendMsg(id, matches);
									}
								}   
						}
					}
				}
			}
				
			
			return count;
		}
		/// <summary>
		/// Make a binding to a message using regular expresssion
		/// </summary>
		/// <param name="newBinding"></param>
		/// <returns></returns>
		public int BindMsg(IvyApplicationBinding newBinding)
		{     
			newBinding.Key = Interlocked.Increment(ref serial);
			
			lock (bindings) bindings.Add(newBinding.Key, newBinding);
			// notifies the other clients this new regexp
			lock (clients)
			{
				foreach (IvyClient c in clients)
				{
					c.stream.TokenAddBinding(newBinding.Binding, newBinding.Key, newBinding.FormattedExpression);
				}
			}
			return newBinding.Key;
		}
		/// <summary>
		/// Subscribes to a regular expression.
		/// </summary>
		/// <param name="regexp">a regular expression, groups are done with parenthesis</param>
		/// <param name="callback">any objects implementing the EventHandler<IvyMessageEventArgs> </param>
		/// <param name="args">The args.</param>
		/// <returns>the id of the regular expression</returns>
		/// <remarks>
		/// The callback will be executed with
		/// the saved parameters of the regexp as arguments when a message will sent
		/// by another agent. A program doesn't receive its own messages.
		/// the expression cant containt some dynamics argument replacement of the form  %number[:objectFormat]% 
		/// the string will be replaced by  arg[number].ToString(objectFormat)
		/// </remarks>
		//
		public int BindMsg(string expression, EventHandler<IvyMessageEventArgs> callback, params object[] args)
		{
			// creates a new binding (regexp,callback)
			IvyApplicationBinding newbind;
			newbind = new IvyApplicationBinding(BindingType.RegularExpression, expression, args);
			newbind.Callback += callback;
			return BindMsg(newbind);
		}

		/// <summary>
		/// unsubscribes a regular expression
		/// </summary>
		/// <param name="id">the id of the regular expression, returned when it was bound</param>
		public void UnbindMsg(int id)
		{
			if (!bindings.ContainsKey(id))
			{
				throw new IvyException("client wants to remove an unexistant regexp " + id);
			}
			lock (clients)
			{
				foreach (IvyClient c in clients)
				{
					try
					{
						if ( c.stream != null )
							c.stream.TokenDelBinding(id);
					}
					catch (IOException)
					{
						// client closed ignore it
					}
				}
			}
			lock (bindings) bindings.Remove(id);
		}
		/// <summary>
		/// Change a binding already registred
		/// </summary>
		/// <param name="id"></param>
		/// <param name="expression"></param>
		/// <returns></returns>
		public int ChangeMsg(int id, string expression)
		{
			IvyApplicationBinding newbind;
			if (!bindings.ContainsKey(id))
			{
				throw new IvyException("client wants to change an unexistant regexp " + id);
			}
			
			// change binding (regexp,callback)
			lock (bindings)
			{
				newbind = bindings[id];
				newbind.Expression = expression;
			}
			// notifies the other clients this new regexp
			lock (clients)
			{
				foreach (IvyClient c in clients)
				{
					c.stream.TokenAddBinding(newbind.Binding, newbind.Key, newbind.FormattedExpression);
				}
			}
			return id;
		}


		/// <summary>
		/// unsubscribes a regular expression
		/// </summary>
		/// <param name="re">the string for the regular expression</param>
		/// <returns>
		/// a boolean, true if the regexp existed, false otherwise or
		/// whenever an exception occured during unbinding
		/// </returns>
		public bool UnbindMsg(string re)
		{
			foreach (IvyApplicationBinding bind in bindings.Values)
			{
				if (bind.Expression == re)
				{
					try
					{
						UnbindMsg(bind.Key);
					}
					catch (IvyException)
					{
						return false;
					}
					return true;
				}
			}
			return false;
		}


		/// <summary>
		/// Subscribes to a simple expression ( msg ar1 arg2 arg3 etc).
		/// </summary>
		/// <remarks>
		/// The callback will be executed with
		/// the saved parameters of the regexp as arguments when a message will sent
		/// by another agent. A program doesn't receive its own messages.
		/// </remarks>
		/// 
		/// <param name='regexp'>a regular expression, groups are done with parenthesis</param>
		/// <param name='callback'>any objects implementing the EventHandler<IvyMessageEventArgs></param>
		/// <returns>
		/// the id of the regular expression
		/// </returns>
		public int BindSimpleMsg(string expression, EventHandler<IvyMessageEventArgs> callback, params object[] args)
		{
			// creates a new binding (regexp,callback)
			IvyApplicationBinding newbind;
			newbind = new IvyApplicationBinding(BindingType.Simple, expression, args);
			newbind.Callback += callback;
			return BindMsg(newbind);
		}
		/// <summary>
		/// Dies the specified target.
		/// </summary>
		/// <param name="target">The target.</param>
		/// <param name="message">The reason message.</param>
		/// <returns></returns>
		public int Die(string target, string message)
		{
			ReadOnlyCollection<IvyClient> v = GetClientsByName(target);
			foreach (IvyClient clnt in v)
				clnt.stream.TokenDie(0, message);
			return v.Count;
		}
		/// <summary>
		/// Pings the specified target.
		/// </summary>
		/// <param name="target">The target.</param>
		/// <param name="message">The message.</param>
		/// <returns></returns>
		public int Ping(string target, string message)
		{
			int id = (int)DateTime.Now.Ticks;
			ReadOnlyCollection<IvyClient> v = GetClientsByName(target);
			foreach (IvyClient clnt in v)
			{
				clnt.stream.TokenPing(id, message);
			}
			return v.Count;
		}


		internal virtual void FireEvent(EventHandler<IvyEventArgs> ev, IvyEventArgs e)
		{
			if (ev != null)
			{
#if (PocketPC) 
				if (parentControl != null)
				{
					parentControl.Invoke(ev, this, e);
				}
#else
				if (synchronous)
				{
					SendOrPostCallback update = delegate(object state)
								  {
									  IvyEventArgs args = (IvyEventArgs)state;
									  ev(this, args);
								  };
					syncContext.Post(update, e);
				}
#endif
				else
					ev(this, e);
			}
		}


		internal virtual void OnDirectMessage(IvyEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyEventArgs> temp = DirectMessageReceived;
			FireEvent(temp,e);
		}
		internal virtual void OnClientConnected(IvyEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyEventArgs> temp = ClientConnected;
			FireEvent(temp,e);
		}
		internal virtual void OnClientDisconnected(IvyEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyEventArgs> temp = ClientDisconnected;
			try
			{
				FireEvent(temp,e);
			}
#if (!PocketPC)
			catch (SynchronizationLockException)
			{
						// protect terminaison 
			}
#endif
			catch (ObjectDisposedException)
			{
				// protect terminaison 
			}
			
		}
		internal virtual void OnClientAddBinding(IvyEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyEventArgs> temp = BindingAdd;
			FireEvent(temp,e);
		}
		internal virtual void OnClientRemoveBinding(IvyEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyEventArgs> temp = BindingRemove;
			FireEvent(temp,e);
		}
		internal virtual void OnClientChangeBinding(IvyEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyEventArgs> temp = BindingChange;
			FireEvent(temp, e);
		}
		internal virtual void OnClientFilterBinding(IvyEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyEventArgs> temp = BindingFilter;
			FireEvent(temp,e);
		}
		internal virtual void OnError(IvyEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyEventArgs> temp = ErrorMessage;
			FireEvent(temp, e);
		}
#if (PocketPC)
		internal virtual void OnDie(IvyDieEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyDieEventArgs> temp = DieReceived;
			if (temp != null)
			{
				if (parentControl != null)
				{
					parentControl.Invoke(temp, this, e);
				}
				else
					temp(this, e);
			}
		}

#else
		internal virtual void OnDie(IvyDieEventArgs e)
		{
			// Copy to a temporary variable to be thread-safe.
			EventHandler<IvyDieEventArgs> temp = DieReceived;
			if (temp != null)
			{
				if (syncContext != null)
				{
					SendOrPostCallback update = delegate(object state)
								  {
									  IvyDieEventArgs args = (IvyDieEventArgs)state;
									  temp(this, args);
								  };
					syncContext.Post(update, e);
				}
				else
					temp(this, e);
			}
		}
#endif
		internal void OnMessage(IvyMessageEventArgs e)
		{
			if (!bindings.ContainsKey( e.Id))
			{
				throw new IvyException("(callCallback) Not regexp matching id " + e.Id);
			}
			IvyApplicationBinding bind = bindings[e.Id];

#if(PocketPC)
			bind.Firevent(parentControl, e);
#else
			bind.Firevent(syncContext,synchronous, e);
#endif
		}
	 
		/*
		* removes a client from the list
		*/
		internal void removeClient(IvyClient c)
		{
			lock (clients)
			{
				clients.Remove(c);
			}
			List<string> purge_bind = new List<string>();
			lock (client_bindings)
			{
				foreach (IvyClientBinding clbind in client_bindings.Values)
				{
					lock (clbind.client_bindind_ids)
					{
						clbind.client_bindind_ids.Remove(c);
						if ( clbind.client_bindind_ids.Count == 0 )
							purge_bind.Add( clbind.binding.Expression);
					}
				}
				// remove Binding if no client
				foreach ( string expr in purge_bind )
				{
					client_bindings.Remove(expr);
				}
			}
		}


		/// <summary>
		/// gives a list of IvyClient(s) with the name given in parameter
		/// </summary>
		/// <param name="name">The name of the Ivy agent you're looking for</param>
		/// <returns></returns>
		public ReadOnlyCollection<IvyClient> GetClientsByName(string name)
		{
			List<IvyClient> v = new List<IvyClient>();
			foreach (IvyClient ic in clients)
			{
				if (ic.ApplicationName.CompareTo(name) == 0)
					v.Add(ic);
			}
			return new ReadOnlyCollection<IvyClient>(v);
		}

		/////////////////////////////////////////////////////////////////:
		//
		// Protected methods
		//
		/////////////////////////////////////////////////////////////////:

		internal void addClient(IvyClient client)
		{
			if (stopped)
				return;
			
			lock (clients)
			{
				clients.Add(client);
			}
			
		}

		/// <summary>
		/// return the first non loopback adress
		/// on a one network interface machine it will be my IP adresse
		/// </summary>
		public static IPAddress LocalIP
		{
			get
			{
				IPAddress returnaddr = null;
				//TODO remove ALL reverse DNS search !!!!
				IPHostEntry ip = Dns.GetHostEntry(Dns.GetHostName());
				foreach (IPAddress addr in ip.AddressList)
				{
					returnaddr = addr;
					if (IPAddress.IsLoopback(addr)) continue;
					break;
				}
				return returnaddr;
			}
		}
		/// <summary>
		/// Get the FDQN Domain from a string
		/// </summary>
		/// <param name="domainBus"></param>
		/// <returns></returns>
		public static string GetDomain(string domainBus)
		{
#if (PocketPC) // TODO integrate in normal version
			if (domainbus == null || domainbus.Length == 0)
			{
				IPAddress addr = GetLocalIP();
				//TODO Find Braodcast addr from IP;
				byte[] bytes = addr.GetAddressBytes();
				if (IPAddress.IsLoopback(addr))
				{
					// 127.255.255.255
					bytes[1] = 255;
					bytes[2] = 255;
					bytes[3] = 255;
				}
				else
				{ 
					// else assume class C network
					// TODO find exact netmask
					bytes[3] = 255;
				}
				IPAddress bcast = new IPAddress(bytes);
				domainbus = bcast + ":" + Domain.getPort(domainbus);
			}
#else
			if (domainBus == null || domainBus.Length == 0 )
			{
				domainBus = Environment.GetEnvironmentVariable("IVYBUS");
			}

			if (domainBus == null || domainBus.Length == 0)
			{
				domainBus = Properties.Settings.Default.IvyBus;
			} 
#endif
			if (domainBus == null || domainBus.Length == 0)
				domainBus = DefaultDomain;
			return domainBus;
		}


		/// checks the "validity" of a regular expression. //TODO put in IvyBinding
		internal bool CheckRegexp(string exp)
		{
			bool regexp_ok = true;
			// Attention Bug 
			// ClockStop ClockStart & ^Clock(Start|Pause)
			// should Stop to the first parent
			if ((sent_messageFilter.Count != 0) && exp.StartsWith("^"))
			{
				regexp_ok = false;
				// extract first word from regexp...
				string token = Regex.Replace(exp, @"^\^(?<token>[a-zA-Z_0-9-]+).*", @"${token}");

				foreach (string exp_class in sent_messageFilter)
				{
					if (exp_class.StartsWith(token))
						return true;
				}
			}
			return regexp_ok;
		}

		/*
		* prevents two clients from connecting to each other at the same time
		* there might still be a lingering bug here, that we could avoid with the
		* SchizoToken.
		*/
		internal IvyClient checkConnected(IvyClient clnt)
		{
			IvyClient sameClnt = null;
			if (clnt.AppPort == 0)
			{
				Console.WriteLine(" client {0} port == 0 ", clnt.appName);
				return sameClnt;
			}
			lock (clients)
			{
				foreach (IvyClient client in clients)
				{
					if (clnt == client) continue; // SKIP himself
					if (client.sameIvyClient(clnt))
					{
						sameClnt = client;
						break;
					}
				}
			}
			return sameClnt;
		}

		/*
		* the service socket thread reader main loop
		*/
		private void TcpListener()
		{
			Ivy.traceProtocol(Resources.Ivy, "Ivy service Thread started");
			bool running = true;
			tcplistener_running.Set();
			while (running)
			{
				try
				{
					Socket socket = app.AcceptSocket();
					// early disconnexion
					if (stopped)
						break;
					// the peer called me
					IvyClient client = new IvyClient(this, socket, "Unkown(waiting for name reception)",0);
					client.SendBindings(); //TODO in a Thread or wait for the peer to sent his before sending mine 
		   
				}
				catch (IOException e)
				{
					Ivy.traceError(Resources.Ivy,Resources.IvyIOException + e.Message);
				}
				catch (SocketException e)
				{
					Ivy.traceError(Resources.Ivy,Resources.IvySocketException + e.Message);
					running = false;
				}
			}
			Ivy.traceProtocol(Resources.Ivy, "Ivy service Thread stopped");
		}

		[Conditional("DEBUG")]
		internal static void traceProtocol(string name, string message)
		{
			if ( debugProtocol )
				Console.WriteLine( "-->{0}<-- {1}", name, message);
		}
		internal static void traceError(string name, string message)
		{
			Console.WriteLine("-->{0}<-- {1}", name, message);
		}

		internal class Domain
		{
			public virtual string Domainaddr
			{
				get
				{
					return domainaddr;
				}

			}
			public virtual int Port
			{
				get
				{
					return port;
				}

			}
			private string domainaddr;
			private int port;
			public Domain(string net):this( getDomain(net),getPort(net)) 
			{
			}
			public Domain(string domainaddr, int port)
			{
				this.domainaddr = domainaddr;
				this.port = port;
			}
			public override string ToString()
			{
				return domainaddr + ":" + port;
			}
			public static string getDomain(string net)
			{
				int sep_index = net.LastIndexOf(":");
				if (sep_index != -1)
				{
					net = net.Substring(0, (sep_index) - (0));
				}
				try
				{
					if (!net.Contains("::")) // if not IPV6 multicast paste with 255
					{
						net += ".255.255.255";
						Regex exp = new Regex("^(\\d+\\.\\d+\\.\\d+\\.\\d+).*");
						net = exp.Replace(net, "$1");
					}
				}
				catch (ArgumentException e)
				{
					Ivy.traceError(Resources.Ivy,Resources.BadBroadcast + net + "error " + e.Message);
					return null;
				}
				return net;
			}

			public static int getPort(string net)
			{
				if (net == null) { return Ivy.DefaultPort; }
				int sep_index = net.LastIndexOf(":");
				int port = (sep_index == -1) ? Ivy.DefaultPort : Int32.Parse(net.Substring(sep_index + 1));
				return port;
			}
		}

		/// <summary>
		/// check Validity of Ivy Bus Domain
		/// </summary>
		/// <param name="domain"></param>
		/// <returns></returns>
        public static bool ValidatingDomain(string domain)
        {
            IPAddress result;
            bool valid = false;
            string addr = Domain.getDomain(domain);
            try
            {
                int port = Domain.getPort(domain);
                if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort) return false;
            }
            catch (OverflowException e)
            {
                return false;
            }
            if (String.IsNullOrEmpty(addr))
            {
                // address wasnt provided so return false
                valid = false;
            }
            else
            {
                //use TryParse to see if this is a 
                //valid ip address. TryParse returns a
                //boolean based on the validity of the
                //provided address, so assign that value
                //to our boolean variable
                valid = IPAddress.TryParse(addr, out result);
            }
            return valid;
        }


        #region IDisposable Membres
        // needed by tcplistener_running
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Free other state (managed objects).
                if (tcplistener_running != null)
                {
                    tcplistener_running.Close();
                    tcplistener_running = null;
                }
            }
            // Free your own state (unmanaged objects).
            // Set large fields to null.

        }

        #endregion
    }
}