gethostbyname isn't reentrant, who knew...
[asterisk/asterisk.git] / channels / chan_skinny.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of the Skinny protocol
5  * 
6  * Asterisk is Copyright (C) 1999-2003 Mark Spencer
7  *
8  * chan_skinny was developed by Jeremy McNamara & Florian Overkamp
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  *
13  */
14
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <pthread.h>
19 #include <string.h>
20 #include <asterisk/lock.h>
21 #include <asterisk/channel.h>
22 #include <asterisk/channel_pvt.h>
23 #include <asterisk/config.h>
24 #include <asterisk/logger.h>
25 #include <asterisk/module.h>
26 #include <asterisk/pbx.h>
27 #include <asterisk/options.h>
28 #include <asterisk/lock.h>
29 #include <asterisk/sched.h>
30 #include <asterisk/io.h>
31 #include <asterisk/rtp.h>
32 #include <asterisk/acl.h>
33 #include <asterisk/callerid.h>
34 #include <asterisk/cli.h>
35 #include <asterisk/say.h>
36 #include <asterisk/cdr.h>
37 #include <asterisk/astdb.h>
38 #include <asterisk/parking.h>
39 #include <asterisk/app.h>
40 #include <asterisk/musiconhold.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <sys/ioctl.h>
45 #include <net/if.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <fcntl.h>
49 #include <netdb.h>
50 #include <arpa/inet.h>
51 #include <sys/signal.h>
52 #include <signal.h>
53 #include <pthread.h>
54 #include <asterisk/dsp.h>
55 #include <ctype.h>
56
57 /************************************************************************************/
58 /*                         Skinny/Asterisk Protocol Settings                        */
59 /************************************************************************************/
60 static char *desc = "Skinny Client Control Protocol (Skinny)";
61 static char *tdesc = "Skinny Client Control Protocol (Skinny)";
62 static char *type = "Skinny";
63 static char *config = "skinny.conf";
64
65 /* Just about everybody seems to support ulaw, so make it a nice default */
66 static int capability = AST_FORMAT_ULAW;
67
68 #define DEFAULT_SKINNY_PORT     2000
69 #define DEFAULT_SKINNY_BACKLOG  2
70 #define SKINNY_MAX_PACKET       1000
71
72 static int  keep_alive = 120;
73 static char date_format[6] = "D-M-Y";
74 static char version_id[16] = "P002F202";
75
76 // these should be in an include file, but dunno what to include
77 typedef unsigned char  UINT8;
78 typedef unsigned short UINT16;
79 typedef unsigned int   UINT32;
80
81 /************************************************************************************/
82 /*                                Protocol Messages                                 */
83 /************************************************************************************/
84 /* message types */
85 #define KEEP_ALIVE_MESSAGE 0x0000
86 /* no additional struct */
87
88 #define REGISTER_MESSAGE 0x0001
89 typedef struct register_message {
90         char name[16];
91         int userId;
92         int instance;
93         char ip[4];
94         int type;
95         int maxStreams;
96 } register_message;
97
98 #define IP_PORT_MESSAGE 0x0002
99
100 #define KEYPAD_BUTTON_MESSAGE 0x0003
101 typedef struct keypad_button_message {
102         int button;
103 } keypad_button_message;
104
105 #define STIMULUS_MESSAGE 0x0005
106 typedef struct stimulus_message {
107         int stimulus;
108         int stimulusInstance;
109 } stimulus_message;
110                 
111 #define OFFHOOK_MESSAGE 0x0006
112 #define ONHOOK_MESSAGE 0x0007
113
114 #define CAPABILITIES_RES_MESSAGE 0x0010
115 typedef struct station_capabilities {   
116         int codec;
117         int frames;
118         union {
119                 char res[8];
120                 long rate;
121         } payloads;     
122 } station_capabilities;
123
124 typedef struct capabilities_res_message {
125         int count;
126         struct station_capabilities caps[18];
127 } capabilities_res_message;
128
129 #define SPEED_DIAL_STAT_REQ_MESSAGE 0x000A
130 typedef struct speed_dial_stat_req_message {
131         int speedDialNumber;
132 } speed_dial_stat_req_message;
133
134 #define LINE_STATE_REQ_MESSAGE 0x000B
135 typedef struct line_state_req_message {
136         int lineNumber;
137 } line_state_req_message;
138
139 #define TIME_DATE_REQ_MESSAGE 0x000D
140 #define VERSION_REQ_MESSAGE 0x000F
141 #define BUTTON_TEMPLATE_REQ_MESSAGE 0x000E
142 #define SERVER_REQUEST_MESSAGE 0x0012
143 #define ALARM_MESSAGE 0x0020
144
145 #define OPEN_RECIEVE_CHANNEL_ACK_MESSAGE 0x0022 
146 typedef struct open_recieve_channel_ack_message {
147         int status;
148         char ipAddr[4];
149         int port;
150         int passThruId;
151 } open_recieve_channel_ack_message;
152
153 #define SOFT_KEY_SET_REQ_MESSAGE 0x0025
154 #define UNREGISTER_MESSAGE 0x0027
155 #define SOFT_KEY_TEMPLATE_REQ_MESSAGE 0x0028
156
157 #define REGISTER_ACK_MESSAGE 0x0081
158 typedef struct register_ack_message {
159         int keepAlive;
160         char dateTemplate[6];
161         char res[2];
162         int secondaryKeepAlive;
163         char res2[4];
164 } register_ack_message;
165
166 #define START_TONE_MESSAGE 0x0082
167 typedef struct start_tone_message {
168         int tone;
169 } start_tone_message;
170
171 #define STOP_TONE_MESSAGE 0x0083
172
173 #define SET_RINGER_MESSAGE 0x0085
174 typedef struct set_ringer_message {
175         int ringerMode;
176 } set_ringer_message;
177
178 #define SET_LAMP_MESSAGE 0x0086
179 typedef struct set_lamp_message {
180         int stimulus;
181         int stimulusInstance;
182         int deviceStimulus;
183 } set_lamp_message;
184
185 #define SET_SPEAKER_MESSAGE 0x0088 
186 typedef struct set_speaker_message {
187         int mode;
188 } set_speaker_message;
189
190 #define START_MEDIA_TRANSMISSION_MESSAGE 0x008A
191 typedef struct media_qualifier {
192         int precedence;
193         int vad;
194         int packets;
195         int bitRate;
196 } media_qualifier;
197
198 typedef struct start_media_transmission_message {
199         int conferenceId;
200         int passThruPartyId;
201         char remoteIp[4];
202         int remotePort;
203         int packetSize;
204         int payloadType;
205         media_qualifier qualifier;
206 } start_media_transmission_message;
207
208 #define STOP_MEDIA_TRANSMISSION_MESSAGE 0x008B
209 typedef struct stop_media_transmission_message {
210         int conferenceId;
211         int passThruPartyId;
212 } stop_media_transmission_message;
213
214 #define CALL_INFO_MESSAGE 0x008F
215 typedef struct call_info_message {
216         char callingPartyName[40];
217         char callingParty[24];
218         char calledPartyName[40];
219         char calledParty[24];
220         int  instance;
221         int  reference;
222         int  type;
223         char originalCalledPartyName[40];
224         char originalCalledParty[24];
225 } call_info_message;
226
227 #define SPEED_DIAL_STAT_RES_MESSAGE 0x0091
228 typedef struct speed_dial_stat_res_message {
229         int speedDialNumber;
230         char speedDialDirNumber[24];
231         char speedDialDisplayName[40];
232 } speed_dial_stat_res_message;
233
234 #define LINE_STAT_RES_MESSAGE 0x0092
235 typedef struct line_stat_res_message {
236         int  linenumber;
237         char lineDirNumber[24];
238         char lineDisplayName[42];
239         int  space;
240 } line_stat_res_message;
241
242 #define DEFINETIMEDATE_MESSAGE 0x0094
243 typedef struct definetimedate_message {
244         int year;       /* since 1900 */
245         int month;
246         int dayofweek;  /* monday = 1 */
247         int day;
248         int hour;
249         int minute;
250         int seconds;
251         int milliseconds;
252         int timestamp;
253 } definetimedate_message;
254  
255 #define DISPLAYTEXT_MESSAGE 0x0099
256 typedef struct displaytext_message {
257         char text[40];
258 } displaytext_message;
259
260 #define REGISTER_REJ_MESSAGE 0x009D
261 typedef struct register_rej_message {
262         char errMsg[33];
263 } register_rej_message;
264
265 #define CAPABILITIES_REQ_MESSAGE 0x009B
266
267 #define SERVER_RES_MESSAGE 0x009E
268 typedef struct server_identifier {
269         char serverName[48];
270 } server_identifier;
271
272 typedef struct server_res_message {
273         server_identifier server[5];
274         int serverListenPort[5];
275         int serverIpAddr[5];
276 } server_res_message;
277
278 #define BUTTON_TEMPLATE_RES_MESSAGE 0x0097
279 static const char *button_definition_hack = {
280         "\x01\x09\x01\x02\x02\x02\x03\x02\x04\x02\x05\x02\x06\x02\x07\x02"
281         "\x08\x02\x09\x02\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff"
282         "\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff"
283         "\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff"
284         "\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff"
285         "\x00\xff\x00\xff"
286 };
287
288 typedef struct buttondefinition {
289         UINT8 instanceNumber;
290         UINT8 buttonDefinition;
291 } button_definition;
292
293 typedef struct button_template_res_message {
294         UINT32 buttonOffset;
295         UINT32 buttonCount;
296         UINT32 totalButtonCount;
297         button_definition definition[42];
298 } button_template_res_message;
299
300 #define VERSION_RES_MESSAGE 0x0098
301 typedef struct version_res_message {
302         char version[16];
303 } version_res_message;
304
305 #define KEEP_ALIVE_ACK_MESSAGE 0x0100
306
307 #define OPEN_RECIEVE_CHANNEL_MESSAGE 0x0105
308 typedef struct open_recieve_channel_message {
309         int conferenceId;
310         int partyId;
311         int packets;
312         int capability;
313         int echo;
314         int bitrate;
315 } open_recieve_channel_message;
316
317 #define CLOSE_RECIEVE_CHANNEL_MESSAGE 0x0106
318 typedef struct close_recieve_channel_message {
319         int conferenceId;
320         int partyId;
321 } close_recieve_channel_message;
322
323 #define SOFT_KEY_TEMPLATE_RES_MESSAGE 0x0108
324 static const char *soft_key_template_hack = {
325         "\x52\x65\x64\x69\x61\x6c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
326         "\x01\x00\x00\x00\x4e\x65\x77\x43\x61\x6c\6c\\x00\x00\x00\x00\x00"
327         "\x00\x00\x00\x00\x02\x00\x00\x00\x48\x6f\x6c\x64\x00\x00\x00\x00"
328         "\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x54\x72\x6e\x73"
329         "\x66\x65\x72\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00"
330         "\x43\x46\x77\x64\x41\x6c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05"
331         "\x00\x00\x00\x43\x46\x77\x64\x20\x42\x75\x73\x79\x00\x00\x00\x00"
332         "\x00\x00\x00\x06\x00\x00\x00\x43\x46\x77\x64\x4e\x6f\x41\x6e\x73"
333         "\x77\x65\x72\x00\x00\x00\x00\x07\x00\x00\x00\x3c\x3c\x00\x00\x00"
334         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x45"
335         "\x6e\x64\x43\x61\x6c\x6c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x09"
336         "\x00\x00\x00\x52\x65\x73\x75\x6d\x65\x00\x00\x00\x00\x00\x00\x00"
337         "\x00\x00\x0a\x00\x00\x00\x41\x6e\x73\x77\x65\x72\x00\x00\x00\x00"
338         "\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00\x49\x6e\x66\x6f\x00\x00"
339         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x43\x6f"
340         "\x6e\x66\x72\x6e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0d\x00\x00"
341         "\x00\x50\x61\x72\x6b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
342         "\x00\x0e\x00\x00\x00\x4a\x6f\x69\x6e\x00\x00\x00\x00\x00\x00\x00"
343         "\x00\x00\x00\x00\x0f\x00\x00\x00\x4d\x65\x65\x74\x4d\x65\x00\x00"
344         "\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00\x50\x69\x63\x6b"
345         "\x55\x70\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11\x00\x00\x00"
346         "\x47\x50\x69\x63\x6b\x55\x70\x00\x00\x00\x00\x00\x00\x00\x00\x00"
347         "\x12\x00\x00\x00\x52\x6d\x4c\x73\x43\x00\x00\x00\x00\x00\x00\x00"
348         "\x00\x00\x00\x13\x00\x00\x00\x42\x61\x72\x67\x65\x00\x00\x00\x00"
349         "\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x42\x61\x72\x67\x65"
350         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x15\x00\x00\x00"
351 };
352
353 typedef struct soft_key_template_definition {
354         char softKeyLabel[16];
355         int softKeyEvent;
356 } soft_key_template_definition;
357
358 typedef struct soft_key_template {
359         int softKeyOffset;
360         int softKeyCount;
361         int totalSoftKeyCount;
362     soft_key_template_definition softKeyTemplateDefinition[32];
363 } soft_key_template;
364
365 #define SOFT_KEY_SET_RES_MESSAGE 0x0109
366 static const char *soft_key_set_hack = {
367         "\x01\x02\x05\x03\x09\x0a\x0b\x10\x11\x12\x04\x0e\x0d\x00\x00\x00"
368         "\x2d\x01\x2e\x01\x31\x01\x2f\x01\x35\x01\x36\x01\x37\x01\x3c\x01"
369         "\x3d\x01\x3e\x01\x30\x01\x3a\x01\x39\x01\x00\x00\x00\x00\x00\x00"
370         "\x03\x09\x04\x0e\x0d\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
371         "\x2f\x01\x35\x01\x30\x01\x3a\x01\x39\x01\x3f\x01\x00\x00\x00\x00"
372         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
373         "\x0a\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
374         "\x36\x01\x2e\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
375         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
376         "\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
377         "\x37\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
378         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
379         "\x01\x09\x05\x10\x11\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
380         "\x2d\x01\x35\x01\x31\x01\x3c\x01\x3d\x01\x3e\x01\x00\x00\x00\x00"
381         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
382         "\x00\x09\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
383         "\x00\x00\x35\x01\x30\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
384         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
385         "\x08\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
386         "\x34\x01\x35\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
387         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
388         "\x00\x09\x0d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
389         "\x00\x00\x35\x01\x39\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
390         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
391         "\x00\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
392         "\x00\x00\x35\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
393         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
394         "\x01\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
395         "\x2d\x01\x35\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
396         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
397         "\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
398         "\x41\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
399         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
400 };
401
402 typedef struct soft_key_set_definition {
403         UINT8  softKeyTemplateIndex[16];
404         UINT16 softKeyInfoIndex[16];
405 } soft_key_set_definition;
406
407 typedef struct soft_key_sets {
408         UINT32 softKeySetOffset;
409         UINT32 softKeySetCount;
410         UINT32 totalSoftKeySetCount;
411         soft_key_set_definition softKeySetDefinition[16];
412         UINT32 res;
413 } soft_key_sets;
414
415 #define SELECT_SOFT_KEYS_MESSAGE 0x0110
416 typedef struct select_soft_keys_message {
417         int instance;
418         int reference;
419         int softKeySetIndex;
420         int validKeyMask;
421 } select_soft_keys_message;
422
423 #define CALL_STATE_MESSAGE 0x0111
424 typedef struct call_state_message {
425         int callState;
426         int lineInstance;
427         int callReference;
428 } call_state_message;
429
430 #define ACTIVATE_CALL_PLANE_MESSAGE 0x0116
431 typedef struct activate_call_plane_message {
432         int lineInstance;
433 } activate_call_plane_message;
434
435 /* packet composition */
436 typedef struct {
437         int len;
438         int res;
439         int e;
440         union {
441                 speed_dial_stat_req_message speeddialreq;
442                 register_message reg;
443                 register_ack_message regack;
444                 register_rej_message regrej;
445                 capabilities_res_message caps;
446                 version_res_message version;
447                 button_template_res_message buttontemplate;
448                 displaytext_message displaytext;
449                 definetimedate_message definetimedate;
450                 start_tone_message starttone;
451                 speed_dial_stat_res_message speeddial;
452                 line_state_req_message line;
453                 line_stat_res_message linestat;
454                 soft_key_sets softkeysets;
455                 soft_key_template softkeytemplate;
456                 server_res_message serverres;
457                 set_lamp_message setlamp;
458                 set_ringer_message setringer;
459                 call_state_message callstate;
460                 keypad_button_message keypad;
461                 select_soft_keys_message selectsoftkey;
462                 activate_call_plane_message activatecallplane;
463                 stimulus_message stimulus;
464                 set_speaker_message setspeaker;
465                 call_info_message callinfo;
466                 start_media_transmission_message startmedia;
467                 stop_media_transmission_message stopmedia;
468                 open_recieve_channel_message openrecievechannel;
469                 open_recieve_channel_ack_message openrecievechannelack;
470                 close_recieve_channel_message closerecievechannel;
471         } data;
472 } skinny_req;
473
474 /************************************************************************************/
475 /*                            Asterisk specific globals                             */
476 /************************************************************************************/
477
478 static int skinnydebug = 1;     /* XXX for now, enable debugging default */
479
480 /* a hostname, portnumber, socket and such is usefull for VoIP protocols */
481 static struct sockaddr_in bindaddr;
482 static char ourhost[256];
483 static int ourport;
484 static struct in_addr __ourip;
485 struct ast_hostent ahp; struct hostent *hp;
486 static int skinnysock  = -1;
487 static pthread_t tcp_thread;
488 static pthread_t accept_t;
489 static char context[AST_MAX_EXTENSION] = "default";
490 static char language[MAX_LANGUAGE] = "";
491 static char musicclass[MAX_LANGUAGE] = "";
492 static char callerid[AST_MAX_EXTENSION] = "";
493 static char linelabel[AST_MAX_EXTENSION] ="";
494 static int nat = 0;
495 static unsigned int cur_callergroup = 0;
496 static unsigned int cur_pickupgroup = 0;
497 static int immediate = 0;
498 static int callwaiting = 0;
499 static int callreturn = 0;
500 static int threewaycalling = 0;
501 /* This is for flashhook transfers */
502 static int transfer = 0;
503 static int cancallforward = 0;
504 /*static int busycount = 3;*/
505 static char accountcode[20] = "";
506 static char mailbox[AST_MAX_EXTENSION];
507 static int amaflags = 0;
508 static int callnums = 1;
509
510
511 #define SUB_REAL 0
512 #define SUB_ALT  1
513 #define MAX_SUBS 2
514
515 #define SKINNY_SPEAKERON 1
516 #define SKINNY_SPEAKEROFF 2
517
518 #define SKINNY_OFFHOOK 1
519 #define SKINNY_ONHOOK 2
520 #define SKINNY_RINGOUT 3
521 #define SKINNY_RINGIN 4
522 #define SKINNY_CONNECTED 5
523 #define SKINNY_BUSY 6
524 #define SKINNY_CONGESTION 7
525 #define SKINNY_HOLD 8
526 #define SKINNY_CALLWAIT 9
527 #define SKINNY_TRANSFER 10
528 #define SKINNY_PARK 11
529 #define SKINNY_PROGRESS 12
530 #define SKINNY_INVALID 14
531
532 #define SKINNY_SILENCE 0
533 #define SKINNY_DIALTONE 33
534 #define SKINNY_BUSYTONE 35
535 #define SKINNY_ALERT 36
536 #define SKINNY_REORDER 37
537 #define SKINNY_CALLWAITTONE 45
538
539 #define SKINNY_LAMP_OFF 1
540 #define SKINNY_LAMP_ON  2
541 #define SKINNY_LAMP_WINK 3
542 #define SKINNY_LAMP_FLASH 4
543 #define SKINNY_LAMP_BLINK 5
544
545 #define SKINNY_RING_OFF 1
546 #define SKINNY_RING_INSIDE 2
547 #define SKINNY_RING_OUTSIDE 3
548 #define SKINNY_RING_FEATURE 4
549
550 #define TYPE_TRUNK              1
551 #define TYPE_LINE               2
552
553 #define STIMULUS_REDIAL 1
554 #define STIMULUS_SPEEDDIAL 2
555 #define STIMULUS_HOLD 3
556 #define STIMULUS_TRANSFER 4
557 #define STIMULUS_FORWARDALL 5
558 #define STIMULUS_FORWARDBUSY 6
559 #define STIMULUS_FORWARDNOANSWER 7
560 #define STIMULUS_DISPLAY 8
561 #define STIMULUS_LINE 9
562
563 /* Skinny rtp stream modes */
564 #define SKINNY_CX_SENDONLY 0
565 #define SKINNY_CX_RECVONLY 1
566 #define SKINNY_CX_SENDRECV 2
567 #define SKINNY_CX_CONF     3
568 #define SKINNY_CX_CONFERENCE 3
569 #define SKINNY_CX_MUTE     4
570 #define SKINNY_CX_INACTIVE 4
571
572 #if 0
573 static char *skinny_cxmodes[] = {
574     "sendonly",
575     "recvonly",
576     "sendrecv",
577     "confrnce",
578     "inactive"
579 };
580 #endif
581
582 /* driver scheduler */
583 static struct sched_context *sched;
584 static struct io_context *io;
585
586 /* usage count and locking */
587 static int usecnt = 0;
588 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
589
590 /* Protect the monitoring thread, so only one process can kill or start it, and not
591    when it's doing something critical. */
592 static ast_mutex_t monlock         = AST_MUTEX_INITIALIZER;
593 /* Protect the network socket */
594 static ast_mutex_t netlock         = AST_MUTEX_INITIALIZER;
595 /* Protect the session list */
596 static ast_mutex_t sessionlock = AST_MUTEX_INITIALIZER;
597 /* Protect the device list */
598 static ast_mutex_t devicelock = AST_MUTEX_INITIALIZER;
599
600 /* This is the thread for the monitor which checks for input on the channels
601    which are not currently in use.  */
602 static pthread_t monitor_thread = AST_PTHREADT_NULL;
603
604 /* Wait up to 16 seconds for first digit */
605 static int firstdigittimeout = 16000;
606
607 /* How long to wait for following digits */
608 static int gendigittimeout = 8000;
609
610 /* How long to wait for an extra digit, if there is an ambiguous match */
611 static int matchdigittimeout = 3000;
612
613 struct skinny_subchannel {
614         ast_mutex_t lock;
615         unsigned int callid;
616         struct ast_channel *owner;
617         struct skinny_line *parent;
618         struct ast_rtp *rtp;
619         time_t lastouttime;
620         int lastout;
621         int cxmode;
622         int nat;
623         int outgoing;
624         int alreadygone;
625         struct skinny_subchannel *next; /* for our circular linked list */
626 };
627
628 struct skinny_line {
629         ast_mutex_t lock;
630         char name[80];
631         char label[42];                                 /* Label that shows next to the line buttons */
632         struct skinny_subchannel *sub;                  /* pointer to our current connection, channel and stuff */
633         char accountcode[80];
634         char exten[AST_MAX_EXTENSION];                  /* Extention where to start */
635         char context[AST_MAX_EXTENSION];
636         char language[MAX_LANGUAGE];
637         char callerid[AST_MAX_EXTENSION];               /* Caller*ID */
638         char lastcallerid[AST_MAX_EXTENSION];           /* Last Caller*ID */
639         char call_forward[AST_MAX_EXTENSION];   
640         char mailbox[AST_MAX_EXTENSION];
641         char musicclass[MAX_LANGUAGE];
642         int curtone;                                    /* Current tone */
643         unsigned int callgroup;
644         unsigned int pickupgroup;
645         int callwaiting;
646         int transfer;
647         int threewaycalling;
648         int cancallforward;
649         int callreturn;
650         int dnd; /* How does this affect callwait?  Do we just deny a skinny_request if we're dnd? */
651         int hascallerid;
652         int hidecallerid;
653         int amaflags;
654         int type;
655         int instance;
656         int group;
657         int needdestroy;
658         int capability;
659         int nonCodecCapability;
660         int onhooktime;
661         int msgstate;           /* voicemail message state */
662         int immediate;
663         int hookstate;
664         int progress;
665         struct skinny_line *next;
666         struct skinny_device *parent;
667 };
668
669 static struct skinny_device {
670         /* A device containing one or more lines */
671         char name[80];
672         char id[16];
673         char version_id[16];    
674         int type;
675         int registered;
676         struct sockaddr_in addr;
677         struct in_addr ourip;
678         struct skinny_line *lines;
679         struct ast_ha *ha;
680         struct skinnysession *session;
681         struct skinny_device *next;
682 } *devices = NULL;
683
684 static struct skinnysession {
685         pthread_t t;
686         ast_mutex_t lock;
687         struct sockaddr_in sin;
688         int fd;
689         char inbuf[SKINNY_MAX_PACKET];
690         struct skinny_device *device;
691         struct skinnysession *next;
692 } *sessions = NULL;
693
694 static skinny_req *req_alloc(size_t size)
695 {
696         skinny_req *req;
697         req = malloc(size+12);
698         if (!req) {
699                 return NULL;
700         }       
701         memset(req, 0, size+12);
702         return req;
703 }
704
705 static struct skinny_subchannel *find_subchannel_by_line(struct skinny_line *l)
706 {
707         /* XXX Need to figure out how to determine which sub we want */
708         struct skinny_subchannel *sub = l->sub;
709         return sub;
710 }
711
712 static struct skinny_subchannel *find_subchannel_by_name(char *dest)
713 {
714         struct skinny_line *l;
715         struct skinny_device *d;
716         char line[256];
717         char *at;
718         char *device;
719         
720         strncpy(line, dest, sizeof(line) - 1);
721         at = strchr(line, '@');
722         if (!at) {
723                 ast_log(LOG_NOTICE, "Device '%s' has no @ (at) sign!\n", dest);
724                 return NULL;
725         }
726         *at = '\0';
727         at++;
728         device = at;
729         ast_mutex_lock(&devicelock);
730         d = devices;
731         while(d) {
732                 if (!strcasecmp(d->name, device)) {
733                         if (skinnydebug) {
734                                 ast_verbose("Found device: %s\n", d->name);
735                         }
736                         /* Found the device */
737                         l = d->lines;
738                         while (l) {
739                                 /* Search for the right line */
740                                 if (!strcasecmp(l->name, line)) {
741                                         ast_mutex_unlock(&devicelock);
742                                         return l->sub;
743                                 }
744                                 l = l->next;
745                         }
746                 }
747                 d = d->next;
748         }
749         /* Device not found*/
750         ast_mutex_unlock(&devicelock);
751         return NULL;
752 }
753
754 static int transmit_response(struct skinnysession *s, skinny_req *req)
755 {
756         int res = 0;
757         ast_mutex_lock(&s->lock);
758 #if 0
759         ast_verbose("writing packet type %d (%d bytes) to socket %d\n", req->e, req->len+8, s->fd);
760 #endif
761         res = write(s->fd, req, req->len+8);
762         if (res != req->len+8) {
763                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, req->len+8, strerror(errno));
764         }
765         ast_mutex_unlock(&s->lock);
766         return 1;
767 }
768
769 /* XXX Do this right*/
770 static int convert_cap(int capability)
771 {
772         return 4; // ulaw (this is not the same as asterisk's '4'  :) 
773
774 }
775
776 static void transmit_speaker_mode(struct skinnysession *s, int mode)
777 {
778         skinny_req *req;
779
780         req = req_alloc(sizeof(struct set_speaker_message));
781         if (!req) {
782                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
783                 return;
784         }
785         req->len = sizeof(set_speaker_message)+4;
786         req->e = SET_SPEAKER_MESSAGE;
787         req->data.setspeaker.mode = mode; 
788         transmit_response(s, req);
789 }
790
791 static void transmit_callstate(struct skinnysession *s, int instance, int state, unsigned callid)
792
793         skinny_req *req;
794         int memsize = sizeof(struct call_state_message);
795
796         req = req_alloc(memsize);
797         if (!req) {
798                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
799                 return;
800         }       
801         if (state == SKINNY_ONHOOK) {
802                 transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
803         }
804         req->len = sizeof(call_state_message)+4;
805         req->e = CALL_STATE_MESSAGE;
806         req->data.callstate.callState = state;
807         req->data.callstate.lineInstance = instance;
808         req->data.callstate.callReference = callid;
809         transmit_response(s, req);
810         if (state == SKINNY_OFFHOOK) {
811                 memset(req, 0, memsize);
812                 req->len = sizeof(activate_call_plane_message)+4;
813                 req->e = ACTIVATE_CALL_PLANE_MESSAGE;
814                 req->data.activatecallplane.lineInstance = instance;
815                 transmit_response(s, req);
816         } else if (state == SKINNY_ONHOOK) {
817                 memset(req, 0, memsize);
818                 req->len = sizeof(activate_call_plane_message)+4;
819                 req->e = ACTIVATE_CALL_PLANE_MESSAGE;
820                 req->data.activatecallplane.lineInstance = 0;
821                 transmit_response(s, req);
822                 memset(req, 0, memsize);
823                 req->len = sizeof(close_recieve_channel_message)+4;
824                 req->e = CLOSE_RECIEVE_CHANNEL_MESSAGE;
825                 req->data.closerecievechannel.conferenceId = 0;
826                 req->data.closerecievechannel.partyId = 0;
827                 transmit_response(s, req);
828                 memset(req, 0, memsize);
829                 req->len = sizeof(stop_media_transmission_message)+4;
830                 req->e = STOP_MEDIA_TRANSMISSION_MESSAGE;
831                 req->data.stopmedia.conferenceId = 0;   
832                 req->data.stopmedia.passThruPartyId = 0;
833                 transmit_response(s, req);      
834         }
835 }       
836
837 static void transmit_connect(struct skinnysession *s)
838 {
839         skinny_req *req;
840         struct skinny_line *l = s->device->lines;
841
842         req = req_alloc(sizeof(struct open_recieve_channel_message));
843         if (!req) {
844                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
845                 return;
846         }       
847         req->len = sizeof(struct call_info_message);
848         req->e = OPEN_RECIEVE_CHANNEL_MESSAGE;
849         req->data.openrecievechannel.conferenceId = 0;
850         req->data.openrecievechannel.partyId = 0;
851         req->data.openrecievechannel.packets = 20;
852         req->data.openrecievechannel.capability = convert_cap(l->capability); 
853         req->data.openrecievechannel.echo = 0;
854         req->data.openrecievechannel.bitrate = 0;
855         transmit_response(s, req);
856 }       
857
858 static void transmit_tone(struct skinnysession *s, int tone)
859 {
860         skinny_req *req;
861
862         if (tone > 0)
863                 req = req_alloc(sizeof(struct start_tone_message));
864         else 
865                 req = req_alloc(4);
866         if (!req) {
867                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
868                 return;
869         }       
870         if (tone > 0) {
871                 req->len = sizeof(start_tone_message)+4;
872                 req->e = START_TONE_MESSAGE;
873                 req->data.starttone.tone = tone; // da tone
874         } else {
875                 req->len = 4;
876                 req->e = STOP_TONE_MESSAGE;
877         }
878         transmit_response(s, req);
879 }
880
881 #if 0
882 static void transmit_selectsoftkeys(struct skinnysession *s, int instance, int callid, int softkey)
883 {
884         skinny_req *req;
885         int memsize = sizeof(struct select_soft_keys_message);
886
887         req = req_alloc(memsize);
888         if (!req) {
889                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
890                 return;
891         }       
892         memset(req, 0, memsize);
893         req->len = sizeof(select_soft_keys_message)+4;
894         req->e = SELECT_SOFT_KEYS_MESSAGE;
895         req->data.selectsoftkey.instance = instance;
896         req->data.selectsoftkey.reference = callid;
897         req->data.selectsoftkey.softKeySetIndex = softkey;
898         transmit_response(s, req);
899 }
900 #endif
901
902 static void transmit_lamp_indication(struct skinnysession *s, int instance, int indication)
903 {
904         skinny_req *req;
905
906         req = req_alloc(sizeof(struct set_lamp_message));
907         if (!req) {
908                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
909                 return;
910         }       
911         req->len = sizeof(set_lamp_message)+4;
912         req->e = SET_LAMP_MESSAGE;
913         req->data.setlamp.stimulus = 0x9;  // magic number
914         req->data.setlamp.stimulusInstance = instance;
915         req->data.setlamp.deviceStimulus = indication;
916         transmit_response(s, req);
917 }
918
919 static void transmit_ringer_mode(struct skinnysession *s, int mode)
920 {
921         skinny_req *req;
922
923         req = req_alloc(sizeof(struct set_ringer_message));
924         if (!req) {
925                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
926                 return;
927         }
928         req->len = sizeof(set_ringer_message)+4;
929         req->e = SET_RINGER_MESSAGE; 
930         req->data.setringer.ringerMode = mode; 
931         transmit_response(s, req);
932 }
933
934 /* I do not believe skinny can deal with video. 
935    Anyone know differently? */
936 static struct ast_rtp *skinny_get_vrtp_peer(struct ast_channel *chan)
937 {
938         return NULL;
939 }
940
941 static struct ast_rtp *skinny_get_rtp_peer(struct ast_channel *chan)
942 {
943         struct skinny_subchannel *sub;
944         sub = chan->pvt->pvt;
945         if (sub && sub->rtp)
946                 return sub->rtp;
947         return NULL;
948 }
949
950 static int skinny_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp)
951 {
952         struct skinny_subchannel *sub;
953         sub = chan->pvt->pvt;
954         if (sub) {
955                 /* transmit_modify_with_sdp(sub, rtp); @@FIXME@@ if needed */
956                 return 0;
957         }
958         return -1;
959 }
960
961 static struct ast_rtp_protocol skinny_rtp = {
962         get_rtp_info: skinny_get_rtp_peer,
963         get_vrtp_info: skinny_get_vrtp_peer,
964         set_rtp_peer: skinny_set_rtp_peer,
965 };
966
967 static int skinny_do_debug(int fd, int argc, char *argv[])
968 {
969         if (argc != 2)
970                 return RESULT_SHOWUSAGE;
971         skinnydebug = 1;
972         ast_cli(fd, "Skinny Debugging Enabled\n");
973         return RESULT_SUCCESS;
974 }
975
976 static int skinny_no_debug(int fd, int argc, char *argv[])
977 {
978         if (argc != 3)
979                 return RESULT_SHOWUSAGE;
980         skinnydebug = 0;
981         ast_cli(fd, "Skinny Debugging Disabled\n");
982         return RESULT_SUCCESS;
983 }
984
985 static int skinny_show_lines(int fd, int argc, char *argv[])
986 {
987         struct skinny_device  *d;
988         struct skinny_line *l;
989         int haslines = 0;
990         if (argc != 3) 
991                 return RESULT_SHOWUSAGE;
992         ast_mutex_lock(&devicelock);
993         d = devices;
994         while(d) {
995                 l = d->lines;
996                 ast_cli(fd, "Device '%s' at %s\n", d->name, inet_ntoa(d->addr.sin_addr));
997                 while(l) {
998                         ast_cli(fd, "   -- '%s@%s in '%s' is %s\n", l->name, d->name, l->context, l->sub->owner ? "active" : "idle");
999                         haslines = 1;
1000                         l = l->next;
1001                 }
1002                 if (!haslines) {
1003                         ast_cli(fd, "   << No Lines Defined >>     ");
1004                 }
1005                 d = d->next;
1006         }
1007         ast_mutex_unlock(&devicelock);
1008         return RESULT_SUCCESS;
1009 }
1010
1011 static char show_lines_usage[] = 
1012 "Usage: skinny show lines\n"
1013 "       Lists all lines known to the Skinny subsystem.\n";
1014
1015 static char debug_usage[] = 
1016 "Usage: skinny debug\n"
1017 "       Enables dumping of Skinny packets for debugging purposes\n";
1018
1019 static char no_debug_usage[] = 
1020 "Usage: skinny no debug\n"
1021 "       Disables dumping of Skinny packets for debugging purposes\n";
1022
1023 static struct ast_cli_entry  cli_show_lines =
1024         { { "skinny", "show", "lines", NULL }, skinny_show_lines, "Show defined Skinny lines per device", show_lines_usage };
1025 static struct ast_cli_entry  cli_debug =
1026         { { "skinny", "debug", NULL }, skinny_do_debug, "Enable Skinny debugging", debug_usage };
1027 static struct ast_cli_entry  cli_no_debug =
1028         { { "skinny", "no", "debug", NULL }, skinny_no_debug, "Disable Skinny debugging", no_debug_usage };
1029
1030 static struct skinny_device *build_device(char *cat, struct ast_variable *v)
1031 {
1032         struct skinny_device *d;
1033         struct skinny_line *l;
1034         struct skinny_subchannel *sub;
1035         int i=0, y=0;
1036         
1037         d = malloc(sizeof(struct skinny_device));
1038         if (d) {
1039                 memset(d, 0, sizeof(struct skinny_device));
1040                 strncpy(d->name, cat, sizeof(d->name) - 1);
1041                 while(v) {
1042                         if (!strcasecmp(v->name, "host")) {
1043                                         if (ast_get_ip(&d->addr, v->value)) {
1044                                                 free(d);
1045                                                 return NULL;
1046                                         }                               
1047                         } else if (!strcasecmp(v->name, "port")) {
1048                                 d->addr.sin_port = htons(atoi(v->value));
1049                         } else if (!strcasecmp(v->name, "device")) {
1050                         strncpy(d->id, v->value, sizeof(d->id)-1);
1051                         } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
1052                                 d->ha = ast_append_ha(v->name, v->value, d->ha);
1053                         } else if (!strcasecmp(v->name, "context")) {
1054                                 strncpy(context, v->value, sizeof(context) - 1);
1055                         } else if (!strcasecmp(v->name, "version")) {
1056                                 strncpy(d->version_id, v->value, sizeof(d->version_id) -1); 
1057                         } else if (!strcasecmp(v->name, "nat")) {
1058                                 nat = ast_true(v->value);
1059                         } else if (!strcasecmp(v->name, "callerid")) {
1060                                 if (!strcasecmp(v->value, "asreceived")) {
1061                                         strcpy(callerid, "");
1062                                 } else {
1063                                         strncpy(callerid, v->value, sizeof(callerid) - 1);
1064                                 }
1065                         } else if (!strcasecmp(v->name, "language")) {
1066                                 strncpy(language, v->value, sizeof(language)-1);
1067                         } else if (!strcasecmp(v->name, "accountcode")) {
1068                                 strncpy(accountcode, v->value, sizeof(accountcode)-1);
1069                         } else if (!strcasecmp(v->name, "amaflags")) {
1070                                 y = ast_cdr_amaflags2int(v->value);
1071                                 if (y < 0) {
1072                                         ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
1073                                 } else {
1074                                 amaflags = y;
1075                                 }
1076                         } else if (!strcasecmp(v->name, "musiconhold")) {
1077                                 strncpy(musicclass, v->value, sizeof(musicclass)-1);
1078                         } else if (!strcasecmp(v->name, "callgroup")) {
1079                                 cur_callergroup = ast_get_group(v->value);
1080                         } else if (!strcasecmp(v->name, "pickupgroup")) {
1081                                 cur_pickupgroup = ast_get_group(v->value);
1082                         } else if (!strcasecmp(v->name, "immediate")) {
1083                                 immediate = ast_true(v->value);
1084                         } else if (!strcasecmp(v->name, "cancallforward")) {
1085                                 cancallforward = ast_true(v->value);
1086                         } else if (!strcasecmp(v->name, "mailbox")) {
1087                                 strncpy(mailbox, v->value, sizeof(mailbox) -1);
1088                         } else if (!strcasecmp(v->name, "callreturn")) {
1089                                 callreturn = ast_true(v->value);
1090                         } else if (!strcasecmp(v->name, "immediate")) {
1091                                 immediate = ast_true(v->value);
1092                         } else if (!strcasecmp(v->name, "callwaiting")) {
1093                                 callwaiting = ast_true(v->value);
1094                         } else if (!strcasecmp(v->name, "transfer")) {
1095                                 transfer = ast_true(v->value);
1096                         } else if (!strcasecmp(v->name, "threewaycalling")) {
1097                                 threewaycalling = ast_true(v->value);
1098                         } else if (!strcasecmp(v->name, "linelabel")) {
1099                                 strncpy(linelabel, v->value, sizeof(linelabel)-1);
1100                         } else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
1101                                 l = malloc(sizeof(struct skinny_line));;
1102                                 if (l) {
1103                                         memset(l, 0, sizeof(struct skinny_line));
1104                                         strncpy(l->name, v->value, sizeof(l->name) - 1);
1105                                         
1106                                         /* XXX Should we check for uniqueness?? XXX */
1107                                         
1108                                         strncpy(l->context, context, sizeof(l->context) - 1);
1109                                         strncpy(l->callerid, callerid, sizeof(l->callerid) - 1);
1110                                         strncpy(l->label, linelabel, sizeof(l->label) - 1);
1111                                         strncpy(l->language, language, sizeof(l->language) - 1);
1112                                         strncpy(l->musicclass, musicclass, sizeof(l->musicclass)-1);
1113                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1114                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1115                                         if (strlen(mailbox)) {
1116                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting mailbox '%s' on %s@%s\n", mailbox, d->name, l->name);
1117                                         }
1118                                 
1119                                         l->msgstate = -1;
1120                                         l->capability = capability;
1121                                         l->parent = d;
1122                                         if (!strcasecmp(v->name, "trunk")) {
1123                                                 l->type = TYPE_TRUNK;
1124                                         } else {
1125                                                 l->type = TYPE_LINE;
1126                                         }
1127                                         l->immediate = immediate;
1128                                         l->callgroup = cur_callergroup;
1129                                         l->pickupgroup = cur_pickupgroup;
1130                                         l->callreturn = callreturn;
1131                                         l->cancallforward = cancallforward;
1132                                         l->callwaiting = callwaiting;
1133                                         l->transfer = transfer; 
1134                                         l->threewaycalling = threewaycalling;
1135                                         l->onhooktime = time(NULL);
1136                                         l->instance = 1;
1137                                         /* ASSUME we're onhook at this point*/
1138                                         l->hookstate = SKINNY_ONHOOK;
1139
1140                                         for (i = 0; i < MAX_SUBS; i++) {
1141                                                 sub = malloc(sizeof(struct skinny_subchannel));
1142                                                 if (sub) {
1143                                                         ast_verbose(VERBOSE_PREFIX_3 "Allocating Skinny subchannel '%d' on %s@%s\n", i, l->name, d->name);
1144                                                         memset(sub, 0, sizeof(struct skinny_subchannel));
1145                                                         sub->parent = l;
1146                                                         /* Make a call*ID */
1147                                                         sub->callid = callnums;
1148                                                         callnums++;
1149                                                         sub->cxmode = SKINNY_CX_INACTIVE;
1150                                                         sub->nat = nat;
1151                                                         sub->next = l->sub;
1152                                                         l->sub = sub;
1153                                                 } else {
1154                                                         /* XXX Should find a way to clean up our memory */
1155                                                         ast_log(LOG_WARNING, "Out of memory allocating subchannel");
1156                                                         return NULL;
1157                                                 }
1158                                         }
1159                                         l->next = d->lines;
1160                                         d->lines = l;                   
1161                                 } else {
1162                                         /* XXX Should find a way to clean up our memory */
1163                                         ast_log(LOG_WARNING, "Out of memory allocating line");
1164                                         return NULL;
1165                                 }
1166                         } else {
1167                                 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
1168                         }
1169                         v = v->next;
1170                 }
1171         
1172                 if (!d->lines) {
1173                         ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
1174                         return NULL;
1175                 }
1176
1177                 if (d->addr.sin_addr.s_addr && !ntohs(d->addr.sin_port))
1178                         d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
1179                 if (d->addr.sin_addr.s_addr) {
1180                         if (ast_ouraddrfor(&d->addr.sin_addr, &d->ourip)) {
1181                                 memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1182                         }
1183                 } else {
1184                         memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1185                 }
1186         }
1187         return d;
1188 }
1189
1190 static int has_voicemail(struct skinny_line *l)
1191 {
1192         return ast_app_has_voicemail(l->mailbox);
1193 }
1194
1195 static int skinny_register(skinny_req *req, struct skinnysession *s)
1196 {
1197         struct skinny_device *d;
1198         
1199         ast_mutex_lock(&devicelock);
1200         d = devices;
1201         while (d) {
1202                 if (!strcasecmp(req->data.reg.name, d->id)) {
1203                         /* XXX Deal with IP authentication */
1204                         s->device = d;
1205                         d->type = req->data.reg.type;
1206                         if (!strlen(d->version_id)) {
1207                                 strncpy(d->version_id, version_id, sizeof(d->version_id));
1208                         }
1209                         d->registered = 1;
1210                         d->session = s;
1211                         break;
1212                 }
1213                 d = d->next;
1214         }
1215         ast_mutex_unlock(&devicelock);
1216
1217         if (!d)
1218                 return 0;
1219         
1220         return 1;
1221 }               
1222
1223 static void start_rtp(struct skinny_subchannel *sub)
1224 {
1225                 ast_mutex_lock(&sub->lock);
1226                 /* Allocate the RTP */
1227                 sub->rtp = ast_rtp_new(sched, io, 1, 0);
1228                 if (sub->rtp && sub->owner)
1229                         sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
1230                 if (sub->rtp)
1231                         ast_rtp_setnat(sub->rtp, sub->nat);
1232                 
1233                 /* Create the RTP connections  */
1234                 transmit_connect(sub->parent->parent->session);
1235                 ast_mutex_unlock(&sub->lock);
1236 }
1237
1238
1239 static void *skinny_ss(void *data)
1240 {
1241         struct ast_channel *chan = data;
1242         struct skinny_subchannel *sub = chan->pvt->pvt;
1243         struct skinny_line *l = sub->parent;
1244         struct skinnysession *s = l->parent->session;
1245         char exten[AST_MAX_EXTENSION] = "";
1246         int len = 0;
1247         int timeout = firstdigittimeout;
1248         int res;
1249         int getforward=0;
1250     
1251         if (option_verbose > 2) 
1252                 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s@%s'\n", l->name, l->parent->name);
1253
1254         while(len < AST_MAX_EXTENSION-1) {
1255         res = ast_waitfordigit(chan, timeout);
1256         timeout = 0;
1257         if (res < 0) {
1258                         if (skinnydebug)
1259                                 ast_verbose("Skinny(%s@%s): waitfordigit returned < 0\n", l->name, l->parent->name);
1260                 ast_indicate(chan, -1);
1261                         ast_hangup(chan);
1262             return NULL;
1263         } else if (res)  {
1264             exten[len++]=res;
1265             exten[len] = '\0';
1266         }
1267         if (!ast_ignore_pattern(chan->context, exten)) {
1268                         transmit_tone(s, SKINNY_SILENCE);
1269         } 
1270         if (ast_exists_extension(chan, chan->context, exten, 1, l->callerid)) {
1271             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, l->callerid)) {
1272                 if (getforward) {
1273                     /* Record this as the forwarding extension */
1274                     strncpy(l->call_forward, exten, sizeof(l->call_forward)); 
1275                     if (option_verbose > 2) {
1276                         ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n", 
1277                                 l->call_forward, chan->name);
1278                     }
1279                     transmit_tone(s, SKINNY_DIALTONE); 
1280                     if (res) {
1281                             break;
1282                     }
1283                     usleep(500000);
1284                     ast_indicate(chan, -1);
1285                     sleep(1);
1286                     memset(exten, 0, sizeof(exten));
1287                     transmit_tone(s, SKINNY_DIALTONE); 
1288                     len = 0;
1289                     getforward = 0;
1290                 } else  {
1291                     strncpy(chan->exten, exten, sizeof(chan->exten)-1);
1292                     if (strlen(l->callerid)) {
1293                         if (!l->hidecallerid)
1294                             chan->callerid = strdup(l->callerid);
1295                         chan->ani = strdup(l->callerid);
1296                     }
1297                     ast_setstate(chan, AST_STATE_RING);
1298                     res = ast_pbx_run(chan);
1299                     if (res) {
1300                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
1301                                                 transmit_tone(s, SKINNY_REORDER); 
1302                     }
1303                     return NULL;
1304                 }
1305             } else {
1306                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
1307                    so just set the timeout to matchdigittimeout and wait some more */
1308                 timeout = matchdigittimeout;
1309             }
1310         } else if (res == 0) {
1311             ast_log(LOG_DEBUG, "Not enough digits (and no ambiguous match)...\n");
1312                 transmit_tone(s, SKINNY_REORDER); 
1313             ast_hangup(chan);
1314             return NULL;
1315         } else if (l->callwaiting && !strcmp(exten, "*70")) {
1316             if (option_verbose > 2) {
1317                 ast_verbose(VERBOSE_PREFIX_3 "Disabling call waiting on %s\n", chan->name);
1318             }
1319             /* Disable call waiting if enabled */
1320             l->callwaiting = 0;
1321             transmit_tone(s, SKINNY_DIALTONE);
1322                         len = 0;
1323             memset(exten, 0, sizeof(exten));
1324             timeout = firstdigittimeout;
1325                 
1326         } else if (!strcmp(exten,ast_pickup_ext())) {
1327             /* Scan all channels and see if any there
1328              * ringing channqels with that have call groups
1329              * that equal this channels pickup group  
1330              */
1331             if (ast_pickup_call(chan)) {
1332                 ast_log(LOG_WARNING, "No call pickup possible...\n");
1333                                 transmit_tone(s, SKINNY_REORDER);
1334             }
1335             ast_hangup(chan);
1336             return NULL;
1337             
1338         } else if (!l->hidecallerid && !strcmp(exten, "*67")) {
1339             if (option_verbose > 2) {
1340                 ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
1341             }
1342             /* Disable Caller*ID if enabled */
1343             l->hidecallerid = 1;
1344             if (chan->callerid)
1345                 free(chan->callerid);
1346             chan->callerid = NULL;
1347             transmit_tone(s, SKINNY_DIALTONE);
1348             len = 0;
1349             memset(exten, 0, sizeof(exten));
1350             timeout = firstdigittimeout;
1351         } else if (l->callreturn && !strcmp(exten, "*69")) {
1352             res = 0;
1353             if (strlen(l->lastcallerid)) {
1354                 res = ast_say_digit_str(chan, l->lastcallerid, "", chan->language);
1355             }
1356             if (!res) {
1357                 transmit_tone(s, SKINNY_DIALTONE);
1358                         }
1359             break;
1360         } else if (!strcmp(exten, "*78")) {
1361             /* Do not disturb */
1362             if (option_verbose > 2) {
1363                 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %s\n", chan->name);
1364             }
1365             transmit_tone(s, SKINNY_DIALTONE);
1366             l->dnd = 1;
1367             getforward = 0;
1368             memset(exten, 0, sizeof(exten));
1369             len = 0;
1370         } else if (!strcmp(exten, "*79")) {
1371             /* Do not disturb */
1372             if (option_verbose > 2) {
1373                 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %s\n", chan->name);
1374             }
1375                         transmit_tone(s, SKINNY_DIALTONE);
1376             l->dnd = 0;
1377             getforward = 0;
1378             memset(exten, 0, sizeof(exten));
1379             len = 0;
1380         } else if (l->cancallforward && !strcmp(exten, "*72")) {
1381             transmit_tone(s, SKINNY_DIALTONE);
1382             getforward = 1;
1383             memset(exten, 0, sizeof(exten));
1384             len = 0;
1385         } else if (l->cancallforward && !strcmp(exten, "*73")) {
1386             if (option_verbose > 2) {
1387                 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %s\n", chan->name);
1388             }
1389             transmit_tone(s, SKINNY_DIALTONE); 
1390             memset(l->call_forward, 0, sizeof(l->call_forward));
1391             getforward = 0;
1392             memset(exten, 0, sizeof(exten));
1393             len = 0;
1394         } else if (!strcmp(exten, ast_parking_ext()) && 
1395                     sub->next->owner &&
1396                     sub->next->owner->bridge) {
1397             /* This is a three way call, the main call being a real channel, 
1398                 and we're parking the first call. */
1399             ast_masq_park_call(sub->next->owner->bridge, chan, 0, NULL);
1400             if (option_verbose > 2) {
1401                 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
1402             }
1403             break;
1404         } else if (strlen(l->lastcallerid) && !strcmp(exten, "*80")) {
1405             if (option_verbose > 2) {
1406                 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", l->lastcallerid);
1407             }
1408             res = ast_db_put("blacklist", l->lastcallerid, "1");
1409             if (!res) {
1410                 transmit_tone(s, SKINNY_DIALTONE);              
1411                 memset(exten, 0, sizeof(exten));
1412                 len = 0;
1413             }
1414         } else if (l->hidecallerid && !strcmp(exten, "*82")) {
1415             if (option_verbose > 2) {
1416                 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
1417             }
1418             /* Enable Caller*ID if enabled */
1419             l->hidecallerid = 0;
1420             if (chan->callerid)
1421                 free(chan->callerid);
1422             if (strlen(l->callerid))
1423                 chan->callerid = strdup(l->callerid);
1424             transmit_tone(s, SKINNY_DIALTONE);
1425             len = 0;
1426             memset(exten, 0, sizeof(exten));
1427             timeout = firstdigittimeout;
1428         } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->callerid) &&
1429                         ((exten[0] != '*') || (strlen(exten) > 2))) {
1430             ast_log(LOG_WARNING, "Can't match [%s] from '%s' in context %s\n", exten, chan->callerid ? chan->callerid : "<Unknown Caller>", chan->context);
1431             transmit_tone(s, SKINNY_REORDER); 
1432                         sleep(3); // hang out for 3 seconds to let congestion play
1433                         break;
1434         }
1435         if (!timeout)
1436             timeout = gendigittimeout;
1437         if (len && !ast_ignore_pattern(chan->context, exten))
1438                         ast_indicate(chan, -1);
1439     }
1440         ast_hangup(chan);
1441         return NULL;
1442 }
1443
1444
1445
1446 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
1447 {
1448         int res = 0;
1449         int tone = 0;
1450         struct skinny_line *l;
1451     struct skinny_subchannel *sub;
1452         struct skinnysession *session;
1453         
1454         sub = ast->pvt->pvt;
1455     l = sub->parent;
1456         session = l->parent->session;
1457
1458         if (!l->parent->registered) {
1459                 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
1460                 return -1;
1461         }
1462         
1463         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1464                 ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
1465                 return -1;
1466         }
1467
1468     if (skinnydebug) {
1469         ast_verbose(VERBOSE_PREFIX_3 "skinny_call(%s)\n", ast->name);
1470     }
1471
1472         if (l->dnd) {
1473                 ast_queue_control(ast, AST_CONTROL_BUSY);
1474                 return -1;
1475         }
1476    
1477         switch (l->hookstate) {
1478         case SKINNY_OFFHOOK:
1479             tone = SKINNY_CALLWAITTONE;
1480             break;
1481         case SKINNY_ONHOOK:
1482                         tone = SKINNY_ALERT;
1483                         break;
1484         default:
1485             ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
1486             break;
1487     }
1488
1489         transmit_lamp_indication(session, l->instance, SKINNY_LAMP_BLINK);
1490         transmit_ringer_mode(session, SKINNY_RING_INSIDE);
1491         transmit_tone(session, tone);
1492         transmit_callstate(session, l->instance, SKINNY_RINGIN, sub->callid);
1493
1494 // Set the prompt
1495 // Select the active softkeys
1496
1497         ast_setstate(ast, AST_STATE_RINGING);
1498         ast_queue_control(ast, AST_CONTROL_RINGING);
1499
1500         sub->outgoing = 1;
1501 //    sub->cxmode = SKINNY_CX_RECVONLY;
1502         if (l->type == TYPE_LINE) {
1503         if (!sub->rtp) {
1504             start_rtp(sub);
1505         } else {
1506                         /* do we need to anything if there already is an RTP allocated? */
1507 //           transmit_modify_request(sub);
1508         }
1509
1510 #if 0
1511         if (sub->next->owner && sub->next->callid) {
1512             /* try to prevent a callwait from disturbing the other connection */
1513             sub->next->cxmode = SKINNY_CX_RECVONLY;
1514       //      transmit_modify_request(sub->next);
1515         }
1516                 
1517                 /* not sure what this doing */
1518                 if (sub->next->owner && sub->next->callid) {
1519             /* Put the connection back in sendrecv */
1520             sub->next->cxmode = SKINNY_CX_SENDRECV;
1521 //           transmit_modify_request(sub->next);
1522         }
1523 #endif
1524
1525         } else {
1526                 ast_log(LOG_NOTICE, "Don't know how to dial on trunks yet\n");
1527                 res = -1;
1528         }
1529         return res;
1530 }
1531
1532
1533 static int skinny_hangup(struct ast_channel *ast)
1534 {
1535     struct skinny_subchannel *sub = ast->pvt->pvt;
1536     struct skinny_line *l = sub->parent;
1537         struct skinnysession *s = l->parent->session;
1538
1539     if (skinnydebug) {
1540         ast_verbose("skinny_hangup(%s) on %s@%s\n", ast->name, l->name, l->parent->name);
1541     }
1542     if (!ast->pvt->pvt) {
1543         ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1544         return 0;
1545     }
1546
1547         if (l->parent->registered) {
1548                     if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_OFFHOOK)) {
1549                         sub->parent->hookstate = SKINNY_ONHOOK;
1550                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
1551                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
1552                 } else if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_ONHOOK)) {
1553                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
1554                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
1555                         transmit_ringer_mode(s, SKINNY_RING_OFF);
1556                         transmit_tone(s, SKINNY_SILENCE);
1557                 } 
1558         }
1559     ast_mutex_lock(&sub->lock);
1560     sub->owner = NULL;
1561     ast->pvt->pvt = NULL;
1562     sub->alreadygone = 0;
1563     sub->outgoing = 0;
1564     sub->cxmode = SKINNY_CX_INACTIVE;
1565     if (sub->rtp) {
1566         ast_rtp_destroy(sub->rtp);
1567         sub->rtp = NULL;
1568     }
1569     ast_mutex_unlock(&sub->lock);
1570     return 0;
1571 }
1572
1573 static int skinny_answer(struct ast_channel *ast)
1574 {
1575         int res = 0;
1576         struct skinny_subchannel *sub = ast->pvt->pvt;
1577         struct skinny_line *l = sub->parent;
1578     sub->cxmode = SKINNY_CX_SENDRECV;
1579     if (!sub->rtp) {
1580                 start_rtp(sub);
1581     } else {
1582 //        transmit_modify_request(sub);
1583     }
1584     ast_verbose("skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, l->parent->name, sub->callid);
1585         if (ast->_state != AST_STATE_UP) {
1586                 ast_setstate(ast, AST_STATE_UP);
1587
1588 //              transmit_notify_request(sub, "");
1589 //              transmit_modify_request(sub);
1590         }
1591         return res;
1592 }
1593
1594 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
1595 {
1596         /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
1597         struct ast_frame *f;
1598         f = ast_rtp_read(sub->rtp);
1599         if (sub->owner) {
1600                 /* We already hold the channel lock */
1601                 if (f->frametype == AST_FRAME_VOICE) {
1602                         if (f->subclass != sub->owner->nativeformats) {
1603                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1604                                 sub->owner->nativeformats = f->subclass;
1605                                 ast_set_read_format(sub->owner, sub->owner->readformat);
1606                                 ast_set_write_format(sub->owner, sub->owner->writeformat);
1607                         }
1608                 }
1609         }
1610         return f;
1611 }
1612
1613
1614 static struct ast_frame  *skinny_read(struct ast_channel *ast)
1615 {
1616         struct ast_frame *fr;
1617         struct skinny_subchannel *sub = ast->pvt->pvt;
1618         ast_mutex_lock(&sub->lock);
1619         fr = skinny_rtp_read(sub);
1620         ast_mutex_unlock(&sub->lock);
1621         return fr;
1622 }
1623
1624 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
1625 {
1626         struct skinny_subchannel *sub = ast->pvt->pvt;
1627         int res = 0;
1628         if (frame->frametype != AST_FRAME_VOICE) {
1629                 if (frame->frametype == AST_FRAME_IMAGE)
1630                         return 0;
1631                 else {
1632                         ast_log(LOG_WARNING, "Can't send %d type frames with SKINNY write\n", frame->frametype);
1633                         return 0;
1634                 }
1635         } else {
1636                 if (!(frame->subclass & ast->nativeformats)) {
1637                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1638                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1639                         return -1;
1640                 }
1641         }
1642         if (sub) {
1643                 ast_mutex_lock(&sub->lock);
1644                 if (sub->rtp) {
1645                         res =  ast_rtp_write(sub->rtp, frame);
1646                 }
1647                 ast_mutex_unlock(&sub->lock);
1648         }
1649         return res;
1650 }
1651
1652 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1653 {
1654         struct skinny_subchannel *sub = newchan->pvt->pvt;
1655     ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", oldchan->name, newchan->name);
1656         if (sub->owner != oldchan) {
1657                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
1658                 return -1;
1659         }
1660         sub->owner = newchan;
1661         return 0;
1662 }
1663
1664 static int skinny_senddigit(struct ast_channel *ast, char digit)
1665 {
1666 //      struct skinny_subchannel *sub = ast->pvt->pvt;
1667 //      int tmp;
1668 //      sprintf(tmp, "%d", digit);  // not right
1669 //      transmit_tone(sub->parent->parent->session, digit);
1670         return -1;
1671 }
1672
1673 static char *control2str(int ind) {
1674     switch (ind) {
1675         case AST_CONTROL_HANGUP:
1676             return "Other end has hungup";
1677         case AST_CONTROL_RING:
1678             return "Local ring";
1679         case AST_CONTROL_RINGING:
1680             return "Remote end is ringing";
1681         case AST_CONTROL_ANSWER:
1682             return "Remote end has answered";
1683         case AST_CONTROL_BUSY:
1684             return "Remote end is busy";
1685         case AST_CONTROL_TAKEOFFHOOK:
1686             return "Make it go off hook";
1687         case AST_CONTROL_OFFHOOK:
1688             return "Line is off hook";
1689         case AST_CONTROL_CONGESTION:
1690             return "Congestion (circuits busy)";
1691         case AST_CONTROL_FLASH:
1692             return "Flash hook";
1693         case AST_CONTROL_WINK:
1694             return "Wink";
1695         case AST_CONTROL_OPTION:
1696             return "Set a low-level option";
1697         case AST_CONTROL_RADIO_KEY:
1698             return "Key Radio";
1699         case AST_CONTROL_RADIO_UNKEY:
1700             return "Un-Key Radio";
1701                 case -1:
1702                         return "Stop tone";
1703     }
1704     return "UNKNOWN";
1705 }
1706
1707
1708 static int skinny_indicate(struct ast_channel *ast, int ind)
1709 {
1710         struct skinny_subchannel *sub = ast->pvt->pvt;
1711         struct skinny_line *l = sub->parent;
1712         struct skinnysession *s = l->parent->session;
1713
1714     if (skinnydebug) {
1715         ast_verbose(VERBOSE_PREFIX_3 "Asked to indicate '%s' condition on channel %s\n", control2str(ind), ast->name);
1716     }
1717         switch(ind) {
1718         case AST_CONTROL_RINGING:
1719                 transmit_tone(s, SKINNY_ALERT);
1720                 transmit_callstate(s, l->instance, SKINNY_PROGRESS, sub->callid);
1721                 break;
1722         case AST_CONTROL_BUSY:
1723                 transmit_tone(s, SKINNY_BUSYTONE);
1724                 transmit_callstate(s, l->instance, SKINNY_BUSY, sub->callid);
1725                 break;
1726         case AST_CONTROL_CONGESTION:
1727                 transmit_tone(s, SKINNY_REORDER);
1728                 transmit_callstate(s, l->instance, SKINNY_CONGESTION, sub->callid);
1729                 break;
1730         case -1:
1731                 transmit_tone(s, SKINNY_SILENCE);
1732                 break;          
1733         default:
1734                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
1735                 return -1;
1736         }
1737         return 0;
1738 }
1739         
1740 static struct ast_channel *skinny_new(struct skinny_subchannel *sub, int state)
1741 {
1742         struct ast_channel *tmp;
1743         struct skinny_line *l = sub->parent;
1744         int fmt;
1745         l = sub->parent;
1746         tmp = ast_channel_alloc(1);
1747         if (tmp) {
1748                 tmp->nativeformats = l->capability;
1749                 if (!tmp->nativeformats)
1750                         tmp->nativeformats = capability;
1751                 fmt = ast_best_codec(tmp->nativeformats);
1752                 snprintf(tmp->name, sizeof(tmp->name), "Skinny/%s@%s-%d", l->name, l->parent->name, sub->callid);
1753                 if (sub->rtp)
1754                         tmp->fds[0] = ast_rtp_fd(sub->rtp);
1755                 tmp->type = type;
1756                 ast_setstate(tmp, state);
1757                 if (state == AST_STATE_RING)
1758                         tmp->rings = 1;
1759                 tmp->writeformat = fmt;
1760                 tmp->pvt->rawwriteformat = fmt;
1761                 tmp->readformat = fmt;
1762                 tmp->pvt->rawreadformat = fmt;
1763                 tmp->pvt->pvt = sub;
1764                 tmp->pvt->call = skinny_call;
1765                 tmp->pvt->hangup = skinny_hangup;
1766                 tmp->pvt->answer = skinny_answer;
1767                 tmp->pvt->read = skinny_read;
1768                 tmp->pvt->write = skinny_write;
1769                 tmp->pvt->indicate = skinny_indicate;
1770                 tmp->pvt->fixup = skinny_fixup;
1771                 tmp->pvt->send_digit = skinny_senddigit;
1772 //              tmp->pvt->bridge = ast_rtp_bridge;
1773                 if (strlen(l->language))
1774                         strncpy(tmp->language, l->language, sizeof(tmp->language)-1);
1775                 if (strlen(l->accountcode))
1776                         strncpy(tmp->accountcode, l->accountcode, sizeof(tmp->accountcode)-1);
1777                 if (l->amaflags)
1778                         tmp->amaflags = l->amaflags;
1779                 sub->owner = tmp;
1780                 ast_mutex_lock(&usecnt_lock);
1781                 usecnt++;
1782                 ast_mutex_unlock(&usecnt_lock);
1783                 ast_update_use_count();
1784                 tmp->callgroup = l->callgroup;
1785                 tmp->pickupgroup = l->pickupgroup;
1786                 strncpy(tmp->call_forward, l->call_forward, sizeof(tmp->call_forward));
1787                 strncpy(tmp->context, l->context, sizeof(tmp->context)-1);
1788                 strncpy(tmp->exten,l->exten, sizeof(tmp->exten)-1);
1789                 if (strlen(l->callerid))
1790                         tmp->callerid = strdup(l->callerid);
1791                 tmp->priority = 1;
1792                 if (state != AST_STATE_DOWN) {
1793                         if (ast_pbx_start(tmp)) {
1794                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1795                                 ast_hangup(tmp);
1796                                 tmp = NULL;
1797                         }
1798                 }
1799         } else {
1800                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1801     }
1802
1803         return tmp;
1804 }
1805
1806 static int handle_message(skinny_req *req, struct skinnysession *s)
1807 {
1808         struct skinny_subchannel *sub;
1809         struct ast_channel *c;
1810         struct ast_frame f = { 0, };    
1811         struct sockaddr_in sin;
1812         struct sockaddr_in us;
1813         struct skinny_line *lines;
1814         char name[16];
1815         char addr[4];
1816         char d;
1817         int digit;
1818         int res=0;
1819         int speedDialNum;
1820         int lineNumber;
1821         int stimulus;
1822         int stimulusInstance;
1823         int status;
1824         int port;
1825         int i;
1826         time_t timer;
1827         struct tm *cmtime;
1828         pthread_t t;
1829         
1830         if ( (!s->device) && (req->e != REGISTER_MESSAGE && req->e != ALARM_MESSAGE)) {
1831                 ast_log(LOG_WARNING, "Client sent message #%d without first registering.\n", req->e);
1832                 free(req);
1833                 return 0;
1834         }
1835
1836                 
1837         switch(req->e)  {
1838         case ALARM_MESSAGE:
1839                 if (skinnydebug)
1840                         ast_verbose("Recieved AlarmMessage\n");
1841                 break;
1842         case REGISTER_MESSAGE:
1843                 if (skinnydebug)
1844                         ast_verbose("Device %s is attempting to register\n", req->data.reg.name);
1845                 res = skinny_register(req, s);  
1846                 if (!res) {
1847                         ast_log(LOG_ERROR, "Rejecting Device %s: Device not found\n", req->data.reg.name);
1848                         memcpy(&name, req->data.reg.name, sizeof(req->data.reg.name));
1849                         memset(req, 0, sizeof(skinny_req));
1850                         req->len = sizeof(register_rej_message)+4;
1851                         req->e = REGISTER_REJ_MESSAGE;
1852                         sprintf(req->data.regrej.errMsg, "No Authority: %s", name);
1853                         transmit_response(s, req);
1854                         break;
1855                 }
1856                 if (option_verbose > 2) 
1857                         ast_verbose(VERBOSE_PREFIX_3 "Device '%s' successfuly registered\n", s->device->name); 
1858                 memset(req, 0, SKINNY_MAX_PACKET);
1859                 req->len = sizeof(register_ack_message)+4;
1860                 req->e = REGISTER_ACK_MESSAGE;
1861                 strcpy(req->data.regack.res, "0");
1862                 req->data.regack.keepAlive = keep_alive;
1863                 strcpy(req->data.regack.dateTemplate, date_format);     
1864                 strcpy(req->data.regack.res2, "0");
1865                 req->data.regack.secondaryKeepAlive = keep_alive;
1866                 transmit_response(s, req);
1867                 if (skinnydebug)
1868                         ast_verbose("Requesting capabilities\n");
1869                 memset(req, 0, SKINNY_MAX_PACKET);
1870                 req->len = 4;
1871                 req->e = CAPABILITIES_REQ_MESSAGE;
1872                 transmit_response(s, req);
1873                 break;
1874         case UNREGISTER_MESSAGE:
1875                 /* XXX Acutally unregister the device */
1876                 break;
1877         case IP_PORT_MESSAGE:
1878                 break;
1879         case STIMULUS_MESSAGE:
1880                 stimulus = req->data.stimulus.stimulus;
1881                 stimulusInstance = req->data.stimulus.stimulusInstance;
1882                 
1883                 switch(stimulus) {
1884                 case STIMULUS_REDIAL:
1885                         // XXX how we gonna deal with redial ?!?!
1886                         if (skinnydebug) {
1887                                 ast_verbose("Recieved Stimulus: Redial(%d)\n", stimulusInstance);
1888                         }
1889                         break;
1890                 case STIMULUS_SPEEDDIAL:
1891                         if (skinnydebug) {
1892                                 ast_verbose("Recieved Stimulus: SpeedDial(%d)\n", stimulusInstance);
1893                         }
1894                         break;
1895                 case STIMULUS_HOLD:
1896                         // Easy enough
1897                         if (skinnydebug) {
1898                                 ast_verbose("Recieved Stimulus: Hold(%d)\n", stimulusInstance);
1899                         }
1900                         break;
1901                 case STIMULUS_TRANSFER:
1902                         if (skinnydebug) {
1903                                 ast_verbose("Recieved Stimulus: Transfer(%d)\n", stimulusInstance);
1904                         }
1905                         transmit_tone(s, SKINNY_DIALTONE);
1906                                 
1907                         // figure out how to transfer
1908
1909                         break;
1910                 case STIMULUS_FORWARDALL:
1911                 case STIMULUS_FORWARDBUSY:
1912                 case STIMULUS_FORWARDNOANSWER:
1913                         // Gonna be fun
1914                         if (skinnydebug) {
1915                                 ast_verbose("Recieved Stimulus: Forward (%d)\n", stimulusInstance);
1916                         }
1917                         break;
1918                 case STIMULUS_DISPLAY:
1919                         // XXX Not sure
1920                         if (skinnydebug) {
1921                                 ast_verbose("Recieved Stimulus: Display(%d)\n", stimulusInstance);
1922                         }
1923                         break;
1924                 case STIMULUS_LINE:
1925                         if (skinnydebug) {
1926                                 ast_verbose("Recieved Stimulus: Line(%d)\n", stimulusInstance);
1927                         }               
1928                         sub = find_subchannel_by_line(s->device->lines);
1929                         transmit_speaker_mode(s, 1);  // Turn on
1930                 break;
1931                 default:
1932                         ast_verbose("RECEIVED UNKNOWN STIMULUS:  %d(%d)\n", stimulus, stimulusInstance);                        
1933                         break;
1934                 }
1935                         
1936                         
1937                 break;
1938         case VERSION_REQ_MESSAGE:
1939                 if (skinnydebug)
1940                         ast_verbose("Version Request\n");
1941                 memset(req, 0, SKINNY_MAX_PACKET);
1942                 req->len = sizeof(version_res_message)+4;
1943                 req->e = VERSION_RES_MESSAGE;
1944                 sprintf(req->data.version.version, s->device->version_id);
1945                 transmit_response(s, req);
1946                 break;
1947         case SERVER_REQUEST_MESSAGE:
1948                 if (skinnydebug)
1949                         ast_verbose("Recieved Server Request\n");
1950                 memset(req, 0, SKINNY_MAX_PACKET);
1951                 req->len = sizeof(server_res_message)+4;
1952                 req->e = SERVER_RES_MESSAGE;
1953                 memcpy(req->data.serverres.server[0].serverName, ourhost, 
1954                                 sizeof(req->data.serverres.server[0].serverName));
1955                 req->data.serverres.serverListenPort[0] = ourport;
1956                 req->data.serverres.serverIpAddr[0] = __ourip.s_addr;
1957                 transmit_response(s, req);      
1958                 break;
1959         case BUTTON_TEMPLATE_REQ_MESSAGE:
1960                 if (skinnydebug)
1961                         ast_verbose("Buttontemplate requested\n");
1962                 memset(req, 0, SKINNY_MAX_PACKET);
1963                 req->len = sizeof(button_template_res_message)+4;
1964                 req->e = BUTTON_TEMPLATE_RES_MESSAGE;   
1965                 req->data.buttontemplate.buttonOffset           = 0;
1966                 req->data.buttontemplate.buttonCount            = 10;
1967                 req->data.buttontemplate.totalButtonCount       = 10;
1968                 /* XXX Figure out how to do this correctly */
1969                 memcpy(req->data.buttontemplate.definition,
1970                            button_definition_hack, 
1971                            sizeof(req->data.buttontemplate.definition));
1972                 transmit_response(s, req);
1973                 break;
1974         case SOFT_KEY_SET_REQ_MESSAGE:
1975                 if (skinnydebug)
1976                         ast_verbose("Received SoftKeySetReq\n");
1977                 memset(req, 0, SKINNY_MAX_PACKET);
1978                 req->len = sizeof(soft_key_sets)+4;
1979                 req->e = SOFT_KEY_SET_RES_MESSAGE;
1980                 req->data.softkeysets.softKeySetOffset          = 0;
1981                 req->data.softkeysets.softKeySetCount           = 11;
1982                 req->data.softkeysets.totalSoftKeySetCount  = 11;       
1983                 /* XXX Wicked hack XXX */
1984                 memcpy(req->data.softkeysets.softKeySetDefinition, 
1985                            soft_key_set_hack, 
1986                            sizeof(req->data.softkeysets.softKeySetDefinition));
1987                 transmit_response(s,req);
1988                 break;
1989         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
1990                 if (skinnydebug)
1991                         ast_verbose("Recieved SoftKey Template Request\n");
1992                 memset(req, 0, SKINNY_MAX_PACKET);
1993                 req->len = sizeof(soft_key_template)+4;
1994                 req->e = SOFT_KEY_TEMPLATE_RES_MESSAGE;
1995                 req->data.softkeytemplate.softKeyOffset         = 0;
1996                 req->data.softkeytemplate.softKeyCount          = 21;
1997                 req->data.softkeytemplate.totalSoftKeyCount = 21; 
1998                 /* XXX Another wicked hack XXX */
1999                 memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
2000                            soft_key_template_hack,
2001                            sizeof(req->data.softkeytemplate.softKeyTemplateDefinition));
2002                 transmit_response(s,req);
2003                 break;
2004         case TIME_DATE_REQ_MESSAGE:
2005                 if (skinnydebug)
2006                         ast_verbose("Received Time/Date Request\n");
2007                 memset(req, 0, SKINNY_MAX_PACKET);
2008                 req->len = sizeof(definetimedate_message)+4;
2009                 req->e = DEFINETIMEDATE_MESSAGE;
2010                 timer=time(NULL);
2011                 cmtime = localtime(&timer);
2012                 req->data.definetimedate.year = cmtime->tm_year+1900;
2013                 req->data.definetimedate.month = cmtime->tm_mon+1;
2014                 req->data.definetimedate.dayofweek = cmtime->tm_wday;
2015                 req->data.definetimedate.day = cmtime->tm_mday;
2016                 req->data.definetimedate.hour = cmtime->tm_hour;
2017                 req->data.definetimedate.minute = cmtime->tm_min;
2018                 req->data.definetimedate.seconds = cmtime->tm_sec;
2019                 transmit_response(s, req);
2020                 break;
2021         case SPEED_DIAL_STAT_REQ_MESSAGE:
2022                 /* Not really sure how Speed Dial's are different than the 
2023                    Softkey templates */
2024                 speedDialNum = req->data.speeddialreq.speedDialNumber;
2025 //              if (skinnydebug)
2026 //                      ast_verbose("Recieved SpeedDialStatReq: %d\n", speedDialNum);
2027                 memset(req, 0, SKINNY_MAX_PACKET);
2028                 req->len = sizeof(speed_dial_stat_res_message)+4;
2029                 req->e = SPEED_DIAL_STAT_RES_MESSAGE;
2030 #if 0   
2031                 /* XXX Do this right XXX */     
2032                 req->data.speeddialreq.speedDialNumber = speedDialNum;
2033                 sprintf(req->data.speeddial.speedDialDirNumber, "31337");
2034                 sprintf(req->data.speeddial.speedDialDisplayName, "Asterisk Rules!");
2035 #endif          
2036                 transmit_response(s, req);
2037                 break;
2038         case LINE_STATE_REQ_MESSAGE:
2039                 lineNumber = req->data.line.lineNumber;
2040                 if (skinnydebug)
2041                         ast_verbose("Received LineStateReq\n");
2042                 memset(req, 0, SKINNY_MAX_PACKET);
2043                 req->len = sizeof(line_stat_res_message)+4;
2044                 req->e = LINE_STAT_RES_MESSAGE; 
2045                 sub = find_subchannel_by_line(s->device->lines);
2046                 if (!sub) {
2047                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2048                         return 0;
2049                 }
2050                 lines = sub->parent;
2051                 ast_mutex_lock(&devicelock);
2052                 for (i=1; i < lineNumber; i++) {
2053                         lines = lines->next;
2054                 }
2055                 ast_mutex_unlock(&devicelock);
2056                 req->data.linestat.linenumber = lineNumber;             
2057                 memcpy(req->data.linestat.lineDirNumber, lines->name,
2058                                 sizeof(req->data.linestat.lineDirNumber));
2059                 memcpy(req->data.linestat.lineDisplayName, lines->label,
2060                                 sizeof(req->data.linestat.lineDisplayName)); 
2061                 transmit_response(s,req);
2062                 break;
2063         case CAPABILITIES_RES_MESSAGE:
2064                 if (skinnydebug)
2065                         ast_verbose("Received CapabilitiesRes\n");      
2066                 // zien wat ie kan en verwerken (handshake)
2067                 break;
2068         case KEEP_ALIVE_MESSAGE:
2069                 memset(req, 0, SKINNY_MAX_PACKET);
2070                 req->len = 4;
2071                 req->e = KEEP_ALIVE_ACK_MESSAGE;
2072                 transmit_response(s, req);
2073                 break;
2074         case OFFHOOK_MESSAGE:
2075                 transmit_ringer_mode(s,SKINNY_RING_OFF);
2076                 transmit_lamp_indication(s, s->device->lines->instance, SKINNY_LAMP_ON); 
2077                 
2078                 sub = find_subchannel_by_line(s->device->lines);
2079                 if (!sub) {
2080                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2081                         return 0;
2082                 }
2083                 sub->parent->hookstate = SKINNY_OFFHOOK;
2084                 
2085                         if (sub->outgoing) {
2086                                 transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2087                                 transmit_tone(s, SKINNY_SILENCE);
2088                                 ast_setstate(sub->owner, AST_STATE_UP);
2089                                 // select soft keys
2090                         } else {        
2091                                 if (!sub->owner) {      
2092
2093                                         transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2094                                         transmit_tone(s, SKINNY_DIALTONE);
2095                                         c = skinny_new(sub, AST_STATE_DOWN);                    
2096                                         if(c) {
2097                                                 /* start switch */
2098                                                 if (pthread_create(&t, NULL, skinny_ss, c)) {
2099                                                         ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
2100                                                         ast_hangup(c);
2101                                                 }
2102                                         } else {
2103                                                 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", sub->parent->name, s->device->name);
2104                                         }
2105                                 
2106                                 } else {
2107                                         ast_log(LOG_DEBUG, "Current sub [%s] already has owner\n", sub->owner->name);
2108                                 }
2109                         }
2110                 break;
2111         case ONHOOK_MESSAGE:
2112                 sub = find_subchannel_by_line(s->device->lines);
2113                 if (sub->parent->hookstate == SKINNY_ONHOOK) {
2114                         /* Somthing else already put us back on hook */ 
2115                         break;
2116                 }
2117                 sub->cxmode = SKINNY_CX_RECVONLY;
2118                 sub->parent->hookstate = SKINNY_ONHOOK;
2119                 transmit_callstate(s, s->device->lines->instance, sub->parent->hookstate,sub->callid);
2120             if (skinnydebug)
2121                         ast_verbose("Skinny %s@%s went on hook\n",sub->parent->name, sub->parent->parent->name);
2122             if (sub->rtp) {
2123  //         transmit_modify_request(sub);
2124         }
2125         if (sub->parent->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
2126                         /* We're allowed to transfer, we have two active calls and */
2127                         /* we made at least one of the calls.  Let's try and transfer */
2128 #if 0
2129              if ((res = attempt_transfer(p)) < 0) {
2130                                  if (p->sub->next->owner) {
2131                                         sub->next->alreadygone = 1;
2132                                         ast_queue_hangup(sub->next->owner,1);
2133                                 }
2134                          } else if (res) {
2135                                     ast_log(LOG_WARNING, "Transfer attempt failed\n");
2136                                         return -1;
2137              }
2138 #endif
2139        } else {
2140            /* Hangup the current call */
2141            /* If there is another active call, skinny_hangup will ring the phone with the other call */
2142            if (sub->owner) {
2143                sub->alreadygone = 1;
2144                ast_queue_hangup(sub->owner);
2145            } else {
2146                ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n", 
2147                            sub->parent->name, sub->parent->parent->name, sub->callid);
2148            }
2149        }
2150        if ((sub->parent->hookstate == SKINNY_ONHOOK) && (!sub->rtp) && (!sub->next->rtp)) {
2151                         if (has_voicemail(sub->parent)) {
2152                                 transmit_lamp_indication(s, s->device->lines->instance, SKINNY_LAMP_FLASH); 
2153             } else {
2154                                 transmit_lamp_indication(s, s->device->lines->instance, SKINNY_LAMP_OFF);
2155             }
2156        }
2157            break;
2158         case KEYPAD_BUTTON_MESSAGE:
2159                 digit = req->data.keypad.button;
2160                 if (skinnydebug) {
2161                         ast_verbose("Collected digit: [%d]\n", digit);
2162                 }
2163                 f.frametype = AST_FRAME_DTMF;
2164                 if (digit == 14) {
2165                         sprintf(&d, "*");
2166                 } else if (digit == 15) {
2167                         sprintf(&d, "#");
2168                 } else {
2169                         sprintf(&d, "%d", digit);
2170                 }
2171                 f.subclass  = d;  
2172                 f.src = "skinny";
2173
2174                 sub = find_subchannel_by_line(s->device->lines);                
2175
2176                 if (sub->owner) {
2177                         /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
2178                         ast_queue_frame(sub->owner, &f);
2179             if (sub->next->owner) {
2180                                 ast_queue_frame(sub->next->owner, &f);
2181             }
2182         } else {
2183                         ast_verbose("No owner: %s\n", s->device->lines->name);
2184                 }
2185                 break;
2186         case OPEN_RECIEVE_CHANNEL_ACK_MESSAGE:
2187                 ast_verbose("Recieved Open Recieve Channel Ack\n");
2188                 status = req->data.openrecievechannelack.status;
2189                 if (status) {
2190                         ast_log(LOG_ERROR, "Open Recieve Channel Failure\n");
2191                         break;
2192                 }
2193                 memcpy(addr, req->data.openrecievechannelack.ipAddr, sizeof(addr));
2194                 port = req->data.openrecievechannelack.port;
2195                                 
2196                 sin.sin_family = AF_INET;
2197                 memcpy(&sin.sin_addr, addr, sizeof(sin.sin_addr));  // Endian?
2198                 sin.sin_port = htons(port);
2199         
2200                 sub = find_subchannel_by_line(s->device->lines);
2201                 if (sub->rtp) {
2202                         ast_rtp_set_peer(sub->rtp, &sin);
2203                         ast_rtp_get_us(sub->rtp, &us);  
2204                 } else {
2205                         ast_log(LOG_ERROR, "No RTP structure, this is very bad\n");
2206                         break;
2207                 }
2208                 memset(req, 0, SKINNY_MAX_PACKET);
2209                 req->len = sizeof(start_media_transmission_message)+4;
2210                 req->e = START_MEDIA_TRANSMISSION_MESSAGE;
2211                 req->data.startmedia.conferenceId = 0;
2212                 req->data.startmedia.passThruPartyId = 0;
2213                 memcpy(req->data.startmedia.remoteIp, &s->device->ourip, 4); // Endian?
2214                 req->data.startmedia.remotePort = ntohs(us.sin_port);
2215                 req->data.startmedia.packetSize = 20;
2216                 req->data.startmedia.payloadType = convert_cap(s->device->lines->capability);
2217                 req->data.startmedia.qualifier.precedence = 127;
2218                 req->data.startmedia.qualifier.vad = 0;
2219                 req->data.startmedia.qualifier.packets = 0;
2220                 req->data.startmedia.qualifier.bitRate = 0;
2221                 transmit_response(s, req);
2222                 break;  
2223         default:
2224                 ast_verbose("RECEIVED UNKNOWN MESSAGE TYPE:  %x\n", req->e);
2225                 break;
2226         }
2227
2228         free(req);
2229         return 1;
2230
2231 }
2232
2233 static void destroy_session(struct skinnysession *s)
2234 {
2235         struct skinnysession *cur, *prev = NULL;
2236         ast_mutex_lock(&sessionlock);
2237         cur = sessions;
2238         while(cur) {
2239                 if (cur == s)
2240                         break;
2241                 prev = cur;
2242                 cur = cur->next;
2243         }
2244         if (cur) {
2245                 if (prev)
2246                         prev->next = cur->next;
2247                 else
2248                         sessions = cur->next;
2249                 if (s->fd > -1)
2250                         close(s->fd);
2251                 free(s);
2252         } else
2253                 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
2254         ast_mutex_unlock(&sessionlock);
2255 }
2256
2257 static int get_input(struct skinnysession *s)  
2258 {  
2259  
2260         int res;  
2261         int dlen = 0;  
2262  
2263         fd_set fds;  
2264         FD_ZERO(&fds);  
2265         FD_SET(s->fd, &fds);  
2266  
2267         res = ast_select(s->fd + 1, &fds, NULL, NULL, NULL);  
2268  
2269         if (res < 0) {
2270                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
2271         } else if (res > 0) {
2272                 memset(s->inbuf,0,sizeof(s->inbuf));
2273                 res = read(s->fd, s->inbuf, 4);
2274                 if (res != 4) {
2275                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2276                         return -1;
2277                 }
2278                 dlen = *(int *)s->inbuf;
2279                 res = read(s->fd, s->inbuf+4, dlen+4);
2280                 ast_mutex_unlock(&s->lock);
2281                 if (res != (dlen+4)) {
2282                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2283                         return -1;
2284                 } 
2285  
2286         }  
2287         return res;  
2288 }   
2289
2290
2291 static skinny_req *skinny_req_parse(struct skinnysession *s)
2292 {
2293         skinny_req *req;
2294         
2295         req = malloc(SKINNY_MAX_PACKET);
2296         if (!req) {
2297                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
2298                 return NULL;
2299         }
2300         memset(req, 0, sizeof(skinny_req));
2301         memcpy(req, s->inbuf, *(int*)(s->inbuf)+8); // +8
2302         if (req->e < 0) {
2303                 ast_log(LOG_ERROR, "Event Message is NULL from socket %d, This is bad\n", s->fd);
2304                 free(req);
2305                 return NULL;
2306         }
2307         return req;
2308 }
2309
2310 static void *skinny_session(void *data)
2311 {
2312         int res;
2313         skinny_req *req;
2314         struct skinnysession *s = data;
2315         
2316         ast_verbose(VERBOSE_PREFIX_3 "Starting Skinny session from %s\n",  inet_ntoa(s->sin.sin_addr));
2317
2318         for (;;) {
2319                 res = 0;
2320                 res = get_input(s);
2321                 if (res < 0)
2322                         break;
2323                 req = skinny_req_parse(s);
2324                 if (!req) {
2325                         return NULL;
2326                 }
2327                 res = handle_message(req, s);
2328                 if (res < 0) {
2329                         destroy_session(s);
2330                         return NULL;
2331                 } 
2332         }
2333         ast_log(LOG_NOTICE, "Skinny Session returned: %s\n", strerror(errno));
2334         destroy_session(s);
2335         return 0;
2336 }
2337
2338 static void *accept_thread(void *ignore)
2339 {
2340         int as;
2341         struct sockaddr_in sin;
2342         int sinlen;
2343         struct skinnysession *s;
2344         struct protoent *p;
2345         int arg = 1;
2346         pthread_attr_t attr;
2347
2348         pthread_attr_init(&attr);
2349         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2350
2351         for (;;) {
2352                 sinlen = sizeof(sin);
2353                 as = accept(skinnysock, (struct sockaddr *)&sin, &sinlen);
2354                 if (as < 0) {
2355                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
2356                         continue;
2357                 }
2358                 p = getprotobyname("tcp");
2359                 if(p) {
2360                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
2361                                 ast_log(LOG_WARNING, "Failed to set Skinny tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
2362                         }
2363                 }
2364                 s = malloc(sizeof(struct skinnysession));
2365                 if (!s) {
2366                         ast_log(LOG_WARNING, "Failed to allocate Skinny session: %s\n", strerror(errno));
2367                         continue;
2368                 } 
2369                 memset(s, 0, sizeof(struct skinnysession));
2370                 memcpy(&s->sin, &sin, sizeof(sin));
2371                 ast_mutex_init(&s->lock);
2372                 s->fd = as;
2373                 ast_mutex_lock(&sessionlock);
2374                 s->next = sessions;
2375                 sessions = s;
2376                 ast_mutex_unlock(&sessionlock);
2377                 
2378                 if (pthread_create(&tcp_thread, NULL, skinny_session, s))
2379                         destroy_session(s);
2380         }
2381         
2382         
2383         if (skinnydebug)
2384                 ast_verbose("killing accept thread\n");
2385         
2386         close(as);
2387         return 0;
2388 }
2389
2390 static void *do_monitor(void *data)
2391 {
2392         int res;
2393
2394         /* This thread monitors all the interfaces which are not yet in use
2395            (and thus do not have a separate thread) indefinitely */
2396         /* From here on out, we die whenever asked */
2397         for(;;) {
2398                 pthread_testcancel();
2399                 /* Wait for sched or io */
2400                 res = ast_sched_wait(sched);
2401                 if ((res < 0) || (res > 1000))
2402                         res = 1000;
2403                 res = ast_io_wait(io, res);
2404                 ast_mutex_lock(&monlock);
2405                 if (res >= 0) 
2406                         ast_sched_runq(sched);
2407                 ast_mutex_unlock(&monlock);
2408         }
2409         /* Never reached */
2410         return NULL;
2411         
2412 }
2413
2414 static int restart_monitor(void)
2415 {
2416
2417         /* If we're supposed to be stopped -- stay stopped */
2418         if (monitor_thread == AST_PTHREADT_STOP)
2419                 return 0;
2420         if (ast_mutex_lock(&monlock)) {
2421                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
2422                 return -1;
2423         }
2424         if (monitor_thread == pthread_self()) {
2425                 ast_mutex_unlock(&monlock);
2426                 ast_log(LOG_WARNING, "Cannot kill myself\n");
2427                 return -1;
2428         }
2429         if (monitor_thread != AST_PTHREADT_NULL) {
2430                 /* Wake up the thread */
2431                 pthread_kill(monitor_thread, SIGURG);
2432         } else {
2433                 /* Start a new monitor */
2434                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
2435                         ast_mutex_unlock(&monlock);
2436                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
2437                         return -1;
2438                 }
2439         }
2440         ast_mutex_unlock(&monlock);
2441         return 0;
2442 }
2443
2444 static struct ast_channel *skinny_request(char *type, int format, void *data)
2445 {
2446         int oldformat;
2447         struct skinny_subchannel *sub;
2448         struct ast_channel *tmpc = NULL;
2449         char tmp[256];
2450         char *dest = data;
2451
2452         oldformat = format;
2453         format &= capability;
2454         if (!format) {
2455                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
2456                 return NULL;
2457         }
2458         
2459         strncpy(tmp, dest, sizeof(tmp) - 1);
2460         if (!strlen(tmp)) {
2461                 ast_log(LOG_NOTICE, "Skinny channels require a device\n");
2462                 return NULL;
2463         }
2464         
2465         sub = find_subchannel_by_name(tmp);  
2466         if (!sub) {
2467                 ast_log(LOG_NOTICE, "No available lines on: %s\n", dest);
2468                 return NULL;
2469         }
2470         
2471     if (option_verbose > 2) {
2472         ast_verbose(VERBOSE_PREFIX_3 "skinny_request(%s)\n", tmp);
2473         ast_verbose(VERBOSE_PREFIX_3 "Skinny cw: %d, dnd: %d, so: %d, sno: %d\n", 
2474                     sub->parent->callwaiting, sub->parent->dnd, sub->owner ? 1 : 0, sub->next->owner ? 1: 0);
2475     }
2476         
2477         tmpc = skinny_new(sub->owner ? sub->next : sub, AST_STATE_DOWN);
2478         if (!tmpc)
2479                 ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
2480         restart_monitor();
2481
2482         /* and finish */        
2483         return tmpc;
2484 }
2485
2486 static int reload_config(void)
2487 {
2488         int on=1;
2489         struct ast_config *cfg;
2490         struct ast_variable *v;
2491         int format;
2492         char *cat;
2493         struct skinny_device *d;
2494         int oldport = ntohs(bindaddr.sin_port);
2495         
2496         if (gethostname(ourhost, sizeof(ourhost))) {
2497                 ast_log(LOG_WARNING, "Unable to get hostname, Skinny disabled\n");
2498                 return 0;
2499         }
2500         cfg = ast_load(config);
2501
2502         /* We *must* have a config file otherwise stop immediately */
2503         if (!cfg) {
2504                 ast_log(LOG_NOTICE, "Unable to load config %s, Skinny disabled\n", config);
2505                 return 0;
2506         }
2507
2508         /* load the general section */
2509         memset(&bindaddr, 0, sizeof(bindaddr));
2510         v = ast_variable_browse(cfg, "general");
2511         while(v) {
2512                 /* Create the interface list */
2513                 if (!strcasecmp(v->name, "bindaddr")) {
2514                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
2515                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2516                         } else {
2517                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2518                         }
2519                 } else if (!strcasecmp(v->name, "keepAlive")) {
2520                         keep_alive = atoi(v->value);            
2521                 } else if (!strcasecmp(v->name, "dateFormat")) {
2522                         strncpy(date_format, v->value, sizeof(date_format) - 1);        
2523                 } else if (!strcasecmp(v->name, "allow")) {
2524                         format = ast_getformatbyname(v->value);
2525                         if (format < 1) 
2526                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
2527                         else
2528                                 capability |= format;
2529                 } else if (!strcasecmp(v->name, "disallow")) {
2530                         format = ast_getformatbyname(v->value);
2531                         if (format < 1) 
2532                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
2533                         else
2534                                 capability &= ~format;
2535                 } else if (!strcasecmp(v->name, "port")) {
2536                         if (sscanf(v->value, "%i", &ourport) == 1) {
2537                                 bindaddr.sin_port = htons(ourport);
2538                         } else {
2539                                 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
2540                         }
2541                 }
2542                 v = v->next;
2543         }
2544
2545         if (ntohl(bindaddr.sin_addr.s_addr)) {
2546                 memcpy(&__ourip, &bindaddr.sin_addr, sizeof(__ourip));
2547         } else {
2548                 hp = ast_gethostbyname(ourhost, &ahp);
2549                 if (!hp) {
2550                         ast_log(LOG_WARNING, "Unable to get our IP address, Skinny disabled\n");
2551                         return 0;
2552                 }
2553                 memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
2554         }
2555         if (!ntohs(bindaddr.sin_port))
2556                 bindaddr.sin_port = ntohs(DEFAULT_SKINNY_PORT);
2557         bindaddr.sin_family = AF_INET;
2558         
2559         /* load the device sections */
2560         cat = ast_category_browse(cfg, NULL);
2561         while(cat) {
2562                 if (strcasecmp(cat, "general")) {
2563                         d = build_device(cat, ast_variable_browse(cfg, cat));
2564                         if (d) {
2565                                 if (option_verbose > 2) {
2566                                         ast_verbose(VERBOSE_PREFIX_3 "Added device '%s'\n", d->name);
2567                 }
2568                                 ast_mutex_lock(&devicelock);
2569                                 d->next = devices;
2570                                 devices = d;
2571                                 ast_mutex_unlock(&devicelock);
2572                         }
2573                 }
2574                 cat = ast_category_browse(cfg, cat);
2575         }
2576         ast_mutex_lock(&netlock);
2577         if ((skinnysock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
2578                 close(skinnysock);
2579                 skinnysock = -1;
2580         }
2581         if (skinnysock < 0) {
2582                 skinnysock = socket(AF_INET, SOCK_STREAM, 0);
2583                 if(setsockopt(skinnysock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
2584                         ast_log(LOG_ERROR, "Set Socket Options failed: errno %d, %s", errno, strerror(errno));
2585                         return 0;
2586                 }
2587
2588                 if (skinnysock < 0) {
2589                         ast_log(LOG_WARNING, "Unable to create Skinny socket: %s\n", strerror(errno));
2590                 } else {
2591                         if (bind(skinnysock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
2592                                 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
2593                                                 inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
2594                                                         strerror(errno));
2595                                 close(skinnysock);
2596                                 skinnysock = -1;
2597                                 return 0;
2598                         } 
2599
2600                         if (listen(skinnysock,DEFAULT_SKINNY_BACKLOG)) {
2601                                         ast_log(LOG_WARNING, "Failed to start listening to %s:%d: %s\n",
2602                                                 inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
2603                                                         strerror(errno));
2604                                         close(skinnysock);
2605                                         skinnysock = -1;
2606                                         return 0;
2607                         }
2608                 
2609                         if (option_verbose > 1)
2610                                 ast_verbose(VERBOSE_PREFIX_2 "Skinny listening on %s:%d\n", 
2611                                         inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
2612
2613                         pthread_create(&accept_t,NULL, accept_thread, NULL);
2614
2615                 }
2616         }
2617         ast_mutex_unlock(&netlock);
2618
2619         /* and unload the configuration when were done */
2620         ast_destroy(cfg);
2621
2622         return 0;
2623 }
2624
2625 #if 0
2626 void delete_devices(void)
2627 {
2628         struct skinny_device *d, *dlast;
2629         struct skinny_line *l, *llast;
2630         struct skinny_subchannel *sub, *slast;
2631         
2632         ast_mutex_lock(&devicelock);
2633         
2634         /* Delete all devices */
2635         for (d=devices;d;) {
2636                 
2637                 /* Delete all lines for this device */
2638                 for (l=d->lines;l;) {
2639                         /* Delete all subchannels for this line */
2640                         for (sub=l->sub;sub;) {
2641                                 slast = sub;
2642                                 sub = sub->next;
2643                                 free(slast);
2644                         }
2645                         llast = l;
2646                         l = l->next;
2647                         free(llast);
2648                 }
2649                 dlast = d;
2650                 d = d->next;
2651                 free(dlast);
2652         }
2653         devices=NULL;
2654         ast_mutex_unlock(&devicelock);
2655 }
2656 #endif
2657
2658 int reload(void)
2659 {
2660 #if 0
2661 // XXX Causes Seg
2662
2663         delete_devices();
2664         reload_config();
2665         restart_monitor();
2666 #endif
2667         return 0;
2668 }
2669
2670
2671 int load_module()
2672 {
2673         int res = 0;
2674
2675         /* load and parse config */
2676         res = reload_config();
2677         
2678         /* Announce our presence to Asterisk */ 
2679         if (!res) {
2680                 /* Make sure we can register our skinny channel type */
2681                 if (ast_channel_register(type, tdesc, capability, skinny_request)) {
2682                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
2683                         return -1;
2684                 }
2685         }
2686         skinny_rtp.type = type;
2687         ast_rtp_proto_register(&skinny_rtp);
2688         ast_cli_register(&cli_show_lines);
2689         ast_cli_register(&cli_debug);
2690         ast_cli_register(&cli_no_debug);
2691         sched = sched_context_create();
2692         if (!sched) {
2693                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2694         }
2695         io = io_context_create();
2696         if (!io) {
2697                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2698         }
2699         /* And start the monitor for the first time */
2700         restart_monitor();
2701         return res;
2702 }
2703
2704 int unload_module()
2705 {
2706 #if 0
2707         struct skinny_session *session, s;
2708         struct skinny_subchannel *sub;
2709         struct skinny_line *line = session;
2710
2711         /* close all IP connections */
2712         if (!ast_mutex_lock(&devicelock)) {
2713                 /* Terminate tcp listener thread */
2714                 
2715
2716         } else {
2717                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2718                 return -1;
2719         }
2720         if (!ast_mutex_lock(&monlock)) {
2721                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
2722                         pthread_cancel(monitor_thread);
2723                         pthread_kill(monitor_thread, SIGURG);
2724                         pthread_join(monitor_thread, NULL);
2725                 }
2726                 monitor_thread = AST_PTHREADT_STOP;
2727                 ast_mutex_unlock(&monlock);
2728         } else {
2729                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2730                 return -1;
2731         }
2732         if (!ast_mutex_lock(&iflock)) {
2733                 /* Destroy all the interfaces and free their memory */
2734                 p = iflist;
2735                 while(p) {
2736                         pl = p;
2737                         p = p->next;
2738                         /* Free associated memory */
2739                         free(pl);
2740                 }
2741                 iflist = NULL;
2742                 ast_mutex_unlock(&iflock);
2743         } else {
2744                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2745                 return -1;
2746         }
2747
2748         ast_rtp_proto_register(&skinny_rtp);
2749         ast_cli_register(&cli_show_lines);
2750         ast_cli_register(&cli_debug);
2751         ast_cli_register(&cli_no_debug);
2752
2753         return 0;
2754 #endif
2755         return -1;
2756 }
2757
2758 int usecount()
2759 {
2760         int res;
2761         ast_mutex_lock(&usecnt_lock);
2762         res = usecnt;
2763         ast_mutex_unlock(&usecnt_lock);
2764         return res;
2765 }
2766
2767 char *key()
2768 {
2769         return ASTERISK_GPL_KEY;
2770 }
2771
2772 char *description()
2773 {
2774         return desc;
2775 }