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