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