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