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