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