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