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