define an AST_MAX_CONTEXT for use instead of AST_MAX_EXTENSION
[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 <unistd.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <netinet/tcp.h>
23 #include <sys/ioctl.h>
24 #include <net/if.h>
25 #include <errno.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(__FILE__, "$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_CONTEXT] = "default";
676 static char language[MAX_LANGUAGE] = "";
677 static char musicclass[MAX_MUSICCLASS] = "";
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 #if 0
778 /* Protect the paging device list */
779 AST_MUTEX_DEFINE_STATIC(pagingdevicelock);
780 #endif
781
782 /* This is the thread for the monitor which checks for input on the channels
783    which are not currently in use.  */
784 static pthread_t monitor_thread = AST_PTHREADT_NULL;
785
786 /* Wait up to 16 seconds for first digit */
787 static int firstdigittimeout = 16000;
788
789 /* How long to wait for following digits */
790 static int gendigittimeout = 8000;
791
792 /* How long to wait for an extra digit, if there is an ambiguous match */
793 static int matchdigittimeout = 3000;
794
795 struct skinny_subchannel {
796         ast_mutex_t lock;
797         unsigned int callid;
798         struct ast_channel *owner;
799         struct skinny_line *parent;
800         struct ast_rtp *rtp;
801         time_t lastouttime;
802         int progress;
803         int ringing;
804         int lastout;
805         int cxmode;
806         int nat;
807         int outgoing;
808         int alreadygone;
809         struct skinny_subchannel *next; 
810 };
811
812 struct skinny_line {
813         ast_mutex_t lock;
814         char name[80];
815         char label[42];                                 /* Label that shows next to the line buttons */
816         struct skinny_subchannel *sub;                  /* pointer to our current connection, channel and stuff */
817         char accountcode[AST_MAX_ACCOUNT_CODE];
818         char exten[AST_MAX_EXTENSION];                  /* Extention where to start */
819         char context[AST_MAX_CONTEXT];
820         char language[MAX_LANGUAGE];
821         char cid_num[AST_MAX_EXTENSION];                /* Caller*ID */
822         char cid_name[AST_MAX_EXTENSION];               /* Caller*ID */
823         char lastcallerid[AST_MAX_EXTENSION];           /* Last Caller*ID */
824         char call_forward[AST_MAX_EXTENSION];   
825         char mailbox[AST_MAX_EXTENSION];
826         char musicclass[MAX_MUSICCLASS];
827         int curtone;                                    /* Current tone being played */
828         ast_group_t callgroup;
829         ast_group_t pickupgroup;
830         int callwaiting;
831         int transfer;
832         int threewaycalling;
833         int mwiblink;
834         int cancallforward;
835         int callreturn;
836         int dnd; /* How does this affect callwait?  Do we just deny a skinny_request if we're dnd? */
837         int hascallerid;
838         int hidecallerid;
839         int amaflags;
840         int type;
841         int instance;
842         int group;
843         int needdestroy;
844         int capability;
845         int nonCodecCapability;
846         int onhooktime;
847         int msgstate;           /* voicemail message state */
848         int immediate;
849         int hookstate;
850         int progress;
851         struct skinny_line *next;
852         struct skinny_device *parent;
853 };
854
855 static struct skinny_device {
856         /* A device containing one or more lines */
857         char name[80];
858         char id[16];
859         char version_id[16];    
860         int type;
861         int registered;
862         char model[6];
863         struct sockaddr_in addr;
864         struct in_addr ourip;
865         struct skinny_line *lines;
866         struct ast_ha *ha;
867         struct skinnysession *session;
868         struct skinny_device *next;
869 } *devices = NULL;
870
871 struct skinny_paging_device {
872         char name[80];
873         char id[16];
874         struct skinny_device ** devices;
875         struct skinny_paging_device *next;
876 };
877
878 static struct skinnysession {
879         pthread_t t;
880         ast_mutex_t lock;
881         struct sockaddr_in sin;
882         int fd;
883         char inbuf[SKINNY_MAX_PACKET];
884         struct skinny_device *device;
885         struct skinnysession *next;
886 } *sessions = NULL;
887
888 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause);
889 static int skinny_call(struct ast_channel *ast, char *dest, int timeout);
890 static int skinny_hangup(struct ast_channel *ast);
891 static int skinny_answer(struct ast_channel *ast);
892 static struct ast_frame *skinny_read(struct ast_channel *ast);
893 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
894 static int skinny_indicate(struct ast_channel *ast, int ind);
895 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
896 static int skinny_senddigit(struct ast_channel *ast, char digit);
897
898 static const struct ast_channel_tech skinny_tech = {
899         .type = type,
900         .description = tdesc,
901         .capabilities = AST_FORMAT_ULAW,
902         .properties = AST_CHAN_TP_WANTSJITTER,
903         .requester = skinny_request,
904         .call = skinny_call,
905         .hangup = skinny_hangup,
906         .answer = skinny_answer,
907         .read = skinny_read,
908         .write = skinny_write,
909         .indicate = skinny_indicate,
910         .fixup = skinny_fixup,
911         .send_digit = skinny_senddigit,
912 /*      .bridge = ast_rtp_bridge, */
913 };
914
915 static skinny_req *req_alloc(size_t size)
916 {
917         skinny_req *req;
918         req = malloc(size+12);
919         if (!req) {
920                 return NULL;
921         }       
922         memset(req, 0, size+12);
923         return req;
924 }
925
926 static struct skinny_subchannel *find_subchannel_by_line(struct skinny_line *l)
927 {
928         /* XXX Need to figure out how to determine which sub we want */
929         struct skinny_subchannel *sub = l->sub;
930         return sub;
931 }
932
933 static struct skinny_subchannel *find_subchannel_by_name(char *dest)
934 {
935         struct skinny_line *l;
936         struct skinny_device *d;
937         char line[256];
938         char *at;
939         char *device;
940         
941         strncpy(line, dest, sizeof(line) - 1);
942         at = strchr(line, '@');
943         if (!at) {
944                 ast_log(LOG_NOTICE, "Device '%s' has no @ (at) sign!\n", dest);
945                 return NULL;
946         }
947         *at = '\0';
948         at++;
949         device = at;
950         ast_mutex_lock(&devicelock);
951         d = devices;
952         while(d) {
953                 if (!strcasecmp(d->name, device)) {
954                         if (skinnydebug) {
955                                 ast_verbose("Found device: %s\n", d->name);
956                         }
957                         /* Found the device */
958                         l = d->lines;
959                         while (l) {
960                                 /* Search for the right line */
961                                 if (!strcasecmp(l->name, line)) {
962                                         ast_mutex_unlock(&devicelock);
963                                         return l->sub;
964                                 }
965                                 l = l->next;
966                         }
967                 }
968                 d = d->next;
969         }
970         /* Device not found*/
971         ast_mutex_unlock(&devicelock);
972         return NULL;
973 }
974
975 static int transmit_response(struct skinnysession *s, skinny_req *req)
976 {
977         int res = 0;
978         ast_mutex_lock(&s->lock);
979         
980 #if 0
981         if (skinnydebug) {
982                 ast_verbose("writing packet type %04X (%d bytes) to socket %d\n", letohl(req->e), letohl(req->len)+8, s->fd);
983         }
984 #endif
985
986         res = write(s->fd, req, letohl(req->len)+8);
987         if (res != letohl(req->len)+8) {
988                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
989         }
990         ast_mutex_unlock(&s->lock);
991         return 1;
992 }
993
994 /* XXX Do this right */
995 static int convert_cap(int capability)
996 {
997         return 4; /* ulaw (this is not the same as asterisk's '4'  */
998
999 }
1000
1001 static void transmit_speaker_mode(struct skinnysession *s, int mode)
1002 {
1003         skinny_req *req;
1004
1005         req = req_alloc(sizeof(struct set_speaker_message));
1006         if (!req) {
1007                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1008                 return;
1009         }
1010         req->len = htolel(sizeof(set_speaker_message)+4);
1011         req->e = htolel(SET_SPEAKER_MESSAGE);
1012         req->data.setspeaker.mode = htolel(mode); 
1013         transmit_response(s, req);
1014 }
1015
1016 static void transmit_callstate(struct skinnysession *s, int instance, int state, unsigned callid)
1017
1018         skinny_req *req;
1019         int memsize = sizeof(struct call_state_message);
1020
1021         req = req_alloc(memsize);
1022         if (!req) {
1023                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1024                 return;
1025         }       
1026         if (state == SKINNY_ONHOOK) {
1027                 transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
1028         }
1029         req->len = htolel(sizeof(call_state_message)+4);
1030         req->e = htolel(CALL_STATE_MESSAGE);
1031         req->data.callstate.callState = htolel(state);
1032         req->data.callstate.lineInstance = htolel(instance);
1033         req->data.callstate.callReference = htolel(callid);
1034         transmit_response(s, req);
1035         if (state == SKINNY_OFFHOOK) {
1036                 memset(req, 0, memsize);
1037                 req->len = htolel(sizeof(activate_call_plane_message)+4);
1038                 req->e = htolel(ACTIVATE_CALL_PLANE_MESSAGE);
1039                 req->data.activatecallplane.lineInstance = htolel(instance);
1040                 transmit_response(s, req);
1041         } else if (state == SKINNY_ONHOOK) {
1042                 memset(req, 0, memsize);
1043                 req->len = htolel(sizeof(activate_call_plane_message)+4);
1044                 req->e = htolel(ACTIVATE_CALL_PLANE_MESSAGE);
1045                 req->data.activatecallplane.lineInstance = 0;
1046                 transmit_response(s, req);
1047                 memset(req, 0, memsize);
1048                 req->len = htolel(sizeof(close_recieve_channel_message)+4);
1049                 req->e = htolel(CLOSE_RECIEVE_CHANNEL_MESSAGE);
1050                 req->data.closerecievechannel.conferenceId = 0;
1051                 req->data.closerecievechannel.partyId = 0;
1052                 transmit_response(s, req);
1053                 memset(req, 0, memsize);
1054                 req->len = htolel(sizeof(stop_media_transmission_message)+4);
1055                 req->e = htolel(STOP_MEDIA_TRANSMISSION_MESSAGE);
1056                 req->data.stopmedia.conferenceId = 0;   
1057                 req->data.stopmedia.passThruPartyId = 0;
1058                 transmit_response(s, req);      
1059         }
1060 }       
1061
1062 static void transmit_callinfo(struct skinnysession *s, char *fromname, char *fromnum, char *toname, char *tonum, int instance, int callid, int calltype)
1063 {
1064         skinny_req *req;
1065
1066         req = req_alloc(sizeof(struct call_info_message));
1067         if (!req) {
1068                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1069                 return;
1070         }       
1071
1072         req->len = htolel(sizeof(struct call_info_message));
1073         req->e = htolel(CALL_INFO_MESSAGE);
1074
1075         if (fromname)
1076                 ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
1077         if (fromnum)
1078                 ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
1079         if (toname)
1080                 ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
1081         if (tonum)
1082                 ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
1083
1084         req->data.callinfo.instance = htolel(instance);
1085         req->data.callinfo.reference = htolel(callid);
1086         req->data.callinfo.type = htolel(calltype);
1087
1088         transmit_response(s, req);
1089 }
1090
1091 static void transmit_connect(struct skinnysession *s)
1092 {
1093         skinny_req *req;
1094         struct skinny_line *l = s->device->lines;
1095
1096         req = req_alloc(sizeof(struct open_recieve_channel_message));
1097         if (!req) {
1098                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1099                 return;
1100         }       
1101         req->len = htolel(sizeof(struct open_recieve_channel_message));
1102         req->e = htolel(OPEN_RECIEVE_CHANNEL_MESSAGE);
1103         req->data.openrecievechannel.conferenceId = 0;
1104         req->data.openrecievechannel.partyId = 0;
1105         req->data.openrecievechannel.packets = htolel(20);
1106         req->data.openrecievechannel.capability = htolel(convert_cap(l->capability)); 
1107         req->data.openrecievechannel.echo = 0;
1108         req->data.openrecievechannel.bitrate = 0;
1109         transmit_response(s, req);
1110 }       
1111
1112 static void transmit_tone(struct skinnysession *s, int tone)
1113 {
1114         skinny_req *req;
1115
1116         if (tone > 0)
1117                 req = req_alloc(sizeof(struct start_tone_message));
1118         else 
1119                 req = req_alloc(4);
1120         if (!req) {
1121                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1122                 return;
1123         }       
1124         if (tone > 0) {
1125                 req->len = htolel(sizeof(start_tone_message)+4);
1126                 req->e = htolel(START_TONE_MESSAGE);
1127                 req->data.starttone.tone = htolel(tone); 
1128         } else {
1129                 req->len = htolel(4);
1130                 req->e = htolel(STOP_TONE_MESSAGE);
1131         }
1132         transmit_response(s, req);
1133 }
1134
1135 #if 0
1136 /* XXX need to properly deal with softkeys */
1137 static void transmit_selectsoftkeys(struct skinnysession *s, int instance, int callid, int softkey)
1138 {
1139         skinny_req *req;
1140         int memsize = sizeof(struct select_soft_keys_message);
1141
1142         req = req_alloc(memsize);
1143         if (!req) {
1144                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1145                 return;
1146         }       
1147         memset(req, 0, memsize);
1148         req->len = htolel(sizeof(select_soft_keys_message)+4);
1149         req->e = htolel(SELECT_SOFT_KEYS_MESSAGE);
1150         req->data.selectsoftkey.instance = htolel(instance);
1151         req->data.selectsoftkey.reference = htolel(callid);
1152         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
1153         transmit_response(s, req);
1154 }
1155 #endif
1156
1157 static void transmit_lamp_indication(struct skinnysession *s, int stimulus, int instance, int indication)
1158 {
1159         skinny_req *req;
1160
1161         req = req_alloc(sizeof(struct set_lamp_message));
1162         if (!req) {
1163                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1164                 return;
1165         }       
1166         req->len = htolel(sizeof(set_lamp_message)+4);
1167         req->e = htolel(SET_LAMP_MESSAGE);
1168         req->data.setlamp.stimulus = htolel(stimulus);
1169         req->data.setlamp.stimulusInstance = htolel(instance);
1170         req->data.setlamp.deviceStimulus = htolel(indication);
1171         transmit_response(s, req);
1172 }
1173
1174 static void transmit_ringer_mode(struct skinnysession *s, int mode)
1175 {
1176         skinny_req *req;
1177
1178         req = req_alloc(sizeof(struct set_ringer_message));
1179         if (!req) {
1180                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1181                 return;
1182         }
1183         req->len = htolel(sizeof(set_ringer_message)+4);
1184         req->e = htolel(SET_RINGER_MESSAGE); 
1185         req->data.setringer.ringerMode = htolel(mode); 
1186         transmit_response(s, req);
1187 }
1188
1189 static void transmit_displaymessage(struct skinnysession *s, char *text)
1190 {
1191         skinny_req *req;
1192
1193         if (text == 0) {
1194                 req = req_alloc(4);
1195                 req->len = htolel(4);
1196                 req->e = htolel(CLEAR_DISPLAY_MESSAGE);
1197         } else {
1198                 req = req_alloc(sizeof(struct displaytext_message));
1199
1200                 strncpy(req->data.displaytext.text, text, sizeof(req->data.displaytext.text)-1);
1201                 req->len = htolel(sizeof(displaytext_message) + 4);
1202                 req->e = htolel(DISPLAYTEXT_MESSAGE);
1203                 if (skinnydebug) {
1204                         ast_verbose("Displaying message '%s'\n", req->data.displaytext.text);
1205                 }
1206         }
1207
1208         if (!req) {
1209                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1210                 return;
1211         }
1212         transmit_response(s, req);
1213 }
1214
1215 static void transmit_displaynotify(struct skinnysession *s, char *text, int t)
1216 {
1217         skinny_req *req;
1218
1219         req = req_alloc(sizeof(struct display_notify_message));
1220
1221         if (!req) {
1222                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1223                 return;
1224         }
1225
1226         req->e = htolel(DISPLAY_NOTIFY_MESSAGE);
1227         req->len = htolel(sizeof(display_notify_message) + 4);
1228         strncpy(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage)-1);
1229         req->data.displaynotify.displayTimeout = htolel(t);
1230
1231         if (skinnydebug) {
1232                 ast_verbose("Displaying notify '%s'\n", text);
1233         }
1234         
1235         transmit_response(s, req);
1236 }
1237
1238 static void transmit_displaypromptstatus(struct skinnysession *s, char *text, int t, int instance, int callid)
1239 {
1240         skinny_req *req;
1241
1242         req = req_alloc(sizeof(struct display_prompt_status_message));
1243
1244         if (!req) {
1245                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1246                 return;
1247         }
1248
1249         req->e = htolel(DISPLAY_PROMPT_STATUS_MESSAGE);
1250         req->len = htolel(sizeof(display_prompt_status_message) + 4);
1251         strncpy(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage)-1);
1252         req->data.displaypromptstatus.messageTimeout = htolel(t);
1253         req->data.displaypromptstatus.lineInstance = htolel(instance);
1254         req->data.displaypromptstatus.callReference = htolel(callid);
1255
1256         if (skinnydebug) {
1257                 ast_verbose("Displaying Prompt Status '%s'\n", text);
1258         }
1259
1260         transmit_response(s, req);
1261 }
1262
1263 static void transmit_diallednumber(struct skinnysession *s, char *text, int instance, int callid)
1264 {
1265         skinny_req *req;
1266
1267         req = req_alloc(sizeof(struct dialled_number_message));
1268
1269         if (!req) {
1270                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1271                 return;
1272         }
1273
1274         req->e = htolel(DIALLED_NUMBER_MESSAGE);
1275         req->len = htolel(sizeof(dialled_number_message) + 4);
1276         strncpy(req->data.diallednumber.dialledNumber, text, sizeof(req->data.diallednumber.dialledNumber)-1);
1277         req->data.diallednumber.lineInstance = htolel(instance);
1278         req->data.diallednumber.callReference = htolel(callid);
1279
1280         transmit_response(s, req);
1281 }
1282
1283 static int has_voicemail(struct skinny_line *l)
1284 {
1285         return ast_app_has_voicemail(l->mailbox, NULL);
1286 }
1287
1288
1289 static void do_housekeeping(struct skinnysession *s)
1290 {
1291         struct skinny_subchannel *sub;
1292         struct skinny_line *l = s->device->lines;
1293
1294         sub = find_subchannel_by_line(l);
1295         transmit_displaymessage(s, NULL);
1296
1297         if (skinnydebug) {
1298                 ast_verbose("Checking for voicemail Skinny %s@%s\n", sub->parent->name, sub->parent->parent->name);
1299         }
1300         if (has_voicemail(sub->parent)) {
1301                 int new;
1302                 int old;
1303                 ast_app_messagecount(sub->parent->mailbox, &new, &old);
1304                 if (skinnydebug) {
1305                         ast_verbose("Skinny %s@%s has voicemail! Yay!\n", sub->parent->name, sub->parent->parent->name);
1306                 }
1307                 transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
1308         } else {
1309                 transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
1310         }
1311
1312 }
1313
1314 /* I do not believe skinny can deal with video. 
1315    Anyone know differently? */
1316 static struct ast_rtp *skinny_get_vrtp_peer(struct ast_channel *chan)
1317 {
1318         return NULL;
1319 }
1320
1321 static struct ast_rtp *skinny_get_rtp_peer(struct ast_channel *chan)
1322 {
1323         struct skinny_subchannel *sub;
1324         sub = chan->tech_pvt;
1325         if (sub && sub->rtp)
1326                 return sub->rtp;
1327         return NULL;
1328 }
1329
1330 static int skinny_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs)
1331 {
1332         struct skinny_subchannel *sub;
1333         sub = chan->tech_pvt;
1334         if (sub) {
1335                 /* transmit_modify_with_sdp(sub, rtp); @@FIXME@@ if needed */
1336                 return 0;
1337         }
1338         return -1;
1339 }
1340
1341 static struct ast_rtp_protocol skinny_rtp = {
1342         .type = type,
1343         .get_rtp_info = skinny_get_rtp_peer,
1344         .get_vrtp_info =  skinny_get_vrtp_peer,
1345         .set_rtp_peer = skinny_set_rtp_peer,
1346 };
1347
1348 static int skinny_do_debug(int fd, int argc, char *argv[])
1349 {
1350         if (argc != 2)
1351                 return RESULT_SHOWUSAGE;
1352         skinnydebug = 1;
1353         ast_cli(fd, "Skinny Debugging Enabled\n");
1354         return RESULT_SUCCESS;
1355 }
1356
1357 static int skinny_no_debug(int fd, int argc, char *argv[])
1358 {
1359         if (argc != 3)
1360                 return RESULT_SHOWUSAGE;
1361         skinnydebug = 0;
1362         ast_cli(fd, "Skinny Debugging Disabled\n");
1363         return RESULT_SUCCESS;
1364 }
1365
1366 static int skinny_show_devices(int fd, int argc, char *argv[])
1367 {
1368         struct skinny_device  *d;
1369         struct skinny_line *l;
1370         int numlines = 0;
1371         char iabuf[INET_ADDRSTRLEN];
1372
1373         if (argc != 3) 
1374                 return RESULT_SHOWUSAGE;
1375
1376         ast_mutex_lock(&devicelock);
1377         d = devices;
1378
1379         ast_cli(fd, "Name                 DeviceId         IP              TypeId R Model  NL\n");
1380         ast_cli(fd, "-------------------- ---------------- --------------- ------ - ------ --\n");
1381         while(d) {
1382                 l = d->lines;
1383                 numlines = 0;
1384                 while(l) { numlines++; l = l->next; }
1385
1386                 ast_cli(fd, "%-20s %-16s %-16s %6X %c %-6s %2d\n", 
1387                                 d->name, 
1388                                 d->id, 
1389                                 ast_inet_ntoa(iabuf, sizeof(iabuf), d->addr.sin_addr), 
1390                                 d->type, 
1391                                 d->registered?'Y':'N', 
1392                                 d->model, 
1393                                 numlines);
1394
1395                 d = d->next;
1396         }
1397         ast_mutex_unlock(&devicelock);
1398
1399         return RESULT_SUCCESS;
1400 }
1401
1402 static int skinny_show_lines(int fd, int argc, char *argv[])
1403 {
1404                 
1405         struct skinny_device  *d;
1406         struct skinny_line *l;
1407
1408         if (argc != 3) 
1409                 return RESULT_SHOWUSAGE;
1410
1411         ast_mutex_lock(&devicelock);
1412         d = devices;
1413         while(d) {
1414                 l = d->lines;
1415                 while (l) {
1416                         ast_cli(fd, "%-20s %2d %-20s %-20s  %c  %c\n",
1417                                 l->parent->name,
1418                                 l->instance,
1419                                 l->name,
1420                                 l->label,
1421                                 l->sub->owner?'Y':'N',
1422                                 l->sub->rtp?'Y':'N');
1423
1424                         l = l->next;
1425                 }
1426                 d = d->next;
1427         }
1428         ast_mutex_unlock(&devicelock);
1429
1430         return RESULT_SUCCESS;
1431 }
1432
1433 static char show_devices_usage[] = 
1434 "Usage: skinny show devices\n"
1435 "       Lists all devices known to the Skinny subsystem.\n";
1436
1437 static char show_lines_usage[] = 
1438 "Usage: skinny show lines\n"
1439 "       Lists all lines known to the Skinny subsystem.\n";
1440
1441 static char debug_usage[] = 
1442 "Usage: skinny debug\n"
1443 "       Enables dumping of Skinny packets for debugging purposes\n";
1444
1445 static char no_debug_usage[] = 
1446 "Usage: skinny no debug\n"
1447 "       Disables dumping of Skinny packets for debugging purposes\n";
1448
1449 static struct ast_cli_entry  cli_show_devices =
1450         { { "skinny", "show", "devices", NULL }, skinny_show_devices, "Show defined Skinny devices", show_devices_usage };
1451
1452 static struct ast_cli_entry  cli_show_lines =
1453         { { "skinny", "show", "lines", NULL }, skinny_show_lines, "Show defined Skinny lines per device", show_lines_usage };
1454
1455 static struct ast_cli_entry  cli_debug =
1456         { { "skinny", "debug", NULL }, skinny_do_debug, "Enable Skinny debugging", debug_usage };
1457
1458 static struct ast_cli_entry  cli_no_debug =
1459         { { "skinny", "no", "debug", NULL }, skinny_no_debug, "Disable Skinny debugging", no_debug_usage };
1460
1461 #if 0
1462 static struct skinny_paging_device *build_paging_device(char *cat, struct ast_variable *v)
1463 {
1464         return NULL;
1465 }
1466 #endif
1467
1468 static struct skinny_device *build_device(char *cat, struct ast_variable *v)
1469 {
1470         struct skinny_device *d;
1471         struct skinny_line *l;
1472         struct skinny_subchannel *sub;
1473         int i=0, y=0;
1474         
1475         d = malloc(sizeof(struct skinny_device));
1476         if (d) {
1477                 memset(d, 0, sizeof(struct skinny_device));
1478                 strncpy(d->name, cat, sizeof(d->name) - 1);
1479                 while(v) {
1480                         if (!strcasecmp(v->name, "host")) {
1481                                         if (ast_get_ip(&d->addr, v->value)) {
1482                                                 free(d);
1483                                                 return NULL;
1484                                         }                               
1485                         } else if (!strcasecmp(v->name, "port")) {
1486                                 d->addr.sin_port = htons(atoi(v->value));
1487                         } else if (!strcasecmp(v->name, "device")) {
1488                         strncpy(d->id, v->value, sizeof(d->id)-1);
1489                         } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
1490                                 d->ha = ast_append_ha(v->name, v->value, d->ha);
1491                         } else if (!strcasecmp(v->name, "context")) {
1492                                 strncpy(context, v->value, sizeof(context) - 1);
1493                         } else if (!strcasecmp(v->name, "version")) {
1494                                 strncpy(d->version_id, v->value, sizeof(d->version_id) -1); 
1495                         } else if (!strcasecmp(v->name, "nat")) {
1496                                 nat = ast_true(v->value);
1497                 } else if (!strcasecmp(v->name, "model")) {
1498                                 strncpy(d->model, v->value, sizeof(d->model) - 1);
1499                         } else if (!strcasecmp(v->name, "callerid")) {
1500                                 if (!strcasecmp(v->value, "asreceived")) {
1501                                         cid_num[0] = '\0';
1502                                         cid_name[0] = '\0';
1503                                 } else {
1504                                         ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
1505                                 }
1506                         } else if (!strcasecmp(v->name, "language")) {
1507                                 strncpy(language, v->value, sizeof(language)-1);
1508                         } else if (!strcasecmp(v->name, "accountcode")) {
1509                                 strncpy(accountcode, v->value, sizeof(accountcode)-1);
1510                         } else if (!strcasecmp(v->name, "amaflags")) {
1511                                 y = ast_cdr_amaflags2int(v->value);
1512                                 if (y < 0) {
1513                                         ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
1514                                 } else {
1515                                 amaflags = y;
1516                                 }
1517                         } else if (!strcasecmp(v->name, "musiconhold")) {
1518                                 strncpy(musicclass, v->value, sizeof(musicclass)-1);
1519                         } else if (!strcasecmp(v->name, "callgroup")) {
1520                                 cur_callergroup = ast_get_group(v->value);
1521                         } else if (!strcasecmp(v->name, "pickupgroup")) {
1522                                 cur_pickupgroup = ast_get_group(v->value);
1523                         } else if (!strcasecmp(v->name, "immediate")) {
1524                                 immediate = ast_true(v->value);
1525                         } else if (!strcasecmp(v->name, "cancallforward")) {
1526                                 cancallforward = ast_true(v->value);
1527                         } else if (!strcasecmp(v->name, "mailbox")) {
1528                                 strncpy(mailbox, v->value, sizeof(mailbox) -1);
1529                         } else if (!strcasecmp(v->name, "callreturn")) {
1530                                 callreturn = ast_true(v->value);
1531                         } else if (!strcasecmp(v->name, "callwaiting")) {
1532                                 callwaiting = ast_true(v->value);
1533                         } else if (!strcasecmp(v->name, "transfer")) {
1534                                 transfer = ast_true(v->value);
1535                         } else if (!strcasecmp(v->name, "threewaycalling")) {
1536                                 threewaycalling = ast_true(v->value);
1537                         } else if (!strcasecmp(v->name, "mwiblink")) {
1538                                 mwiblink = ast_true(v->value);
1539                         } else if (!strcasecmp(v->name, "linelabel")) {
1540                                 strncpy(linelabel, v->value, sizeof(linelabel)-1);
1541                         } else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
1542                                 l = malloc(sizeof(struct skinny_line));;
1543                                 if (l) {
1544                                         memset(l, 0, sizeof(struct skinny_line));
1545                                         ast_mutex_init(&l->lock);
1546                                         strncpy(l->name, v->value, sizeof(l->name) - 1);
1547                                         
1548                                         /* XXX Should we check for uniqueness?? XXX */
1549
1550                                         strncpy(l->context, context, sizeof(l->context) - 1);
1551                                         strncpy(l->cid_num, cid_num, sizeof(l->cid_num) - 1);
1552                                         strncpy(l->cid_name, cid_name, sizeof(l->cid_name) - 1);
1553                                         strncpy(l->label, linelabel, sizeof(l->label) - 1);
1554                                         strncpy(l->language, language, sizeof(l->language) - 1);
1555                                         strncpy(l->musicclass, musicclass, sizeof(l->musicclass)-1);
1556                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1557                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1558                                         if (!ast_strlen_zero(mailbox)) {
1559                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting mailbox '%s' on %s@%s\n", mailbox, d->name, l->name);
1560                                         }
1561                                 
1562                                         l->msgstate = -1;
1563                                         l->capability = capability;
1564                                         l->parent = d;
1565                                         if (!strcasecmp(v->name, "trunk")) {
1566                                                 l->type = TYPE_TRUNK;
1567                                         } else {
1568                                                 l->type = TYPE_LINE;
1569                                         }
1570                                         l->immediate = immediate;
1571                                         l->callgroup = cur_callergroup;
1572                                         l->pickupgroup = cur_pickupgroup;
1573                                         l->callreturn = callreturn;
1574                                         l->cancallforward = cancallforward;
1575                                         l->callwaiting = callwaiting;
1576                                         l->transfer = transfer; 
1577                                         l->threewaycalling = threewaycalling;
1578                                         l->mwiblink = mwiblink;
1579                                         l->onhooktime = time(NULL);
1580                                         l->instance = 1;
1581                                         /* ASSUME we're onhook at this point*/
1582                                         l->hookstate = SKINNY_ONHOOK;
1583
1584                                         for (i = 0; i < MAX_SUBS; i++) {
1585                                                 sub = malloc(sizeof(struct skinny_subchannel));
1586                                                 if (sub) {
1587                                                         ast_verbose(VERBOSE_PREFIX_3 "Allocating Skinny subchannel '%d' on %s@%s\n", i, l->name, d->name);
1588                                                         memset(sub, 0, sizeof(struct skinny_subchannel));
1589                                                         ast_mutex_init(&sub->lock);
1590                                                         sub->parent = l;
1591                                                         /* Make a call*ID */
1592                                                         sub->callid = callnums;
1593                                                         callnums++;
1594                                                         sub->cxmode = SKINNY_CX_INACTIVE;
1595                                                         sub->nat = nat;
1596                                                         sub->next = l->sub;
1597                                                         l->sub = sub;
1598                                                 } else {
1599                                                         /* XXX Should find a way to clean up our memory */
1600                                                         ast_log(LOG_WARNING, "Out of memory allocating subchannel");
1601                                                         return NULL;
1602                                                 }
1603                                         }
1604                                         l->next = d->lines;
1605                                         d->lines = l;                   
1606                                 } else {
1607                                         /* XXX Should find a way to clean up our memory */
1608                                         ast_log(LOG_WARNING, "Out of memory allocating line");
1609                                         return NULL;
1610                                 }
1611                         } else {
1612                                 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
1613                         }
1614                         v = v->next;
1615                 }
1616         
1617                 if (!d->lines) {
1618                         ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
1619                         return NULL;
1620                 }
1621
1622                 if (d->addr.sin_addr.s_addr && !ntohs(d->addr.sin_port))
1623                         d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
1624                 if (d->addr.sin_addr.s_addr) {
1625                         if (ast_ouraddrfor(&d->addr.sin_addr, &d->ourip)) {
1626                                 memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1627                         }
1628                 } else {
1629                         memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1630                 }
1631         }
1632         return d;
1633 }
1634
1635 static int skinny_register(skinny_req *req, struct skinnysession *s)
1636 {
1637         struct skinny_device *d;
1638         
1639         ast_mutex_lock(&devicelock);
1640         d = devices;
1641         while (d) {
1642                 if (!strcasecmp(req->data.reg.name, d->id) 
1643                                         && ast_apply_ha(d->ha, &(s->sin))) {
1644                         s->device = d;
1645                         d->type = letohl(req->data.reg.type);
1646                         if (ast_strlen_zero(d->version_id)) {
1647                                 strncpy(d->version_id, version_id, sizeof(d->version_id) - 1);
1648                         }
1649                         d->registered = 1;
1650                         d->session = s;
1651                         break;
1652                 }
1653                 d = d->next;
1654         }
1655         ast_mutex_unlock(&devicelock);
1656
1657         if (!d)
1658                 return 0;
1659         
1660         return 1;
1661 }               
1662
1663 static void start_rtp(struct skinny_subchannel *sub)
1664 {
1665                 ast_mutex_lock(&sub->lock);
1666                 /* Allocate the RTP */
1667                 sub->rtp = ast_rtp_new(sched, io, 1, 0);
1668                 if (sub->rtp && sub->owner)
1669                         sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
1670                 if (sub->rtp)
1671                         ast_rtp_setnat(sub->rtp, sub->nat);
1672                 
1673                 /* Create the RTP connection */
1674                 transmit_connect(sub->parent->parent->session);
1675                 ast_mutex_unlock(&sub->lock);
1676 }
1677
1678
1679 static void *skinny_ss(void *data)
1680 {
1681         struct ast_channel *chan = data;
1682         struct skinny_subchannel *sub = chan->tech_pvt;
1683         struct skinny_line *l = sub->parent;
1684         struct skinnysession *s = l->parent->session;
1685         char exten[AST_MAX_EXTENSION] = "";
1686         int len = 0;
1687         int timeout = firstdigittimeout;
1688         int res;
1689         int getforward=0;
1690     
1691         if (option_verbose > 2) {
1692                 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s@%s'\n", l->name, l->parent->name);
1693         }
1694         while(len < AST_MAX_EXTENSION-1) {
1695         res = ast_waitfordigit(chan, timeout);
1696         timeout = 0;
1697         if (res < 0) {
1698                 if (skinnydebug) {
1699                         ast_verbose("Skinny(%s@%s): waitfordigit returned < 0\n", l->name, l->parent->name);
1700                 }
1701                 ast_indicate(chan, -1);
1702                 ast_hangup(chan);
1703                 return NULL;
1704         } else if (res)  {
1705             exten[len++]=res;
1706             exten[len] = '\0';
1707         }
1708         if (!ast_ignore_pattern(chan->context, exten)) {
1709                         transmit_tone(s, SKINNY_SILENCE);
1710         } 
1711         if (ast_exists_extension(chan, chan->context, exten, 1, l->cid_num)) {
1712             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, l->cid_num)) {
1713                 if (getforward) {
1714                     /* Record this as the forwarding extension */
1715                     strncpy(l->call_forward, exten, sizeof(l->call_forward) - 1); 
1716                     if (option_verbose > 2) {
1717                         ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n", 
1718                                 l->call_forward, chan->name);
1719                     }
1720                     transmit_tone(s, SKINNY_DIALTONE); 
1721                     if (res) {
1722                             break;
1723                     }
1724                     usleep(500000);
1725                     ast_indicate(chan, -1);
1726                     sleep(1);
1727                     memset(exten, 0, sizeof(exten));
1728                     transmit_tone(s, SKINNY_DIALTONE); 
1729                     len = 0;
1730                     getforward = 0;
1731                 } else  {
1732                     strncpy(chan->exten, exten, sizeof(chan->exten)-1);
1733                     if (!ast_strlen_zero(l->cid_num)) {
1734                         if (!l->hidecallerid)
1735                             chan->cid.cid_num = strdup(l->cid_num);
1736                         chan->cid.cid_ani = strdup(l->cid_num);
1737                     }
1738                     ast_setstate(chan, AST_STATE_RING);
1739                     res = ast_pbx_run(chan);
1740                     if (res) {
1741                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
1742                                                 transmit_tone(s, SKINNY_REORDER); 
1743                     }
1744                     return NULL;
1745                 }
1746             } else {
1747                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
1748                    so just set the timeout to matchdigittimeout and wait some more */
1749                 timeout = matchdigittimeout;
1750             }
1751         } else if (res == 0) {
1752             ast_log(LOG_DEBUG, "Not enough digits (and no ambiguous match)...\n");
1753                 transmit_tone(s, SKINNY_REORDER); 
1754             ast_hangup(chan);
1755             return NULL;
1756         } else if (l->callwaiting && !strcmp(exten, "*70")) {
1757             if (option_verbose > 2) {
1758                 ast_verbose(VERBOSE_PREFIX_3 "Disabling call waiting on %s\n", chan->name);
1759             }
1760             /* Disable call waiting if enabled */
1761             l->callwaiting = 0;
1762             transmit_tone(s, SKINNY_DIALTONE);
1763                         len = 0;
1764             memset(exten, 0, sizeof(exten));
1765             timeout = firstdigittimeout;
1766                 
1767         } else if (!strcmp(exten,ast_pickup_ext())) {
1768             /* Scan all channels and see if any there
1769              * ringing channqels with that have call groups
1770              * that equal this channels pickup group  
1771              */
1772             if (ast_pickup_call(chan)) {
1773                 ast_log(LOG_WARNING, "No call pickup possible...\n");
1774                                 transmit_tone(s, SKINNY_REORDER);
1775             }
1776             ast_hangup(chan);
1777             return NULL;
1778             
1779         } else if (!l->hidecallerid && !strcmp(exten, "*67")) {
1780             if (option_verbose > 2) {
1781                 ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
1782             }
1783             /* Disable Caller*ID if enabled */
1784             l->hidecallerid = 1;
1785             if (chan->cid.cid_num)
1786                 free(chan->cid.cid_num);
1787             chan->cid.cid_num = NULL;
1788             
1789                         if (chan->cid.cid_name)
1790                 free(chan->cid.cid_name);
1791             chan->cid.cid_name = NULL;
1792                         
1793             transmit_tone(s, SKINNY_DIALTONE);
1794             len = 0;
1795             memset(exten, 0, sizeof(exten));
1796             timeout = firstdigittimeout;
1797         } else if (l->callreturn && !strcmp(exten, "*69")) {
1798             res = 0;
1799             if (!ast_strlen_zero(l->lastcallerid)) {
1800                 res = ast_say_digit_str(chan, l->lastcallerid, "", chan->language);
1801             }
1802             if (!res) {
1803                 transmit_tone(s, SKINNY_DIALTONE);
1804                         }
1805             break;
1806         } else if (!strcmp(exten, "*78")) {
1807             /* Do not disturb */
1808             if (option_verbose > 2) {
1809                 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %s\n", chan->name);
1810             }
1811             transmit_tone(s, SKINNY_DIALTONE);
1812             l->dnd = 1;
1813             getforward = 0;
1814             memset(exten, 0, sizeof(exten));
1815             len = 0;
1816         } else if (!strcmp(exten, "*79")) {
1817             /* Do not disturb */
1818             if (option_verbose > 2) {
1819                 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %s\n", chan->name);
1820             }
1821                         transmit_tone(s, SKINNY_DIALTONE);
1822             l->dnd = 0;
1823             getforward = 0;
1824             memset(exten, 0, sizeof(exten));
1825             len = 0;
1826         } else if (l->cancallforward && !strcmp(exten, "*72")) {
1827             transmit_tone(s, SKINNY_DIALTONE);
1828             getforward = 1;
1829             memset(exten, 0, sizeof(exten));
1830             len = 0;
1831         } else if (l->cancallforward && !strcmp(exten, "*73")) {
1832             if (option_verbose > 2) {
1833                 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %s\n", chan->name);
1834             }
1835             transmit_tone(s, SKINNY_DIALTONE); 
1836             memset(l->call_forward, 0, sizeof(l->call_forward));
1837             getforward = 0;
1838             memset(exten, 0, sizeof(exten));
1839             len = 0;
1840         } else if (!strcmp(exten, ast_parking_ext()) && 
1841                     sub->next->owner &&
1842                     ast_bridged_channel(sub->next->owner)) {
1843             /* This is a three way call, the main call being a real channel, 
1844                 and we're parking the first call. */
1845             ast_masq_park_call(ast_bridged_channel(sub->next->owner), chan, 0, NULL);
1846             if (option_verbose > 2) {
1847                 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
1848             }
1849             break;
1850         } else if (!ast_strlen_zero(l->lastcallerid) && !strcmp(exten, "*60")) {
1851             if (option_verbose > 2) {
1852                 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", l->lastcallerid);
1853             }
1854             res = ast_db_put("blacklist", l->lastcallerid, "1");
1855             if (!res) {
1856                 transmit_tone(s, SKINNY_DIALTONE);              
1857                 memset(exten, 0, sizeof(exten));
1858                 len = 0;
1859             }
1860         } else if (l->hidecallerid && !strcmp(exten, "*82")) {
1861             if (option_verbose > 2) {
1862                 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
1863             }
1864             /* Enable Caller*ID if enabled */
1865             l->hidecallerid = 0;
1866             if (chan->cid.cid_num)
1867                 free(chan->cid.cid_num);
1868             if (!ast_strlen_zero(l->cid_num))
1869                 chan->cid.cid_num = strdup(l->cid_num);
1870
1871             if (chan->cid.cid_name)
1872                 free(chan->cid.cid_name);
1873             if (!ast_strlen_zero(l->cid_name))
1874                 chan->cid.cid_name = strdup(l->cid_name);
1875
1876             transmit_tone(s, SKINNY_DIALTONE);
1877             len = 0;
1878             memset(exten, 0, sizeof(exten));
1879             timeout = firstdigittimeout;
1880         } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
1881                         ((exten[0] != '*') || (!ast_strlen_zero(exten) > 2))) {
1882             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);
1883             transmit_tone(s, SKINNY_REORDER); 
1884                         sleep(3); /* hang out for 3 seconds to let congestion play */
1885                         break;
1886         }
1887         if (!timeout)
1888             timeout = gendigittimeout;
1889         if (len && !ast_ignore_pattern(chan->context, exten))
1890                         ast_indicate(chan, -1);
1891     }
1892         ast_hangup(chan);
1893         return NULL;
1894 }
1895
1896
1897
1898 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
1899 {
1900         int res = 0;
1901         int tone = 0;
1902         struct skinny_line *l;
1903         struct skinny_subchannel *sub;
1904         struct skinnysession *session;
1905         
1906         sub = ast->tech_pvt;
1907         l = sub->parent;
1908         session = l->parent->session;
1909
1910         if (!l->parent->registered) {
1911                 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
1912                 return -1;
1913         }
1914         
1915         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1916                 ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
1917                 return -1;
1918         }
1919
1920         if (skinnydebug) {
1921                 ast_verbose(VERBOSE_PREFIX_3 "skinny_call(%s)\n", ast->name);
1922         }
1923
1924         if (l->dnd) {
1925                 ast_queue_control(ast, AST_CONTROL_BUSY);
1926                 return -1;
1927         }
1928    
1929         switch (l->hookstate) {
1930         case SKINNY_OFFHOOK:
1931             tone = SKINNY_CALLWAITTONE;
1932             break;
1933         case SKINNY_ONHOOK:
1934                         tone = SKINNY_ALERT;
1935                         break;
1936         default:
1937             ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
1938             break;
1939         }
1940
1941         transmit_lamp_indication(session, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
1942         transmit_ringer_mode(session, SKINNY_RING_INSIDE);
1943         
1944         if (ast->cid.cid_num) { 
1945                 char ciddisplay[41];
1946                 char *work;
1947                 size_t size = sizeof(ciddisplay);
1948
1949                 /* We'll assume that if it is 10 numbers, it is a standard NANPA number
1950                    Why? Because I am bloody American, and I'm bigoted that way. */
1951
1952                 if (strlen(ast->cid.cid_num) == 10) {
1953                         ast_build_string(&work, &size, "(xxx)xxx-xxxx      %s",
1954                                          ast->cid.cid_name ? ast->cid.cid_name : "");
1955                         memcpy(&ciddisplay[1], ast->cid.cid_num, 3);
1956                         memcpy(&ciddisplay[5], &ast->cid.cid_num[3], 3);
1957                         memcpy(&ciddisplay[9], &ast->cid.cid_num[6], 4);
1958                 } else {
1959                         if (strlen(ast->cid.cid_num) < 41)
1960                                 ast_build_string(&work, &size, "%s -- %s", ast->cid.cid_num,
1961                                                  ast->cid.cid_name ? ast->cid.cid_name : "");
1962                         else
1963                                 strncpy(ciddisplay, "Number too long!", 15);
1964                 }
1965
1966                 if (skinnydebug)
1967                         ast_verbose("Trying to send: '%s'\n",ciddisplay);
1968
1969                 transmit_displaymessage(session, ciddisplay);
1970         } else
1971                 transmit_displaymessage(session, "Unknown Name");
1972
1973         transmit_tone(session, tone);
1974         transmit_callstate(session, l->instance, SKINNY_RINGIN, sub->callid);
1975         transmit_displaypromptstatus(session, "Ring-In", 0, l->instance, sub->callid);
1976         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 */
1977
1978         /* XXX need to deal with softkeys */
1979
1980         ast_setstate(ast, AST_STATE_RINGING);
1981         ast_queue_control(ast, AST_CONTROL_RINGING);
1982
1983         sub->outgoing = 1;
1984
1985         return res;
1986 }
1987
1988
1989 static int skinny_hangup(struct ast_channel *ast)
1990 {
1991     struct skinny_subchannel *sub = ast->tech_pvt;
1992     struct skinny_line *l = sub->parent;
1993     struct skinnysession *s = l->parent->session;
1994
1995     if (skinnydebug) {
1996         ast_verbose("skinny_hangup(%s) on %s@%s\n", ast->name, l->name, l->parent->name);
1997     }
1998     if (!ast->tech_pvt) {
1999         ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
2000         return 0;
2001     }
2002
2003     if (l->parent->registered) {
2004         if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_OFFHOOK)) {
2005                         sub->parent->hookstate = SKINNY_ONHOOK;
2006                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2007                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2008                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
2009                 } else if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_ONHOOK)) {
2010                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2011                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
2012                         transmit_ringer_mode(s, SKINNY_RING_OFF);
2013                         transmit_tone(s, SKINNY_SILENCE);
2014                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2015                         do_housekeeping(s);
2016                 } 
2017     }
2018     ast_mutex_lock(&sub->lock);
2019     sub->owner = NULL;
2020     ast->tech_pvt = NULL;
2021     sub->alreadygone = 0;
2022     sub->outgoing = 0;
2023     if (sub->rtp) {
2024         ast_rtp_destroy(sub->rtp);
2025         sub->rtp = NULL;
2026     }
2027     ast_mutex_unlock(&sub->lock);
2028     return 0;
2029 }
2030
2031 static int skinny_answer(struct ast_channel *ast)
2032 {
2033     int res = 0;
2034     struct skinny_subchannel *sub = ast->tech_pvt;
2035     struct skinny_line *l = sub->parent;
2036     struct skinnysession *s = l->parent->session;
2037
2038     sub->cxmode = SKINNY_CX_SENDRECV;
2039     if (!sub->rtp) {
2040                 start_rtp(sub);
2041     } 
2042     ast_verbose("skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, l->parent->name, sub->callid);
2043     if (ast->_state != AST_STATE_UP) {
2044         ast_setstate(ast, AST_STATE_UP);
2045     }
2046
2047     transmit_tone(s, SKINNY_NOTONE);
2048     transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
2049     transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
2050     return res;
2051 }
2052
2053 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
2054 {
2055         /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
2056         struct ast_frame *f;
2057         f = ast_rtp_read(sub->rtp);
2058         if (sub->owner) {
2059                 /* We already hold the channel lock */
2060                 if (f->frametype == AST_FRAME_VOICE) {
2061                         if (f->subclass != sub->owner->nativeformats) {
2062                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2063                                 sub->owner->nativeformats = f->subclass;
2064                                 ast_set_read_format(sub->owner, sub->owner->readformat);
2065                                 ast_set_write_format(sub->owner, sub->owner->writeformat);
2066                         }
2067                 }
2068         }
2069         return f;
2070 }
2071
2072 static struct ast_frame  *skinny_read(struct ast_channel *ast)
2073 {
2074         struct ast_frame *fr;
2075         struct skinny_subchannel *sub = ast->tech_pvt;
2076         ast_mutex_lock(&sub->lock);
2077         fr = skinny_rtp_read(sub);
2078         ast_mutex_unlock(&sub->lock);
2079         return fr;
2080 }
2081
2082 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
2083 {
2084         struct skinny_subchannel *sub = ast->tech_pvt;
2085         int res = 0;
2086         if (frame->frametype != AST_FRAME_VOICE) {
2087                 if (frame->frametype == AST_FRAME_IMAGE)
2088                         return 0;
2089                 else {
2090                         ast_log(LOG_WARNING, "Can't send %d type frames with skinny_write\n", frame->frametype);
2091                         return 0;
2092                 }
2093         } else {
2094                 if (!(frame->subclass & ast->nativeformats)) {
2095                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2096                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2097                         return -1;
2098                 }
2099         }
2100         if (sub) {
2101                 ast_mutex_lock(&sub->lock);
2102                 if (sub->rtp) {
2103                         res =  ast_rtp_write(sub->rtp, frame);
2104                 }
2105                 ast_mutex_unlock(&sub->lock);
2106         }
2107         return res;
2108 }
2109
2110 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2111 {
2112         struct skinny_subchannel *sub = newchan->tech_pvt;
2113         ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", oldchan->name, newchan->name);
2114         if (sub->owner != oldchan) {
2115                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
2116                 return -1;
2117         }
2118         sub->owner = newchan;
2119         return 0;
2120 }
2121
2122 static int skinny_senddigit(struct ast_channel *ast, char digit)
2123 {
2124 #if 0
2125         struct skinny_subchannel *sub = ast->tech_pvt;
2126         int tmp;
2127         /* not right */
2128         sprintf(tmp, "%d", digit);  
2129         transmit_tone(sub->parent->parent->session, digit);
2130 #endif
2131         return -1;
2132 }
2133
2134 static char *control2str(int ind) {
2135     static char tmp[100];
2136
2137     switch (ind) {
2138         case AST_CONTROL_HANGUP:
2139             return "Other end has hungup";
2140         case AST_CONTROL_RING:
2141             return "Local ring";
2142         case AST_CONTROL_RINGING:
2143             return "Remote end is ringing";
2144         case AST_CONTROL_ANSWER:
2145             return "Remote end has answered";
2146         case AST_CONTROL_BUSY:
2147             return "Remote end is busy";
2148         case AST_CONTROL_TAKEOFFHOOK:
2149             return "Make it go off hook";
2150         case AST_CONTROL_OFFHOOK:
2151             return "Line is off hook";
2152         case AST_CONTROL_CONGESTION:
2153             return "Congestion (circuits busy)";
2154         case AST_CONTROL_FLASH:
2155             return "Flash hook";
2156         case AST_CONTROL_WINK:
2157             return "Wink";
2158         case AST_CONTROL_OPTION:
2159             return "Set a low-level option";
2160         case AST_CONTROL_RADIO_KEY:
2161             return "Key Radio";
2162         case AST_CONTROL_RADIO_UNKEY:
2163             return "Un-Key Radio";
2164         case AST_CONTROL_PROGRESS:
2165             return "Remote end is making Progress";
2166         case AST_CONTROL_PROCEEDING:
2167             return "Remote end is proceeding";
2168         case AST_CONTROL_HOLD:
2169             return "Hold";
2170         case AST_CONTROL_UNHOLD:
2171             return "Unhold";
2172         case -1:
2173             return "Stop tone";
2174     }
2175     snprintf(tmp, 100, "UNKNOWN-%d", ind);
2176     return tmp;
2177 }
2178
2179
2180 static int skinny_indicate(struct ast_channel *ast, int ind)
2181 {
2182         struct skinny_subchannel *sub = ast->tech_pvt;
2183         struct skinny_line *l = sub->parent;
2184         struct skinnysession *s = l->parent->session;
2185
2186         if (skinnydebug) {
2187                 ast_verbose(VERBOSE_PREFIX_3 "Asked to indicate '%s' condition on channel %s\n", control2str(ind), ast->name);
2188         }
2189         switch(ind) {
2190         case AST_CONTROL_RINGING:
2191                 if (ast->_state != AST_STATE_UP) {
2192                         if (!sub->progress) {           
2193                                 transmit_tone(s, SKINNY_ALERT);
2194                                 transmit_callstate(s, l->instance, SKINNY_RINGOUT, sub->callid);
2195                                 transmit_diallednumber(s, ast->exten, l->instance, sub->callid);
2196                                 transmit_displaypromptstatus(s, "Ring Out", 0, l->instance, sub->callid);
2197                                 transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2198                                 sub->ringing = 1;
2199                                 break;
2200                         }
2201                 }
2202                 return -1;
2203         case AST_CONTROL_BUSY:
2204                 if (ast->_state != AST_STATE_UP) {              
2205                         transmit_tone(s, SKINNY_BUSYTONE);
2206                         transmit_callstate(s, l->instance, SKINNY_BUSY, sub->callid);
2207                         sub->alreadygone = 1;
2208                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2209                         break;
2210                 }
2211                 return -1;
2212         case AST_CONTROL_CONGESTION:
2213                 if (ast->_state != AST_STATE_UP) {              
2214                         transmit_tone(s, SKINNY_REORDER);
2215                         transmit_callstate(s, l->instance, SKINNY_CONGESTION, sub->callid);
2216                         sub->alreadygone = 1;
2217                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2218                         break;
2219                 }
2220                 return -1;
2221         case AST_CONTROL_PROGRESS:
2222                 if ((ast->_state != AST_STATE_UP) && !sub->progress && !sub->outgoing) {
2223                         transmit_tone(s, SKINNY_ALERT);
2224                         transmit_callstate(s, l->instance, SKINNY_PROGRESS, sub->callid);
2225                         transmit_displaypromptstatus(s, "Call Progress", 0, l->instance, sub->callid);
2226                         transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2227                         sub->progress = 1;
2228                         break;
2229                 }
2230                 return -1;  
2231         case -1:
2232                 transmit_tone(s, SKINNY_SILENCE);
2233                 break;          
2234         case AST_CONTROL_PROCEEDING:
2235                 break;
2236         default:
2237                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
2238                 return -1;
2239         }
2240         return 0;
2241 }
2242         
2243 static struct ast_channel *skinny_new(struct skinny_subchannel *sub, int state)
2244 {
2245         struct ast_channel *tmp;
2246         struct skinny_line *l = sub->parent;
2247         int fmt;
2248         l = sub->parent;
2249         tmp = ast_channel_alloc(1);
2250         if (tmp) {
2251                 tmp->tech = &skinny_tech;
2252                 tmp->nativeformats = l->capability;
2253                 if (!tmp->nativeformats)
2254                         tmp->nativeformats = capability;
2255                 fmt = ast_best_codec(tmp->nativeformats);
2256 ast_verbose("chan_skinny: skinny_new: tmp->nativeformats=%d fmt=%d\n", tmp->nativeformats, fmt);
2257                 snprintf(tmp->name, sizeof(tmp->name), "Skinny/%s@%s-%d", l->name, l->parent->name, sub->callid);
2258                 if (sub->rtp)
2259                         tmp->fds[0] = ast_rtp_fd(sub->rtp);
2260                 tmp->type = type;
2261                 ast_setstate(tmp, state);
2262                 if (state == AST_STATE_RING)
2263                         tmp->rings = 1;
2264                 tmp->writeformat = fmt;
2265                 tmp->rawwriteformat = fmt;
2266                 tmp->readformat = fmt;
2267                 tmp->rawreadformat = fmt;
2268                 tmp->tech_pvt = sub;
2269                 if (!ast_strlen_zero(l->language))
2270                         strncpy(tmp->language, l->language, sizeof(tmp->language)-1);
2271                 if (!ast_strlen_zero(l->accountcode))
2272                         strncpy(tmp->accountcode, l->accountcode, sizeof(tmp->accountcode)-1);
2273                 if (l->amaflags)
2274                         tmp->amaflags = l->amaflags;
2275                 sub->owner = tmp;
2276                 ast_mutex_lock(&usecnt_lock);
2277                 usecnt++;
2278                 ast_mutex_unlock(&usecnt_lock);
2279                 ast_update_use_count();
2280                 tmp->callgroup = l->callgroup;
2281                 tmp->pickupgroup = l->pickupgroup;
2282                 strncpy(tmp->call_forward, l->call_forward, sizeof(tmp->call_forward) - 1);
2283                 strncpy(tmp->context, l->context, sizeof(tmp->context)-1);
2284                 strncpy(tmp->exten,l->exten, sizeof(tmp->exten)-1);
2285                 if (!ast_strlen_zero(l->cid_num)) {
2286                         tmp->cid.cid_num = strdup(l->cid_num);
2287                 }
2288                 if (!ast_strlen_zero(l->cid_name)) {
2289                         tmp->cid.cid_name = strdup(l->cid_name);
2290                 }
2291                 tmp->priority = 1;
2292
2293                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2294
2295
2296                 if (state != AST_STATE_DOWN) {
2297                         if (ast_pbx_start(tmp)) {
2298                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2299                                 ast_hangup(tmp);
2300                                 tmp = NULL;
2301                         }
2302                 }
2303         } else {
2304                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2305     }
2306
2307         return tmp;
2308 }
2309
2310 static int handle_message(skinny_req *req, struct skinnysession *s)
2311 {
2312         struct skinny_subchannel *sub;
2313         struct ast_channel *c;
2314         struct ast_frame f = { 0, };    
2315         struct sockaddr_in sin;
2316         struct sockaddr_in us;
2317         struct skinny_line *lines;
2318         char name[16];
2319         char addr[4];
2320         char d;
2321         char iabuf[INET_ADDRSTRLEN];
2322         int digit;
2323         int res=0;
2324         int speedDialNum;
2325         int lineNumber;
2326         int stimulus;
2327         int stimulusInstance;
2328         int status;
2329         int port;
2330         int i;
2331         time_t timer;
2332         struct tm *cmtime;
2333         pthread_t t;
2334         button_defs_t *b, *buse;
2335         
2336         if ( (!s->device) && (letohl(req->e) != REGISTER_MESSAGE && letohl(req->e) != ALARM_MESSAGE)) {
2337                 ast_log(LOG_WARNING, "Client sent message #%d without first registering.\n", req->e);
2338                 free(req);
2339                 return 0;
2340         }
2341
2342         switch(letohl(req->e))  {
2343         case ALARM_MESSAGE:
2344                 /* no response necessary */
2345                 break;
2346         case REGISTER_MESSAGE:
2347                 if (skinnydebug) {
2348                         ast_verbose("Device %s is attempting to register\n", req->data.reg.name);
2349                 }
2350                 res = skinny_register(req, s);  
2351                 if (!res) {
2352                         ast_log(LOG_ERROR, "Rejecting Device %s: Device not found\n", req->data.reg.name);
2353                         memcpy(&name, req->data.reg.name, sizeof(req->data.reg.name));
2354                         memset(req, 0, sizeof(skinny_req));
2355                         req->len = htolel(sizeof(register_rej_message)+4);
2356                         req->e = htolel(REGISTER_REJ_MESSAGE);
2357                         snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2358                         transmit_response(s, req);
2359                         break;
2360                 }
2361                 if (option_verbose > 2) {
2362                         ast_verbose(VERBOSE_PREFIX_3 "Device '%s' successfuly registered\n", s->device->name); 
2363                 }
2364                 memset(req, 0, SKINNY_MAX_PACKET);
2365                 req->len = htolel(sizeof(register_ack_message)+4);
2366                 req->e = htolel(REGISTER_ACK_MESSAGE);
2367                 req->data.regack.res[0] = '0';
2368                 req->data.regack.res[1] = '\0';
2369                 req->data.regack.keepAlive = htolel(keep_alive);
2370                 strncpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate) - 1); 
2371                 req->data.regack.res2[0] = '0';
2372                 req->data.regack.res2[1] = '\0';
2373                 req->data.regack.secondaryKeepAlive = htolel(keep_alive);
2374                 transmit_response(s, req);
2375                 if (skinnydebug) {
2376                         ast_verbose("Requesting capabilities\n");
2377                 }
2378                 memset(req, 0, SKINNY_MAX_PACKET);
2379                 req->len = htolel(4);
2380                 req->e = htolel(CAPABILITIES_REQ_MESSAGE);
2381                 transmit_response(s, req);
2382                 break;
2383         case UNREGISTER_MESSAGE:
2384                 /* XXX Acutally unregister the device */
2385                 break;
2386         case IP_PORT_MESSAGE:
2387                 /* no response necessary */
2388                 break;
2389         case STIMULUS_MESSAGE:
2390                 stimulus = letohl(req->data.stimulus.stimulus);
2391                 stimulusInstance = letohl(req->data.stimulus.stimulusInstance);
2392                 
2393                 switch(stimulus) {
2394                 case STIMULUS_REDIAL:
2395                         /* If we can keep an array of dialed frames we can implement a quick 
2396                            and dirty redial, feeding the frames we last got into the queue
2397                            function */
2398
2399                         if (skinnydebug) {
2400                                 ast_verbose("Recieved Stimulus: Redial(%d)\n", stimulusInstance);
2401                         }
2402
2403
2404                         break;
2405                 case STIMULUS_SPEEDDIAL:
2406                         if (skinnydebug) {
2407                                 ast_verbose("Recieved Stimulus: SpeedDial(%d)\n", stimulusInstance);
2408                         }
2409                         break;
2410                 case STIMULUS_HOLD:
2411                         /* start moh? set RTP to 0.0.0.0? */
2412                         if (skinnydebug) {
2413                                 ast_verbose("Recieved Stimulus: Hold(%d)\n", stimulusInstance);
2414                         }
2415                         break;
2416                 case STIMULUS_TRANSFER:
2417                         if (skinnydebug) {
2418                                 ast_verbose("Recieved Stimulus: Transfer(%d)\n", stimulusInstance);
2419                         }
2420                         transmit_tone(s, SKINNY_DIALTONE);
2421                                 
2422                         /* figure out how to transfer */
2423
2424                         break;
2425                 case STIMULUS_CONFERENCE:
2426                         if (skinnydebug) {
2427                                 ast_verbose("Recieved Stimulus: Transfer(%d)\n", stimulusInstance);
2428                         }
2429                         transmit_tone(s, SKINNY_DIALTONE);
2430
2431                         /* figure out how to bridge n' stuff */
2432                                 
2433
2434                         break;
2435                 case STIMULUS_VOICEMAIL:
2436                         if (skinnydebug) {
2437                                 ast_verbose("Recieved Stimulus: Voicemail(%d)\n", stimulusInstance);
2438                         }
2439                                 
2440                         /* Dial Voicemail */
2441
2442                         break;
2443                 case STIMULUS_CALLPARK:
2444                         if (skinnydebug) {
2445                                 ast_verbose("Recieved Stimulus: Park Call(%d)\n", stimulusInstance);
2446                         }
2447
2448                         break;
2449                 case STIMULUS_FORWARDALL:
2450                         /* Do not disturb */
2451                         transmit_tone(s, SKINNY_DIALTONE);
2452                         if(s->device->lines->dnd != 0){
2453                                 if (option_verbose > 2) {
2454                                         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);
2455                                 }
2456                                 s->device->lines->dnd = 0;
2457                                 transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
2458                                 transmit_displaynotify(s, "DnD disabled",10);
2459                         }else{
2460                                 if (option_verbose > 2) {
2461                                         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);
2462                                 }
2463                                 s->device->lines->dnd = 1;
2464                                 transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_OFF);
2465                                 transmit_displaynotify(s, "DnD enabled",10);
2466                         }
2467                         break;
2468                 case STIMULUS_FORWARDBUSY:
2469                 case STIMULUS_FORWARDNOANSWER:
2470                         /* Gonna be fun, not */
2471                         if (skinnydebug) {
2472                                 ast_verbose("Recieved Stimulus: Forward (%d)\n", stimulusInstance);
2473                         }
2474                         break;
2475                 case STIMULUS_DISPLAY:
2476                         /* Not sure what this is */
2477                         if (skinnydebug) {
2478                                 ast_verbose("Recieved Stimulus: Display(%d)\n", stimulusInstance);
2479                         }
2480                         break;
2481                 case STIMULUS_LINE:
2482                         if (skinnydebug) {
2483                                 ast_verbose("Recieved Stimulus: Line(%d)\n", stimulusInstance);
2484                         }               
2485                         sub = find_subchannel_by_line(s->device->lines);
2486                         /* turn the speaker on */
2487                         transmit_speaker_mode(s, 1);  
2488                 break;
2489                 default:
2490                         ast_verbose("RECEIVED UNKNOWN STIMULUS:  %d(%d)\n", stimulus, stimulusInstance);                        
2491                         break;
2492                 }
2493                 break;
2494         case VERSION_REQ_MESSAGE:
2495                 if (skinnydebug) {
2496                         ast_verbose("Version Request\n");
2497                 }
2498                 memset(req, 0, SKINNY_MAX_PACKET);
2499                 req->len = htolel(sizeof(version_res_message)+4);
2500                 req->e = htolel(VERSION_RES_MESSAGE);
2501                 snprintf(req->data.version.version, sizeof(req->data.version.version), s->device->version_id);
2502                 transmit_response(s, req);
2503                 break;
2504         case SERVER_REQUEST_MESSAGE:
2505                 if (skinnydebug) {
2506                         ast_verbose("Recieved Server Request\n");
2507                 }
2508                 memset(req, 0, SKINNY_MAX_PACKET);
2509                 req->len = htolel(sizeof(server_res_message)+4);
2510                 req->e = htolel(SERVER_RES_MESSAGE);
2511                 memcpy(req->data.serverres.server[0].serverName, ourhost, 
2512                                 sizeof(req->data.serverres.server[0].serverName));
2513                 req->data.serverres.serverListenPort[0] = htolel(ourport);
2514                 req->data.serverres.serverIpAddr[0] = htolel(__ourip.s_addr);
2515                 transmit_response(s, req);      
2516                 break;
2517         case BUTTON_TEMPLATE_REQ_MESSAGE:
2518                 if (skinnydebug) {
2519                         ast_verbose("Buttontemplate requested\n");
2520                 }
2521
2522                 sub = find_subchannel_by_line(s->device->lines);
2523
2524                 memset(req, 0, SKINNY_MAX_PACKET);
2525                 req->e = htolel(BUTTON_TEMPLATE_RES_MESSAGE);   
2526                 req->len = htolel(sizeof(button_template_res_message)+4);
2527
2528                 /* Find a matching button definition, default to first in the
2529                    list */
2530                 buse = button_defs;
2531                 for(b=button_defs; b->type; b++) {
2532                         if (!strcmp(s->device->model, b->type)) {
2533                                 buse = b;
2534                         }
2535                 }
2536
2537                 req->data.buttontemplate.buttonOffset = 0;
2538                 req->data.buttontemplate.buttonCount  = htolel(buse->num_buttons);
2539                 req->data.buttontemplate.totalButtonCount = htolel(buse->num_buttons);
2540                 for (i=0; i<42; i++) {
2541                         if (i < buse->num_buttons) {
2542                                 memcpy(&(req->data.buttontemplate.definition[i]),
2543                                         &(buse->button_def[i]),
2544                                         sizeof(button_definition));
2545                         } else {
2546                                 memcpy(&(req->data.buttontemplate.definition[i]),
2547                                         &(button_def_none),
2548                                         sizeof(button_definition));
2549                         }
2550                 }
2551
2552                 if(skinnydebug){                        
2553                         ast_verbose("Sending %s template to %s@%s (%s)\n",
2554                                                 buse->type, 
2555                                                 sub->parent->name, 
2556                                                 sub->parent->parent->name, 
2557                                                 s->device->model);
2558                 }
2559
2560                 transmit_response(s, req);
2561                 break;
2562         case SOFT_KEY_SET_REQ_MESSAGE:
2563                 if (skinnydebug)  {
2564                         ast_verbose("Received SoftKeySetReq\n");
2565                 }
2566                 memset(req, 0, SKINNY_MAX_PACKET);
2567                 req->len = htolel(sizeof(soft_key_sets)+4);
2568                 req->e = htolel(SOFT_KEY_SET_RES_MESSAGE);
2569                 req->data.softkeysets.softKeySetOffset          = 0;
2570                 req->data.softkeysets.softKeySetCount           = htolel(11);
2571                 req->data.softkeysets.totalSoftKeySetCount  = htolel(11);       
2572                 /* XXX Wicked hack XXX */
2573                 memcpy(req->data.softkeysets.softKeySetDefinition, 
2574                            soft_key_set_hack, 
2575                            sizeof(req->data.softkeysets.softKeySetDefinition));
2576                 transmit_response(s,req);
2577                 break;
2578         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
2579                 if (skinnydebug) {
2580                         ast_verbose("Recieved SoftKey Template Request\n");
2581                 }
2582                 memset(req, 0, SKINNY_MAX_PACKET);
2583                 req->len = htolel(sizeof(soft_key_template)+4);
2584                 req->e = htolel(SOFT_KEY_TEMPLATE_RES_MESSAGE);
2585                 req->data.softkeytemplate.softKeyOffset         = 0;
2586                 req->data.softkeytemplate.softKeyCount          = htolel(sizeof(soft_key_template_default) / sizeof(soft_key_template_definition));
2587                 req->data.softkeytemplate.totalSoftKeyCount     = htolel(sizeof(soft_key_template_default) / sizeof(soft_key_template_definition)); 
2588                 memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
2589                            soft_key_template_default,
2590                            sizeof(soft_key_template_default));
2591                 transmit_response(s,req);
2592                 break;
2593         case TIME_DATE_REQ_MESSAGE:
2594                 if (skinnydebug) {
2595                         ast_verbose("Received Time/Date Request\n");
2596                 }
2597                 memset(req, 0, SKINNY_MAX_PACKET);
2598                 req->len = htolel(sizeof(definetimedate_message)+4);
2599                 req->e = htolel(DEFINETIMEDATE_MESSAGE);
2600                 timer=time(NULL);
2601                 cmtime = localtime(&timer);
2602                 req->data.definetimedate.year = htolel(cmtime->tm_year+1900);
2603                 req->data.definetimedate.month = htolel(cmtime->tm_mon+1);
2604                 req->data.definetimedate.dayofweek = htolel(cmtime->tm_wday);
2605                 req->data.definetimedate.day = htolel(cmtime->tm_mday);
2606                 req->data.definetimedate.hour = htolel(cmtime->tm_hour);
2607                 req->data.definetimedate.minute = htolel(cmtime->tm_min);
2608                 req->data.definetimedate.seconds = htolel(cmtime->tm_sec);
2609                 transmit_response(s, req);
2610                 break;
2611         case SPEED_DIAL_STAT_REQ_MESSAGE:
2612                 /* Not really sure how Speed Dial's are different than the 
2613                    Softkey templates */
2614                 speedDialNum = letohl(req->data.speeddialreq.speedDialNumber);
2615                 memset(req, 0, SKINNY_MAX_PACKET);
2616                 req->len = htolel(sizeof(speed_dial_stat_res_message)+4);
2617                 req->e = htolel(SPEED_DIAL_STAT_RES_MESSAGE);
2618 #if 0
2619                 /* XXX Do this right XXX */     
2620                 /* If the redial function works the way I think it will, a modification of it
2621                    can work here was well. Yikes. */
2622                 req->data.speeddialreq.speedDialNumber = speedDialNum;
2623                 snprintf(req->data.speeddial.speedDialDirNumber, sizeof(req->data.speeddial.speedDialDirNumber), "31337");
2624                 snprintf(req->data.speeddial.speedDialDisplayName,  sizeof(req->data.speeddial.speedDialDisplayName),"Asterisk Rules!");
2625 #endif  
2626                 transmit_response(s, req);
2627                 break;
2628         case LINE_STATE_REQ_MESSAGE:
2629                 lineNumber = letohl(req->data.line.lineNumber);
2630                 if (skinnydebug) {
2631                         ast_verbose("Received LineStateReq\n");
2632                 }
2633                 memset(req, 0, SKINNY_MAX_PACKET);
2634                 req->len = htolel(sizeof(line_stat_res_message)+4);
2635                 req->e = htolel(LINE_STAT_RES_MESSAGE); 
2636                 sub = find_subchannel_by_line(s->device->lines);
2637                 if (!sub) {
2638                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2639                         return 0;
2640                 }
2641                 lines = sub->parent;
2642                 ast_mutex_lock(&devicelock);
2643                 for (i=1; i < lineNumber; i++) {
2644                         lines = lines->next;
2645                 }
2646                 ast_mutex_unlock(&devicelock);
2647                 req->data.linestat.linenumber = letohl(lineNumber);             
2648                 memcpy(req->data.linestat.lineDirNumber, lines->name,
2649                                 sizeof(req->data.linestat.lineDirNumber));
2650                 memcpy(req->data.linestat.lineDisplayName, lines->label,
2651                                 sizeof(req->data.linestat.lineDisplayName)); 
2652                 transmit_response(s,req);
2653                 break;
2654         case CAPABILITIES_RES_MESSAGE:
2655                 if (skinnydebug) {
2656                         ast_verbose("Received CapabilitiesRes\n");      
2657                 }
2658                 /* XXX process the capabilites  */
2659                 break;
2660         case KEEP_ALIVE_MESSAGE:
2661                 memset(req, 0, SKINNY_MAX_PACKET);
2662                 req->len = htolel(4);
2663                 req->e = htolel(KEEP_ALIVE_ACK_MESSAGE);
2664                 transmit_response(s, req);
2665                 do_housekeeping(s);
2666
2667                 break;
2668         case OFFHOOK_MESSAGE:
2669                 transmit_ringer_mode(s,SKINNY_RING_OFF);
2670                 transmit_lamp_indication(s, STIMULUS_LINE, s->device->lines->instance, SKINNY_LAMP_ON); 
2671                 
2672                 sub = find_subchannel_by_line(s->device->lines);
2673                 if (!sub) {
2674                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2675                         return 0;
2676                 }
2677                 sub->parent->hookstate = SKINNY_OFFHOOK;
2678                 
2679                 if (sub->outgoing) {
2680                         /* We're answering a ringing call */
2681                         ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
2682                         transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2683                         transmit_tone(s, SKINNY_SILENCE);
2684                         transmit_callstate(s, s->device->lines->instance, SKINNY_CONNECTED, sub->callid);
2685                         start_rtp(sub);
2686                         ast_setstate(sub->owner, AST_STATE_UP);
2687                         /* XXX select the appropriate soft key here */
2688                 } else {        
2689                         if (!sub->owner) {      
2690                                 transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2691                                 if (skinnydebug) {
2692                                         ast_verbose("Attempting to Clear display on Skinny %s@%s\n",sub->parent->name, sub->parent->parent->name);
2693                                 }
2694                                 transmit_displaymessage(s, NULL); /* clear display */ 
2695                                 transmit_tone(s, SKINNY_DIALTONE);
2696                                 c = skinny_new(sub, AST_STATE_DOWN);                    
2697                                 if(c) {
2698                                         /* start switch */
2699                                         if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
2700                                                 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
2701                                                 ast_hangup(c);
2702                                         }
2703                                 } else {
2704                                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", sub->parent->name, s->device->name);
2705                                 }
2706                                 
2707                         } else {
2708                                 ast_log(LOG_DEBUG, "Current sub [%s] already has owner\n", sub->owner->name);
2709                         }
2710                 }
2711                 break;
2712         case ONHOOK_MESSAGE:
2713                 sub = find_subchannel_by_line(s->device->lines);
2714                 if (sub->parent->hookstate == SKINNY_ONHOOK) {
2715                         /* Somthing else already put us back on hook */ 
2716                         break;
2717                 }
2718                 sub->cxmode = SKINNY_CX_RECVONLY;
2719                 sub->parent->hookstate = SKINNY_ONHOOK;
2720                 transmit_callstate(s, s->device->lines->instance, sub->parent->hookstate,sub->callid);
2721
2722                 if (skinnydebug) {
2723                         ast_verbose("Skinny %s@%s went on hook\n",sub->parent->name, sub->parent->parent->name);
2724                 }
2725
2726                 if (sub->parent->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
2727                         /* We're allowed to transfer, we have two active calls and */
2728                         /* we made at least one of the calls.  Let's try and transfer */
2729
2730 #if 0
2731                         if ((res = attempt_transfer(p)) < 0) {
2732                                  if (p->sub->next->owner) {
2733                                         sub->next->alreadygone = 1;
2734                                         ast_queue_hangup(sub->next->owner,1);
2735                                 }
2736                         } else if (res) {
2737                                 ast_log(LOG_WARNING, "Transfer attempt failed\n");
2738                                 return -1;
2739                         }
2740 #endif
2741                 } else {
2742                         /* Hangup the current call */
2743                         /* If there is another active call, skinny_hangup will ring the phone with the other call */
2744                         if (sub->owner) {
2745                                 sub->alreadygone = 1;
2746                                 ast_queue_hangup(sub->owner);
2747                         } else {
2748                                 ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n", 
2749                                    sub->parent->name, sub->parent->parent->name, sub->callid);
2750                         }
2751                 }
2752
2753                 if ((sub->parent->hookstate == SKINNY_ONHOOK) && (!sub->next->rtp)) {
2754                         do_housekeeping(s);
2755                 }
2756
2757                 break;
2758
2759         case KEYPAD_BUTTON_MESSAGE:
2760                 digit = letohl(req->data.keypad.button);
2761                 if (skinnydebug) {
2762                         ast_verbose("Collected digit: [%d]\n", digit);
2763                 }
2764                 f.frametype = AST_FRAME_DTMF;
2765                 if (digit == 14) {
2766                         d = '*';
2767                 } else if (digit == 15) {
2768                         d = '#';
2769                 } else if (digit >=0 && digit <= 9) {
2770                         d = '0' + digit;
2771                 } else {
2772                         /* digit=10-13 (A,B,C,D ?), or
2773                          * digit is bad value
2774                          * 
2775                          * probably should not end up here, but set
2776                          * value for backward compatibility, and log
2777                          * a warning.
2778                          */
2779                         d = '0' + digit;
2780                         ast_log(LOG_WARNING, "Unsupported digit %d\n", digit);
2781                 }
2782                 f.subclass  = d;  
2783                 f.src = "skinny";
2784
2785                 sub = find_subchannel_by_line(s->device->lines);                
2786
2787                 if (sub->owner) {
2788                         /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
2789                         ast_queue_frame(sub->owner, &f);
2790                         if (sub->next->owner) {
2791                                 ast_queue_frame(sub->next->owner, &f);
2792                         }
2793                 } else {
2794                         ast_verbose("No owner: %s\n", s->device->lines->name);
2795                 }
2796                 break;
2797         case OPEN_RECIEVE_CHANNEL_ACK_MESSAGE:
2798                 ast_verbose("Recieved Open Recieve Channel Ack\n");
2799                 status = letohl(req->data.openrecievechannelack.status);
2800                 if (status) {
2801                         ast_log(LOG_ERROR, "Open Recieve Channel Failure\n");
2802                         break;
2803                 }
2804                 /* ENDIAN */
2805                 memcpy(addr, req->data.openrecievechannelack.ipAddr, sizeof(addr));
2806                 port = htolel(req->data.openrecievechannelack.port);
2807                                 
2808                 sin.sin_family = AF_INET;
2809                 /* I smell endian problems */
2810                 memcpy(&sin.sin_addr, addr, sizeof(sin.sin_addr));  
2811                 sin.sin_port = htons(port);
2812
2813                 ast_verbose("ipaddr = %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2814         
2815                 sub = find_subchannel_by_line(s->device->lines);
2816                 if (sub->rtp) {
2817                         ast_rtp_set_peer(sub->rtp, &sin);
2818                         ast_rtp_get_us(sub->rtp, &us);  
2819                 } else {
2820                         ast_log(LOG_ERROR, "No RTP structure, this is very bad\n");
2821                         break;
2822                 }
2823                 memset(req, 0, SKINNY_MAX_PACKET);
2824                 req->len = htolel(sizeof(start_media_transmission_message)+4);
2825                 req->e = htolel(START_MEDIA_TRANSMISSION_MESSAGE);
2826                 req->data.startmedia.conferenceId = 0;
2827                 req->data.startmedia.passThruPartyId = 0;
2828                 memcpy(req->data.startmedia.remoteIp, &s->device->ourip, 4); /* Endian? */
2829                 req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
2830                 req->data.startmedia.packetSize = htolel(20);
2831                 req->data.startmedia.payloadType = htolel(convert_cap(s->device->lines->capability));
2832                 req->data.startmedia.qualifier.precedence = htolel(127);
2833                 req->data.startmedia.qualifier.vad = 0;
2834                 req->data.startmedia.qualifier.packets = 0;
2835                 req->data.startmedia.qualifier.bitRate = 0;
2836                 transmit_response(s, req);
2837                 break;  
2838         default:
2839                 ast_verbose("RECEIVED UNKNOWN MESSAGE TYPE:  %x\n", letohl(req->e));
2840                 break;
2841         }
2842
2843         free(req);
2844         return 1;
2845
2846 }
2847
2848 static void destroy_session(struct skinnysession *s)
2849 {
2850         struct skinnysession *cur, *prev = NULL;
2851         ast_mutex_lock(&sessionlock);
2852         cur = sessions;
2853         while(cur) {
2854                 if (cur == s)
2855                         break;
2856                 prev = cur;
2857                 cur = cur->next;
2858         }
2859         if (cur) {
2860                 if (prev)
2861                         prev->next = cur->next;
2862                 else
2863                         sessions = cur->next;
2864                 if (s->fd > -1)
2865                         close(s->fd);
2866                 ast_mutex_destroy(&s->lock);
2867                 free(s);
2868         } else
2869                 ast_log(LOG_WARNING, "Trying to delete nonexistent session %p?\n", s);
2870         ast_mutex_unlock(&sessionlock);
2871 }
2872
2873 static int get_input(struct skinnysession *s)  
2874 {  
2875         int res;  
2876         int dlen = 0;
2877         struct pollfd fds[1];  
2878  
2879         fds[0].fd = s->fd;
2880         fds[0].events = POLLIN;
2881         res = poll(fds, 1, -1);
2882  
2883         if (res < 0) {
2884                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
2885         } else if (res > 0) {
2886                 memset(s->inbuf,0,sizeof(s->inbuf));
2887                 res = read(s->fd, s->inbuf, 4);
2888                 if (res != 4) {
2889                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2890                         return -1;
2891                 }
2892                 dlen = letohl(*(int *)s->inbuf);
2893                 if (dlen+8 > sizeof(s->inbuf))
2894                         dlen = sizeof(s->inbuf) - 8;
2895                 *(int *)s->inbuf = htolel(dlen);
2896                 res = read(s->fd, s->inbuf+4, dlen+4);
2897                 ast_mutex_unlock(&s->lock);
2898                 if (res != (dlen+4)) {
2899                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2900                         return -1;
2901                 } 
2902         }  
2903         return res;  
2904 }   
2905
2906 static skinny_req *skinny_req_parse(struct skinnysession *s)
2907 {
2908         skinny_req *req;
2909         
2910         req = malloc(SKINNY_MAX_PACKET);
2911         if (!req) {
2912                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
2913                 return NULL;
2914         }
2915         memset(req, 0, sizeof(skinny_req));
2916         /* +8 to account for reserved and length fields */
2917         memcpy(req, s->inbuf, letohl(*(int*)(s->inbuf))+8); 
2918         if (letohl(req->e) < 0) {
2919                 ast_log(LOG_ERROR, "Event Message is NULL from socket %d, This is bad\n", s->fd);
2920                 free(req);
2921                 return NULL;
2922         }
2923         return req;
2924 }
2925
2926 static void *skinny_session(void *data)
2927 {
2928         int res;
2929         skinny_req *req;
2930         struct skinnysession *s = data;
2931         char iabuf[INET_ADDRSTRLEN];
2932         
2933         ast_verbose(VERBOSE_PREFIX_3 "Starting Skinny session from %s\n",  ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
2934
2935         for (;;) {
2936                 res = 0;
2937                 res = get_input(s);
2938                 if (res < 0)
2939                         break;
2940                 req = skinny_req_parse(s);
2941                 if (!req) {
2942                         return NULL;
2943                 }
2944                 res = handle_message(req, s);
2945                 if (res < 0) {
2946                         destroy_session(s);
2947                         return NULL;
2948                 } 
2949         }
2950         ast_log(LOG_NOTICE, "Skinny Session returned: %s\n", strerror(errno));
2951         destroy_session(s);
2952         return 0;
2953 }
2954
2955 static void *accept_thread(void *ignore)
2956 {
2957         int as;
2958         struct sockaddr_in sin;
2959         socklen_t sinlen;
2960         struct skinnysession *s;
2961         struct protoent *p;
2962         int arg = 1;
2963         pthread_attr_t attr;
2964
2965         pthread_attr_init(&attr);
2966         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2967
2968         for (;;) {
2969                 sinlen = sizeof(sin);
2970                 as = accept(skinnysock, (struct sockaddr *)&sin, &sinlen);
2971                 if (as < 0) {
2972                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
2973                         continue;
2974                 }
2975                 p = getprotobyname("tcp");
2976                 if(p) {
2977                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
2978                                 ast_log(LOG_WARNING, "Failed to set Skinny tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
2979                         }
2980                 }
2981                 s = malloc(sizeof(struct skinnysession));
2982                 if (!s) {
2983                         ast_log(LOG_WARNING, "Failed to allocate Skinny session: %s\n", strerror(errno));
2984                         continue;
2985                 } 
2986                 memset(s, 0, sizeof(struct skinnysession));
2987                 memcpy(&s->sin, &sin, sizeof(sin));
2988                 ast_mutex_init(&s->lock);
2989                 s->fd = as;
2990                 ast_mutex_lock(&sessionlock);
2991                 s->next = sessions;
2992                 sessions = s;
2993                 ast_mutex_unlock(&sessionlock);
2994                 
2995                 if (ast_pthread_create(&tcp_thread, NULL, skinny_session, s)) {
2996                         destroy_session(s);
2997                 }
2998         }
2999         
3000         
3001         if (skinnydebug) {
3002                 ast_verbose("killing accept thread\n");
3003         }
3004         close(as);
3005         return 0;
3006 }
3007
3008 static void *do_monitor(void *data)
3009 {
3010         int res;
3011
3012         /* This thread monitors all the interfaces which are not yet in use
3013            (and thus do not have a separate thread) indefinitely */
3014         /* From here on out, we die whenever asked */
3015         for(;;) {
3016                 pthread_testcancel();
3017                 /* Wait for sched or io */
3018                 res = ast_sched_wait(sched);
3019                 if ((res < 0) || (res > 1000)) {
3020                         res = 1000;
3021                 }
3022                 res = ast_io_wait(io, res);
3023                 ast_mutex_lock(&monlock);
3024                 if (res >= 0) {
3025                         ast_sched_runq(sched);
3026                 }
3027                 ast_mutex_unlock(&monlock);
3028         }
3029         /* Never reached */
3030         return NULL;
3031         
3032 }
3033
3034 static int restart_monitor(void)
3035 {
3036         /* If we're supposed to be stopped -- stay stopped */
3037         if (monitor_thread == AST_PTHREADT_STOP)
3038                 return 0;
3039         if (ast_mutex_lock(&monlock)) {
3040                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
3041                 return -1;
3042         }
3043         if (monitor_thread == pthread_self()) {
3044                 ast_mutex_unlock(&monlock);
3045                 ast_log(LOG_WARNING, "Cannot kill myself\n");
3046                 return -1;
3047         }
3048         if (monitor_thread != AST_PTHREADT_NULL) {
3049                 /* Wake up the thread */
3050                 pthread_kill(monitor_thread, SIGURG);
3051         } else {
3052                 /* Start a new monitor */
3053                 if (ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
3054                         ast_mutex_unlock(&monlock);
3055                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
3056                         return -1;
3057                 }
3058         }
3059         ast_mutex_unlock(&monlock);
3060         return 0;
3061 }
3062
3063 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause)
3064 {
3065         int oldformat;
3066         struct skinny_subchannel *sub;
3067         struct ast_channel *tmpc = NULL;
3068         char tmp[256];
3069         char *dest = data;
3070
3071         oldformat = format;
3072         format &= capability;
3073         if (!format) {
3074                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
3075                 return NULL;
3076         }
3077         
3078         strncpy(tmp, dest, sizeof(tmp) - 1);
3079         if (ast_strlen_zero(tmp)) {
3080                 ast_log(LOG_NOTICE, "Skinny channels require a device\n");
3081                 return NULL;
3082         }
3083         
3084         sub = find_subchannel_by_name(tmp);  
3085         if (!sub) {
3086                 ast_log(LOG_NOTICE, "No available lines on: %s\n", dest);
3087                 return NULL;
3088         }
3089         
3090         if (option_verbose > 2) {
3091                 ast_verbose(VERBOSE_PREFIX_3 "skinny_request(%s)\n", tmp);
3092                 ast_verbose(VERBOSE_PREFIX_3 "Skinny cw: %d, dnd: %d, so: %d, sno: %d\n", 
3093                         sub->parent->callwaiting, sub->parent->dnd, sub->owner ? 1 : 0, sub->next->owner ? 1: 0);
3094         }
3095         tmpc = skinny_new(sub->owner ? sub->next : sub, AST_STATE_DOWN);
3096         if (!tmpc) {
3097                 ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
3098         }
3099         restart_monitor();
3100
3101         /* and finish */        
3102         return tmpc;
3103 }
3104