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