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