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