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