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