Fix monitor thread issue.
[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 #define SOFT_KEY_TEMPLATE_RES_MESSAGE 0x0108
322 static const char *soft_key_template_hack = {
323         "\x52\x65\x64\x69\x61\x6c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
324         "\x01\x00\x00\x00\x4e\x65\x77\x43\x61\x6c\6c\\x00\x00\x00\x00\x00"
325         "\x00\x00\x00\x00\x02\x00\x00\x00\x48\x6f\x6c\x64\x00\x00\x00\x00"
326         "\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x54\x72\x6e\x73"
327         "\x66\x65\x72\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00"
328         "\x43\x46\x77\x64\x41\x6c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05"
329         "\x00\x00\x00\x43\x46\x77\x64\x20\x42\x75\x73\x79\x00\x00\x00\x00"
330         "\x00\x00\x00\x06\x00\x00\x00\x43\x46\x77\x64\x4e\x6f\x41\x6e\x73"
331         "\x77\x65\x72\x00\x00\x00\x00\x07\x00\x00\x00\x3c\x3c\x00\x00\x00"
332         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x45"
333         "\x6e\x64\x43\x61\x6c\x6c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x09"
334         "\x00\x00\x00\x52\x65\x73\x75\x6d\x65\x00\x00\x00\x00\x00\x00\x00"
335         "\x00\x00\x0a\x00\x00\x00\x41\x6e\x73\x77\x65\x72\x00\x00\x00\x00"
336         "\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00\x49\x6e\x66\x6f\x00\x00"
337         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x43\x6f"
338         "\x6e\x66\x72\x6e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0d\x00\x00"
339         "\x00\x50\x61\x72\x6b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
340         "\x00\x0e\x00\x00\x00\x4a\x6f\x69\x6e\x00\x00\x00\x00\x00\x00\x00"
341         "\x00\x00\x00\x00\x0f\x00\x00\x00\x4d\x65\x65\x74\x4d\x65\x00\x00"
342         "\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00\x50\x69\x63\x6b"
343         "\x55\x70\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11\x00\x00\x00"
344         "\x47\x50\x69\x63\x6b\x55\x70\x00\x00\x00\x00\x00\x00\x00\x00\x00"
345         "\x12\x00\x00\x00\x52\x6d\x4c\x73\x43\x00\x00\x00\x00\x00\x00\x00"
346         "\x00\x00\x00\x13\x00\x00\x00\x42\x61\x72\x67\x65\x00\x00\x00\x00"
347         "\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x42\x61\x72\x67\x65"
348         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x15\x00\x00\x00"
349 };
350
351 typedef struct soft_key_template_definition {
352         char softKeyLabel[16];
353         int softKeyEvent;
354 } soft_key_template_definition;
355
356 typedef struct soft_key_template {
357         int softKeyOffset;
358         int softKeyCount;
359         int totalSoftKeyCount;
360     soft_key_template_definition softKeyTemplateDefinition[32];
361 } soft_key_template;
362
363 #define SOFT_KEY_SET_RES_MESSAGE 0x0109
364 static const char *soft_key_set_hack = {
365         "\x01\x02\x05\x03\x09\x0a\x0b\x10\x11\x12\x04\x0e\x0d\x00\x00\x00"
366         "\x2d\x01\x2e\x01\x31\x01\x2f\x01\x35\x01\x36\x01\x37\x01\x3c\x01"
367         "\x3d\x01\x3e\x01\x30\x01\x3a\x01\x39\x01\x00\x00\x00\x00\x00\x00"
368         "\x03\x09\x04\x0e\x0d\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
369         "\x2f\x01\x35\x01\x30\x01\x3a\x01\x39\x01\x3f\x01\x00\x00\x00\x00"
370         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
371         "\x0a\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
372         "\x36\x01\x2e\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
373         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
374         "\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
375         "\x37\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
376         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
377         "\x01\x09\x05\x10\x11\x12\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
378         "\x2d\x01\x35\x01\x31\x01\x3c\x01\x3d\x01\x3e\x01\x00\x00\x00\x00"
379         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
380         "\x00\x09\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
381         "\x00\x00\x35\x01\x30\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
382         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
383         "\x08\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
384         "\x34\x01\x35\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
385         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
386         "\x00\x09\x0d\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
387         "\x00\x00\x35\x01\x39\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
388         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
389         "\x00\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
390         "\x00\x00\x35\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
391         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
392         "\x01\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
393         "\x2d\x01\x35\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
394         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
395         "\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
396         "\x41\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
397         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
398 };
399
400 typedef struct soft_key_set_definition {
401         UINT8  softKeyTemplateIndex[16];
402         UINT16 softKeyInfoIndex[16];
403 } soft_key_set_definition;
404
405 typedef struct soft_key_sets {
406         UINT32 softKeySetOffset;
407         UINT32 softKeySetCount;
408         UINT32 totalSoftKeySetCount;
409         soft_key_set_definition softKeySetDefinition[16];
410         UINT32 res;
411 } soft_key_sets;
412
413 #define SELECT_SOFT_KEYS_MESSAGE 0x0110
414 typedef struct select_soft_keys_message {
415         int instance;
416         int reference;
417         int softKeySetIndex;
418         int validKeyMask;
419 } select_soft_keys_message;
420
421 #define CALL_STATE_MESSAGE 0x0111
422 typedef struct call_state_message {
423         int callState;
424         int lineInstance;
425         int callReference;
426 } call_state_message;
427
428 #define ACTIVATE_CALL_PLANE_MESSAGE 0x0116
429 typedef struct activate_call_plane_message {
430         int lineInstance;
431 } activate_call_plane_message;
432
433 /* packet composition */
434 typedef struct {
435         int len;
436         int res;
437         int e;
438         union {
439                 speed_dial_stat_req_message speeddialreq;
440                 register_message reg;
441                 register_ack_message regack;
442                 register_rej_message regrej;
443                 capabilities_res_message caps;
444                 version_res_message version;
445                 button_template_res_message buttontemplate;
446                 displaytext_message displaytext;
447                 definetimedate_message definetimedate;
448                 start_tone_message starttone;
449                 speed_dial_stat_res_message speeddial;
450                 line_state_req_message line;
451                 line_stat_res_message linestat;
452                 soft_key_sets softkeysets;
453                 soft_key_template softkeytemplate;
454                 server_res_message serverres;
455                 set_lamp_message setlamp;
456                 set_ringer_message setringer;
457                 call_state_message callstate;
458                 keypad_button_message keypad;
459                 select_soft_keys_message selectsoftkey;
460                 activate_call_plane_message activatecallplane;
461                 stimulus_message stimulus;
462                 set_speaker_message setspeaker;
463                 call_info_message callinfo;
464                 start_media_transmission_message startmedia;
465                 stop_media_transmission_message stopmedia;
466                 open_recieve_channel_message openrecievechannel;
467                 open_recieve_channel_ack_message openrecievechannelack;
468                 close_recieve_channel_message closerecievechannel;
469         } data;
470 } skinny_req;
471
472 /************************************************************************************/
473 /*                            Asterisk specific globals                             */
474 /************************************************************************************/
475
476 static int skinnydebug = 1;     /* XXX for now, enable debugging default */
477
478 /* a hostname, portnumber, socket and such is usefull for VoIP protocols */
479 static struct sockaddr_in bindaddr;
480 static char ourhost[256];
481 static int ourport;
482 static struct in_addr __ourip;
483 struct hostent *hp;
484 static int skinnysock  = -1;
485 static pthread_t tcp_thread;
486 static pthread_t accept_t;
487 static char context[AST_MAX_EXTENSION] = "default";
488 static char language[MAX_LANGUAGE] = "";
489 static char musicclass[MAX_LANGUAGE] = "";
490 static char callerid[AST_MAX_EXTENSION] = "";
491 static char linelabel[AST_MAX_EXTENSION] ="";
492 static int nat = 0;
493 static unsigned int cur_callergroup = 0;
494 static unsigned int cur_pickupgroup = 0;
495 static int immediate = 0;
496 static int callwaiting = 0;
497 static int callreturn = 0;
498 static int threewaycalling = 0;
499 /* This is for flashhook transfers */
500 static int transfer = 0;
501 static int cancallforward = 0;
502 /*static int busycount = 3;*/
503 static char accountcode[20] = "";
504 static char mailbox[AST_MAX_EXTENSION];
505 static int amaflags = 0;
506 static int callnums = 1;
507
508
509 #define SUB_REAL 0
510 #define SUB_ALT  1
511 #define MAX_SUBS 2
512
513 #define SKINNY_SPEAKERON 1
514 #define SKINNY_SPEAKEROFF 2
515
516 #define SKINNY_OFFHOOK 1
517 #define SKINNY_ONHOOK 2
518 #define SKINNY_RINGOUT 3
519 #define SKINNY_RINGIN 4
520 #define SKINNY_CONNECTED 5
521 #define SKINNY_BUSY 6
522 #define SKINNY_CONGESTION 7
523 #define SKINNY_HOLD 8
524 #define SKINNY_CALLWAIT 9
525 #define SKINNY_TRANSFER 10
526 #define SKINNY_PARK 11
527 #define SKINNY_PROGRESS 12
528 #define SKINNY_INVALID 14
529
530 #define SKINNY_SILENCE 0
531 #define SKINNY_DIALTONE 33
532 #define SKINNY_BUSYTONE 35
533 #define SKINNY_ALERT 36
534 #define SKINNY_REORDER 37
535 #define SKINNY_CALLWAITTONE 45
536
537 #define SKINNY_LAMP_OFF 1
538 #define SKINNY_LAMP_ON  2
539 #define SKINNY_LAMP_WINK 3
540 #define SKINNY_LAMP_FLASH 4
541 #define SKINNY_LAMP_BLINK 5
542
543 #define SKINNY_RING_OFF 1
544 #define SKINNY_RING_INSIDE 2
545 #define SKINNY_RING_OUTSIDE 3
546 #define SKINNY_RING_FEATURE 4
547
548 #define TYPE_TRUNK              1
549 #define TYPE_LINE               2
550
551 #define STIMULUS_REDIAL 1
552 #define STIMULUS_SPEEDDIAL 2
553 #define STIMULUS_HOLD 3
554 #define STIMULUS_TRANSFER 4
555 #define STIMULUS_FORWARDALL 5
556 #define STIMULUS_FORWARDBUSY 6
557 #define STIMULUS_FORWARDNOANSWER 7
558 #define STIMULUS_DISPLAY 8
559 #define STIMULUS_LINE 9
560
561 /* Skinny rtp stream modes */
562 #define SKINNY_CX_SENDONLY 0
563 #define SKINNY_CX_RECVONLY 1
564 #define SKINNY_CX_SENDRECV 2
565 #define SKINNY_CX_CONF     3
566 #define SKINNY_CX_CONFERENCE 3
567 #define SKINNY_CX_MUTE     4
568 #define SKINNY_CX_INACTIVE 4
569
570 #if 0
571 static char *skinny_cxmodes[] = {
572     "sendonly",
573     "recvonly",
574     "sendrecv",
575     "confrnce",
576     "inactive"
577 };
578 #endif
579
580 /* driver scheduler */
581 static struct sched_context *sched;
582 static struct io_context *io;
583
584 /* usage count and locking */
585 static int usecnt = 0;
586 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
587
588 /* Protect the monitoring thread, so only one process can kill or start it, and not
589    when it's doing something critical. */
590 static ast_mutex_t monlock         = AST_MUTEX_INITIALIZER;
591 /* Protect the network socket */
592 static ast_mutex_t netlock         = AST_MUTEX_INITIALIZER;
593 /* Protect the session list */
594 static ast_mutex_t sessionlock = AST_MUTEX_INITIALIZER;
595 /* Protect the device list */
596 static ast_mutex_t devicelock = AST_MUTEX_INITIALIZER;
597
598 /* This is the thread for the monitor which checks for input on the channels
599    which are not currently in use.  */
600 static pthread_t monitor_thread = 0;
601
602 /* Wait up to 16 seconds for first digit */
603 static int firstdigittimeout = 16000;
604
605 /* How long to wait for following digits */
606 static int gendigittimeout = 8000;
607
608 /* How long to wait for an extra digit, if there is an ambiguous match */
609 static int matchdigittimeout = 3000;
610
611 struct skinny_subchannel {
612         ast_mutex_t lock;
613         unsigned int callid;
614         struct ast_channel *owner;
615         struct skinny_line *parent;
616         struct ast_rtp *rtp;
617         time_t lastouttime;
618         int lastout;
619         int cxmode;
620         int nat;
621         int outgoing;
622         int alreadygone;
623         struct skinny_subchannel *next; /* for our circular linked list */
624 };
625
626 struct skinny_line {
627         ast_mutex_t lock;
628         char name[80];
629         char label[42];                                                 /* Label that shows next to the line buttons */
630         struct skinny_subchannel *sub;                  /* pointer to our current connection, channel and stuff */
631         char accountcode[80];
632         char exten[AST_MAX_EXTENSION];                  /* Extention where to start */
633         char context[AST_MAX_EXTENSION];
634         char language[MAX_LANGUAGE];
635         char callerid[AST_MAX_EXTENSION];               /* Caller*ID */
636         char lastcallerid[AST_MAX_EXTENSION];   /* Last Caller*ID */
637         char call_forward[AST_MAX_EXTENSION];   
638         char mailbox[AST_MAX_EXTENSION];
639         char musicclass[MAX_LANGUAGE];
640         int curtone;                                            /* Current tone */
641         unsigned int callgroup;
642         unsigned int pickupgroup;
643         int callwaiting;
644         int transfer;
645         int threewaycalling;
646         int cancallforward;
647         int callreturn;
648         int dnd; /* How does this affect callwait?  Do we just deny a skinny_request if we're dnd? */
649         int hascallerid;
650         int hidecallerid;
651         int amaflags;
652         int type;
653         int instance;
654         int group;
655         int needdestroy;
656         int capability;
657         int nonCodecCapability;
658         int onhooktime;
659         int msgstate;           /* voicemail message state */
660         int immediate;
661         int hookstate;
662         int progress;
663         struct skinny_line *next;
664         struct skinny_device *parent;
665 };
666
667 static struct skinny_device {
668         /* A device containing one or more lines */
669         char name[80];
670         char id[16];
671         char version_id[16];    
672         int type;
673         int registered;
674         struct sockaddr_in addr;
675         struct in_addr ourip;
676         struct skinny_line *lines;
677         struct ast_ha *ha;
678         struct skinnysession *session;
679         struct skinny_device *next;
680 } *devices = NULL;
681
682 struct skinnysession {
683         pthread_t t;
684         ast_mutex_t lock;
685         struct sockaddr_in sin;
686         int fd;
687         char inbuf[SKINNY_MAX_PACKET];
688         struct skinny_device *device;
689         struct skinnysession *next;
690 } *sessions = NULL;
691
692 static skinny_req *req_alloc(size_t size)
693 {
694         skinny_req *req;
695         req = malloc(size+12);
696         if (!req) {
697                 return NULL;
698         }       
699         memset(req, 0, size+12);
700         return req;
701 }
702
703 static struct skinny_subchannel *find_subchannel_by_line(struct skinny_line *l)
704 {
705         /* Need to figure out how to determine which sub we want */
706         
707         struct skinny_subchannel *sub = l->sub;
708         return sub;
709 }
710
711 static struct skinny_subchannel *find_subchannel_by_name(char *dest)
712 {
713         struct skinny_line *l;
714         struct skinny_device *d;
715         char line[256];
716         char *at;
717         char *device;
718         
719         strncpy(line, dest, sizeof(line) - 1);
720         at = strchr(line, '@');
721         if (!at) {
722                 ast_log(LOG_NOTICE, "Device '%s' has no @ (at) sign!\n", dest);
723                 return NULL;
724         }
725         *at = '\0';
726         at++;
727         device = at;
728         ast_mutex_lock(&devicelock);
729         d = devices;
730         while(d) {
731                 if (!strcasecmp(d->name, device)) {
732                         if (skinnydebug) {
733                                 printf("Found device: %s\n", d->name);
734                         }
735                         /* Found the device */
736                         l = d->lines;
737                         while (l) {
738                                 /* Search for the right line */
739                                 if (!strcasecmp(l->name, line)) {
740                                         ast_mutex_unlock(&devicelock);
741                                         return l->sub;
742                                 }
743                                 l = l->next;
744                         }
745                 }
746                 d = d->next;
747         }
748         /* Device not found*/
749         ast_mutex_unlock(&devicelock);
750         return NULL;
751 }
752
753 static int transmit_response(struct skinnysession *s, skinny_req *req)
754 {
755         int res = 0;
756         ast_mutex_lock(&s->lock);
757 #if 0
758         printf("writing packet type %d (%d bytes) to socket %d\n", req->e, req->len+8, s->fd);
759 #endif
760         res = write(s->fd, req, req->len+8);
761         if (res != req->len+8) {
762                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, req->len+8, strerror(errno));
763         }
764         ast_mutex_unlock(&s->lock);
765         return 1;
766 }
767
768 /* XXX Do this right*/
769 static int convert_cap(int capability)
770 {
771         return 4; // ulaw (this is not the same as asterisk's '4'  :) 
772
773 }
774
775 static void transmit_speaker_mode(struct skinnysession *s, int mode)
776 {
777         skinny_req *req;
778
779         req = req_alloc(sizeof(struct set_speaker_message));
780         if (!req) {
781                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
782                 return;
783         }
784         req->len = sizeof(set_speaker_message)+4;
785         req->e = SET_SPEAKER_MESSAGE;
786         req->data.setspeaker.mode = mode; 
787         transmit_response(s, req);
788 }
789
790 static void transmit_callstate(struct skinnysession *s, int instance, int state, unsigned callid)
791
792         skinny_req *req;
793         int memsize = sizeof(struct call_state_message);
794
795         req = req_alloc(memsize);
796         if (!req) {
797                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
798                 return;
799         }       
800         if (state == SKINNY_ONHOOK) {
801                 transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
802         }
803         req->len = sizeof(call_state_message)+4;
804         req->e = CALL_STATE_MESSAGE;
805         req->data.callstate.callState = state;
806         req->data.callstate.lineInstance = instance;
807         req->data.callstate.callReference = callid;
808         transmit_response(s, req);
809         if (state == SKINNY_OFFHOOK) {
810                 memset(req, 0, memsize);
811                 req->len = sizeof(activate_call_plane_message)+4;
812                 req->e = ACTIVATE_CALL_PLANE_MESSAGE;
813                 req->data.activatecallplane.lineInstance = instance;
814                 transmit_response(s, req);
815         } else if (state == SKINNY_ONHOOK) {
816                 memset(req, 0, memsize);
817                 req->len = sizeof(activate_call_plane_message)+4;
818                 req->e = ACTIVATE_CALL_PLANE_MESSAGE;
819                 req->data.activatecallplane.lineInstance = 0;
820                 transmit_response(s, req);
821                 memset(req, 0, memsize);
822                 req->len = sizeof(close_recieve_channel_message)+4;
823                 req->e = CLOSE_RECIEVE_CHANNEL_MESSAGE;
824                 req->data.closerecievechannel.conferenceId = 0;
825                 req->data.closerecievechannel.partyId = 0;
826                 transmit_response(s, req);
827                 memset(req, 0, memsize);
828                 req->len = sizeof(stop_media_transmission_message)+4;
829                 req->e = STOP_MEDIA_TRANSMISSION_MESSAGE;
830                 req->data.stopmedia.conferenceId = 0;   
831                 req->data.stopmedia.passThruPartyId = 0;
832                 transmit_response(s, req);      
833         }
834 }       
835
836 static void transmit_connect(struct skinnysession *s)
837 {
838         skinny_req *req;
839         struct skinny_line *l = s->device->lines;
840
841         req = req_alloc(sizeof(struct open_recieve_channel_message));
842         if (!req) {
843                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
844                 return;
845         }       
846         req->len = sizeof(struct call_info_message);
847         req->e = OPEN_RECIEVE_CHANNEL_MESSAGE;
848         req->data.openrecievechannel.conferenceId = 0;
849         req->data.openrecievechannel.partyId = 0;
850         req->data.openrecievechannel.packets = 20;
851         req->data.openrecievechannel.capability = convert_cap(l->capability); 
852         req->data.openrecievechannel.echo = 0;
853         req->data.openrecievechannel.bitrate = 0;
854         transmit_response(s, req);
855 }       
856
857 static void transmit_tone(struct skinnysession *s, int tone)
858 {
859         skinny_req *req;
860
861         if (tone > 0)
862                 req = req_alloc(sizeof(struct start_tone_message));
863         else 
864                 req = req_alloc(4);
865         if (!req) {
866                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
867                 return;
868         }       
869         if (tone > 0) {
870                 req->len = sizeof(start_tone_message)+4;
871                 req->e = START_TONE_MESSAGE;
872                 req->data.starttone.tone = tone; // da tone
873         } else {
874                 req->len = 4;
875                 req->e = STOP_TONE_MESSAGE;
876         }
877         transmit_response(s, req);
878 }
879
880 #if 0
881 static void transmit_selectsoftkeys(struct skinnysession *s, int instance, int callid, int softkey)
882 {
883         skinny_req *req;
884         int memsize = sizeof(struct select_soft_keys_message);
885
886         req = req_alloc(memsize);
887         if (!req) {
888                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
889                 return;
890         }       
891         memset(req, 0, memsize);
892         req->len = sizeof(select_soft_keys_message)+4;
893         req->e = SELECT_SOFT_KEYS_MESSAGE;
894         req->data.selectsoftkey.instance = instance;
895         req->data.selectsoftkey.reference = callid;
896         req->data.selectsoftkey.softKeySetIndex = softkey;
897         transmit_response(s, req);
898 }
899 #endif
900
901 static void transmit_lamp_indication(struct skinnysession *s, int instance, int indication)
902 {
903         skinny_req *req;
904
905         req = req_alloc(sizeof(struct set_lamp_message));
906         if (!req) {
907                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
908                 return;
909         }       
910         req->len = sizeof(set_lamp_message)+4;
911         req->e = SET_LAMP_MESSAGE;
912         req->data.setlamp.stimulus = 0x9;  // magic number
913         req->data.setlamp.stimulusInstance = instance;
914         req->data.setlamp.deviceStimulus = indication;
915         transmit_response(s, req);
916 }
917
918 static void transmit_ringer_mode(struct skinnysession *s, int mode)
919 {
920         skinny_req *req;
921
922         req = req_alloc(sizeof(struct set_ringer_message));
923         if (!req) {
924                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
925                 return;
926         }
927         req->len = sizeof(set_ringer_message)+4;
928         req->e = SET_RINGER_MESSAGE; 
929         req->data.setringer.ringerMode = mode; 
930         transmit_response(s, req);
931 }
932
933 /* I do not believe skinny can deal with video. 
934    Anyone know differently? */
935 static struct ast_rtp *skinny_get_vrtp_peer(struct ast_channel *chan)
936 {
937         return NULL;
938 }
939
940 static struct ast_rtp *skinny_get_rtp_peer(struct ast_channel *chan)
941 {
942         struct skinny_subchannel *sub;
943         sub = chan->pvt->pvt;
944         if (sub && sub->rtp)
945                 return sub->rtp;
946         return NULL;
947 }
948
949 static int skinny_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp)
950 {
951         struct skinny_subchannel *sub;
952         sub = chan->pvt->pvt;
953         if (sub) {
954                 /* transmit_modify_with_sdp(sub, rtp); @@FIXME@@ if needed */
955                 return 0;
956         }
957         return -1;
958 }
959
960 static struct ast_rtp_protocol skinny_rtp = {
961         get_rtp_info: skinny_get_rtp_peer,
962         get_vrtp_info: skinny_get_vrtp_peer,
963         set_rtp_peer: skinny_set_rtp_peer,
964 };
965
966 static int skinny_do_debug(int fd, int argc, char *argv[])
967 {
968         if (argc != 2)
969                 return RESULT_SHOWUSAGE;
970         skinnydebug = 1;
971         ast_cli(fd, "Skinny Debugging Enabled\n");
972         return RESULT_SUCCESS;
973 }
974
975 static int skinny_no_debug(int fd, int argc, char *argv[])
976 {
977         if (argc != 3)
978                 return RESULT_SHOWUSAGE;
979         skinnydebug = 0;
980         ast_cli(fd, "Skinny Debugging Disabled\n");
981         return RESULT_SUCCESS;
982 }
983
984 static int skinny_show_lines(int fd, int argc, char *argv[])
985 {
986         struct skinny_device  *d;
987         struct skinny_line *l;
988         int haslines = 0;
989         if (argc != 3) 
990                 return RESULT_SHOWUSAGE;
991         ast_mutex_lock(&devicelock);
992         d = devices;
993         while(d) {
994                 l = d->lines;
995                 ast_cli(fd, "Device '%s' at %s\n", d->name, inet_ntoa(d->addr.sin_addr));
996                 while(l) {
997                         ast_cli(fd, "   -- '%s@%s in '%s' is %s\n", l->name, d->name, l->context, l->sub->owner ? "active" : "idle");
998                         haslines = 1;
999                         l = l->next;
1000                 }
1001                 if (!haslines) {
1002                         ast_cli(fd, "   << No Lines Defined >>     ");
1003                 }
1004                 d = d->next;
1005         }
1006         ast_mutex_unlock(&devicelock);
1007         return RESULT_SUCCESS;
1008 }
1009
1010 static char show_lines_usage[] = 
1011 "Usage: skinny show lines\n"
1012 "       Lists all lines known to the Skinny subsystem.\n";
1013
1014 static char debug_usage[] = 
1015 "Usage: skinny debug\n"
1016 "       Enables dumping of Skinny packets for debugging purposes\n";
1017
1018 static char no_debug_usage[] = 
1019 "Usage: skinny no debug\n"
1020 "       Disables dumping of Skinny packets for debugging purposes\n";
1021
1022 static struct ast_cli_entry  cli_show_lines =
1023         { { "skinny", "show", "lines", NULL }, skinny_show_lines, "Show defined Skinny lines per device", show_lines_usage };
1024 static struct ast_cli_entry  cli_debug =
1025         { { "skinny", "debug", NULL }, skinny_do_debug, "Enable Skinny debugging", debug_usage };
1026 static struct ast_cli_entry  cli_no_debug =
1027         { { "skinny", "no", "debug", NULL }, skinny_no_debug, "Disable Skinny debugging", no_debug_usage };
1028
1029 static struct skinny_device *build_device(char *cat, struct ast_variable *v)
1030 {
1031         struct skinny_device *d;
1032         struct skinny_line *l;
1033         struct skinny_subchannel *sub;
1034         int i=0, y=0;
1035         
1036         d = malloc(sizeof(struct skinny_device));
1037         if (d) {
1038                 memset(d, 0, sizeof(struct skinny_device));
1039                 strncpy(d->name, cat, sizeof(d->name) - 1);
1040                 while(v) {
1041                         if (!strcasecmp(v->name, "host")) {
1042                                         if (ast_get_ip(&d->addr, v->value)) {
1043                                                 free(d);
1044                                                 return NULL;
1045                                         }                               
1046                         } else if (!strcasecmp(v->name, "port")) {
1047                                 d->addr.sin_port = htons(atoi(v->value));
1048                         } else if (!strcasecmp(v->name, "device")) {
1049                         strncpy(d->id, v->value, sizeof(d->id)-1);
1050                         } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
1051                                 d->ha = ast_append_ha(v->name, v->value, d->ha);
1052                         } else if (!strcasecmp(v->name, "context")) {
1053                                 strncpy(context, v->value, sizeof(context) - 1);
1054                         } else if (!strcasecmp(v->name, "version")) {
1055                                 strncpy(d->version_id, v->value, sizeof(d->version_id) -1); 
1056                         } else if (!strcasecmp(v->name, "nat")) {
1057                                 nat = ast_true(v->value);
1058                         } else if (!strcasecmp(v->name, "callerid")) {
1059                                 if (!strcasecmp(v->value, "asreceived")) {
1060                                         strcpy(callerid, "");
1061                                 } else {
1062                                         strncpy(callerid, v->value, sizeof(callerid) - 1);
1063                                 }
1064                         } else if (!strcasecmp(v->name, "language")) {
1065                                 strncpy(language, v->value, sizeof(language)-1);
1066                         } else if (!strcasecmp(v->name, "accountcode")) {
1067                                 strncpy(accountcode, v->value, sizeof(accountcode)-1);
1068                         } else if (!strcasecmp(v->name, "amaflags")) {
1069                                 y = ast_cdr_amaflags2int(v->value);
1070                                 if (y < 0) {
1071                                         ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
1072                                 } else {
1073                                 amaflags = y;
1074                                 }
1075                         } else if (!strcasecmp(v->name, "musiconhold")) {
1076                                 strncpy(musicclass, v->value, sizeof(musicclass)-1);
1077                         } else if (!strcasecmp(v->name, "callgroup")) {
1078                                 cur_callergroup = ast_get_group(v->value);
1079                         } else if (!strcasecmp(v->name, "pickupgroup")) {
1080                                 cur_pickupgroup = ast_get_group(v->value);
1081                         } else if (!strcasecmp(v->name, "immediate")) {
1082                                 immediate = ast_true(v->value);
1083                         } else if (!strcasecmp(v->name, "cancallforward")) {
1084                                 cancallforward = ast_true(v->value);
1085                         } else if (!strcasecmp(v->name, "mailbox")) {
1086                                 strncpy(mailbox, v->value, sizeof(mailbox) -1);
1087                         } else if (!strcasecmp(v->name, "callreturn")) {
1088                                 callreturn = ast_true(v->value);
1089                         } else if (!strcasecmp(v->name, "immediate")) {
1090                                 immediate = ast_true(v->value);
1091                         } else if (!strcasecmp(v->name, "callwaiting")) {
1092                                 callwaiting = ast_true(v->value);
1093                         } else if (!strcasecmp(v->name, "transfer")) {
1094                                 transfer = ast_true(v->value);
1095                         } else if (!strcasecmp(v->name, "threewaycalling")) {
1096                                 threewaycalling = ast_true(v->value);
1097                         } else if (!strcasecmp(v->name, "linelabel")) {
1098                                 strncpy(linelabel, v->value, sizeof(linelabel)-1);
1099                         } else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
1100                                 l = malloc(sizeof(struct skinny_line));;
1101                                 if (l) {
1102                                         memset(l, 0, sizeof(struct skinny_line));
1103                                         strncpy(l->name, v->value, sizeof(l->name) - 1);
1104                                         
1105                                         /* XXX Should we check for uniqueness?? XXX */
1106                                         
1107                                         strncpy(l->context, context, sizeof(l->context) - 1);
1108                                         strncpy(l->callerid, callerid, sizeof(l->callerid) - 1);
1109                                         strncpy(l->label, linelabel, sizeof(l->label) - 1);
1110                                         strncpy(l->language, language, sizeof(l->language) - 1);
1111                                         strncpy(l->musicclass, musicclass, sizeof(l->musicclass)-1);
1112                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1113                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1114                                         if (strlen(mailbox)) {
1115                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting mailbox '%s' on %s@%s\n", mailbox, d->name, l->name);
1116                                         }
1117                                 
1118                                         l->msgstate = -1;
1119                                         l->capability = capability;
1120                                         l->parent = d;
1121                                         if (!strcasecmp(v->name, "trunk")) {
1122                                                 l->type = TYPE_TRUNK;
1123                                         } else {
1124                                                 l->type = TYPE_LINE;
1125                                         }
1126                                         l->immediate = immediate;
1127                                         l->callgroup = cur_callergroup;
1128                                         l->pickupgroup = cur_pickupgroup;
1129                                         l->callreturn = callreturn;
1130                                         l->cancallforward = cancallforward;
1131                                         l->callwaiting = callwaiting;
1132                                         l->transfer = transfer; 
1133                                         l->threewaycalling = threewaycalling;
1134                                         l->onhooktime = time(NULL);
1135                                         l->instance = 1;
1136                                         /* ASSUME we're onhook at this point*/
1137                                         l->hookstate = SKINNY_ONHOOK;
1138
1139                                         for (i = 0; i < MAX_SUBS; i++) {
1140                                                 sub = malloc(sizeof(struct skinny_subchannel));
1141                                                 if (sub) {
1142                                                         ast_verbose(VERBOSE_PREFIX_3 "Allocating Skinny subchannel '%d' on %s@%s\n", i, l->name, d->name);
1143                                                         memset(sub, 0, sizeof(struct skinny_subchannel));
1144                                                         sub->parent = l;
1145                                                         /* Make a call*ID */
1146                                                         sub->callid = callnums;
1147                                                         callnums++;
1148                                                         sub->cxmode = SKINNY_CX_INACTIVE;
1149                                                         sub->nat = nat;
1150                                                         sub->next = l->sub;
1151                                                         l->sub = sub;
1152                                                 } else {
1153                                                         /* XXX Should find a way to clean up our memory */
1154                                                         ast_log(LOG_WARNING, "Out of memory allocating subchannel");
1155                                                         return NULL;
1156                                                 }
1157                                         }
1158                                         l->next = d->lines;
1159                                         d->lines = l;                   
1160                                 } else {
1161                                         /* XXX Should find a way to clean up our memory */
1162                                         ast_log(LOG_WARNING, "Out of memory allocating line");
1163                                         return NULL;
1164                                 }
1165                         } else {
1166                                 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
1167                         }
1168                         v = v->next;
1169                 }
1170         
1171                 if (!d->lines) {
1172                         ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
1173                         return NULL;
1174                 }
1175
1176                 if (d->addr.sin_addr.s_addr && !ntohs(d->addr.sin_port))
1177                         d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
1178                 if (d->addr.sin_addr.s_addr) {
1179                         if (ast_ouraddrfor(&d->addr.sin_addr, &d->ourip)) {
1180                                 memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1181                         }
1182                 } else {
1183                         memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1184                 }
1185         }
1186         return d;
1187 }
1188
1189 static int has_voicemail(struct skinny_line *l)
1190 {
1191         return ast_app_has_voicemail(l->mailbox);
1192 }
1193
1194 static int skinny_register(skinny_req *req, struct skinnysession *s)
1195 {
1196         struct skinny_device *d;
1197         
1198         ast_mutex_lock(&devicelock);
1199         d = devices;
1200         while (d) {
1201                 if (!strcasecmp(req->data.reg.name, d->id)) {
1202                         /* XXX Deal with IP authentication */
1203                         s->device = d;
1204                         d->type = req->data.reg.type;
1205                         if (!strlen(d->version_id)) {
1206                                 strncpy(d->version_id, version_id, sizeof(d->version_id));
1207                         }
1208                         d->registered = 1;
1209                         d->session = s;
1210                         break;
1211                 }
1212                 d = d->next;
1213         }
1214         ast_mutex_unlock(&devicelock);
1215
1216         if (!d)
1217                 return 0;
1218         
1219         return 1;
1220 }               
1221
1222 static void start_rtp(struct skinny_subchannel *sub)
1223 {
1224                 ast_mutex_lock(&sub->lock);
1225                 /* Allocate the RTP */
1226                 sub->rtp = ast_rtp_new(sched, io, 1, 0);
1227                 if (sub->rtp && sub->owner)
1228                         sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
1229                 if (sub->rtp)
1230                         ast_rtp_setnat(sub->rtp, sub->nat);
1231                 
1232                 /* Create the RTP connections  */
1233                 transmit_connect(sub->parent->parent->session);
1234                 ast_mutex_unlock(&sub->lock);
1235 }
1236
1237
1238 static void *skinny_ss(void *data)
1239 {
1240         struct ast_channel *chan = data;
1241         struct skinny_subchannel *sub = chan->pvt->pvt;
1242         struct skinny_line *l = sub->parent;
1243         struct skinnysession *s = l->parent->session;
1244         char exten[AST_MAX_EXTENSION] = "";
1245         int len = 0;
1246         int timeout = firstdigittimeout;
1247         int res;
1248         int getforward=0;
1249     
1250         if (option_verbose > 2) 
1251                 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s@%s'\n", l->name, l->parent->name);
1252
1253         while(len < AST_MAX_EXTENSION-1) {
1254         res = ast_waitfordigit(chan, timeout);
1255         timeout = 0;
1256         if (res < 0) {
1257                         if (skinnydebug)
1258                                 printf("Skinny(%s@%s): waitfordigit returned < 0\n", l->name, l->parent->name);
1259                 ast_indicate(chan, -1);
1260                         ast_hangup(chan);
1261             return NULL;
1262         } else if (res)  {
1263             exten[len++]=res;
1264             exten[len] = '\0';
1265         }
1266         if (!ast_ignore_pattern(chan->context, exten)) {
1267                         transmit_tone(s, SKINNY_SILENCE);
1268         } 
1269         if (ast_exists_extension(chan, chan->context, exten, 1, l->callerid)) {
1270             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, l->callerid)) {
1271                 if (getforward) {
1272                     /* Record this as the forwarding extension */
1273                     strncpy(l->call_forward, exten, sizeof(l->call_forward)); 
1274                     if (option_verbose > 2) {
1275                         ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n", 
1276                                 l->call_forward, chan->name);
1277                     }
1278                     transmit_tone(s, SKINNY_DIALTONE); 
1279                     if (res) {
1280                             break;
1281                     }
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(%d)\n", stimulusInstance);
1887                         }
1888                         break;
1889                 case STIMULUS_SPEEDDIAL:
1890                         if (skinnydebug) {
1891                                 printf("Recieved Stimulus: SpeedDial(%d)\n", stimulusInstance);
1892                         }
1893                         break;
1894                 case STIMULUS_HOLD:
1895                         // Easy enough
1896                         if (skinnydebug) {
1897                                 printf("Recieved Stimulus: Hold(%d)\n", stimulusInstance);
1898                         }
1899                         break;
1900                 case STIMULUS_TRANSFER:
1901                         if (skinnydebug) {
1902                                 printf("Recieved Stimulus: Transfer(%d)\n", stimulusInstance);
1903                         }
1904                         transmit_tone(s, SKINNY_DIALTONE);
1905                                 
1906                         // figure out how to transfer
1907
1908                         break;
1909                 case STIMULUS_FORWARDALL:
1910                 case STIMULUS_FORWARDBUSY:
1911                 case STIMULUS_FORWARDNOANSWER:
1912                         // Gonna be fun
1913                         if (skinnydebug) {
1914                                 printf("Recieved Stimulus: Forward (%d)\n", stimulusInstance);
1915                         }
1916                         break;
1917                 case STIMULUS_DISPLAY:
1918                         // XXX Not sure
1919                         if (skinnydebug) {
1920                                 printf("Recieved Stimulus: Display(%d)\n", stimulusInstance);
1921                         }
1922                         break;
1923                 case STIMULUS_LINE:
1924                         if (skinnydebug) {
1925                                 printf("Recieved Stimulus: Line(%d)\n", stimulusInstance);
1926                         }               
1927                         sub = find_subchannel_by_line(s->device->lines);
1928                         transmit_speaker_mode(s, 1);  // Turn on
1929                 break;
1930                 default:
1931                         printf("RECEIVED UNKNOWN STIMULUS:  %d(%d)\n", stimulus, stimulusInstance);                     
1932                         break;
1933                 }
1934                         
1935                         
1936                 break;
1937         case VERSION_REQ_MESSAGE:
1938                 if (skinnydebug)
1939                         printf ("Version Request\n");
1940                 memset(req, 0, SKINNY_MAX_PACKET);
1941                 req->len = sizeof(version_res_message)+4;
1942                 req->e = VERSION_RES_MESSAGE;
1943                 sprintf(req->data.version.version, s->device->version_id);
1944                 transmit_response(s, req);
1945                 break;
1946         case SERVER_REQUEST_MESSAGE:
1947                 if (skinnydebug)
1948                         printf ("Recieved Server Request\n");
1949                 memset(req, 0, SKINNY_MAX_PACKET);
1950                 req->len = sizeof(server_res_message)+4;
1951                 req->e = SERVER_RES_MESSAGE;
1952                 memcpy(req->data.serverres.server[0].serverName, ourhost, 
1953                                 sizeof(req->data.serverres.server[0].serverName));
1954                 req->data.serverres.serverListenPort[0] = ourport;
1955                 req->data.serverres.serverIpAddr[0] = __ourip.s_addr;
1956                 transmit_response(s, req);      
1957                 break;
1958         case BUTTON_TEMPLATE_REQ_MESSAGE:
1959                 if (skinnydebug)
1960                         printf ("Buttontemplate requested\n");
1961                 memset(req, 0, SKINNY_MAX_PACKET);
1962                 req->len = sizeof(button_template_res_message)+4;
1963                 req->e = BUTTON_TEMPLATE_RES_MESSAGE;   
1964                 req->data.buttontemplate.buttonOffset           = 0;
1965                 req->data.buttontemplate.buttonCount            = 10;
1966                 req->data.buttontemplate.totalButtonCount       = 10;
1967                 /* XXX Figure out how to do this correctly */
1968                 memcpy(req->data.buttontemplate.definition,
1969                            button_definition_hack, 
1970                            sizeof(req->data.buttontemplate.definition));
1971                 transmit_response(s, req);
1972                 break;
1973         case SOFT_KEY_SET_REQ_MESSAGE:
1974                 if (skinnydebug)
1975                         printf ("Received SoftKeySetReq\n");
1976                 memset(req, 0, SKINNY_MAX_PACKET);
1977                 req->len = sizeof(soft_key_sets)+4;
1978                 req->e = SOFT_KEY_SET_RES_MESSAGE;
1979                 req->data.softkeysets.softKeySetOffset          = 0;
1980                 req->data.softkeysets.softKeySetCount           = 11;
1981                 req->data.softkeysets.totalSoftKeySetCount  = 11;       
1982                 /* XXX Wicked hack XXX */
1983                 memcpy(req->data.softkeysets.softKeySetDefinition, 
1984                            soft_key_set_hack, 
1985                            sizeof(req->data.softkeysets.softKeySetDefinition));
1986                 transmit_response(s,req);
1987                 break;
1988         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
1989                 if (skinnydebug)
1990                         printf ("Recieved SoftKey Template Request\n");
1991                 memset(req, 0, SKINNY_MAX_PACKET);
1992                 req->len = sizeof(soft_key_template)+4;
1993                 req->e = SOFT_KEY_TEMPLATE_RES_MESSAGE;
1994                 req->data.softkeytemplate.softKeyOffset         = 0;
1995                 req->data.softkeytemplate.softKeyCount          = 21;
1996                 req->data.softkeytemplate.totalSoftKeyCount = 21; 
1997                 /* XXX Another wicked hack XXX */
1998                 memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
1999                            soft_key_template_hack,
2000                            sizeof(req->data.softkeytemplate.softKeyTemplateDefinition));
2001                 transmit_response(s,req);
2002                 break;
2003         case TIME_DATE_REQ_MESSAGE:
2004                 if (skinnydebug)
2005                         printf ("Received Time/Date Request\n");
2006                 memset(req, 0, SKINNY_MAX_PACKET);
2007                 req->len = sizeof(definetimedate_message)+4;
2008                 req->e = DEFINETIMEDATE_MESSAGE;
2009                 timer=time(NULL);
2010                 cmtime = localtime(&timer);
2011                 req->data.definetimedate.year = cmtime->tm_year+1900;
2012                 req->data.definetimedate.month = cmtime->tm_mon+1;
2013                 req->data.definetimedate.dayofweek = cmtime->tm_wday;
2014                 req->data.definetimedate.day = cmtime->tm_mday;
2015                 req->data.definetimedate.hour = cmtime->tm_hour;
2016                 req->data.definetimedate.minute = cmtime->tm_min;
2017                 req->data.definetimedate.seconds = cmtime->tm_sec;
2018                 transmit_response(s, req);
2019                 break;
2020         case SPEED_DIAL_STAT_REQ_MESSAGE:
2021                 /* Not really sure how Speed Dial's are different than the 
2022                    Softkey templates */
2023                 speedDialNum = req->data.speeddialreq.speedDialNumber;
2024 //              if (skinnydebug)
2025 //                      printf ("Recieved SpeedDialStatReq: %d\n", speedDialNum);
2026                 memset(req, 0, SKINNY_MAX_PACKET);
2027                 req->len = sizeof(speed_dial_stat_res_message)+4;
2028                 req->e = SPEED_DIAL_STAT_RES_MESSAGE;
2029 #if 0   
2030                 /* XXX Do this right XXX */     
2031                 req->data.speeddialreq.speedDialNumber = speedDialNum;
2032                 sprintf(req->data.speeddial.speedDialDirNumber, "31337");
2033                 sprintf(req->data.speeddial.speedDialDisplayName, "Asterisk Rules!");
2034 #endif          
2035                 transmit_response(s, req);
2036                 break;
2037         case LINE_STATE_REQ_MESSAGE:
2038                 lineNumber = req->data.line.lineNumber;
2039                 if (skinnydebug)
2040                         printf ("Received LineStateReq\n");
2041                 memset(req, 0, SKINNY_MAX_PACKET);
2042                 req->len = sizeof(line_stat_res_message)+4;
2043                 req->e = LINE_STAT_RES_MESSAGE; 
2044                 sub = find_subchannel_by_line(s->device->lines);
2045                 if (!sub) {
2046                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2047                         return 0;
2048                 }
2049                 lines = sub->parent;
2050                 ast_mutex_lock(&devicelock);
2051                 for (i=1; i < lineNumber; i++) {
2052                         lines = lines->next;
2053                 }
2054                 ast_mutex_unlock(&devicelock);
2055                 req->data.linestat.linenumber = lineNumber;             
2056                 memcpy(req->data.linestat.lineDirNumber, lines->name,
2057                                 sizeof(req->data.linestat.lineDirNumber));
2058                 memcpy(req->data.linestat.lineDisplayName, lines->label,
2059                                 sizeof(req->data.linestat.lineDisplayName)); 
2060                 transmit_response(s,req);
2061                 break;
2062         case CAPABILITIES_RES_MESSAGE:
2063                 if (skinnydebug)
2064                         printf ("Received CapabilitiesRes\n");  
2065                 // zien wat ie kan en verwerken (handshake)
2066                 break;
2067         case KEEP_ALIVE_MESSAGE:
2068                 memset(req, 0, SKINNY_MAX_PACKET);
2069                 req->len = 4;
2070                 req->e = KEEP_ALIVE_ACK_MESSAGE;
2071                 transmit_response(s, req);
2072                 break;
2073         case OFFHOOK_MESSAGE:
2074                 transmit_ringer_mode(s,SKINNY_RING_OFF);
2075                 transmit_lamp_indication(s, s->device->lines->instance, SKINNY_LAMP_ON); 
2076                 
2077                 sub = find_subchannel_by_line(s->device->lines);
2078                 if (!sub) {
2079                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2080                         return 0;
2081                 }
2082                 sub->parent->hookstate = SKINNY_OFFHOOK;
2083                 
2084                         if (sub->outgoing) {
2085                                 transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2086                                 transmit_tone(s, SKINNY_SILENCE);
2087                                 ast_setstate(sub->owner, AST_STATE_UP);
2088                                 // select soft keys
2089                         } else {        
2090                                 if (!sub->owner) {      
2091
2092                                         transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2093                                         transmit_tone(s, SKINNY_DIALTONE);
2094                                         c = skinny_new(sub, AST_STATE_DOWN);                    
2095                                         if(c) {
2096                                                 /* start switch */
2097                                                 if (pthread_create(&t, NULL, skinny_ss, c)) {
2098                                                         ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
2099                                                         ast_hangup(c);
2100                                                 }
2101                                         } else {
2102                                                 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", sub->parent->name, s->device->name);
2103                                         }
2104                                 
2105                                 } else {
2106                                         ast_log(LOG_DEBUG, "Current sub [%s] already has owner\n", sub->owner->name);
2107                                 }
2108                         }
2109                 break;
2110         case ONHOOK_MESSAGE:
2111                 sub = find_subchannel_by_line(s->device->lines);
2112                 if (sub->parent->hookstate == SKINNY_ONHOOK) {
2113                         /* Somthing else already put us back on hook */ 
2114                         break;
2115                 }
2116                 sub->cxmode = SKINNY_CX_RECVONLY;
2117                 sub->parent->hookstate = SKINNY_ONHOOK;
2118                 transmit_callstate(s, s->device->lines->instance, sub->parent->hookstate,sub->callid);
2119             if (skinnydebug)
2120                         printf("Skinny %s@%s went on hook\n",sub->parent->name, sub->parent->parent->name);
2121             if (sub->rtp) {
2122  //         transmit_modify_request(sub);
2123         }
2124         if (sub->parent->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
2125                         /* We're allowed to transfer, we have two active calls and */
2126                         /* we made at least one of the calls.  Let's try and transfer */
2127 #if 0
2128              if ((res = attempt_transfer(p)) < 0) {
2129                                  if (p->sub->next->owner) {
2130                                         sub->next->alreadygone = 1;
2131                                         ast_queue_hangup(sub->next->owner,1);
2132                                 }
2133                          } else if (res) {
2134                                     ast_log(LOG_WARNING, "Transfer attempt failed\n");
2135                                         return -1;
2136              }
2137 #endif
2138        } else {
2139            /* Hangup the current call */
2140            /* If there is another active call, skinny_hangup will ring the phone with the other call */
2141            if (sub->owner) {
2142                sub->alreadygone = 1;
2143                ast_queue_hangup(sub->owner, 1);
2144            } else {
2145                ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n", 
2146                            sub->parent->name, sub->parent->parent->name, sub->callid);
2147            }
2148        }
2149        if ((sub->parent->hookstate == SKINNY_ONHOOK) && (!sub->rtp) && (!sub->next->rtp)) {
2150                         if (has_voicemail(sub->parent)) {
2151                                 transmit_lamp_indication(s, s->device->lines->instance, SKINNY_LAMP_FLASH); 
2152             } else {
2153                                 transmit_lamp_indication(s, s->device->lines->instance, SKINNY_LAMP_OFF);
2154             }
2155        }
2156            break;
2157         case KEYPAD_BUTTON_MESSAGE:
2158                 digit = req->data.keypad.button;
2159                 if (skinnydebug) {
2160                         printf("Collected digit: [%d]\n", digit);
2161                 }
2162                 f.frametype = AST_FRAME_DTMF;
2163                 if (digit == 14) {
2164                         sprintf(&d, "*");
2165                 } else if (digit == 15) {
2166                         sprintf(&d, "#");
2167                 } else {
2168                         sprintf(&d, "%d", digit);
2169                 }
2170                 f.subclass  = d;  
2171                 f.src = "skinny";
2172
2173                 sub = find_subchannel_by_line(s->device->lines);                
2174
2175                 if (sub->owner) {
2176                         /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
2177                         ast_queue_frame(sub->owner, &f, 1);
2178             if (sub->next->owner) {
2179                                 ast_queue_frame(sub->next->owner, &f, 1);
2180             }
2181         } else {
2182                         printf("No owner: %s\n", s->device->lines->name);
2183                 }
2184                 break;
2185         case OPEN_RECIEVE_CHANNEL_ACK_MESSAGE:
2186                 printf("Recieved Open Recieve Channel Ack\n");
2187                 status = req->data.openrecievechannelack.status;
2188                 if (status) {
2189                         ast_log(LOG_ERROR, "Open Recieve Channel Failure\n");
2190                         break;
2191                 }
2192                 memcpy(addr, req->data.openrecievechannelack.ipAddr, sizeof(addr));
2193                 port = req->data.openrecievechannelack.port;
2194                                 
2195                 sin.sin_family = AF_INET;
2196                 memcpy(&sin.sin_addr, addr, sizeof(sin.sin_addr));  // Endian?
2197                 sin.sin_port = htons(port);
2198         
2199                 sub = find_subchannel_by_line(s->device->lines);
2200                 ast_rtp_set_peer(sub->rtp, &sin);
2201                 ast_rtp_get_us(sub->rtp, &us);
2202                 
2203                 printf("us port: %d\n", ntohs(us.sin_port));
2204                 printf("sin port: %d\n", ntohs(sin.sin_port));
2205
2206                 memset(req, 0, SKINNY_MAX_PACKET);
2207                 req->len = sizeof(start_media_transmission_message)+4;
2208                 req->e = START_MEDIA_TRANSMISSION_MESSAGE;
2209                 req->data.startmedia.conferenceId = 0;
2210                 req->data.startmedia.passThruPartyId = 0;
2211                 memcpy(req->data.startmedia.remoteIp, &s->device->ourip, 4); // Endian?
2212                 req->data.startmedia.remotePort = ntohs(us.sin_port);
2213                 req->data.startmedia.packetSize = 20;
2214                 req->data.startmedia.payloadType = convert_cap(s->device->lines->capability);
2215                 req->data.startmedia.qualifier.precedence = 127;
2216                 req->data.startmedia.qualifier.vad = 0;
2217                 req->data.startmedia.qualifier.packets = 0;
2218                 req->data.startmedia.qualifier.bitRate = 0;
2219                 transmit_response(s, req);
2220                 break;  
2221         default:
2222                 printf("RECEIVED UNKNOWN MESSAGE TYPE:  %x\n", req->e);
2223                 break;
2224         }
2225
2226         free(req);
2227         return 1;
2228
2229 }
2230
2231 static void destroy_session(struct skinnysession *s)
2232 {
2233         struct skinnysession *cur, *prev = NULL;
2234         ast_mutex_lock(&sessionlock);
2235         cur = sessions;
2236         while(cur) {
2237                 if (cur == s)
2238                         break;
2239                 prev = cur;
2240                 cur = cur->next;
2241         }
2242         if (cur) {
2243                 if (prev)
2244                         prev->next = cur->next;
2245                 else
2246                         sessions = cur->next;
2247                 if (s->fd > -1)
2248                         close(s->fd);
2249                 free(s);
2250         } else
2251                 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
2252         ast_mutex_unlock(&sessionlock);
2253 }
2254
2255 static int get_input(struct skinnysession *s)  
2256 {  
2257  
2258         int res;  
2259         int dlen = 0;  
2260  
2261         fd_set fds;  
2262         FD_ZERO(&fds);  
2263         FD_SET(s->fd, &fds);  
2264  
2265         res = ast_select(s->fd + 1, &fds, NULL, NULL, NULL);  
2266  
2267         if (res < 0) {
2268                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
2269         } else if (res > 0) {
2270                 memset(s->inbuf,0,sizeof(s->inbuf));
2271                 res = read(s->fd, s->inbuf, 4);
2272                 if (res != 4) {
2273                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2274                         return -1;
2275                 }
2276                 dlen = *(int *)s->inbuf;
2277                 res = read(s->fd, s->inbuf+4, dlen+4);
2278                 ast_mutex_unlock(&s->lock);
2279                 if (res != (dlen+4)) {
2280                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2281                         return -1;
2282                 } 
2283  
2284         }  
2285         return res;  
2286 }   
2287
2288
2289 static skinny_req *skinny_req_parse(struct skinnysession *s)
2290 {
2291         skinny_req *req;
2292         
2293         req = malloc(SKINNY_MAX_PACKET);
2294         if (!req) {
2295                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
2296                 return NULL;
2297         }
2298         memset(req, 0, sizeof(skinny_req));
2299         memcpy(req, s->inbuf, *(int*)(s->inbuf)+8); // +8
2300         if (req->e < 0) {
2301                 ast_log(LOG_ERROR, "Event Message is NULL from socket %d, This is bad\n", s->fd);
2302                 free(req);
2303                 return NULL;
2304         }
2305         return req;
2306 }
2307
2308 static void *skinny_session(void *data)
2309 {
2310         int res;
2311         skinny_req *req;
2312         struct skinnysession *s = data;
2313         
2314         ast_verbose(VERBOSE_PREFIX_3 "Starting Skinny session from %s\n",  inet_ntoa(s->sin.sin_addr));
2315
2316         for (;;) {
2317                 res = 0;
2318                 res = get_input(s);
2319                 if (res < 0)
2320                         break;
2321                 req = skinny_req_parse(s);
2322                 if (!req) {
2323                         return NULL;
2324                 }
2325                 res = handle_message(req, s);
2326                 if (res < 0) {
2327                         destroy_session(s);
2328                         return NULL;
2329                 } 
2330         }
2331         ast_log(LOG_NOTICE, "Skinny Session returned: %s\n", strerror(errno));
2332         destroy_session(s);
2333         return 0;
2334 }
2335
2336 static void *accept_thread(void *ignore)
2337 {
2338         int as;
2339         struct sockaddr_in sin;
2340         int sinlen;
2341         struct skinnysession *s;
2342         struct protoent *p;
2343         int arg = 1;
2344         pthread_attr_t attr;
2345
2346         pthread_attr_init(&attr);
2347         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2348
2349         for (;;) {
2350                 sinlen = sizeof(sin);
2351                 as = accept(skinnysock, (struct sockaddr *)&sin, &sinlen);
2352                 if (as < 0) {
2353                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
2354                         continue;
2355                 }
2356                 p = getprotobyname("tcp");
2357                 if(p) {
2358                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
2359                                 ast_log(LOG_WARNING, "Failed to set Skinny tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
2360                         }
2361                 }
2362                 s = malloc(sizeof(struct skinnysession));
2363                 if (!s) {
2364                         ast_log(LOG_WARNING, "Failed to allocate Skinny session: %s\n", strerror(errno));
2365                         continue;
2366                 } 
2367                 memset(s, 0, sizeof(struct skinnysession));
2368                 memcpy(&s->sin, &sin, sizeof(sin));
2369                 ast_mutex_init(&s->lock);
2370                 s->fd = as;
2371                 ast_mutex_lock(&sessionlock);
2372                 s->next = sessions;
2373                 sessions = s;
2374                 ast_mutex_unlock(&sessionlock);
2375                 
2376                 if (pthread_create(&tcp_thread, NULL, skinny_session, s))
2377                         destroy_session(s);
2378         }
2379         
2380         
2381         if (skinnydebug)
2382                 printf("killing accept thread\n");
2383         
2384         close(as);
2385         return 0;
2386 }
2387
2388 static void *do_monitor(void *data)
2389 {
2390         int res;
2391
2392 #if 0
2393         /* Add an I/O event to our TCP socket */
2394         if (skinnysock > -1)  {
2395                 ast_io_add(io, skinnysock, accept_thread, AST_IO_IN, NULL);
2396         } else {
2397                 ast_log(LOG_WARNING, "Unable to create I/O socket event\n");            
2398         }
2399 #endif
2400
2401
2402         /* This thread monitors all the interfaces which are not yet in use
2403            (and thus do not have a separate thread) indefinitely */
2404         /* From here on out, we die whenever asked */
2405         for(;;) {
2406                 pthread_testcancel();
2407                 /* Wait for sched or io */
2408                 res = ast_sched_wait(sched);
2409                 if ((res < 0) || (res > 1000))
2410                         res = 1000;
2411                 res = ast_io_wait(io, res);
2412                 ast_mutex_lock(&monlock);
2413                 if (res >= 0) 
2414                         ast_sched_runq(sched);
2415                 ast_mutex_unlock(&monlock);
2416         }
2417         /* Never reached */
2418         return NULL;
2419         
2420 }
2421
2422 static int restart_monitor(void)
2423 {
2424
2425         /* If we're supposed to be stopped -- stay stopped */
2426         if (monitor_thread == (pthread_t)-2)
2427                 return 0;
2428         if (ast_mutex_lock(&monlock)) {
2429                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
2430                 return -1;
2431         }
2432         if (monitor_thread == pthread_self()) {
2433                 ast_mutex_unlock(&monlock);
2434                 ast_log(LOG_WARNING, "Cannot kill myself\n");
2435                 return -1;
2436         }
2437         if (monitor_thread) {
2438                 /* Wake up the thread */
2439                 pthread_kill(monitor_thread, SIGURG);
2440         } else {
2441                 /* Start a new monitor */
2442                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
2443                         ast_mutex_unlock(&monlock);
2444                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
2445                         return -1;
2446                 }
2447         }
2448         ast_mutex_unlock(&monlock);
2449         return 0;
2450 }
2451
2452 static struct ast_channel *skinny_request(char *type, int format, void *data)
2453 {
2454         int oldformat;
2455         struct skinny_subchannel *sub;
2456         struct ast_channel *tmpc = NULL;
2457         char tmp[256];
2458         char *dest = data;
2459
2460         oldformat = format;
2461         format &= capability;
2462         if (!format) {
2463                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
2464                 return NULL;
2465         }
2466         
2467         strncpy(tmp, dest, sizeof(tmp) - 1);
2468         if (!strlen(tmp)) {
2469                 ast_log(LOG_NOTICE, "Skinny channels require a device\n");
2470                 return NULL;
2471         }
2472         
2473         sub = find_subchannel_by_name(tmp);  
2474         if (!sub) {
2475                 ast_log(LOG_NOTICE, "No available lines on: %s\n", dest);
2476                 return NULL;
2477         }
2478         
2479     if (option_verbose > 2) {
2480         ast_verbose(VERBOSE_PREFIX_3 "skinny_request(%s)\n", tmp);
2481         ast_verbose(VERBOSE_PREFIX_3 "Skinny cw: %d, dnd: %d, so: %d, sno: %d\n", 
2482                     sub->parent->callwaiting, sub->parent->dnd, sub->owner ? 1 : 0, sub->next->owner ? 1: 0);
2483     }
2484         
2485         tmpc = skinny_new(sub->owner ? sub->next : sub, AST_STATE_DOWN);
2486         if (!tmpc)
2487                 ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
2488         restart_monitor();
2489
2490         /* and finish */        
2491         return tmpc;
2492 }
2493
2494 static int reload_config(void)
2495 {
2496         int on=1;
2497         struct ast_config *cfg;
2498         struct ast_variable *v;
2499         int format;
2500         char *cat;
2501         struct skinny_device *d;
2502         int oldport = ntohs(bindaddr.sin_port);
2503         
2504         if (gethostname(ourhost, sizeof(ourhost))) {
2505                 ast_log(LOG_WARNING, "Unable to get hostname, Skinny disabled\n");
2506                 return 0;
2507         }
2508         cfg = ast_load(config);
2509
2510         /* We *must* have a config file otherwise stop immediately */
2511         if (!cfg) {
2512                 ast_log(LOG_NOTICE, "Unable to load config %s, Skinny disabled\n", config);
2513                 return 0;
2514         }
2515
2516         /* load the general section */
2517         memset(&bindaddr, 0, sizeof(bindaddr));
2518         v = ast_variable_browse(cfg, "general");
2519         while(v) {
2520                 /* Create the interface list */
2521                 if (!strcasecmp(v->name, "bindaddr")) {
2522                         if (!(hp = gethostbyname(v->value))) {
2523                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
2524                         } else {
2525                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
2526                         }
2527                 } else if (!strcasecmp(v->name, "keepAlive")) {
2528                         keep_alive = atoi(v->value);            
2529                 } else if (!strcasecmp(v->name, "dateFormat")) {
2530                         strncpy(date_format, v->value, sizeof(date_format) - 1);        
2531                 } else if (!strcasecmp(v->name, "allow")) {
2532                         format = ast_getformatbyname(v->value);
2533                         if (format < 1) 
2534                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
2535                         else
2536                                 capability |= format;
2537                 } else if (!strcasecmp(v->name, "disallow")) {
2538                         format = ast_getformatbyname(v->value);
2539                         if (format < 1) 
2540                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
2541                         else
2542                                 capability &= ~format;
2543                 } else if (!strcasecmp(v->name, "port")) {
2544                         if (sscanf(v->value, "%i", &ourport) == 1) {
2545                                 bindaddr.sin_port = htons(ourport);
2546                         } else {
2547                                 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
2548                         }
2549                 }
2550                 v = v->next;
2551         }
2552
2553         if (ntohl(bindaddr.sin_addr.s_addr)) {
2554                 memcpy(&__ourip, &bindaddr.sin_addr, sizeof(__ourip));
2555         } else {
2556                 hp = gethostbyname(ourhost);
2557                 if (!hp) {
2558                         ast_log(LOG_WARNING, "Unable to get our IP address, Skinny disabled\n");
2559                         return 0;
2560                 }
2561                 memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
2562         }
2563         if (!ntohs(bindaddr.sin_port))
2564                 bindaddr.sin_port = ntohs(DEFAULT_SKINNY_PORT);
2565         bindaddr.sin_family = AF_INET;
2566         
2567         /* load the device sections */
2568         cat = ast_category_browse(cfg, NULL);
2569         while(cat) {
2570                 if (strcasecmp(cat, "general")) {
2571                         d = build_device(cat, ast_variable_browse(cfg, cat));
2572                         if (d) {
2573                                 if (option_verbose > 2) {
2574                                         ast_verbose(VERBOSE_PREFIX_3 "Added device '%s'\n", d->name);
2575                 }
2576                                 ast_mutex_lock(&devicelock);
2577                                 d->next = devices;
2578                                 devices = d;
2579                                 ast_mutex_unlock(&devicelock);
2580                         }
2581                 }
2582                 cat = ast_category_browse(cfg, cat);
2583         }
2584         ast_mutex_lock(&netlock);
2585         if ((skinnysock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
2586                 close(skinnysock);
2587                 skinnysock = -1;
2588         }
2589         if (skinnysock < 0) {
2590                 skinnysock = socket(AF_INET, SOCK_STREAM, 0);
2591                 if(setsockopt(skinnysock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
2592                         ast_log(LOG_ERROR, "Set Socket Options failed: errno %d, %s", errno, strerror(errno));
2593                         return 0;
2594                 }
2595
2596                 if (skinnysock < 0) {
2597                         ast_log(LOG_WARNING, "Unable to create Skinny socket: %s\n", strerror(errno));
2598                 } else {
2599                         if (bind(skinnysock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
2600                                 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
2601                                                 inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
2602                                                         strerror(errno));
2603                                 close(skinnysock);
2604                                 skinnysock = -1;
2605                                 return 0;
2606                         } 
2607
2608                         if (listen(skinnysock,DEFAULT_SKINNY_BACKLOG)) {
2609                                         ast_log(LOG_WARNING, "Failed to start listening to %s:%d: %s\n",
2610                                                 inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
2611                                                         strerror(errno));
2612                                         close(skinnysock);
2613                                         skinnysock = -1;
2614                                         return 0;
2615                         }
2616                 
2617                         if (option_verbose > 1)
2618                                 ast_verbose(VERBOSE_PREFIX_2 "Skinny listening on %s:%d\n", 
2619                                         inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
2620
2621                         pthread_create(&accept_t,NULL, accept_thread, NULL);
2622
2623                 }
2624         }
2625         ast_mutex_unlock(&netlock);
2626
2627
2628         /* and unload the configuration when were done */
2629         ast_destroy(cfg);
2630
2631         return 0;
2632 }
2633
2634 void delete_devices(void)
2635 {
2636         struct skinny_device *d, *dlast;
2637         struct skinny_line *l, *llast;
2638         struct skinny_subchannel *sub, *slast;
2639         
2640         ast_mutex_lock(&devicelock);
2641         
2642         /* Delete all devices */
2643         for (d=devices;d;) {
2644                 
2645                 /* Delete all lines for this device */
2646                 for (l=d->lines;l;) {
2647                         /* Delete all subchannels for this line */
2648                         for (sub=l->sub;sub;) {
2649                                 slast = sub;
2650                                 sub = sub->next;
2651                                 free(slast);
2652                         }
2653                         llast = l;
2654                         l = l->next;
2655                         free(llast);
2656                 }
2657                 dlast = d;
2658                 d = d->next;
2659                 free(dlast);
2660         }
2661         devices=NULL;
2662         ast_mutex_unlock(&devicelock);
2663 }
2664
2665 int reload(void)
2666 {
2667 #if 0
2668 // XXX Causes Seg
2669
2670         delete_devices();
2671         reload_config();
2672         restart_monitor();
2673 #endif
2674         return 0;
2675 }
2676
2677
2678 int load_module()
2679 {
2680         int res = 0;
2681
2682         /* load and parse config */
2683         res = reload_config();
2684         
2685         /* Announce our presence to Asterisk */ 
2686         if (!res) {
2687                 /* Make sure we can register our skinny channel type */
2688                 if (ast_channel_register(type, tdesc, capability, skinny_request)) {
2689                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
2690                         return -1;
2691                 }
2692         }
2693         skinny_rtp.type = type;
2694         ast_rtp_proto_register(&skinny_rtp);
2695         ast_cli_register(&cli_show_lines);
2696         ast_cli_register(&cli_debug);
2697         ast_cli_register(&cli_no_debug);
2698         sched = sched_context_create();
2699         if (!sched) {
2700                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
2701         }
2702         io = io_context_create();
2703         if (!io) {
2704                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
2705         }
2706         /* And start the monitor for the first time */
2707         restart_monitor();
2708         return res;
2709 }
2710
2711 int unload_module()
2712 {
2713
2714 #if 0   
2715         struct skinny_subchannel *p, *pl;
2716
2717         ast_channel_unregister(type);
2718         ast_verbose("Skinny module unloading\n");
2719         
2720         /* First, take us out of the channel loop */
2721         ast_channel_unregister(type);
2722         
2723         /* close all IP connections */
2724         if (!ast_mutex_lock(&devicelock)) {
2725                 /* Hangup all interfaces if they have an owner */
2726                 p = iflist;
2727                 while(p) {
2728                         if (p->owner)
2729                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2730                         p = p->next;
2731                 }
2732                 iflist = NULL;
2733                 ast_mutex_unlock(&iflock);
2734         } else {
2735                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2736                 return -1;
2737         }
2738         if (!ast_mutex_lock(&monlock)) {
2739                 if (monitor_thread && (monitor_thread != -2)) {
2740                         pthread_cancel(monitor_thread);
2741                         pthread_kill(monitor_thread, SIGURG);
2742                         pthread_join(monitor_thread, NULL);
2743                 }
2744                 monitor_thread = -2;
2745                 ast_mutex_unlock(&monlock);
2746         } else {
2747                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2748                 return -1;
2749         }
2750
2751         if (!ast_mutex_lock(&iflock)) {
2752                 /* Destroy all the interfaces and free their memory */
2753                 p = iflist;
2754                 while(p) {
2755                         pl = p;
2756                         p = p->next;
2757                         /* Free associated memory */
2758                         free(pl);
2759                 }
2760                 iflist = NULL;
2761                 ast_mutex_unlock(&iflock);
2762         } else {
2763                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2764                 return -1;
2765         }
2766 #endif
2767         /* if we're still here something was fscked up */   
2768         return -1;
2769 }
2770
2771 int usecount()
2772 {
2773         int res;
2774         ast_mutex_lock(&usecnt_lock);
2775         res = usecnt;
2776         ast_mutex_unlock(&usecnt_lock);
2777         return res;
2778 }
2779
2780 char *key()
2781 {
2782         return ASTERISK_GPL_KEY;
2783 }
2784
2785 char *description()
2786 {
2787         return desc;
2788 }