Merge major BSD mutex and symbol conflict patches (bug #1816) (link patch still pending)
[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                                         ast_mutex_init(&l->lock);
1108                                         strncpy(l->name, v->value, sizeof(l->name) - 1);
1109                                         
1110                                         /* XXX Should we check for uniqueness?? XXX */
1111                                         
1112                                         strncpy(l->context, context, sizeof(l->context) - 1);
1113                                         strncpy(l->callerid, callerid, sizeof(l->callerid) - 1);
1114                                         strncpy(l->label, linelabel, sizeof(l->label) - 1);
1115                                         strncpy(l->language, language, sizeof(l->language) - 1);
1116                                         strncpy(l->musicclass, musicclass, sizeof(l->musicclass)-1);
1117                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1118                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1119                                         if (!ast_strlen_zero(mailbox)) {
1120                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting mailbox '%s' on %s@%s\n", mailbox, d->name, l->name);
1121                                         }
1122                                 
1123                                         l->msgstate = -1;
1124                                         l->capability = capability;
1125                                         l->parent = d;
1126                                         if (!strcasecmp(v->name, "trunk")) {
1127                                                 l->type = TYPE_TRUNK;
1128                                         } else {
1129                                                 l->type = TYPE_LINE;
1130                                         }
1131                                         l->immediate = immediate;
1132                                         l->callgroup = cur_callergroup;
1133                                         l->pickupgroup = cur_pickupgroup;
1134                                         l->callreturn = callreturn;
1135                                         l->cancallforward = cancallforward;
1136                                         l->callwaiting = callwaiting;
1137                                         l->transfer = transfer; 
1138                                         l->threewaycalling = threewaycalling;
1139                                         l->onhooktime = time(NULL);
1140                                         l->instance = 1;
1141                                         /* ASSUME we're onhook at this point*/
1142                                         l->hookstate = SKINNY_ONHOOK;
1143
1144                                         for (i = 0; i < MAX_SUBS; i++) {
1145                                                 sub = malloc(sizeof(struct skinny_subchannel));
1146                                                 if (sub) {
1147                                                         ast_verbose(VERBOSE_PREFIX_3 "Allocating Skinny subchannel '%d' on %s@%s\n", i, l->name, d->name);
1148                                                         memset(sub, 0, sizeof(struct skinny_subchannel));
1149                                                         ast_mutex_init(&sub->lock);
1150                                                         sub->parent = l;
1151                                                         /* Make a call*ID */
1152                                                         sub->callid = callnums;
1153                                                         callnums++;
1154                                                         sub->cxmode = SKINNY_CX_INACTIVE;
1155                                                         sub->nat = nat;
1156                                                         sub->next = l->sub;
1157                                                         l->sub = sub;
1158                                                 } else {
1159                                                         /* XXX Should find a way to clean up our memory */
1160                                                         ast_log(LOG_WARNING, "Out of memory allocating subchannel");
1161                                                         return NULL;
1162                                                 }
1163                                         }
1164                                         l->next = d->lines;
1165                                         d->lines = l;                   
1166                                 } else {
1167                                         /* XXX Should find a way to clean up our memory */
1168                                         ast_log(LOG_WARNING, "Out of memory allocating line");
1169                                         return NULL;
1170                                 }
1171                         } else {
1172                                 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
1173                         }
1174                         v = v->next;
1175                 }
1176         
1177                 if (!d->lines) {
1178                         ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
1179                         return NULL;
1180                 }
1181
1182                 if (d->addr.sin_addr.s_addr && !ntohs(d->addr.sin_port))
1183                         d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
1184                 if (d->addr.sin_addr.s_addr) {
1185                         if (ast_ouraddrfor(&d->addr.sin_addr, &d->ourip)) {
1186                                 memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1187                         }
1188                 } else {
1189                         memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1190                 }
1191         }
1192         return d;
1193 }
1194
1195 static int has_voicemail(struct skinny_line *l)
1196 {
1197         return ast_app_has_voicemail(l->mailbox);
1198 }
1199
1200 static int skinny_register(skinny_req *req, struct skinnysession *s)
1201 {
1202         struct skinny_device *d;
1203         
1204         ast_mutex_lock(&devicelock);
1205         d = devices;
1206         while (d) {
1207                 if (!strcasecmp(req->data.reg.name, d->id)) {
1208                         /* XXX Deal with IP authentication */
1209                         s->device = d;
1210                         d->type = req->data.reg.type;
1211                         if (ast_strlen_zero(d->version_id)) {
1212                                 strncpy(d->version_id, version_id, sizeof(d->version_id));
1213                         }
1214                         d->registered = 1;
1215                         d->session = s;
1216                         break;
1217                 }
1218                 d = d->next;
1219         }
1220         ast_mutex_unlock(&devicelock);
1221
1222         if (!d)
1223                 return 0;
1224         
1225         return 1;
1226 }               
1227
1228 static void start_rtp(struct skinny_subchannel *sub)
1229 {
1230                 ast_mutex_lock(&sub->lock);
1231                 /* Allocate the RTP */
1232                 sub->rtp = ast_rtp_new(sched, io, 1, 0);
1233                 if (sub->rtp && sub->owner)
1234                         sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
1235                 if (sub->rtp)
1236                         ast_rtp_setnat(sub->rtp, sub->nat);
1237                 
1238                 /* Create the RTP connection */
1239                 transmit_connect(sub->parent->parent->session);
1240                 ast_mutex_unlock(&sub->lock);
1241 }
1242
1243
1244 static void *skinny_ss(void *data)
1245 {
1246         struct ast_channel *chan = data;
1247         struct skinny_subchannel *sub = chan->pvt->pvt;
1248         struct skinny_line *l = sub->parent;
1249         struct skinnysession *s = l->parent->session;
1250         char exten[AST_MAX_EXTENSION] = "";
1251         int len = 0;
1252         int timeout = firstdigittimeout;
1253         int res;
1254         int getforward=0;
1255     
1256         if (option_verbose > 2) {
1257                 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s@%s'\n", l->name, l->parent->name);
1258         }
1259         while(len < AST_MAX_EXTENSION-1) {
1260         res = ast_waitfordigit(chan, timeout);
1261         timeout = 0;
1262         if (res < 0) {
1263                 if (skinnydebug) {
1264                         ast_verbose("Skinny(%s@%s): waitfordigit returned < 0\n", l->name, l->parent->name);
1265                 }
1266                 ast_indicate(chan, -1);
1267                 ast_hangup(chan);
1268                 return NULL;
1269         } else if (res)  {
1270             exten[len++]=res;
1271             exten[len] = '\0';
1272         }
1273         if (!ast_ignore_pattern(chan->context, exten)) {
1274                         transmit_tone(s, SKINNY_SILENCE);
1275         } 
1276         if (ast_exists_extension(chan, chan->context, exten, 1, l->callerid)) {
1277             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, l->callerid)) {
1278                 if (getforward) {
1279                     /* Record this as the forwarding extension */
1280                     strncpy(l->call_forward, exten, sizeof(l->call_forward)); 
1281                     if (option_verbose > 2) {
1282                         ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n", 
1283                                 l->call_forward, chan->name);
1284                     }
1285                     transmit_tone(s, SKINNY_DIALTONE); 
1286                     if (res) {
1287                             break;
1288                     }
1289                     usleep(500000);
1290                     ast_indicate(chan, -1);
1291                     sleep(1);
1292                     memset(exten, 0, sizeof(exten));
1293                     transmit_tone(s, SKINNY_DIALTONE); 
1294                     len = 0;
1295                     getforward = 0;
1296                 } else  {
1297                     strncpy(chan->exten, exten, sizeof(chan->exten)-1);
1298                     if (!ast_strlen_zero(l->callerid)) {
1299                         if (!l->hidecallerid)
1300                             chan->callerid = strdup(l->callerid);
1301                         chan->ani = strdup(l->callerid);
1302                     }
1303                     ast_setstate(chan, AST_STATE_RING);
1304                     res = ast_pbx_run(chan);
1305                     if (res) {
1306                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
1307                                                 transmit_tone(s, SKINNY_REORDER); 
1308                     }
1309                     return NULL;
1310                 }
1311             } else {
1312                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
1313                    so just set the timeout to matchdigittimeout and wait some more */
1314                 timeout = matchdigittimeout;
1315             }
1316         } else if (res == 0) {
1317             ast_log(LOG_DEBUG, "Not enough digits (and no ambiguous match)...\n");
1318                 transmit_tone(s, SKINNY_REORDER); 
1319             ast_hangup(chan);
1320             return NULL;
1321         } else if (l->callwaiting && !strcmp(exten, "*70")) {
1322             if (option_verbose > 2) {
1323                 ast_verbose(VERBOSE_PREFIX_3 "Disabling call waiting on %s\n", chan->name);
1324             }
1325             /* Disable call waiting if enabled */
1326             l->callwaiting = 0;
1327             transmit_tone(s, SKINNY_DIALTONE);
1328                         len = 0;
1329             memset(exten, 0, sizeof(exten));
1330             timeout = firstdigittimeout;
1331                 
1332         } else if (!strcmp(exten,ast_pickup_ext())) {
1333             /* Scan all channels and see if any there
1334              * ringing channqels with that have call groups
1335              * that equal this channels pickup group  
1336              */
1337             if (ast_pickup_call(chan)) {
1338                 ast_log(LOG_WARNING, "No call pickup possible...\n");
1339                                 transmit_tone(s, SKINNY_REORDER);
1340             }
1341             ast_hangup(chan);
1342             return NULL;
1343             
1344         } else if (!l->hidecallerid && !strcmp(exten, "*67")) {
1345             if (option_verbose > 2) {
1346                 ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
1347             }
1348             /* Disable Caller*ID if enabled */
1349             l->hidecallerid = 1;
1350             if (chan->callerid)
1351                 free(chan->callerid);
1352             chan->callerid = NULL;
1353             transmit_tone(s, SKINNY_DIALTONE);
1354             len = 0;
1355             memset(exten, 0, sizeof(exten));
1356             timeout = firstdigittimeout;
1357         } else if (l->callreturn && !strcmp(exten, "*69")) {
1358             res = 0;
1359             if (!ast_strlen_zero(l->lastcallerid)) {
1360                 res = ast_say_digit_str(chan, l->lastcallerid, "", chan->language);
1361             }
1362             if (!res) {
1363                 transmit_tone(s, SKINNY_DIALTONE);
1364                         }
1365             break;
1366         } else if (!strcmp(exten, "*78")) {
1367             /* Do not disturb */
1368             if (option_verbose > 2) {
1369                 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %s\n", chan->name);
1370             }
1371             transmit_tone(s, SKINNY_DIALTONE);
1372             l->dnd = 1;
1373             getforward = 0;
1374             memset(exten, 0, sizeof(exten));
1375             len = 0;
1376         } else if (!strcmp(exten, "*79")) {
1377             /* Do not disturb */
1378             if (option_verbose > 2) {
1379                 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %s\n", chan->name);
1380             }
1381                         transmit_tone(s, SKINNY_DIALTONE);
1382             l->dnd = 0;
1383             getforward = 0;
1384             memset(exten, 0, sizeof(exten));
1385             len = 0;
1386         } else if (l->cancallforward && !strcmp(exten, "*72")) {
1387             transmit_tone(s, SKINNY_DIALTONE);
1388             getforward = 1;
1389             memset(exten, 0, sizeof(exten));
1390             len = 0;
1391         } else if (l->cancallforward && !strcmp(exten, "*73")) {
1392             if (option_verbose > 2) {
1393                 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %s\n", chan->name);
1394             }
1395             transmit_tone(s, SKINNY_DIALTONE); 
1396             memset(l->call_forward, 0, sizeof(l->call_forward));
1397             getforward = 0;
1398             memset(exten, 0, sizeof(exten));
1399             len = 0;
1400         } else if (!strcmp(exten, ast_parking_ext()) && 
1401                     sub->next->owner &&
1402                     sub->next->owner->bridge) {
1403             /* This is a three way call, the main call being a real channel, 
1404                 and we're parking the first call. */
1405             ast_masq_park_call(sub->next->owner->bridge, chan, 0, NULL);
1406             if (option_verbose > 2) {
1407                 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
1408             }
1409             break;
1410         } else if (!ast_strlen_zero(l->lastcallerid) && !strcmp(exten, "*80")) {
1411             if (option_verbose > 2) {
1412                 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", l->lastcallerid);
1413             }
1414             res = ast_db_put("blacklist", l->lastcallerid, "1");
1415             if (!res) {
1416                 transmit_tone(s, SKINNY_DIALTONE);              
1417                 memset(exten, 0, sizeof(exten));
1418                 len = 0;
1419             }
1420         } else if (l->hidecallerid && !strcmp(exten, "*82")) {
1421             if (option_verbose > 2) {
1422                 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
1423             }
1424             /* Enable Caller*ID if enabled */
1425             l->hidecallerid = 0;
1426             if (chan->callerid)
1427                 free(chan->callerid);
1428             if (!ast_strlen_zero(l->callerid))
1429                 chan->callerid = strdup(l->callerid);
1430             transmit_tone(s, SKINNY_DIALTONE);
1431             len = 0;
1432             memset(exten, 0, sizeof(exten));
1433             timeout = firstdigittimeout;
1434         } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->callerid) &&
1435                         ((exten[0] != '*') || (!ast_strlen_zero(exten) > 2))) {
1436             ast_log(LOG_WARNING, "Can't match [%s] from '%s' in context %s\n", exten, chan->callerid ? chan->callerid : "<Unknown Caller>", chan->context);
1437             transmit_tone(s, SKINNY_REORDER); 
1438                         sleep(3); // hang out for 3 seconds to let congestion play
1439                         break;
1440         }
1441         if (!timeout)
1442             timeout = gendigittimeout;
1443         if (len && !ast_ignore_pattern(chan->context, exten))
1444                         ast_indicate(chan, -1);
1445     }
1446         ast_hangup(chan);
1447         return NULL;
1448 }
1449
1450
1451
1452 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
1453 {
1454         int res = 0;
1455         int tone = 0;
1456         struct skinny_line *l;
1457         struct skinny_subchannel *sub;
1458         struct skinnysession *session;
1459         
1460         sub = ast->pvt->pvt;
1461         l = sub->parent;
1462         session = l->parent->session;
1463
1464         if (!l->parent->registered) {
1465                 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
1466                 return -1;
1467         }
1468         
1469         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1470                 ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
1471                 return -1;
1472         }
1473
1474         if (skinnydebug) {
1475                 ast_verbose(VERBOSE_PREFIX_3 "skinny_call(%s)\n", ast->name);
1476         }
1477
1478         if (l->dnd) {
1479                 ast_queue_control(ast, AST_CONTROL_BUSY);
1480                 return -1;
1481         }
1482    
1483         switch (l->hookstate) {
1484         case SKINNY_OFFHOOK:
1485             tone = SKINNY_CALLWAITTONE;
1486             break;
1487         case SKINNY_ONHOOK:
1488                         tone = SKINNY_ALERT;
1489                         break;
1490         default:
1491             ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
1492             break;
1493         }
1494
1495         transmit_lamp_indication(session, l->instance, SKINNY_LAMP_BLINK);
1496         transmit_ringer_mode(session, SKINNY_RING_INSIDE);
1497         transmit_tone(session, tone);
1498         transmit_callstate(session, l->instance, SKINNY_RINGIN, sub->callid);
1499
1500         /* XXX need to set the prompt */
1501         /* XXX need to deal with softkeys */
1502
1503         ast_setstate(ast, AST_STATE_RINGING);
1504         ast_queue_control(ast, AST_CONTROL_RINGING);
1505
1506         sub->outgoing = 1;
1507         if (l->type == TYPE_LINE) {
1508         if (!sub->rtp) {
1509             start_rtp(sub);
1510         } else {
1511                 /* do/should we need to anything if there already is an RTP allocated? */
1512         }
1513
1514         } else {
1515                 ast_log(LOG_ERROR, "I don't know how to dial on trunks, yet\n");
1516                 res = -1;
1517         }
1518         return res;
1519 }
1520
1521
1522 static int skinny_hangup(struct ast_channel *ast)
1523 {
1524     struct skinny_subchannel *sub = ast->pvt->pvt;
1525     struct skinny_line *l = sub->parent;
1526     struct skinnysession *s = l->parent->session;
1527
1528     if (skinnydebug) {
1529         ast_verbose("skinny_hangup(%s) on %s@%s\n", ast->name, l->name, l->parent->name);
1530     }
1531     if (!ast->pvt->pvt) {
1532         ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1533         return 0;
1534     }
1535
1536     if (l->parent->registered) {
1537         if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_OFFHOOK)) {
1538                         sub->parent->hookstate = SKINNY_ONHOOK;
1539                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
1540                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
1541                 } else if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_ONHOOK)) {
1542                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
1543                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
1544                         transmit_ringer_mode(s, SKINNY_RING_OFF);
1545                         transmit_tone(s, SKINNY_SILENCE);
1546                 } 
1547     }
1548     ast_mutex_lock(&sub->lock);
1549     sub->owner = NULL;
1550     ast->pvt->pvt = NULL;
1551     sub->alreadygone = 0;
1552     sub->outgoing = 0;
1553     if (sub->rtp) {
1554         ast_rtp_destroy(sub->rtp);
1555         sub->rtp = NULL;
1556     }
1557     ast_mutex_unlock(&sub->lock);
1558     return 0;
1559 }
1560
1561 static int skinny_answer(struct ast_channel *ast)
1562 {
1563     int res = 0;
1564     struct skinny_subchannel *sub = ast->pvt->pvt;
1565     struct skinny_line *l = sub->parent;
1566     sub->cxmode = SKINNY_CX_SENDRECV;
1567     if (!sub->rtp) {
1568                 start_rtp(sub);
1569     } 
1570     ast_verbose("skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, l->parent->name, sub->callid);
1571     if (ast->_state != AST_STATE_UP) {
1572         ast_setstate(ast, AST_STATE_UP);
1573     }
1574     return res;
1575 }
1576
1577 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
1578 {
1579         /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
1580         struct ast_frame *f;
1581         f = ast_rtp_read(sub->rtp);
1582         if (sub->owner) {
1583                 /* We already hold the channel lock */
1584                 if (f->frametype == AST_FRAME_VOICE) {
1585                         if (f->subclass != sub->owner->nativeformats) {
1586                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1587                                 sub->owner->nativeformats = f->subclass;
1588                                 ast_set_read_format(sub->owner, sub->owner->readformat);
1589                                 ast_set_write_format(sub->owner, sub->owner->writeformat);
1590                         }
1591                 }
1592         }
1593         return f;
1594 }
1595
1596 static struct ast_frame  *skinny_read(struct ast_channel *ast)
1597 {
1598         struct ast_frame *fr;
1599         struct skinny_subchannel *sub = ast->pvt->pvt;
1600         ast_mutex_lock(&sub->lock);
1601         fr = skinny_rtp_read(sub);
1602         ast_mutex_unlock(&sub->lock);
1603         return fr;
1604 }
1605
1606 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
1607 {
1608         struct skinny_subchannel *sub = ast->pvt->pvt;
1609         int res = 0;
1610         if (frame->frametype != AST_FRAME_VOICE) {
1611                 if (frame->frametype == AST_FRAME_IMAGE)
1612                         return 0;
1613                 else {
1614                         ast_log(LOG_WARNING, "Can't send %d type frames with skinny_write\n", frame->frametype);
1615                         return 0;
1616                 }
1617         } else {
1618                 if (!(frame->subclass & ast->nativeformats)) {
1619                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1620                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1621                         return -1;
1622                 }
1623         }
1624         if (sub) {
1625                 ast_mutex_lock(&sub->lock);
1626                 if (sub->rtp) {
1627                         res =  ast_rtp_write(sub->rtp, frame);
1628                 }
1629                 ast_mutex_unlock(&sub->lock);
1630         }
1631         return res;
1632 }
1633
1634 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1635 {
1636         struct skinny_subchannel *sub = newchan->pvt->pvt;
1637         ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", oldchan->name, newchan->name);
1638         if (sub->owner != oldchan) {
1639                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
1640                 return -1;
1641         }
1642         sub->owner = newchan;
1643         return 0;
1644 }
1645
1646 static int skinny_senddigit(struct ast_channel *ast, char digit)
1647 {
1648 #if 0
1649         struct skinny_subchannel *sub = ast->pvt->pvt;
1650         int tmp;
1651         /* not right */
1652         sprintf(tmp, "%d", digit);  
1653         transmit_tone(sub->parent->parent->session, digit);
1654 #endif
1655         return -1;
1656 }
1657
1658 static char *control2str(int ind) {
1659     switch (ind) {
1660         case AST_CONTROL_HANGUP:
1661             return "Other end has hungup";
1662         case AST_CONTROL_RING:
1663             return "Local ring";
1664         case AST_CONTROL_RINGING:
1665             return "Remote end is ringing";
1666         case AST_CONTROL_ANSWER:
1667             return "Remote end has answered";
1668         case AST_CONTROL_BUSY:
1669             return "Remote end is busy";
1670         case AST_CONTROL_TAKEOFFHOOK:
1671             return "Make it go off hook";
1672         case AST_CONTROL_OFFHOOK:
1673             return "Line is off hook";
1674         case AST_CONTROL_CONGESTION:
1675             return "Congestion (circuits busy)";
1676         case AST_CONTROL_FLASH:
1677             return "Flash hook";
1678         case AST_CONTROL_WINK:
1679             return "Wink";
1680         case AST_CONTROL_OPTION:
1681             return "Set a low-level option";
1682         case AST_CONTROL_RADIO_KEY:
1683             return "Key Radio";
1684         case AST_CONTROL_RADIO_UNKEY:
1685             return "Un-Key Radio";
1686                 case -1:
1687                         return "Stop tone";
1688     }
1689     return "UNKNOWN";
1690 }
1691
1692
1693 static int skinny_indicate(struct ast_channel *ast, int ind)
1694 {
1695         struct skinny_subchannel *sub = ast->pvt->pvt;
1696         struct skinny_line *l = sub->parent;
1697         struct skinnysession *s = l->parent->session;
1698
1699         if (skinnydebug) {
1700                 ast_verbose(VERBOSE_PREFIX_3 "Asked to indicate '%s' condition on channel %s\n", control2str(ind), ast->name);
1701         }
1702         switch(ind) {
1703         case AST_CONTROL_RINGING:
1704                 if (ast->_state == AST_STATE_RINGING) {
1705                         if (!sub->progress) {           
1706                                 transmit_tone(s, SKINNY_ALERT);
1707                                 transmit_callstate(s, l->instance, SKINNY_RINGOUT, sub->callid);
1708                                 sub->ringing = 1;
1709                                 break;
1710                         }
1711                 }
1712                 return -1;
1713         case AST_CONTROL_BUSY:
1714                 if (ast->_state != AST_STATE_UP) {              
1715                         transmit_tone(s, SKINNY_BUSYTONE);
1716                         transmit_callstate(s, l->instance, SKINNY_BUSY, sub->callid);
1717                         sub->alreadygone = 1;
1718                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1719                         break;
1720                 }
1721                 return -1;
1722         case AST_CONTROL_CONGESTION:
1723                 if (ast->_state != AST_STATE_UP) {              
1724                         transmit_tone(s, SKINNY_REORDER);
1725                         transmit_callstate(s, l->instance, SKINNY_CONGESTION, sub->callid);
1726                         sub->alreadygone = 1;
1727                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1728                         break;
1729                 }
1730                 return -1;
1731         case AST_CONTROL_PROGRESS:
1732                 if ((ast->_state != AST_STATE_UP) && !sub->progress && !sub->outgoing) {
1733                         transmit_callstate(s, l->instance, SKINNY_PROGRESS, sub->callid);
1734                         sub->progress = 1;
1735                         break;
1736                 }
1737                 return -1;  
1738         case -1:
1739                 transmit_tone(s, SKINNY_SILENCE);
1740                 break;          
1741         case AST_CONTROL_PROCEEDING:
1742                 break;
1743         default:
1744                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
1745                 return -1;
1746         }
1747         return 0;
1748 }
1749         
1750 static struct ast_channel *skinny_new(struct skinny_subchannel *sub, int state)
1751 {
1752         struct ast_channel *tmp;
1753         struct skinny_line *l = sub->parent;
1754         int fmt;
1755         l = sub->parent;
1756         tmp = ast_channel_alloc(1);
1757         if (tmp) {
1758                 tmp->nativeformats = l->capability;
1759                 if (!tmp->nativeformats)
1760                         tmp->nativeformats = capability;
1761                 fmt = ast_best_codec(tmp->nativeformats);
1762                 snprintf(tmp->name, sizeof(tmp->name), "Skinny/%s@%s-%d", l->name, l->parent->name, sub->callid);
1763                 if (sub->rtp)
1764                         tmp->fds[0] = ast_rtp_fd(sub->rtp);
1765                 tmp->type = type;
1766                 ast_setstate(tmp, state);
1767                 if (state == AST_STATE_RING)
1768                         tmp->rings = 1;
1769                 tmp->writeformat = fmt;
1770                 tmp->pvt->rawwriteformat = fmt;
1771                 tmp->readformat = fmt;
1772                 tmp->pvt->rawreadformat = fmt;
1773                 tmp->pvt->pvt = sub;
1774                 tmp->pvt->call = skinny_call;
1775                 tmp->pvt->hangup = skinny_hangup;
1776                 tmp->pvt->answer = skinny_answer;
1777                 tmp->pvt->read = skinny_read;
1778                 tmp->pvt->write = skinny_write;
1779                 tmp->pvt->indicate = skinny_indicate;
1780                 tmp->pvt->fixup = skinny_fixup;
1781                 tmp->pvt->send_digit = skinny_senddigit;
1782 /*              tmp->pvt->bridge = ast_rtp_bridge; */
1783                 if (!ast_strlen_zero(l->language))
1784                         strncpy(tmp->language, l->language, sizeof(tmp->language)-1);
1785                 if (!ast_strlen_zero(l->accountcode))
1786                         strncpy(tmp->accountcode, l->accountcode, sizeof(tmp->accountcode)-1);
1787                 if (l->amaflags)
1788                         tmp->amaflags = l->amaflags;
1789                 sub->owner = tmp;
1790                 ast_mutex_lock(&usecnt_lock);
1791                 usecnt++;
1792                 ast_mutex_unlock(&usecnt_lock);
1793                 ast_update_use_count();
1794                 tmp->callgroup = l->callgroup;
1795                 tmp->pickupgroup = l->pickupgroup;
1796                 strncpy(tmp->call_forward, l->call_forward, sizeof(tmp->call_forward));
1797                 strncpy(tmp->context, l->context, sizeof(tmp->context)-1);
1798                 strncpy(tmp->exten,l->exten, sizeof(tmp->exten)-1);
1799                 if (!ast_strlen_zero(l->callerid)) {
1800                         tmp->callerid = strdup(l->callerid);
1801                 }
1802                 tmp->priority = 1;
1803                 if (state != AST_STATE_DOWN) {
1804                         if (ast_pbx_start(tmp)) {
1805                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1806                                 ast_hangup(tmp);
1807                                 tmp = NULL;
1808                         }
1809                 }
1810         } else {
1811                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1812     }
1813
1814         return tmp;
1815 }
1816
1817 static int handle_message(skinny_req *req, struct skinnysession *s)
1818 {
1819         struct skinny_subchannel *sub;
1820         struct ast_channel *c;
1821         struct ast_frame f = { 0, };    
1822         struct sockaddr_in sin;
1823         struct sockaddr_in us;
1824         struct skinny_line *lines;
1825         char name[16];
1826         char addr[4];
1827         char d;
1828         int digit;
1829         int res=0;
1830         int speedDialNum;
1831         int lineNumber;
1832         int stimulus;
1833         int stimulusInstance;
1834         int status;
1835         int port;
1836         int i;
1837         time_t timer;
1838         struct tm *cmtime;
1839         pthread_t t;
1840         
1841         if ( (!s->device) && (req->e != REGISTER_MESSAGE && req->e != ALARM_MESSAGE)) {
1842                 ast_log(LOG_WARNING, "Client sent message #%d without first registering.\n", req->e);
1843                 free(req);
1844                 return 0;
1845         }
1846                 
1847         switch(req->e)  {
1848         case ALARM_MESSAGE:
1849                 /* no response necessary */
1850                 break;
1851         case REGISTER_MESSAGE:
1852                 if (skinnydebug) {
1853                         ast_verbose("Device %s is attempting to register\n", req->data.reg.name);
1854                 }
1855                 res = skinny_register(req, s);  
1856                 if (!res) {
1857                         ast_log(LOG_ERROR, "Rejecting Device %s: Device not found\n", req->data.reg.name);
1858                         memcpy(&name, req->data.reg.name, sizeof(req->data.reg.name));
1859                         memset(req, 0, sizeof(skinny_req));
1860                         req->len = sizeof(register_rej_message)+4;
1861                         req->e = REGISTER_REJ_MESSAGE;
1862                         sprintf(req->data.regrej.errMsg, "No Authority: %s", name);
1863                         transmit_response(s, req);
1864                         break;
1865                 }
1866                 if (option_verbose > 2) {
1867                         ast_verbose(VERBOSE_PREFIX_3 "Device '%s' successfuly registered\n", s->device->name); 
1868                 }
1869                 memset(req, 0, SKINNY_MAX_PACKET);
1870                 req->len = sizeof(register_ack_message)+4;
1871                 req->e = REGISTER_ACK_MESSAGE;
1872                 strcpy(req->data.regack.res, "0");
1873                 req->data.regack.keepAlive = keep_alive;
1874                 strcpy(req->data.regack.dateTemplate, date_format);     
1875                 strcpy(req->data.regack.res2, "0");
1876                 req->data.regack.secondaryKeepAlive = keep_alive;
1877                 transmit_response(s, req);
1878                 if (skinnydebug) {
1879                         ast_verbose("Requesting capabilities\n");
1880                 }
1881                 memset(req, 0, SKINNY_MAX_PACKET);
1882                 req->len = 4;
1883                 req->e = CAPABILITIES_REQ_MESSAGE;
1884                 transmit_response(s, req);
1885                 break;
1886         case UNREGISTER_MESSAGE:
1887                 /* XXX Acutally unregister the device */
1888                 break;
1889         case IP_PORT_MESSAGE:
1890                 /* no response necessary */
1891                 break;
1892         case STIMULUS_MESSAGE:
1893                 stimulus = req->data.stimulus.stimulus;
1894                 stimulusInstance = req->data.stimulus.stimulusInstance;
1895                 
1896                 switch(stimulus) {
1897                 case STIMULUS_REDIAL:
1898                         /* XXX how we gonna deal with redial ?!?! */
1899                         if (skinnydebug) {
1900                                 ast_verbose("Recieved Stimulus: Redial(%d)\n", stimulusInstance);
1901                         }
1902                         break;
1903                 case STIMULUS_SPEEDDIAL:
1904                         if (skinnydebug) {
1905                                 ast_verbose("Recieved Stimulus: SpeedDial(%d)\n", stimulusInstance);
1906                         }
1907                         break;
1908                 case STIMULUS_HOLD:
1909                         /* start moh? set RTP to 0.0.0.0? */
1910                         if (skinnydebug) {
1911                                 ast_verbose("Recieved Stimulus: Hold(%d)\n", stimulusInstance);
1912                         }
1913                         break;
1914                 case STIMULUS_TRANSFER:
1915                         if (skinnydebug) {
1916                                 ast_verbose("Recieved Stimulus: Transfer(%d)\n", stimulusInstance);
1917                         }
1918                         transmit_tone(s, SKINNY_DIALTONE);
1919                                 
1920                         /* figure out how to transfer */
1921
1922                         break;
1923                 case STIMULUS_FORWARDALL:
1924                 case STIMULUS_FORWARDBUSY:
1925                 case STIMULUS_FORWARDNOANSWER:
1926                         /* Gonna be fun, not */
1927                         if (skinnydebug) {
1928                                 ast_verbose("Recieved Stimulus: Forward (%d)\n", stimulusInstance);
1929                         }
1930                         break;
1931                 case STIMULUS_DISPLAY:
1932                         /* Not sure what this is */
1933                         if (skinnydebug) {
1934                                 ast_verbose("Recieved Stimulus: Display(%d)\n", stimulusInstance);
1935                         }
1936                         break;
1937                 case STIMULUS_LINE:
1938                         if (skinnydebug) {
1939                                 ast_verbose("Recieved Stimulus: Line(%d)\n", stimulusInstance);
1940                         }               
1941                         sub = find_subchannel_by_line(s->device->lines);
1942                         /* turn the speaker on */
1943                         transmit_speaker_mode(s, 1);  
1944                 break;
1945                 default:
1946                         ast_verbose("RECEIVED UNKNOWN STIMULUS:  %d(%d)\n", stimulus, stimulusInstance);                        
1947                         break;
1948                 }
1949                 break;
1950         case VERSION_REQ_MESSAGE:
1951                 if (skinnydebug) {
1952                         ast_verbose("Version Request\n");
1953                 }
1954                 memset(req, 0, SKINNY_MAX_PACKET);
1955                 req->len = sizeof(version_res_message)+4;
1956                 req->e = VERSION_RES_MESSAGE;
1957                 sprintf(req->data.version.version, s->device->version_id);
1958                 transmit_response(s, req);
1959                 break;
1960         case SERVER_REQUEST_MESSAGE:
1961                 if (skinnydebug) {
1962                         ast_verbose("Recieved Server Request\n");
1963                 }
1964                 memset(req, 0, SKINNY_MAX_PACKET);
1965                 req->len = sizeof(server_res_message)+4;
1966                 req->e = SERVER_RES_MESSAGE;
1967                 memcpy(req->data.serverres.server[0].serverName, ourhost, 
1968                                 sizeof(req->data.serverres.server[0].serverName));
1969                 req->data.serverres.serverListenPort[0] = ourport;
1970                 req->data.serverres.serverIpAddr[0] = __ourip.s_addr;
1971                 transmit_response(s, req);      
1972                 break;
1973         case BUTTON_TEMPLATE_REQ_MESSAGE:
1974                 if (skinnydebug) {
1975                         ast_verbose("Buttontemplate requested\n");
1976                 }
1977                 memset(req, 0, SKINNY_MAX_PACKET);
1978                 req->len = sizeof(button_template_res_message)+4;
1979                 req->e = BUTTON_TEMPLATE_RES_MESSAGE;   
1980                 req->data.buttontemplate.buttonOffset = 0;
1981                 req->data.buttontemplate.buttonCount  = 10;
1982                 req->data.buttontemplate.totalButtonCount = 10;
1983                 /* XXX Figure out how to do this correctly */
1984                 memcpy(req->data.buttontemplate.definition,
1985                            button_definition_hack, 
1986                            sizeof(req->data.buttontemplate.definition));
1987                 transmit_response(s, req);
1988                 break;
1989         case SOFT_KEY_SET_REQ_MESSAGE:
1990                 if (skinnydebug)  {
1991                         ast_verbose("Received SoftKeySetReq\n");
1992                 }
1993                 memset(req, 0, SKINNY_MAX_PACKET);
1994                 req->len = sizeof(soft_key_sets)+4;
1995                 req->e = SOFT_KEY_SET_RES_MESSAGE;
1996                 req->data.softkeysets.softKeySetOffset          = 0;
1997                 req->data.softkeysets.softKeySetCount           = 11;
1998                 req->data.softkeysets.totalSoftKeySetCount  = 11;       
1999                 /* XXX Wicked hack XXX */
2000                 memcpy(req->data.softkeysets.softKeySetDefinition, 
2001                            soft_key_set_hack, 
2002                            sizeof(req->data.softkeysets.softKeySetDefinition));
2003                 transmit_response(s,req);
2004                 break;
2005         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
2006                 if (skinnydebug) {
2007                         ast_verbose("Recieved SoftKey Template Request\n");
2008                 }
2009                 memset(req, 0, SKINNY_MAX_PACKET);
2010                 req->len = sizeof(soft_key_template)+4;
2011                 req->e = SOFT_KEY_TEMPLATE_RES_MESSAGE;
2012                 req->data.softkeytemplate.softKeyOffset         = 0;
2013                 req->data.softkeytemplate.softKeyCount          = 21;
2014                 req->data.softkeytemplate.totalSoftKeyCount = 21; 
2015                 /* XXX Another wicked hack XXX */
2016                 memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
2017                            soft_key_template_hack,
2018                            sizeof(req->data.softkeytemplate.softKeyTemplateDefinition));
2019                 transmit_response(s,req);
2020                 break;
2021         case TIME_DATE_REQ_MESSAGE:
2022                 if (skinnydebug) {
2023                         ast_verbose("Received Time/Date Request\n");
2024                 }
2025                 memset(req, 0, SKINNY_MAX_PACKET);
2026                 req->len = sizeof(definetimedate_message)+4;
2027                 req->e = DEFINETIMEDATE_MESSAGE;
2028                 timer=time(NULL);
2029                 cmtime = localtime(&timer);
2030                 req->data.definetimedate.year = cmtime->tm_year+1900;
2031                 req->data.definetimedate.month = cmtime->tm_mon+1;
2032                 req->data.definetimedate.dayofweek = cmtime->tm_wday;
2033                 req->data.definetimedate.day = cmtime->tm_mday;
2034                 req->data.definetimedate.hour = cmtime->tm_hour;
2035                 req->data.definetimedate.minute = cmtime->tm_min;
2036                 req->data.definetimedate.seconds = cmtime->tm_sec;
2037                 transmit_response(s, req);
2038                 break;
2039         case SPEED_DIAL_STAT_REQ_MESSAGE:
2040                 /* Not really sure how Speed Dial's are different than the 
2041                    Softkey templates */
2042                 speedDialNum = req->data.speeddialreq.speedDialNumber;
2043                 memset(req, 0, SKINNY_MAX_PACKET);
2044                 req->len = sizeof(speed_dial_stat_res_message)+4;
2045                 req->e = SPEED_DIAL_STAT_RES_MESSAGE;
2046 #if 0   
2047                 /* XXX Do this right XXX */     
2048                 req->data.speeddialreq.speedDialNumber = speedDialNum;
2049                 sprintf(req->data.speeddial.speedDialDirNumber, "31337");
2050                 sprintf(req->data.speeddial.speedDialDisplayName, "Asterisk Rules!");
2051 #endif          
2052                 transmit_response(s, req);
2053                 break;
2054         case LINE_STATE_REQ_MESSAGE:
2055                 lineNumber = req->data.line.lineNumber;
2056                 if (skinnydebug) {
2057                         ast_verbose("Received LineStateReq\n");
2058                 }
2059                 memset(req, 0, SKINNY_MAX_PACKET);
2060                 req->len = sizeof(line_stat_res_message)+4;
2061                 req->e = LINE_STAT_RES_MESSAGE; 
2062                 sub = find_subchannel_by_line(s->device->lines);
2063                 if (!sub) {
2064                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2065                         return 0;
2066                 }
2067                 lines = sub->parent;
2068                 ast_mutex_lock(&devicelock);
2069                 for (i=1; i < lineNumber; i++) {
2070                         lines = lines->next;
2071                 }
2072                 ast_mutex_unlock(&devicelock);
2073                 req->data.linestat.linenumber = lineNumber;             
2074                 memcpy(req->data.linestat.lineDirNumber, lines->name,
2075                                 sizeof(req->data.linestat.lineDirNumber));
2076                 memcpy(req->data.linestat.lineDisplayName, lines->label,
2077                                 sizeof(req->data.linestat.lineDisplayName)); 
2078                 transmit_response(s,req);
2079                 break;
2080         case CAPABILITIES_RES_MESSAGE:
2081                 if (skinnydebug) {
2082                         ast_verbose("Received CapabilitiesRes\n");      
2083                 }
2084                 /* XXX process the capabilites  */
2085                 break;
2086         case KEEP_ALIVE_MESSAGE:
2087                 memset(req, 0, SKINNY_MAX_PACKET);
2088                 req->len = 4;
2089                 req->e = KEEP_ALIVE_ACK_MESSAGE;
2090                 transmit_response(s, req);
2091                 break;
2092         case OFFHOOK_MESSAGE:
2093                 transmit_ringer_mode(s,SKINNY_RING_OFF);
2094                 transmit_lamp_indication(s, s->device->lines->instance, SKINNY_LAMP_ON); 
2095                 
2096                 sub = find_subchannel_by_line(s->device->lines);
2097                 if (!sub) {
2098                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2099                         return 0;
2100                 }
2101                 sub->parent->hookstate = SKINNY_OFFHOOK;
2102                 
2103                 if (sub->outgoing) {
2104                         transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2105                         transmit_tone(s, SKINNY_SILENCE);
2106                         ast_setstate(sub->owner, AST_STATE_UP);
2107                         /* XXX select the appropriate soft key here */
2108                         } else {        
2109                                 if (!sub->owner) {      
2110                                         transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2111                                         transmit_tone(s, SKINNY_DIALTONE);
2112                                         c = skinny_new(sub, AST_STATE_DOWN);                    
2113                                         if(c) {
2114                                                 /* start switch */
2115                                                 if (pthread_create(&t, NULL, skinny_ss, c)) {
2116                                                         ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
2117                                                         ast_hangup(c);
2118                                                 }
2119                                         } else {
2120                                                 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", sub->parent->name, s->device->name);
2121                                         }
2122                                 
2123                                 } else {
2124                                         ast_log(LOG_DEBUG, "Current sub [%s] already has owner\n", sub->owner->name);
2125                                 }
2126                 }
2127                 break;
2128         case ONHOOK_MESSAGE:
2129                 sub = find_subchannel_by_line(s->device->lines);
2130                 if (sub->parent->hookstate == SKINNY_ONHOOK) {
2131                         /* Somthing else already put us back on hook */ 
2132                         break;
2133                 }
2134                 sub->cxmode = SKINNY_CX_RECVONLY;
2135                 sub->parent->hookstate = SKINNY_ONHOOK;
2136                 transmit_callstate(s, s->device->lines->instance, sub->parent->hookstate,sub->callid);
2137             if (skinnydebug) {
2138                         ast_verbose("Skinny %s@%s went on hook\n",sub->parent->name, sub->parent->parent->name);
2139             }
2140             if (sub->parent->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
2141                         /* We're allowed to transfer, we have two active calls and */
2142                         /* we made at least one of the calls.  Let's try and transfer */
2143 #if 0
2144              if ((res = attempt_transfer(p)) < 0) {
2145                                  if (p->sub->next->owner) {
2146                                         sub->next->alreadygone = 1;
2147                                         ast_queue_hangup(sub->next->owner,1);
2148                                 }
2149                          } else if (res) {
2150                                     ast_log(LOG_WARNING, "Transfer attempt failed\n");
2151                                         return -1;
2152              }
2153 #endif
2154         } else {
2155            /* Hangup the current call */
2156            /* If there is another active call, skinny_hangup will ring the phone with the other call */
2157            if (sub->owner) {
2158                sub->alreadygone = 1;
2159                ast_queue_hangup(sub->owner);
2160            } else {
2161                ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n", 
2162                            sub->parent->name, sub->parent->parent->name, sub->callid);
2163            }
2164         }
2165
2166         if ((sub->parent->hookstate == SKINNY_ONHOOK) && (!sub->next->rtp)) {
2167             if (has_voicemail(sub->parent)) {
2168                 transmit_lamp_indication(s, s->device->lines->instance, SKINNY_LAMP_FLASH); 
2169             } else {
2170                 transmit_lamp_indication(s, s->device->lines->instance, SKINNY_LAMP_OFF);
2171             }
2172         }
2173         break;
2174         case KEYPAD_BUTTON_MESSAGE:
2175                 digit = req->data.keypad.button;
2176                 if (skinnydebug) {
2177                         ast_verbose("Collected digit: [%d]\n", digit);
2178                 }
2179                 f.frametype = AST_FRAME_DTMF;
2180                 if (digit == 14) {
2181                         sprintf(&d, "*");
2182                 } else if (digit == 15) {
2183                         sprintf(&d, "#");
2184                 } else {
2185                         sprintf(&d, "%d", digit);
2186                 }
2187                 f.subclass  = d;  
2188                 f.src = "skinny";
2189
2190                 sub = find_subchannel_by_line(s->device->lines);                
2191
2192                 if (sub->owner) {
2193                         /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
2194                         ast_queue_frame(sub->owner, &f);
2195                         if (sub->next->owner) {
2196                                 ast_queue_frame(sub->next->owner, &f);
2197                         }
2198                 } else {
2199                         ast_verbose("No owner: %s\n", s->device->lines->name);
2200                 }
2201                 break;
2202         case OPEN_RECIEVE_CHANNEL_ACK_MESSAGE:
2203                 ast_verbose("Recieved Open Recieve Channel Ack\n");
2204                 status = req->data.openrecievechannelack.status;
2205                 if (status) {
2206                         ast_log(LOG_ERROR, "Open Recieve Channel Failure\n");
2207                         break;
2208                 }
2209                 memcpy(addr, req->data.openrecievechannelack.ipAddr, sizeof(addr));
2210                 port = req->data.openrecievechannelack.port;
2211                                 
2212                 sin.sin_family = AF_INET;
2213                 /* I smell endian problems */
2214                 memcpy(&sin.sin_addr, addr, sizeof(sin.sin_addr));  
2215                 sin.sin_port = htons(port);
2216         
2217                 sub = find_subchannel_by_line(s->device->lines);
2218                 if (sub->rtp) {
2219                         ast_rtp_set_peer(sub->rtp, &sin);
2220                         ast_rtp_get_us(sub->rtp, &us);  
2221                 } else {
2222                         ast_log(LOG_ERROR, "No RTP structure, this is very bad\n");
2223                         break;
2224                 }
2225                 memset(req, 0, SKINNY_MAX_PACKET);
2226                 req->len = sizeof(start_media_transmission_message)+4;
2227                 req->e = START_MEDIA_TRANSMISSION_MESSAGE;
2228                 req->data.startmedia.conferenceId = 0;
2229                 req->data.startmedia.passThruPartyId = 0;
2230                 memcpy(req->data.startmedia.remoteIp, &s->device->ourip, 4); /* Endian? */
2231                 req->data.startmedia.remotePort = ntohs(us.sin_port);
2232                 req->data.startmedia.packetSize = 20;
2233                 req->data.startmedia.payloadType = convert_cap(s->device->lines->capability);
2234                 req->data.startmedia.qualifier.precedence = 127;
2235                 req->data.startmedia.qualifier.vad = 0;
2236                 req->data.startmedia.qualifier.packets = 0;
2237                 req->data.startmedia.qualifier.bitRate = 0;
2238                 transmit_response(s, req);
2239                 break;  
2240         default:
2241                 ast_verbose("RECEIVED UNKNOWN MESSAGE TYPE:  %x\n", req->e);
2242                 break;
2243         }
2244         free(req);
2245         return 1;
2246
2247 }
2248
2249 static void destroy_session(struct skinnysession *s)
2250 {
2251         struct skinnysession *cur, *prev = NULL;
2252         ast_mutex_lock(&sessionlock);
2253         cur = sessions;
2254         while(cur) {
2255                 if (cur == s)
2256                         break;
2257                 prev = cur;
2258                 cur = cur->next;
2259         }
2260         if (cur) {
2261                 if (prev)
2262                         prev->next = cur->next;
2263                 else
2264                         sessions = cur->next;
2265                 if (s->fd > -1)
2266                         close(s->fd);
2267                 ast_mutex_destroy(&s->lock);
2268                 free(s);
2269         } else
2270                 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
2271         ast_mutex_unlock(&sessionlock);
2272 }
2273
2274 static int get_input(struct skinnysession *s)  
2275 {  
2276         int res;  
2277         int dlen = 0;
2278         struct pollfd fds[1];  
2279  
2280         fds[0].fd = s->fd;
2281         fds[0].events = POLLIN;
2282         res = poll(fds, 1, -1);
2283  
2284         if (res < 0) {
2285                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
2286         } else if (res > 0) {
2287                 memset(s->inbuf,0,sizeof(s->inbuf));
2288                 res = read(s->fd, s->inbuf, 4);
2289                 if (res != 4) {
2290                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2291                         return -1;
2292                 }
2293                 dlen = *(int *)s->inbuf;
2294                 if (dlen+8 > sizeof(s->inbuf))
2295                         dlen = sizeof(s->inbuf) - 8;
2296                 res = read(s->fd, s->inbuf+4, dlen+4);
2297                 ast_mutex_unlock(&s->lock);
2298                 if (res != (dlen+4)) {
2299                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2300                         return -1;
2301                 } 
2302         }  
2303         return res;  
2304 }   
2305
2306 static skinny_req *skinny_req_parse(struct skinnysession *s)
2307 {
2308         skinny_req *req;
2309         
2310         req = malloc(SKINNY_MAX_PACKET);
2311         if (!req) {
2312                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
2313                 return NULL;
2314         }
2315         memset(req, 0, sizeof(skinny_req));
2316         /* +8 to account for reserved and length fields */
2317         memcpy(req, s->inbuf, *(int*)(s->inbuf)+8); 
2318         if (req->e < 0) {
2319                 ast_log(LOG_ERROR, "Event Message is NULL from socket %d, This is bad\n", s->fd);
2320                 free(req);
2321                 return NULL;
2322         }
2323         return req;
2324 }
2325
2326 static void *skinny_session(void *data)
2327 {
2328         int res;
2329         skinny_req *req;
2330         struct skinnysession *s = data;
2331         
2332         ast_verbose(VERBOSE_PREFIX_3 "Starting Skinny session from %s\n",  inet_ntoa(s->sin.sin_addr));
2333
2334         for (;;) {
2335                 res = 0;
2336                 res = get_input(s);
2337                 if (res < 0)
2338                         break;
2339                 req = skinny_req_parse(s);
2340                 if (!req) {
2341                         return NULL;
2342                 }
2343                 res = handle_message(req, s);
2344                 if (res < 0) {
2345                         destroy_session(s);
2346                         return NULL;
2347                 } 
2348         }
2349         ast_log(LOG_NOTICE, "Skinny Session returned: %s\n", strerror(errno));
2350         destroy_session(s);
2351         return 0;
2352 }
2353
2354 static void *accept_thread(void *ignore)
2355 {
2356         int as;
2357         struct sockaddr_in sin;
2358         int sinlen;
2359         struct skinnysession *s;
2360         struct protoent *p;
2361         int arg = 1;
2362         pthread_attr_t attr;
2363
2364         pthread_attr_init(&attr);
2365         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2366
2367         for (;;) {
2368                 sinlen = sizeof(sin);
2369                 as = accept(skinnysock, (struct sockaddr *)&sin, &sinlen);
2370                 if (as < 0) {
2371                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
2372                         continue;
2373                 }
2374                 p = getprotobyname("tcp");
2375                 if(p) {
2376                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
2377                                 ast_log(LOG_WARNING, "Failed to set Skinny tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
2378                         }
2379                 }
2380                 s = malloc(sizeof(struct skinnysession));
2381                 if (!s) {
2382                         ast_log(LOG_WARNING, "Failed to allocate Skinny session: %s\n", strerror(errno));
2383                         continue;
2384                 } 
2385                 memset(s, 0, sizeof(struct skinnysession));
2386                 memcpy(&s->sin, &sin, sizeof(sin));
2387                 ast_mutex_init(&s->lock);
2388                 s->fd = as;
2389                 ast_mutex_lock(&sessionlock);
2390                 s->next = sessions;
2391                 sessions = s;
2392                 ast_mutex_unlock(&sessionlock);
2393                 
2394                 if (pthread_create(&tcp_thread, NULL, skinny_session, s)) {
2395                         destroy_session(s);
2396                 }
2397         }
2398         
2399         
2400         if (skinnydebug) {
2401                 ast_verbose("killing accept thread\n");
2402         }
2403         close(as);
2404         return 0;
2405 }
2406
2407 static void *do_monitor(void *data)
2408 {
2409         int res;
2410
2411         /* This thread monitors all the interfaces which are not yet in use
2412            (and thus do not have a separate thread) indefinitely */
2413         /* From here on out, we die whenever asked */
2414         for(;;) {
2415                 pthread_testcancel();
2416                 /* Wait for sched or io */
2417                 res = ast_sched_wait(sched);
2418                 if ((res < 0) || (res > 1000)) {
2419                         res = 1000;
2420                 }
2421                 res = ast_io_wait(io, res);
2422                 ast_mutex_lock(&monlock);
2423                 if (res >= 0) {
2424                         ast_sched_runq(sched);
2425                 }
2426                 ast_mutex_unlock(&monlock);
2427         }
2428         /* Never reached */
2429         return NULL;
2430         
2431 }
2432
2433 static int restart_monitor(void)
2434 {
2435         /* If we're supposed to be stopped -- stay stopped */
2436         if (monitor_thread == AST_PTHREADT_STOP)
2437                 return 0;
2438         if (ast_mutex_lock(&monlock)) {
2439                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
2440                 return -1;
2441         }
2442         if (monitor_thread == pthread_self()) {
2443                 ast_mutex_unlock(&monlock);
2444                 ast_log(LOG_WARNING, "Cannot kill myself\n");
2445                 return -1;
2446         }
2447         if (monitor_thread != AST_PTHREADT_NULL) {
2448                 /* Wake up the thread */
2449                 pthread_kill(monitor_thread, SIGURG);
2450         } else {
2451                 /* Start a new monitor */
2452                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
2453                         ast_mutex_unlock(&monlock);
2454                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
2455                         return -1;
2456                 }
2457         }
2458         ast_mutex_unlock(&monlock);
2459         return 0;
2460 }
2461
2462 static struct ast_channel *skinny_request(char *type, int format, void *data)
2463 {
2464         int oldformat;
2465         struct skinny_subchannel *sub;
2466         struct ast_channel *tmpc = NULL;
2467         char tmp[256];
2468         char *dest = data;
2469
2470         oldformat = format;
2471         format &= capability;
2472         if (!format) {
2473                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
2474                 return NULL;
2475         }
2476         
2477         strncpy(tmp, dest, sizeof(tmp) - 1);
2478         if (ast_strlen_zero(tmp)) {
2479                 ast_log(LOG_NOTICE, "Skinny channels require a device\n");
2480                 return NULL;
2481         }
2482         
2483         sub = find_subchannel_by_name(tmp);  
2484         if (!sub) {
2485                 ast_log(LOG_NOTICE, "No available lines on: %s\n", dest);
2486                 return NULL;
2487         }
2488         
2489         if (option_verbose > 2) {
2490                 ast_verbose(VERBOSE_PREFIX_3 "skinny_request(%s)\n", tmp);
2491                 ast_verbose(VERBOSE_PREFIX_3 "Skinny cw: %d, dnd: %d, so: %d, sno: %d\n", 
2492                         sub->parent->callwaiting, sub->parent->dnd, sub->owner ? 1 : 0, sub->next->owner ? 1: 0);
2493         }
2494         tmpc = skinny_new(sub->owner ? sub->next : sub, AST_STATE_DOWN);
2495         if (!tmpc) {
2496                 ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
2497         }
2498         restart_monitor();
2499
2500         /* and finish */        
2501         return tmpc;
2502 }
2503
2504 static int reload_config(void)
2505 {
2506         int on=1;
2507         struct ast_config *cfg;
2508         struct ast_variable *v;
2509         int format;
2510         char *cat;
2511         struct skinny_device *d;
2512         int oldport = ntohs(bindaddr.sin_port);
2513
2514 #if 0           
2515         hp = ast_gethostbyname(ourhost, &ahp);
2516         if (!hp) {
2517                 ast_log(LOG_WARNING, "Unable to get hostname, Skinny disabled\n");
2518                 return 0;
2519         }
2520 #endif
2521         cfg = ast_load(config);
2522
2523         /* We *must* have a config file otherwise stop immediately */
2524         if (!cfg) {
2525                 ast_log(LOG_NOTICE, "Unable to load config %s, Skinny disabled\n", config);
2526                 return 0;
2527         }
2528
2529         /* load the general section */
2530         memset(&bindaddr, 0, sizeof(bindaddr));
2531         v = ast_variable_browse(cfg, "general");
2532         while(v) {
2533                 /* Create the interface list */
2534                 if (!strcasecmp(v->name, "bindaddr")) {
2535                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
2536                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2537                         } else {
2538                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2539                         }
2540                 } else if (!strcasecmp(v->name, "keepAlive")) {
2541                         keep_alive = atoi(v->value);            
2542                 } else if (!strcasecmp(v->name, "dateFormat")) {
2543                         strncpy(date_format, v->value, sizeof(date_format) - 1);        
2544                 } else if (!strcasecmp(v->name, "allow")) {
2545                         format = ast_getformatbyname(v->value);
2546                         if (format < 1) 
2547                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
2548                         else
2549                                 capability |= format;
2550                 } else if (!strcasecmp(v->name, "disallow")) {
2551                         format = ast_getformatbyname(v->value);
2552                         if (format < 1) 
2553                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
2554                         else
2555                                 capability &= ~format;
2556                 } else if (!strcasecmp(v->name, "port")) {
2557                         if (sscanf(v->value, "%i", &ourport) == 1) {
2558                                 bindaddr.sin_port = htons(ourport);
2559                         } else {
2560                                 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
2561                         }
2562                 }
2563                 v = v->next;
2564         }
2565
2566         if (ntohl(bindaddr.sin_addr.s_addr)) {
2567                 memcpy(&__ourip, &bindaddr.sin_addr, sizeof(__ourip));
2568         } else {
2569                 hp = ast_gethostbyname(ourhost, &ahp);
2570                 if (!hp) {
2571                         ast_log(LOG_WARNING, "Unable to get our IP address, Skinny disabled\n");
2572                         ast_destroy(cfg);
2573                         return 0;
2574                 }
2575                 memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
2576         }
2577         if (!ntohs(bindaddr.sin_port)) {
2578                 bindaddr.sin_port = ntohs(DEFAULT_SKINNY_PORT);
2579         }
2580         bindaddr.sin_family = AF_INET;
2581         
2582         /* load the device sections */
2583         cat = ast_category_browse(cfg, NULL);
2584         while(cat) {
2585                 if (strcasecmp(cat, "general")) {
2586                         d = build_device(cat, ast_variable_browse(cfg, cat));
2587                         if (d) {
2588                                 if (option_verbose > 2) {
2589                                         ast_verbose(VERBOSE_PREFIX_3 "Added device '%s'\n", d->name);
2590                 }
2591                                 ast_mutex_lock(&devicelock);
2592                                 d->next = devices;
2593                                 devices = d;
2594                                 ast_mutex_unlock(&devicelock);
2595                         }
2596                 }
2597                 cat = ast_category_browse(cfg, cat);
2598         }
2599         ast_mutex_lock(&netlock);
2600         if ((skinnysock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
2601                 close(skinnysock);
2602                 skinnysock = -1;
2603         }
2604         if (skinnysock < 0) {
2605                 skinnysock = socket(AF_INET, SOCK_STREAM, 0);
2606                 if(setsockopt(skinnysock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
2607                         ast_log(LOG_ERROR, "Set Socket Options failed: errno %d, %s", errno, strerror(errno));
2608                         ast_destroy(cfg);
2609                         return 0;
2610                 }
2611
2612                 if (skinnysock < 0) {
2613                         ast_log(LOG_WARNING, "Unable to create Skinny socket: %s\n", strerror(errno));
2614                 } else {
2615                         if (bind(skinnysock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
2616                                 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
2617                                                 inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
2618                                                         strerror(errno));
2619                                 close(skinnysock);
2620                                 skinnysock = -1;
2621                                 ast_destroy(cfg);
2622                                 return 0;
2623                         } 
2624
2625                         if (listen(skinnysock,DEFAULT_SKINNY_BACKLOG)) {
2626                                         ast_log(LOG_WARNING, "Failed to start listening to %s:%d: %s\n",
2627                                                 inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
2628                                                         strerror(errno));
2629                                         close(skinnysock);
2630                                         skinnysock = -1;
2631                                         ast_destroy(cfg);
2632                                         return 0;
2633                         }
2634                 
2635                         if (option_verbose > 1)
2636                                 ast_verbose(VERBOSE_PREFIX_2 "Skinny listening on %s:%d\n", 
2637                                         inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
2638
2639                         pthread_create(&accept_t,NULL, accept_thread, NULL);
2640                 }
2641         }
2642         ast_mutex_unlock(&netlock);
2643
2644         /* and unload the configuration when were done */
2645         ast_destroy(cfg);
2646
2647         return 0;
2648 }
2649
2650 #if 0
2651 void delete_devices(void)
2652 {
2653         struct skinny_device *d, *dlast;
2654         struct skinny_line *l, *llast;
2655         struct skinny_subchannel *sub, *slast;
2656         
2657         ast_mutex_lock(&devicelock);
2658         
2659         /* Delete all devices */
2660         for (d=devices;d;) {
2661                 
2662                 /* Delete all lines for this device */
2663                 for (l=d->lines;l;) {
2664                         /* Delete all subchannels for this line */
2665                         for (sub=l->sub;sub;) {
2666                                 slast = sub;
2667                                 sub = sub->next;
2668                                 ast_mutex_destroy(&slast->lock);
2669                                 free(slast);
2670                         }
2671                         llast = l;
2672                         l = l->next;
2673                         ast_mutex_destroy(&llast->lock);
2674                         free(llast);
2675                 }
2676                 dlast = d;
2677                 d = d->next;
2678                 free(dlast);
2679         }
2680         devices=NULL;
2681         ast_mutex_unlock(&devicelock);
2682 }
2683 #endif
2684
2685 int reload(void)
2686 {
2687 #if 0
2688 // XXX Causes Seg
2689
2690         delete_devices();
2691         reload_config();
2692         restart_monitor();
2693 #endif
2694         return 0;
2695 }
2696
2697
2698 int load_module()
2699 {
2700         int res = 0;
2701
2702         /* load and parse config */
2703         res = reload_config();
2704         
2705         /* Announce our presence to Asterisk */ 
2706         if (!res) {
2707                 /* Make sure we can register our skinny channel type */
2708                 if (ast_channel_register(type, tdesc, capability, skinny_request)) {
2709                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
2710                         return -1;
2711                 }
2712         }
2713         skinny_rtp.type = type;
2714         ast_rtp_proto_register(&skinny_rtp);
2715         ast_cli_register(&cli_show_lines);
2716         ast_cli_register(&cli_debug);
2717         ast_cli_register(&cli_no_debug);
2718         sched = sched_context_create();
2719         if (!sched) {
2720                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2721         }
2722         io = io_context_create();
2723         if (!io) {
2724                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2725         }
2726         /* And start the monitor for the first time */
2727         restart_monitor();
2728         return res;
2729 }
2730
2731 int unload_module()
2732 {
2733 #if 0
2734         struct skinny_session *session, s;
2735         struct skinny_subchannel *sub;
2736         struct skinny_line *line = session;
2737
2738         /* close all IP connections */
2739         if (!ast_mutex_lock(&devicelock)) {
2740                 /* Terminate tcp listener thread */
2741                 
2742
2743         } else {
2744                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2745                 return -1;
2746         }
2747         if (!ast_mutex_lock(&monlock)) {
2748                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
2749                         pthread_cancel(monitor_thread);
2750                         pthread_kill(monitor_thread, SIGURG);
2751                         pthread_join(monitor_thread, NULL);
2752                 }
2753                 monitor_thread = AST_PTHREADT_STOP;
2754                 ast_mutex_unlock(&monlock);
2755         } else {
2756                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2757                 return -1;
2758         }
2759         if (!ast_mutex_lock(&iflock)) {
2760                 /* Destroy all the interfaces and free their memory */
2761                 p = iflist;
2762                 while(p) {
2763                         pl = p;
2764                         p = p->next;
2765                         /* Free associated memory */
2766                         ast_mutex_destroy(&pl->lock);
2767                         free(pl);
2768                 }
2769                 iflist = NULL;
2770                 ast_mutex_unlock(&iflock);
2771         } else {
2772                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2773                 return -1;
2774         }
2775
2776         ast_rtp_proto_register(&skinny_rtp);
2777         ast_cli_register(&cli_show_lines);
2778         ast_cli_register(&cli_debug);
2779         ast_cli_register(&cli_no_debug);
2780
2781         return 0;
2782 #endif
2783         return -1;
2784 }
2785
2786 int usecount()
2787 {
2788         int res;
2789         ast_mutex_lock(&usecnt_lock);
2790         res = usecnt;
2791         ast_mutex_unlock(&usecnt_lock);
2792         return res;
2793 }
2794
2795 char *key()
2796 {
2797         return ASTERISK_GPL_KEY;
2798 }
2799
2800 char *description()
2801 {
2802         return desc;
2803 }