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