summaryrefslogtreecommitdiffstats
path: root/modules/asterisk.module/module.cpp
blob: 60a28dff0f39cbf651352e9e13417638cb8f5476 (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
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
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
/*  Copyright 2008,2009,2010 Edwin Eefting (edwin@datux.nl) 

    This file is part of Synapse.

    Synapse is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Synapse is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Synapse.  If not, see <http://www.gnu.org/licenses/>. */


/** \file
Asterisk Control Module.

Uses the AMI module (and maybe others) to track and control asterisk.

The complex flow of asterisk events is converted to a few simple events, usable in operator panels and other apps.

\code
To capture test-data from a asterisk server:
  script -c telnet 1.2.3.4 5038 -t ami.txt 2> ami.timing

and login with:
 Action: Login
 ActionID: Login
 Events: on
 Secret: password
 UserName: username



To setup a fake server replaying this:

 tcpserver 0.0.0.0 5555 scriptreplay ami.timing ami.txt
 

\endcode



*/

/*
    Data structure overview:

    groupMap->groupPtr------------------>Cgroup
                                          ^ ^
    sessionMap->sessionPtr->Csession:     | |
        groupPtr--->----------------------  |
                                            |
    serverMap->serverPtr->Cserver:          |
        channelMap->channelPtr->Cchannel:   |
            devicePtr--->-------\           |
                                 v          |
        deviceMap->devicePtr->Cdevice:      |
            groupPtr--->--------------------

*/

#include "synapse.h"
#include <boost/regex.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include "./csession.h"
#include "cconfig.h"
//#include "./cgroup.h"
//#include "./csession_types.h"
//#include "./cgroup_types.h"

#define ASTERISK_AUTH "9999"

namespace asterisk
{
	using namespace std;
	using namespace boost;

	typedef long int TauthCookie;
 	struct drand48_data randomBuffer;


	SYNAPSE_REGISTER(module_Init)
	{
		Cmsg out;


		//FIXME: unsafe randomiser?
		srand48_r(time(NULL), &randomBuffer);
	
		out.clear();
		out.event="core_ChangeModule";
		out["maxThreads"]=1; //NOTE: this module is single threaded only!
		out.send();
	
		out.clear();
		out.event="core_ChangeSession";
		out["maxThreads"]=1;
		out.send();
	
		out.clear();
		out.event="core_LoadModule";
		out["path"]="modules/ami.module/libami.so";
		out.send();
	
	
		out.clear();
		out.event="core_LoadModule";
		out["path"]="modules/timer.module/libtimer.so";
		out.send();


		out.clear();
		out.event="core_LoadModule";
		out["path"]="modules/http_json.module/libhttp_json.so";
		out.send();

	
		out.clear();


		//send by anonymous only:
		out.event="core_ChangeEvent";
		out["modifyGroup"]=	"modules";
		out["sendGroup"]=	"anonymous";
		out["recvGroup"]=	"modules";

		out["event"]=		"asterisk_authReq";
		out.send();

		out["event"]=		"asterisk_refresh";
		out.send();

		//receive by anonymous only:
		out.event="core_ChangeEvent";
		out["modifyGroup"]=	"modules";
		out["sendGroup"]=	"modules";
		out["recvGroup"]=	"anonymous";

	
	 	out["event"]=		"asterisk_debugChannel"; 
 	 	out.send();
	

		out["event"]=		"asterisk_authCall"; 
		out.send();
	
		out["event"]=		"asterisk_authOk"; 
		out.send();
	
		out["event"]=		"asterisk_updateChannel"; 
		out.send();
	
		out["event"]=		"asterisk_delChannel"; 
		out.send();
	
		out["event"]=		"asterisk_updateDevice"; 
		out.send();
	
		out["event"]=		"asterisk_delDevice"; 
		out.send();

		out["event"]=		"asterisk_reset"; 
		out.send();
	
	}


	string getDeviceIdFromChannel(string channel)
	{
		//a channel can be either:
		// technology/number-random
		//or
		// agent/number
		smatch what;
		if (!regex_search(
			channel,
			what, 
			boost::regex("^(.*)-([^-]*)$")
		))
		{
			//return whole string, appearently there is no random channel identifier added. (happens with agents)
			return (channel);
//			WARNING("Invalid channel: " << channel << ", using 'unknown' instead");
//	/		return (string("unknown"));
		}
		else
		{
			return (what[1]);
		}
	}

	CsessionMap sessionMap;

	CgroupMap groupMap;

	typedef shared_ptr<class Cdevice> CdevicePtr;
	typedef map<string, CdevicePtr> CdeviceMap;

	typedef shared_ptr<class Cchannel> CchannelPtr;
	typedef map<string, CchannelPtr> CchannelMap;

	typedef map<int, class Cserver> CserverMap;
	CserverMap serverMap;




	




	//devices: these can be sip devices, misdn, local channels, agent-stuff etc
	//every device points to a corresponding Cgroup. 
	class Cdevice
	{
		private: 

		bool trunk;
		bool online;
		string callerId;
		string callerIdName;
		string id;
		bool changed;
		CgroupPtr groupPtr;	
		TauthCookie authCookie;
	
		public:

		Cdevice()
		{
			mrand48_r(&randomBuffer, &authCookie);

			changed=true;
			online=true;
			trunk=true; //assume true, to prevent showing trunks on asterisk-reconnect
		}

		//check if the device should be filtered from the endusers, according to various filtering options
		bool isFiltered()
		{
			//dont show trunks
			if (trunk)
				return (true);

			//dont show devices with empty caller ID's
			if (callerIdName=="")
				return (true);

			//dont show anything thats not sip (for now)
			if (id.substr(0,3)!="SIP")
				return (true);

			return(false);
		}

		CgroupPtr getGroupPtr()
		{
			return (groupPtr);
		}

		TauthCookie getAuthCookie()
		{
			return (authCookie);
		}


		void setId(string id)
		{
			if (id!=this->id)
			{
				this->id=id;
				if (callerId=="")
				{
					callerId=id;
				}

				//now we determine the corresponding group from the device Id string:
				size_t pos=id.find("-");
				string groupId;

				if (pos!=string::npos)
					groupId=id.substr(pos+1);

				if (groupId=="")
					groupId="default";

				if (groupMap.find(groupId) == groupMap.end())
				{
					groupMap[groupId]=CgroupPtr(new Cgroup());
					groupMap[groupId]->setId(groupId);
				}
				groupPtr=groupMap[groupId];

				changed=true;
			}
		}

		string getId()
		{
			return (id);
		}
	
		void setCallerId(string callerId)
		{
			if (callerId!="" && callerId!=this->callerId)
			{
				this->callerId=callerId;
				changed=true;
			}
		}

		string getCallerId()
		{
			return(callerId);
		}

		void setCallerIdName(string callerIdName)
		{
			if (callerIdName!="" && callerIdName!=this->callerIdName)
			{
				this->callerIdName=callerIdName;
				changed=true;
			}
		}

		string getCallerIdName()
		{
			return(callerIdName);
		}


		void setTrunk(bool trunk)
		{
			this->trunk=trunk;
			changed=true;
		}

		void setOnline(bool online)
		{
			if (online!=this->online)
			{
				this->online=online;
				changed=true;
			}
		}


	

		bool sendUpdate(int forceDst=0)
		{
			if (groupPtr==NULL)	
				return(false);

			if (isFiltered())
				return(false);

			if (groupPtr!=NULL)
			{
				Cmsg out;
				out.event="asterisk_updateDevice";
				out.dst=forceDst;
				out["id"]=id;
				out["callerId"]=callerId;
				out["callerIdName"]=callerIdName;
				out["online"]=online;
				out["trunk"]=trunk;
				out["groupId"]=groupPtr->getId();
				groupPtr->send(sessionMap,out);
			}

			return(true);
		}


		void sendChanges()
		{
			if (changed)
			{	
				if (sendUpdate())
					changed=false;
			}
		}


		void sendRefresh(int dst)
		{
			//refresh device
			sendUpdate(dst);
		}

		string getStatus(string prefix)
		{
			return (
				prefix+"Device "+id+":\n"+
				groupPtr->getStatus(prefix+" ")
			);
		}


		~Cdevice()
		{
			Cmsg out;
			out.event="asterisk_delDevice";
			out.dst=0; 
			out["id"]=id;

			if (groupPtr!=NULL)
				groupPtr->send(sessionMap,out);
		}

		
	};
	
	//asterisk channels. these always point to a corresponding Cdevice
	class Cchannel
	{
		private:

		string id;
		int changes;
		string state;
		CchannelPtr linkChannelPtr;
		string callerId;
		string callerIdName;
		string linkCallerId;
		string linkCallerIdName;
		string firstExtension;
//		bool initiator;
		CdevicePtr devicePtr;

		int changesSent;		

		public:

		Cchannel()
		{
			changes=1;
			changesSent=0;
//			initiator=true;
		}

		bool sendDebug(Cmsg msg, int serverId)
		{
			if (devicePtr==NULL || devicePtr->getGroupPtr()==NULL)
				return (false);

			msg.event="asterisk_debugChannel";
			msg["serverId"]=serverId;
			msg["id"]=id;
			if (devicePtr!=CdevicePtr())
			{
				msg["deviceId"]=devicePtr->getId();
			}
			msg.dst=0;
			msg.src=0;

			devicePtr->getGroupPtr()->send(sessionMap,msg);
			return (true);
		}

		int getChanges()
		{
			return (changes);
		}


		void setFirstExtension(string firstExtension)
		{
			if (firstExtension!=this->firstExtension)
			{
				this->firstExtension=firstExtension;
				changes++;
			}

		}

		string getFirstExtension()
		{
			return(firstExtension);
		}

//		void setInitiator(bool initiator)
//		{
//			if (initiator!=this->initiator)
//			{
//				this->initiator=initiator;
//				changes++;
//			}
//
//		}

		void setDevicePtr(CdevicePtr devicePtr)
		{
			if (devicePtr!=this->devicePtr)
			{
				if (
						//device disappeared somehow?
						(this->devicePtr && devicePtr) ||
						//or channel moved to other device?
						(this->devicePtr && devicePtr && this->devicePtr->getGroupPtr()!=devicePtr->getGroupPtr())
				)
				{
					//the channel is moving to another group.
					//send a delete to the group of the current device:
					//(otherwise the people in the current group wont see the delChannel lateron)
					if (this->devicePtr->getGroupPtr())
					{
						Cmsg out;
						out.event="asterisk_delChannel";
						out.dst=0;
						out["id"]=id;
						if (this->devicePtr!=NULL)
						{
							out["deviceId"]=this->devicePtr->getId();
						}
						this->devicePtr->getGroupPtr()->send(sessionMap,out);
					}
				}

				//store the new device
				this->devicePtr=devicePtr;
				changes++;
			}
		}

		void setId(string id)
		{
			if (id!=this->id)
			{
				this->id=id;
				changes++;
			}
		}

		void setLinkPtr(CchannelPtr channelPtr)
		{
			if (channelPtr!=this->linkChannelPtr)
			{
				this->linkChannelPtr=channelPtr;
				if (linkChannelPtr!=CchannelPtr())
				{
					linkChannelPtr->setLinkCallerId(callerId);
					linkChannelPtr->setLinkCallerIdName(callerIdName);
				}
				changes++;
			}
		}

		void delLink()
		{
			//unset our link
			setLinkPtr(CchannelPtr());
		}

		CchannelPtr getLinkPtr()
		{
			return(linkChannelPtr);
		}


		void setCallerId(string callerId)
		{
			if (callerId!=this->callerId)
			{
				this->callerId=callerId;
				if (linkChannelPtr!=CchannelPtr())
					linkChannelPtr->setLinkCallerId(callerId);
				changes++;
			}
		}

		void setCallerIdName(string callerIdName)
		{
			if (callerIdName!=this->callerIdName)
			{
				this->callerIdName=callerIdName;
				if (linkChannelPtr!=CchannelPtr())
					linkChannelPtr->setLinkCallerIdName(callerIdName);
				changes++;
			}
		}

		void setLinkCallerId(string callerId)
		{
			if (callerId!=this->linkCallerId)
			{
				this->linkCallerId=callerId;
				changes++;
			}
		}

		void setLinkCallerIdName(string callerIdName)
		{
			if (callerIdName!=this->linkCallerIdName)
			{
				this->linkCallerIdName=callerIdName;
				changes++;
			}
		}


		string getCallerId()
		{
			return (callerId);
		}

		string getCallerIdName()
		{
			return (callerIdName);
		}

		string getState()
		{
			return (state);
		}
	
		void setState(string state)
		{
	
			if (state!=this->state)
			{
				this->state=state;
				changes++;
			}
		}

		void sendChanges()
		{

			// are there changes we didnt send yet?
			if (changes>changesSent)
			{
				if (sendUpdate())
					changesSent=changes;
			}	


		}

		bool sendUpdate(int forceDst=0)
		{
			if (devicePtr==NULL || devicePtr->getGroupPtr()==NULL)
				return (false);

			if (devicePtr->isFiltered())
				return (false);

			Cmsg out;
			out.event="asterisk_updateChannel";
			out.dst=forceDst;
			out["id"]=id;
			out["state"]=state;
//			out["initiator"]=initiator;
			out["callerId"]=callerId;
			out["callerIdName"]=callerIdName;

			if (devicePtr!=CdevicePtr())
			{
				out["deviceId"]=devicePtr->getId();
				out["deviceCallerId"]=devicePtr->getCallerId();
				out["deviceCallerIdName"]=devicePtr->getCallerIdName();
			}

			out["linkCallerId"]=linkCallerId;
			out["linkCallerIdName"]=linkCallerIdName;

			out["firstExtension"]=firstExtension;

			devicePtr->getGroupPtr()->send(sessionMap,out);

			return (true);
		}

		void sendRefresh(int dst)
		{
			sendUpdate(dst);
		}

		string getStatus(string prefix)
		{
			return (
				prefix + "Channel " + id + ":\n" +
				devicePtr->getStatus(prefix+" ")
			);
		}

		~Cchannel()
		{

			if (devicePtr!=NULL && devicePtr->getGroupPtr()!=NULL)
			{
				Cmsg out;
				out.event="asterisk_delChannel";
				out.dst=0; 
				out["id"]=id;
				if (devicePtr!=CdevicePtr())
				{
					out["deviceId"]=devicePtr->getId();
				}
				devicePtr->getGroupPtr()->send(sessionMap,out);
			}
		}

	};
	
	
	//physical asterisk servers. every server has its own device and channel map
	class Cserver
	{
		private:
		CdeviceMap deviceMap;
		CchannelMap channelMap;

		public:	
		enum Estatus
		{
			CONNECTING,
			AUTHENTICATING,
			AUTHENTICATED,
		};

		Estatus status;

		string id;
		string username;
		string password;
		string host;
		string port;

		int sessionId;

		Cserver()
		{
			status=CONNECTING;
		}

	
		CdevicePtr getDevicePtr(string deviceId, bool autoCreate=true)
		{
			if (deviceMap.find(deviceId)==deviceMap.end())
			{
				if (autoCreate)
				{
					deviceMap[deviceId]=CdevicePtr(new Cdevice());
					deviceMap[deviceId]->setId(deviceId);
					DEB("created device " << deviceId);
				}
				else
				{
					return (CdevicePtr());
				}
			}
			return (deviceMap[deviceId]);
		}
		
		void sendRefresh(int dst)
		{
			//let all devices send a refresh
			for (CdeviceMap::iterator I=deviceMap.begin(); I!=deviceMap.end(); I++)
			{
				I->second->sendRefresh(dst);
			}

			//let all channels send a update
			for (CchannelMap::iterator I=channelMap.begin(); I!=channelMap.end(); I++)
			{
				I->second->sendRefresh(dst);
			}

		}

		void sendChanges()
		{
			//let all devices send their changes, if they have them.
			for (CdeviceMap::iterator I=deviceMap.begin(); I!=deviceMap.end(); I++)
			{
				I->second->sendChanges();
			}

			//let all channels send their changes, if they have them.
			for (CchannelMap::iterator I=channelMap.begin(); I!=channelMap.end(); I++)
			{
				I->second->sendChanges();
			}
		}
	
		CchannelPtr getChannelPtr(string channelId)
		{
			if (channelMap[channelId]==NULL)
			{
				channelMap[channelId]=CchannelPtr(new Cchannel());
				channelMap[channelId]->setId(channelId);
				DEB("created channel " << channelId);
			}
			return (channelMap[channelId]);
		}
	
		void delChannel(string channelId)
		{
			CchannelPtr channelPtr=getChannelPtr(channelId);
			//delete the link, to prevent "hanging" shared_ptrs
			channelPtr->delLink();
			channelMap.erase(channelId);
			DEB("deleted channel from map: " << channelId);

		}


		//on a disconnect this is called to remove all channels/devices.
		void clear()
		{
			//unlink all channels to prevent dangling shared_ptrs
			for (CchannelMap::iterator I=channelMap.begin(); I!=channelMap.end(); I++)
			{
				I->second->delLink();
			}

			//this should send out automated delChannel/delDevice events, on destruction of the objects
			deviceMap.clear();
			channelMap.clear();
		}


		string getStatus(string prefix)
		{
			string s;
			s=prefix+"Server "+id+": ";



			if (status==CONNECTING)
				s=s+"connecting...";
			if (status==AUTHENTICATING)
				s=s+"authenticating...";
			if (status==AUTHENTICATED)
				s=s+"authenticated";

			s=s+"\n";

			s=s+prefix+" Channels:\n";
			for (CchannelMap::iterator I=channelMap.begin(); I!=channelMap.end(); I++)
			{
				s= s + I->second->getStatus(prefix+"  ") + "\n";
			}

			s=s+prefix+" Devices:\n";
			for (CdeviceMap::iterator I=deviceMap.begin(); I!=deviceMap.end(); I++)
			{
				s=s + I->second->getStatus(prefix+"  ")+"\n";
			}

			return (s);
		}

		~Cserver()
		{

		}

	};

	SYNAPSE_REGISTER(asterisk_GetStatus)
	{
		Cmsg out;
		out.event="asterisk_Status";
		out.dst=msg.src;
		out["status"]="";

		out["status"].str()+="Sessions:\n";
		for (CsessionMap::iterator I=sessionMap.begin(); I!=sessionMap.end(); I++)
		{
			stringstream id;
			id << I->first;
			out["status"].str()+=I->second->getStatus(" ")+"\n";
		}


		out["status"].str()+="Groups:\n";
		for (CgroupMap::iterator I=groupMap.begin(); I!=groupMap.end(); I++)
		{
			out["status"].str()+=I->second->getStatus(" ")+"\n";
		}

		out["status"].str()+="Servers:\n";
		for (CserverMap::iterator I=serverMap.begin(); I!=serverMap.end(); I++)
		{
			out["status"].str()+= I->second.getStatus(" ");
		}


		out.send();
	}
	
	SYNAPSE_REGISTER(timer_Ready)
	{
		Cmsg out;
		out.clear();
		out.event="timer_Set";
		out["seconds"]=1;
		out["repeat"]=-1;
		out["dst"]=dst;
		out["event"]="asterisk_SendChanges";
		out.send();
	}
	
	

	
	SYNAPSE_REGISTER(asterisk_SendChanges)
	{
		CserverMap::iterator I;
//		I->second.sendChanges();

		//let all servers send their changes 
		for (CserverMap::iterator I=serverMap.begin(); I!=serverMap.end(); I++)
		{
			I->second.sendChanges();
		}
	
	}
	
	
	SYNAPSE_REGISTER(ami_Ready)
	{
		///if ami is ready, we are ready ;)
		Cmsg out;
		out.clear();
		out.event="core_Ready";
		out.send();

		out.clear();
		out.event="asterisk_Config";
		out.send();
	}
	
	/** Connects to specified asterisk server
		\param host Hostname of the asterisk server.
		\param port AMI port (normally 5038)
		\param username Asterisk manager username
		\param password Asterisk manager password
	
	*/

// replaced by asterisk_Config for now, which lo
//	SYNAPSE_REGISTER(asterisk_Connect)
//	{
//		//ami connections are src-session based, so we need a new session for every connection.
//		Cmsg out;
//		out.event="core_NewSession";
//		out["server"]["username"]=msg["username"];
//		out["server"]["password"]=msg["password"];
//		out["server"]["port"]=msg["port"];
//		out["server"]["host"]=msg["host"];
//		out.send();
//	}

	/** Loads asterisk.conf and connects to specified servers.
	 * It will also handle server deletes/changes.
	 */
	SYNAPSE_REGISTER(asterisk_Config)
	{
		using synapse::Cconfig;
		Cconfig config;
		config.load("etc/synapse/asterisk.conf");

		//delete servers that have been changed or removed from the config
		for (CserverMap::iterator serverI=serverMap.begin(); serverI!=serverMap.end(); serverI++)
		{
			//server config removed or changed?
			if (
				!config.isSet(serverI->second.id) ||
				serverI->second.username!=config[serverI->second.id]["username"].str() ||
				serverI->second.password!=config[serverI->second.id]["password"].str() ||
				serverI->second.host!=config[serverI->second.id]["host"].str() ||
				serverI->second.port!=config[serverI->second.id]["port"].str()
			)
			{
				//delete server and connection by ending session
				//the rest will get cleaned up automaticly by the module_SessionEnd(ed) events.
				Cmsg out;
				out.src=serverI->first;
				out.event="core_DelSession";
				out.send();
			}
			else
			{
				//nothing changed, deleted it from config-object
				config.map().erase(serverI->second.id);
			}
		}

		//the remaining config entries need to be (re)created and (re)connected.
		for (Cconfig::iterator configI=config.begin(); configI!=config.end(); configI++)
		{
			//start a new session for every new connection, and supply the config info
			Cmsg out;
			out.event="core_NewSession";
			out["server"]=configI->second;
			out["server"]["id"]=configI->first;
			out["description"]="asterisk-ami connection session.";
			out.send();
		}
	}
	

	SYNAPSE_REGISTER(module_SessionStart)
	{
		//new session that is started with server info
		if (msg.isSet("server"))
		{
			//setup a new server object
			serverMap[msg.dst].id=msg["server"]["id"].str();
			serverMap[msg.dst].username=msg["server"]["username"].str();
			serverMap[msg.dst].password=msg["server"]["password"].str();
			serverMap[msg.dst].host=msg["server"]["host"].str();
			serverMap[msg.dst].port=msg["server"]["port"].str();
	
			//instruct ami to connect to the server
			Cmsg out;
			out.clear();
			out.event="ami_Connect";
			out.src=msg.dst;
			out["host"]=msg["server"]["host"].str();
			out["port"]=msg["server"]["port"].str();
			out.send();
		}
	}

	//a session owned by us ended, remove the corresponding server.
	SYNAPSE_REGISTER(module_SessionEnd)
	{
		//since the ami module also sees a module_SessionEnded, it will automaticly disconnect the server
		serverMap[msg.dst].clear();
		serverMap.erase(msg.dst);
	}

	//a session owned by another module ended. check if we created local stuff that we need to delete.
	SYNAPSE_REGISTER(module_SessionEnded)
	{
		if (sessionMap.find(msg["session"]) != sessionMap.end())
		{
			//remove the session. we use smartpointers , so it should be safe.
			DEB("Removing session object " << msg["session"]);
			sessionMap.erase(msg["session"]);
		}
	}

	
	SYNAPSE_REGISTER(ami_Connected)
	{
		//ami is connected, now login with the right credentials for this server:
		Cmsg out;
		out.clear();
		out.src=msg.dst;
		out.event="ami_Action";
		out["Action"]="Login";
		out["UserName"]=serverMap[msg.dst].username;
		out["Secret"]=serverMap[msg.dst].password;
		out["ActionID"]="Login";
		out["Events"]="on";
		out.send();

		serverMap[msg.dst].status=Cserver::AUTHENTICATING;
	
	}
	
	SYNAPSE_REGISTER(ami_Response_Success)
	{
		
		//AMI is broken by design: why didnt they just use a Event, instead of defining the format of a Response exception. Now we need to use the ActionID and do extra marshhalling:
		//SIPshowPeer response
		if (msg["ActionID"].str()=="SIPshowPeer")
		{
			string deviceId=msg["Channeltype"].str()+"/"+msg["ObjectName"].str();
			CdevicePtr devicePtr=serverMap[msg.dst].getDevicePtr(deviceId);
	
			//NOTE: we handle Unmonitored sip peers as online, while we dont actually know if its online or not.		
			if (msg["Status"].str().find("OK")==0 || msg["Status"].str().find("Unmonitored")==0 )//||  msg["Status"].str().find("UNKNOWN")==0)
				devicePtr->setOnline(true);
			else
				devicePtr->setOnline(false);
	
			if (msg["Callerid"].str() != "\"\" <>")
			{
				//split up the the callerid+callerIdname string
				//Why the heck are the asterisk folks pre-formatting it like this?? Everywhere else in the ami a caller id is just a number instead of a preformatted string!
				smatch what;
				if (regex_search(
					msg["Callerid"].str(),
					what,
					boost::regex("\"(.*)\" <(.*)>")
				))
				{
					devicePtr->setCallerIdName(what[1]);
					devicePtr->setCallerId(what[2]);
				}
				else
				{
					//cant parse somehow? just set the whole string as callerIdName
					devicePtr->setCallerIdName(msg["CallerId"]);
				}
			}
			else
				devicePtr->setCallerIdName(msg["ObjectName"]);

			if (msg["ToHost"].str() != "")
				devicePtr->setTrunk(true);
			else
				devicePtr->setTrunk(false);


		}
		//login response
		else if (msg["ActionID"].str()=="Login")
		{
			serverMap[msg.dst].status=Cserver::AUTHENTICATED;


			//learn all SIP peers as soon as we login
			Cmsg out;
			out.clear();
			out.src=msg.dst;
			out.event="ami_Action";
			out["Action"]="SIPPeers";
			out.send();
	
			//learn current channel status as soon as we login
			out.clear();
			out.src=msg.dst;
			out.event="ami_Action";
			out["Action"]="Status";
			out.send();
	
		}
			
		
	}
	
	SYNAPSE_REGISTER(ami_Response_Error)
	{
		ERROR("ERROR:" << msg["Message"].str());
		//TODO: pass to clients?
	
	}
	
	
	SYNAPSE_REGISTER(ami_Disconnected)
	{
		//since we're disconnected, clear all devices/channels
		serverMap[msg.dst].clear();
		serverMap[msg.dst].status=Cserver::CONNECTING;
		
		//ami reconnects automaticly
	}
	
	
	
	SYNAPSE_REGISTER(asterisk_refresh)
	{
		//indicate start of a refresh, deletes all known state-info in client
		Cmsg out;
		out.event="asterisk_reset";
		out.dst=msg.src; 
		out.send();
	
		for (CserverMap::iterator I=serverMap.begin(); I!=serverMap.end(); I++)
		{
			I->second.sendRefresh(msg.src);
		}
	
	}
	
	
	//we got a response to our SIPPeers request.
	SYNAPSE_REGISTER(ami_Event_PeerEntry)
	{
		serverMap[msg.dst].getDevicePtr(msg["Channeltype"].str()+"/"+msg["ObjectName"].str());
	
		//request additional device info for this SIP peer
		//example: "SIP/604"
		if (msg["Channeltype"].str()=="SIP")
		{
			//(peerEntrys should be ALWAYS of type SIP?)
			Cmsg out;
			out.clear();
			out.src=msg.dst;
			out.dst=msg.src;
			out.event="ami_Action";
			out["Action"]="SIPshowPeer";
			out["ActionID"]="SIPshowPeer";
			out["Peer"]=msg["ObjectName"].str();
			out.send();
		}
	
	}
	
	void channelStatus(Cmsg & msg)
	{
		CchannelPtr channelPtr=serverMap[msg.dst].getChannelPtr(msg["Uniqueid"]);
		CdevicePtr devicePtr=serverMap[msg.dst].getDevicePtr(
			getDeviceIdFromChannel(msg["Channel"])
		);
	
		channelPtr->setDevicePtr(devicePtr);

		//States:
		// ringing: somebody is calling the device
		// in     : incoming call in progress
		// out    : outgoing call in progress
		// ''     : other (uninteresting) states

		//device is ringing
		if (msg["State"].str()=="Ringing")
		{
			channelPtr->setState("ringing");
		}
		//device is dialing (ringing other side)
		else if (msg["State"].str()=="Ring")
		{
			channelPtr->setState("out");
		}
		//device is connected with other side
		else if (msg["State"].str()=="Up")
		{
			if (channelPtr->getState()=="ringing")
			{
				channelPtr->setState("in");
			}
			else
			{
				channelPtr->setState("out");
			}
		}
		//device is down/other stuff
		else
		{
			channelPtr->setState("");
		}
	
		//NOTE: whats with all the different namings and <unknown> vs <Unknown> in Newcallerid?
	
		if (msg.isSet("CallerIDNum"))
		{
			if (msg["CallerIDNum"].str() == "<unknown>")
				;//channelPtr->setCallerId("");
			else
				channelPtr->setCallerId(msg["CallerIDNum"]);
		}
	
		if (msg.isSet("CallerID"))
		{
			if (msg["CallerID"].str() == "<unknown>")
				;//channelPtr->setCallerId("");
			else
				channelPtr->setCallerId(msg["CallerID"]);
		}
	
		if (msg.isSet("CallerIDName"))
		{
			if (msg["CallerIDName"].str() == "<unknown>")
				channelPtr->setCallerIdName("");
			else
				channelPtr->setCallerIdName(msg["CallerIDName"]);
		}
	
//		devicePtr->sendChanges();
		channelPtr->sendDebug(msg, msg.dst);
	
		
	}
	
	
	// new channel created
	SYNAPSE_REGISTER(ami_Event_Newchannel)
	{
	
	/*	Event: Newchannel
		Privilege: call,all
		Channel: SIP/604-00000069
		State: Down
		CallerIDNum: 604
		CallerIDName: Edwin (draadloos)
		Uniqueid: 1269871368.143
	
		Event: Newchannel
		Privilege: call,all
		Channel: SIP/605-0000006a
		State: Down
		CallerIDNum: <unknown>
		CallerIDName: <unknown>
		Uniqueid: 1269871368.144*/
	
		channelStatus(msg);
	}
	
	// initial channel status event, requested just after connecting to an asterisk server.
	SYNAPSE_REGISTER(ami_Event_Status)
	{
	// 	Event: Status
	// 	Privilege: Call
	// 	Channel: SIP/601-00000048
	// 	CallerID: 601
	// 	CallerIDNum: 601
	// 	CallerIDName: <unknown>
	// 	Account:
	// 	State: Ringing
	// 	Uniqueid: 1269958019.99
	// 
	// 	Event: Status
	// 	Privilege: Call
	// 	Channel: SIP/605-00000047
	// 	CallerID: 605
	// 	CallerIDNum: 605
	// 	CallerIDName: <unknown>
	// 	Account:
	// 	State: Up
	// 	Link: SIP/604-00000046
	// 	Uniqueid: 1269958018.98
	
	
		channelStatus(msg);
	
	}
	
	// channel status is changing
	SYNAPSE_REGISTER(ami_Event_Newstate)
	{
		/*
		|CallerID = 605 (string)
		|CallerIDName = <unknown> (string)
		|Channel = SIP/605-0000005b (string)
		|Event = Newstate (string)
		|Privilege = call,all (string)
		|State = Ringing (string)
		|Uniqueid = 1269870185.119 (string)                                                                                                     */
	
		channelStatus(msg);
	}
	
	
	SYNAPSE_REGISTER(ami_Event_Hangup)
	{
		CchannelPtr channelPtr=serverMap[msg.dst].getChannelPtr(msg["Uniqueid"]);
		channelPtr->sendDebug(msg, msg.dst);
		serverMap[msg.dst].delChannel(msg["Uniqueid"]);
	//	serverMap[msg.dst].getDevicePtr(getDeviceId(msg["Channel"]))->sendStatus();
	//	INFO("\n" << serverMap[msg.dst].getStatusStr());
	
	}
	
	SYNAPSE_REGISTER(ami_Event_PeerStatus)
	{
		
		CdevicePtr devicePtr=serverMap[msg.dst].getDevicePtr(msg["Peer"]);
		if (msg["PeerStatus"].str()=="Reachable" || msg["PeerStatus"].str()=="Registered" )
			devicePtr->setOnline(true);
		else
			devicePtr->setOnline(false);
	
//		devicePtr->sendChanges();
	
	}
	
	
	
	SYNAPSE_REGISTER(ami_Event_Link)
	{
	/*	Event: Link
		Privilege: call,all
		Channel1: SIP/604-00000022
		Channel2: SIP/605-00000023
		Uniqueid1: 1269864649.42
		Uniqueid2: 1269864649.43
		CallerID1: 604
		CallerID2: 605*/
		CchannelPtr channelPtr1=serverMap[msg.dst].getChannelPtr(msg["Uniqueid1"]);
		CchannelPtr channelPtr2=serverMap[msg.dst].getChannelPtr(msg["Uniqueid2"]);
	
		channelPtr1->setLinkPtr(channelPtr2);
		channelPtr2->setLinkPtr(channelPtr1);
	
	
		channelPtr1->sendDebug(msg, msg.dst);
		channelPtr2->sendDebug(msg, msg.dst);
	}
	
	
	SYNAPSE_REGISTER(ami_Event_Unlink)
	{
		/*Event: Unlink
		Privilege: call,all
		Channel1: SIP/604-00000020
		Channel2: SIP/605-00000021
		Uniqueid1: 1269864479.40
		Uniqueid2: 1269864479.41
		CallerID1: 604
		CallerID2: 605*/
		CchannelPtr channelPtr=serverMap[msg.dst].getChannelPtr(msg["Uniqueid1"]);
		channelPtr->delLink();
		channelPtr->sendDebug(msg, msg.dst);
	
		channelPtr=serverMap[msg.dst].getChannelPtr(msg["Uniqueid2"]);
		channelPtr->delLink();
		channelPtr->sendDebug(msg, msg.dst);
	
	
	
	}
	

	/** Requests authentication for \c src 
	
	\par Replys \c asterisk_authCall
		The session should authenticate by dialing a special crafted  number. After this asterisk knows to which device the client belongs, and can determine to which group the user belongs.
			\arg \c number The number the client should call to authenticate.

	\par Replys \c asterisk_authOk
		After the user called the specified number.
			\arg \c deviceId The deviceId the user was calling from.
	
	*/
	SYNAPSE_REGISTER(asterisk_authReq)
	{
		//create a Csession object for the src session?
		if (sessionMap.find(msg.src) == sessionMap.end())
		{
			sessionMap[msg.src]=CsessionPtr(new Csession(msg.src));
		}

		//deviceId + correct authCookie ?
		if (msg.isSet("deviceId") && msg.isSet("authCookie"))
		{
			//traverse all the servers and find the device
			for (CserverMap::iterator I=serverMap.begin(); I!=serverMap.end(); I++)
			{
				CdevicePtr devicePtr=I->second.getDevicePtr(msg["deviceId"],false);
				//device exists?
				if (devicePtr!=NULL)
				{
					//autoCookie checks out?
					if (devicePtr->getAuthCookie()==msg["authCookie"])
					{

						//session is now authenticated, set corresponding group
						sessionMap[msg.src]->setGroupPtr(devicePtr->getGroupPtr());

						//session is re-authenticated, by authCookie
						Cmsg out;
						out.event="asterisk_authOk";
						out.dst=msg.src;
						out["deviceId"]=msg["deviceId"].str();
						out["authCookie"]=msg["authCookie"].str();
						out.send();
						return;
					}
				}
			}
		}
		else
		{
			//de-authenticate the user (e.g. logout)
			sessionMap[msg.src]->setGroupPtr(CgroupPtr());
		}

		//tell the client which number to call, to authenticate
		stringstream number;
		number << ASTERISK_AUTH << msg.src;

		Cmsg out;
		out.event="asterisk_reset"; //since we're logged out again, make sure the screen is cleared.
		out.dst=msg.src;
		out.send();

		out.event="asterisk_authCall";
		out["number"]=number.str();
		out.send();
	}

	
	SYNAPSE_REGISTER(ami_Event_Newexten)
	{
		// Event: Newexten
		// Privilege: call,all
		// Channel: SIP/604-00000007
		// Context: DLPN_DatuX
		// Extension: 9991234
		// Priority: 1
		// Application: Macro
		// AppData: trunkdial-failover-0.3|SIP/0858784323/9991234|mISDN/g:trunk_m1/9991234|0858784323|trunk_m1
		// Uniqueid: 1269802539.12
		
		/* |AppData = SIP/605 (string)
		|Application = Dial (string)
		|Channel = SIP/604-0000002f (string)
		|Context = DLPN_DatuX (string)
		|Event = Newexten (string)
		|Extension = 605 (string)
		|Priority = 1 (string)
		|Privilege = call,all (string)
		|Uniqueid = 1269866053.55 (string)*/
	
		//somebody dialed the special authnumber?
		if (msg["Extension"].str().find(ASTERISK_AUTH)==0)
		{
			//determine specified session number
			int sessionId=lexical_cast<int>(msg["Extension"].str().substr(strlen(ASTERISK_AUTH)));
			//do we know the specified session?
			if (sessionMap.find(sessionId) != sessionMap.end())
			{
				//session is not yet authenticated?
				if (sessionMap[sessionId]->getGroupPtr() == NULL)
				{
					//get the device
					CdevicePtr devicePtr=serverMap[msg.dst].getDevicePtr(getDeviceIdFromChannel(msg["Channel"]));

					//session is now authenticated, set corresponding group
					sessionMap[sessionId]->setGroupPtr(devicePtr->getGroupPtr());

					Cmsg out;
					out.event="asterisk_authOk";
					out.dst=sessionId;
					out["deviceId"]=getDeviceIdFromChannel(msg["Channel"]);
					out["authCookie"]=serverMap[msg.dst].getDevicePtr(out["deviceId"])->getAuthCookie();
					out.send();
	
					//hang up
					out.clear();
					out.dst=msg.src;
					out.src=msg.dst;
					out.event="ami_Action";
					out["Action"]="Hangup";
					out["Channel"]=msg["Channel"].str();
					out.send();
	
					return;
				}
			}
		}
	
		CchannelPtr channelPtr=serverMap[msg.dst].getChannelPtr(msg["Uniqueid"]);
		if (channelPtr->getFirstExtension()=="")
		{
			channelPtr->setFirstExtension(msg["Extension"]);
		}
	
		//TOO much info..channelPtr->sendDebug(msg, msg.dst);	
	}
	
	
	// 
	// SYNAPSE_REGISTER(ami_Event_ExtensionStatus)
	// {
	
	// }
	// 
	
	SYNAPSE_REGISTER(ami_Event_Dial)
	{
	// 	Event: Dial
	// 	Privilege: call,all
	// 	Source: SIP/604-0000002f
	// 	Destination: SIP/605-00000030
	// 	CallerID: 604
	// 	CallerIDName: Edwin (draadloos)
	// 	SrcUniqueID: 1269866053.55
	// 	DestUniqueID: 1269866053.56
	
	// 	Event: Dial
	// 	Privilege: call,all
	// 	Source: SIP/604-00000031
	// 	Destination: mISDN/0-u5
	// 	CallerID: 0858784323
	// 	CallerIDName: <unknown>
	// 	SrcUniqueID: 1269866267.57
	// 	DestUniqueID: 1269866267.58
	
	
		//NOTE: a "link" for us, is something different then a link for asterisk.
		CchannelPtr channelPtr1=serverMap[msg.dst].getChannelPtr(msg["SrcUniqueID"]);
		CchannelPtr channelPtr2=serverMap[msg.dst].getChannelPtr(msg["DestUniqueID"]);
		channelPtr1->setLinkPtr(channelPtr2);
		channelPtr2->setLinkPtr(channelPtr1);
	
/*		channelPtr1->setInitiator(true);
		channelPtr2->setInitiator(false);*/
		
		//in case of followme and other situation its important we use the Dial callerId as well, for SrcUniqueID:
		if (msg["CallerID"].str() == "<unknown>")
			;//channelPtr->setCallerId("");
		else
			channelPtr1->setCallerId(msg["CallerID"]);
	
		if (msg["CallerIDName"].str() == "<unknown>")
			channelPtr1->setCallerIdName("");
		else
			channelPtr1->setCallerIdName(msg["CallerIDName"]);
	
	
	
		//this will automagically send updates to BOTH channels, sinces they're linked now:
		channelPtr1->sendDebug(msg, msg.dst);
		channelPtr2->sendDebug(msg, msg.dst);
	
	/*
		channelPtr=serverMap[msg.dst].getChannelPtr(msg["DestUniqueID"]);
		channelPtr->setLink(msg["SrcUniqueID"]);*/
	
	// 	CchannelPtr channelPtr=serverMap[msg.dst].getChannelPtr(msg["Destination"]);
	// 	channelPtr->setCallerId("gettingcalled\"" + msg["CallerIDName"].str() + "\" <" + msg["CallerID"].str() + ">" );
	
	// 	channelPtr=serverMap[msg.dst].getChannelPtr(msg["Source"]);
	// 	channelPtr->setCallerId("calling\"" + msg["CallerIDName"].str() + "\" <" + msg["CallerID"].str() + ">" );
	
	}
	
	// renaming usually happens on things like call-transfers
	
	SYNAPSE_REGISTER(ami_Event_Rename)
	{
		// Event: Rename
		// Privilege: call,all
		// Oldname: SIP/604-00000044
		// Newname: SIP/605-00000043
		// Uniqueid: 1269956933.94
		CchannelPtr channelPtr=serverMap[msg.dst].getChannelPtr(msg["Uniqueid"]);
		CdevicePtr devicePtr=serverMap[msg.dst].getDevicePtr(
			getDeviceIdFromChannel(msg["Newname"])
		);
	
		//we assume a rename only is possible for channels that are already up?
		if (channelPtr->getState()=="ringing")
		{
			channelPtr->setState("in");
		}
		else
		{
			channelPtr->setState("out");
		}
		channelPtr->setDevicePtr(devicePtr);
	
		if (channelPtr->getLinkPtr()==CchannelPtr())
		{
			//when we get renamed while NOT linked, we store the current callerids in the linkedcallerids.
			//after the rename we usually receive our new caller id immeadiatly
			channelPtr->setLinkCallerId(channelPtr->getCallerId());
			channelPtr->setLinkCallerIdName(channelPtr->getCallerIdName());
		}
	
		channelPtr->sendDebug(msg, msg.dst);
	}
	
	SYNAPSE_REGISTER(ami_Event_Newcallerid)
	{
	// 	Event: Newcallerid
	// 	Privilege: call,all
	// 	Channel: SIP/605-00000033
	// 	CallerID: 605
	// 	CallerIDName: <Unknown>
	// 	Uniqueid: 1269866486.60
	// 	CID-CallingPres: 0 (Presentation Allowed, Not Screened)
	
	// Event: Newcallerid
	// Privilege: call,all
	// Channel: mISDN/0-u5
	// CallerID: 0622588835
	// CallerIDName: <Unknown>
	// Uniqueid: 1269866267.58
	// CID-CallingPres: 0 (Presentation Allowed, Not Screened)
	
	// Event: Newcallerid
	// Privilege: call,all
	// Channel: SIP/604-00000031
	// CallerID: 0858784323
	// CallerIDName: <Unknown>
	// Uniqueid: 1269866267.57
	// CID-CallingPres: 0 (Presentation Allowed, Not Screened)
	
		CchannelPtr channelPtr=serverMap[msg.dst].getChannelPtr(msg["Uniqueid"]);
	
		if (msg["CallerID"].str() == "<Unknown>")
			;//channelPtr->setCallerId("");
		else
			channelPtr->setCallerId(msg["CallerID"]);
	
		if (msg["CallerIDName"].str() == "<Unknown>")
			channelPtr->setCallerIdName("");
		else
			channelPtr->setCallerIdName(msg["CallerIDName"]);
		
		channelPtr->sendDebug(msg, msg.dst);
	
	}
	
	
	// 
	// 
	// SYNAPSE_REGISTER(ami_Event_PeerStatus)
	// {
	
	// 
	// }
	
}