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