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