6a6702af0b4563332bc25a22f39be35f2890602f
[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 DIALLED_NUMBER_MESSAGE 0x011D
624 typedef struct dialled_number_message {
625         char dialledNumber[24];
626         int lineInstance;
627         int callReference;
628 } dialled_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                 dialled_number_message diallednumber;
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];                  /* Extention 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_diallednumber(struct skinnysession *s, char *text, int instance, int callid)
1279 {
1280         skinny_req *req;
1281
1282         req = req_alloc(sizeof(struct dialled_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(DIALLED_NUMBER_MESSAGE);
1290         req->len = htolel(sizeof(dialled_number_message) + 4);
1291         strncpy(req->data.diallednumber.dialledNumber, text, sizeof(req->data.diallednumber.dialledNumber)-1);
1292         req->data.diallednumber.lineInstance = htolel(instance);
1293         req->data.diallednumber.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                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting mailbox '%s' on %s@%s\n", mailbox, d->name, l->name);
1573                                         }
1574                                         l->msgstate = -1;
1575                                         l->capability = capability;
1576                                         l->parent = d;
1577                                         if (!strcasecmp(v->name, "trunk")) {
1578                                                 l->type = TYPE_TRUNK;
1579                                         } else {
1580                                                 l->type = TYPE_LINE;
1581                                         }
1582                                         l->immediate = immediate;
1583                                         l->callgroup = cur_callergroup;
1584                                         l->pickupgroup = cur_pickupgroup;
1585                                         l->callreturn = callreturn;
1586                                         l->cancallforward = cancallforward;
1587                                         l->callwaiting = callwaiting;
1588                                         l->transfer = transfer; 
1589                                         l->threewaycalling = threewaycalling;
1590                                         l->mwiblink = mwiblink;
1591                                         l->onhooktime = time(NULL);
1592                                         l->instance = 1;
1593                                         /* ASSUME we're onhook at this point*/
1594                                         l->hookstate = SKINNY_ONHOOK;
1595
1596                                         for (i = 0; i < MAX_SUBS; i++) {
1597                                                 sub = malloc(sizeof(struct skinny_subchannel));
1598                                                 if (sub) {
1599                                                         ast_verbose(VERBOSE_PREFIX_3 "Allocating Skinny subchannel '%d' on %s@%s\n", i, l->name, d->name);
1600                                                         memset(sub, 0, sizeof(struct skinny_subchannel));
1601                                                         ast_mutex_init(&sub->lock);
1602                                                         sub->parent = l;
1603                                                         /* Make a call*ID */
1604                                                         sub->callid = callnums;
1605                                                         callnums++;
1606                                                         sub->cxmode = SKINNY_CX_INACTIVE;
1607                                                         sub->nat = nat;
1608                                                         sub->next = l->sub;
1609                                                         l->sub = sub;
1610                                                 } else {
1611                                                         /* XXX Should find a way to clean up our memory */
1612                                                         ast_log(LOG_WARNING, "Out of memory allocating subchannel");
1613                                                         return NULL;
1614                                                 }
1615                                         }
1616                                         l->next = d->lines;
1617                                         d->lines = l;                   
1618                                 } else {
1619                                         /* XXX Should find a way to clean up our memory */
1620                                         ast_log(LOG_WARNING, "Out of memory allocating line");
1621                                         return NULL;
1622                                 }
1623                         } else {
1624                                 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
1625                         }
1626                         v = v->next;
1627                 }
1628         
1629                 if (!d->lines) {
1630                         ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
1631                         return NULL;
1632                 }
1633                 if (d->addr.sin_addr.s_addr && !ntohs(d->addr.sin_port)) {
1634                         d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
1635                 }
1636                 if (d->addr.sin_addr.s_addr) {
1637                         if (ast_ouraddrfor(&d->addr.sin_addr, &d->ourip)) {
1638                                 memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1639                         }
1640                 } else {
1641                         memcpy(&d->ourip, &__ourip, sizeof(d->ourip));
1642                 }
1643         }
1644         return d;
1645 }
1646
1647 static int skinny_register(skinny_req *req, struct skinnysession *s)
1648 {
1649         struct skinny_device *d;
1650         
1651         ast_mutex_lock(&devicelock);
1652         d = devices;
1653         while (d) {
1654                 if (!strcasecmp(req->data.reg.name, d->id) 
1655                                 && ast_apply_ha(d->ha, &(s->sin))) {
1656                         s->device = d;
1657                         d->type = letohl(req->data.reg.type);
1658                         if (ast_strlen_zero(d->version_id)) {
1659                                 strncpy(d->version_id, version_id, sizeof(d->version_id) - 1);
1660                         }
1661                         d->registered = 1;
1662                         d->session = s;
1663                         break;
1664                 }
1665                 d = d->next;
1666         }
1667         ast_mutex_unlock(&devicelock);
1668         if (!d) {
1669                 return 0;
1670         }
1671         return 1;
1672 }               
1673
1674 static void start_rtp(struct skinny_subchannel *sub)
1675 {
1676         ast_mutex_lock(&sub->lock);
1677         /* Allocate the RTP */
1678         sub->rtp = ast_rtp_new(sched, io, 1, 0);
1679         if (sub->rtp && sub->owner) {
1680                 sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
1681         }
1682         if (sub->rtp) {
1683                 ast_rtp_setnat(sub->rtp, sub->nat);
1684         }
1685         /* Create the RTP connection */
1686         transmit_connect(sub->parent->parent->session);
1687         ast_mutex_unlock(&sub->lock);
1688 }
1689
1690 static void *skinny_ss(void *data)
1691 {
1692         struct ast_channel *chan = data;
1693         struct skinny_subchannel *sub = chan->tech_pvt;
1694         struct skinny_line *l = sub->parent;
1695         struct skinnysession *s = l->parent->session;
1696         char exten[AST_MAX_EXTENSION] = "";
1697         int len = 0;
1698         int timeout = firstdigittimeout;
1699         int res;
1700         int getforward=0;
1701     
1702         if (option_verbose > 2) {
1703                 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s@%s'\n", l->name, l->parent->name);
1704         }
1705         while(len < AST_MAX_EXTENSION-1) {
1706                 res = ast_waitfordigit(chan, timeout);
1707                 timeout = 0;
1708                 if (res < 0) {
1709                         if (skinnydebug) {
1710                                 ast_verbose("Skinny(%s@%s): waitfordigit returned < 0\n", l->name, l->parent->name);
1711                         }
1712                         ast_indicate(chan, -1);
1713                         ast_hangup(chan);
1714                         return NULL;
1715                 } else if (res)  {
1716                         exten[len++]=res;
1717                         exten[len] = '\0';
1718                 }
1719                 if (!ast_ignore_pattern(chan->context, exten)) {
1720                         transmit_tone(s, SKINNY_SILENCE);
1721                 } 
1722                 if (ast_exists_extension(chan, chan->context, exten, 1, l->cid_num)) {
1723                         if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, l->cid_num)) {
1724                                 if (getforward) {
1725                                         /* Record this as the forwarding extension */
1726                                         strncpy(l->call_forward, exten, sizeof(l->call_forward) - 1); 
1727                                         if (option_verbose > 2) {
1728                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n", 
1729                                                         l->call_forward, chan->name);
1730                                         }
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                         }
1772                         /* Disable call waiting if enabled */
1773                         l->callwaiting = 0;
1774                         transmit_tone(s, SKINNY_DIALTONE);
1775                         len = 0;
1776                         memset(exten, 0, sizeof(exten));\
1777                         timeout = firstdigittimeout;
1778                } else if (!strcmp(exten,ast_pickup_ext())) {
1779                         /* Scan all channels and see if any there
1780                          * ringing channqels with that have call groups
1781                          * that equal this channels pickup group  
1782                          */
1783                         if (ast_pickup_call(chan)) {
1784                                 ast_log(LOG_WARNING, "No call pickup possible...\n");
1785                                 transmit_tone(s, SKINNY_REORDER);
1786                         }
1787                         ast_hangup(chan);
1788                         return NULL;
1789                 } else if (!l->hidecallerid && !strcmp(exten, "*67")) {
1790                         if (option_verbose > 2) {
1791                                  ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
1792                         }
1793                         /* Disable Caller*ID if enabled */
1794                         l->hidecallerid = 1;
1795                         if (chan->cid.cid_num) {
1796                                 free(chan->cid.cid_num);
1797                         }
1798                         chan->cid.cid_num = NULL;
1799                         if (chan->cid.cid_name) {
1800                                 free(chan->cid.cid_name);
1801                         }
1802                         chan->cid.cid_name = NULL;
1803                         transmit_tone(s, SKINNY_DIALTONE);
1804                         len = 0;
1805                         memset(exten, 0, sizeof(exten));
1806                         timeout = firstdigittimeout;
1807                 } else if (l->callreturn && !strcmp(exten, "*69")) {
1808                         res = 0;
1809                         if (!ast_strlen_zero(l->lastcallerid)) {
1810                                 res = ast_say_digit_str(chan, l->lastcallerid, "", chan->language);
1811                         }
1812                         if (!res) {
1813                                 transmit_tone(s, SKINNY_DIALTONE);
1814                         }
1815                         break;
1816                 } else if (!strcmp(exten, "*78")) {
1817                         /* Do not disturb */
1818                         if (option_verbose > 2) {
1819                                 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %s\n", chan->name);
1820                         }
1821                         transmit_tone(s, SKINNY_DIALTONE);
1822                         l->dnd = 1;
1823                         getforward = 0;
1824                         memset(exten, 0, sizeof(exten));
1825                         len = 0;
1826                 } else if (!strcmp(exten, "*79")) {
1827                         /* Do not disturb */
1828                         if (option_verbose > 2) {
1829                                 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %s\n", chan->name);
1830                         }
1831                         transmit_tone(s, SKINNY_DIALTONE);
1832                         l->dnd = 0;
1833                         getforward = 0;
1834                         memset(exten, 0, sizeof(exten));
1835                         len = 0;
1836                 } else if (l->cancallforward && !strcmp(exten, "*72")) {
1837                         transmit_tone(s, SKINNY_DIALTONE);
1838                         getforward = 1;
1839                         memset(exten, 0, sizeof(exten));
1840                         len = 0;
1841                 } else if (l->cancallforward && !strcmp(exten, "*73")) {
1842                         if (option_verbose > 2) {
1843                                 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %s\n", chan->name);
1844                         }
1845                         transmit_tone(s, SKINNY_DIALTONE); 
1846                         memset(l->call_forward, 0, sizeof(l->call_forward));
1847                         getforward = 0;
1848                         memset(exten, 0, sizeof(exten));
1849                         len = 0;
1850                 } else if (!strcmp(exten, ast_parking_ext()) && 
1851                                 sub->next->owner &&
1852                                 ast_bridged_channel(sub->next->owner)) {
1853                         /* This is a three way call, the main call being a real channel, 
1854                                 and we're parking the first call. */
1855                                 ast_masq_park_call(ast_bridged_channel(sub->next->owner), chan, 0, NULL);
1856                         if (option_verbose > 2) {
1857                                 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
1858                         }
1859                         break;
1860                 } else if (!ast_strlen_zero(l->lastcallerid) && !strcmp(exten, "*60")) {
1861                         if (option_verbose > 2) {
1862                                 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", l->lastcallerid);
1863                         }
1864                         res = ast_db_put("blacklist", l->lastcallerid, "1");
1865                         if (!res) {
1866                                 transmit_tone(s, SKINNY_DIALTONE);              
1867                                 memset(exten, 0, sizeof(exten));
1868                                 len = 0;
1869                         }
1870                 } else if (l->hidecallerid && !strcmp(exten, "*82")) {
1871                         if (option_verbose > 2) {
1872                                 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
1873                         }
1874                         /* Enable Caller*ID if enabled */
1875                         l->hidecallerid = 0;
1876                         if (chan->cid.cid_num) {
1877                                 free(chan->cid.cid_num);        
1878                         }
1879                         if (!ast_strlen_zero(l->cid_num)) {
1880                                 chan->cid.cid_num = strdup(l->cid_num);
1881                         }
1882                         if (chan->cid.cid_name) {
1883                                 free(chan->cid.cid_name);
1884                         }
1885                         if (!ast_strlen_zero(l->cid_name)) {
1886                                 chan->cid.cid_name = strdup(l->cid_name);       
1887                         }
1888                         transmit_tone(s, SKINNY_DIALTONE);
1889                         len = 0;
1890                         memset(exten, 0, sizeof(exten));
1891                         timeout = firstdigittimeout;
1892                 } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
1893                                 ((exten[0] != '*') || (!ast_strlen_zero(exten) > 2))) {
1894                         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);
1895                         transmit_tone(s, SKINNY_REORDER);       
1896                         /* hang out for 3 seconds to let congestion play */
1897                         ast_safe_sleep(chan, 3000); 
1898                         break;
1899                 }
1900                 if (!timeout) {
1901                         timeout = gendigittimeout;
1902                 }
1903                 if (len && !ast_ignore_pattern(chan->context, exten)) {
1904                         ast_indicate(chan, -1);
1905                 }
1906         }       
1907         ast_hangup(chan);
1908         return NULL;
1909 }
1910
1911
1912
1913 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
1914 {
1915         int res = 0;
1916         int tone = 0;
1917         struct skinny_line *l;
1918         struct skinny_subchannel *sub;
1919         struct skinnysession *session;
1920         
1921         sub = ast->tech_pvt;
1922         l = sub->parent;
1923         session = l->parent->session;
1924
1925         if (!l->parent->registered) {
1926                 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
1927                 return -1;
1928         }
1929         
1930         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1931                 ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
1932                 return -1;
1933         }
1934
1935         if (skinnydebug) {
1936                 ast_verbose(VERBOSE_PREFIX_3 "skinny_call(%s)\n", ast->name);
1937         }
1938
1939         if (l->dnd) {
1940                 ast_queue_control(ast, AST_CONTROL_BUSY);
1941                 return -1;
1942         }
1943    
1944         switch (l->hookstate) {
1945         case SKINNY_OFFHOOK:
1946                 tone = SKINNY_CALLWAITTONE;
1947                 break;
1948         case SKINNY_ONHOOK:
1949                 tone = SKINNY_ALERT;
1950                 break;
1951         default:
1952                 ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
1953                 break;
1954         }
1955
1956         transmit_lamp_indication(session, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
1957         transmit_ringer_mode(session, SKINNY_RING_INSIDE);
1958         
1959         if (ast->cid.cid_num) { 
1960                 char ciddisplay[41];
1961                 char *work;
1962                 size_t size = sizeof(ciddisplay);
1963
1964                 /* For now, we'll assume that if it is 10 numbers, it is a standard NANPA number */
1965                 if (strlen(ast->cid.cid_num) == 10) {
1966                         ast_build_string(&work, &size, "(xxx)xxx-xxxx      %s",
1967                                          ast->cid.cid_name ? ast->cid.cid_name : "");
1968                         memcpy(&ciddisplay[1], ast->cid.cid_num, 3);
1969                         memcpy(&ciddisplay[5], &ast->cid.cid_num[3], 3);
1970                         memcpy(&ciddisplay[9], &ast->cid.cid_num[6], 4);
1971                 } else {
1972                         if (strlen(ast->cid.cid_num) < 41) {
1973                                 ast_build_string(&work, &size, "%s -- %s", ast->cid.cid_num,
1974                                                  ast->cid.cid_name ? ast->cid.cid_name : "");
1975                         } else {
1976                                 strncpy(ciddisplay, "Number too long!", 15);
1977                         }
1978                 }
1979                 if (skinnydebug) {
1980                         ast_verbose("Trying to send: '%s'\n",ciddisplay);
1981                 }
1982                 transmit_displaymessage(session, ciddisplay);
1983         } else {
1984                 transmit_displaymessage(session, "Unknown Name");
1985         }
1986         transmit_tone(session, tone);
1987         transmit_callstate(session, l->instance, SKINNY_RINGIN, sub->callid);
1988         transmit_displaypromptstatus(session, "Ring-In", 0, l->instance, sub->callid);
1989         transmit_callinfo(session, ast->cid.cid_name, ast->cid.cid_num, l->cid_name, l->cid_num, l->instance, sub->callid, 1); 
1990
1991         /* XXX need to deal with softkeys */
1992
1993         ast_setstate(ast, AST_STATE_RINGING);
1994         ast_queue_control(ast, AST_CONTROL_RINGING);
1995         sub->outgoing = 1;
1996         return res;
1997 }
1998
1999 static int skinny_hangup(struct ast_channel *ast)
2000 {
2001     struct skinny_subchannel *sub = ast->tech_pvt;
2002     struct skinny_line *l = sub->parent;
2003     struct skinnysession *s = l->parent->session;
2004
2005     if (skinnydebug) {
2006         ast_verbose("skinny_hangup(%s) on %s@%s\n", ast->name, l->name, l->parent->name);
2007     }
2008     if (!ast->tech_pvt) {
2009         ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
2010         return 0;
2011     }
2012
2013     if (l->parent->registered) {
2014         if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_OFFHOOK)) {
2015                         sub->parent->hookstate = SKINNY_ONHOOK;
2016                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2017                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2018                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
2019                 } else if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_ONHOOK)) {
2020                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2021                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
2022                         transmit_ringer_mode(s, SKINNY_RING_OFF);
2023                         transmit_tone(s, SKINNY_SILENCE);
2024                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2025                         do_housekeeping(s);
2026                 } 
2027     }
2028     ast_mutex_lock(&sub->lock);
2029     sub->owner = NULL;
2030     ast->tech_pvt = NULL;
2031     sub->alreadygone = 0;
2032     sub->outgoing = 0;
2033     if (sub->rtp) {
2034         ast_rtp_destroy(sub->rtp);
2035         sub->rtp = NULL;
2036     }
2037     ast_mutex_unlock(&sub->lock);
2038     return 0;
2039 }
2040
2041 static int skinny_answer(struct ast_channel *ast)
2042 {
2043     int res = 0;
2044     struct skinny_subchannel *sub = ast->tech_pvt;
2045     struct skinny_line *l = sub->parent;
2046     struct skinnysession *s = l->parent->session;
2047
2048     sub->cxmode = SKINNY_CX_SENDRECV;
2049     if (!sub->rtp) {
2050                 start_rtp(sub);
2051     } 
2052     ast_verbose("skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, l->parent->name, sub->callid);
2053     if (ast->_state != AST_STATE_UP) {
2054         ast_setstate(ast, AST_STATE_UP);
2055     }
2056     transmit_tone(s, SKINNY_NOTONE);
2057     transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
2058     transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
2059     return res;
2060 }
2061
2062 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
2063 {
2064         /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
2065         struct ast_frame *f;
2066         f = ast_rtp_read(sub->rtp);
2067         if (sub->owner) {
2068                 /* We already hold the channel lock */
2069                 if (f->frametype == AST_FRAME_VOICE) {
2070                         if (f->subclass != sub->owner->nativeformats) {
2071                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2072                                 sub->owner->nativeformats = f->subclass;
2073                                 ast_set_read_format(sub->owner, sub->owner->readformat);
2074                                 ast_set_write_format(sub->owner, sub->owner->writeformat);
2075                         }
2076                 }
2077         }
2078         return f;
2079 }
2080
2081 static struct ast_frame  *skinny_read(struct ast_channel *ast)
2082 {
2083         struct ast_frame *fr;
2084         struct skinny_subchannel *sub = ast->tech_pvt;
2085         ast_mutex_lock(&sub->lock);
2086         fr = skinny_rtp_read(sub);
2087         ast_mutex_unlock(&sub->lock);
2088         return fr;
2089 }
2090
2091 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
2092 {
2093         struct skinny_subchannel *sub = ast->tech_pvt;
2094         int res = 0;
2095         if (frame->frametype != AST_FRAME_VOICE) {
2096                 if (frame->frametype == AST_FRAME_IMAGE) {
2097                         return 0;
2098                 } else {
2099                         ast_log(LOG_WARNING, "Can't send %d type frames with skinny_write\n", frame->frametype);
2100                         return 0;
2101                 }
2102         } else {
2103                 if (!(frame->subclass & ast->nativeformats)) {
2104                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2105                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2106                         return -1;
2107                 }
2108         }
2109         if (sub) {
2110                 ast_mutex_lock(&sub->lock);
2111                 if (sub->rtp) {
2112                         res =  ast_rtp_write(sub->rtp, frame);
2113                 }
2114                 ast_mutex_unlock(&sub->lock);
2115         }
2116         return res;
2117 }
2118
2119 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2120 {
2121         struct skinny_subchannel *sub = newchan->tech_pvt;
2122         ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", oldchan->name, newchan->name);
2123         if (sub->owner != oldchan) {
2124                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
2125                 return -1;
2126         }
2127         sub->owner = newchan;
2128         return 0;
2129 }
2130
2131 static int skinny_senddigit(struct ast_channel *ast, char digit)
2132 {
2133 #if 0
2134         struct skinny_subchannel *sub = ast->tech_pvt;
2135         int tmp;
2136         /* not right */
2137         sprintf(tmp, "%d", digit);  
2138         transmit_tone(sub->parent->parent->session, digit);
2139 #endif
2140         return -1;
2141 }
2142
2143 static char *control2str(int ind) {
2144     static char tmp[100];
2145
2146     switch (ind) {
2147         case AST_CONTROL_HANGUP:
2148             return "Other end has hungup";
2149         case AST_CONTROL_RING:
2150             return "Local ring";
2151         case AST_CONTROL_RINGING:
2152             return "Remote end is ringing";
2153         case AST_CONTROL_ANSWER:
2154             return "Remote end has answered";
2155         case AST_CONTROL_BUSY:
2156             return "Remote end is busy";
2157         case AST_CONTROL_TAKEOFFHOOK:
2158             return "Make it go off hook";
2159         case AST_CONTROL_OFFHOOK:
2160             return "Line is off hook";
2161         case AST_CONTROL_CONGESTION:
2162             return "Congestion (circuits busy)";
2163         case AST_CONTROL_FLASH:
2164             return "Flash hook";
2165         case AST_CONTROL_WINK:
2166             return "Wink";
2167         case AST_CONTROL_OPTION:
2168             return "Set a low-level option";
2169         case AST_CONTROL_RADIO_KEY:
2170             return "Key Radio";
2171         case AST_CONTROL_RADIO_UNKEY:
2172             return "Un-Key Radio";
2173         case AST_CONTROL_PROGRESS:
2174             return "Remote end is making Progress";
2175         case AST_CONTROL_PROCEEDING:
2176             return "Remote end is proceeding";
2177         case AST_CONTROL_HOLD:
2178             return "Hold";
2179         case AST_CONTROL_UNHOLD:
2180             return "Unhold";
2181         case -1:
2182             return "Stop tone";
2183     }
2184     snprintf(tmp, 100, "UNKNOWN-%d", ind);
2185     return tmp;
2186 }
2187
2188
2189 static int skinny_indicate(struct ast_channel *ast, int ind)
2190 {
2191         struct skinny_subchannel *sub = ast->tech_pvt;
2192         struct skinny_line *l = sub->parent;
2193         struct skinnysession *s = l->parent->session;
2194
2195         if (skinnydebug) {
2196                 ast_verbose(VERBOSE_PREFIX_3 "Asked to indicate '%s' condition on channel %s\n", control2str(ind), ast->name);
2197         }
2198         switch(ind) {
2199         case AST_CONTROL_RINGING:
2200                 if (ast->_state != AST_STATE_UP) {
2201                         if (!sub->progress) {           
2202                                 transmit_tone(s, SKINNY_ALERT);
2203                                 transmit_callstate(s, l->instance, SKINNY_RINGOUT, sub->callid);
2204                                 transmit_diallednumber(s, ast->exten, l->instance, sub->callid);
2205                                 transmit_displaypromptstatus(s, "Ring Out", 0, l->instance, sub->callid);
2206                                 transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2207                                 sub->ringing = 1;
2208                                 break;
2209                         }
2210                 }
2211                 return -1;
2212         case AST_CONTROL_BUSY:
2213                 if (ast->_state != AST_STATE_UP) {              
2214                         transmit_tone(s, SKINNY_BUSYTONE);
2215                         transmit_callstate(s, l->instance, SKINNY_BUSY, sub->callid);
2216                         sub->alreadygone = 1;
2217                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2218                         break;
2219                 }
2220                 return -1;
2221         case AST_CONTROL_CONGESTION:
2222                 if (ast->_state != AST_STATE_UP) {              
2223                         transmit_tone(s, SKINNY_REORDER);
2224                         transmit_callstate(s, l->instance, SKINNY_CONGESTION, sub->callid);
2225                         sub->alreadygone = 1;
2226                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2227                         break;
2228                 }
2229                 return -1;
2230         case AST_CONTROL_PROGRESS:
2231                 if ((ast->_state != AST_STATE_UP) && !sub->progress && !sub->outgoing) {
2232                         transmit_tone(s, SKINNY_ALERT);
2233                         transmit_callstate(s, l->instance, SKINNY_PROGRESS, sub->callid);
2234                         transmit_displaypromptstatus(s, "Call Progress", 0, l->instance, sub->callid);
2235                         transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2236                         sub->progress = 1;
2237                         break;
2238                 }
2239                 return -1;  
2240         case -1:
2241                 transmit_tone(s, SKINNY_SILENCE);
2242                 break;          
2243         case AST_CONTROL_PROCEEDING:
2244                 break;
2245         default:
2246                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
2247                 return -1;
2248         }
2249         return 0;
2250 }
2251         
2252 static struct ast_channel *skinny_new(struct skinny_subchannel *sub, int state)
2253 {
2254         struct ast_channel *tmp;
2255         struct skinny_line *l = sub->parent;
2256         int fmt;
2257         l = sub->parent;
2258         tmp = ast_channel_alloc(1);
2259         if (tmp) {
2260                 tmp->tech = &skinny_tech;
2261                 tmp->nativeformats = l->capability;
2262                 if (!tmp->nativeformats)
2263                         tmp->nativeformats = capability;
2264                 fmt = ast_best_codec(tmp->nativeformats);
2265                 ast_verbose("skinny_new: tmp->nativeformats=%d fmt=%d\n", tmp->nativeformats, fmt);
2266                 ast_string_field_build(tmp, name, "Skinny/%s@%s-%d", l->name, l->parent->name, sub->callid);
2267                 if (sub->rtp) {
2268                         tmp->fds[0] = ast_rtp_fd(sub->rtp);
2269                 }
2270                 ast_setstate(tmp, state);
2271                 if (state == AST_STATE_RING) {
2272                         tmp->rings = 1;
2273                 }
2274                 tmp->writeformat = fmt;
2275                 tmp->rawwriteformat = fmt;
2276                 tmp->readformat = fmt;
2277                 tmp->rawreadformat = fmt;
2278                 tmp->tech_pvt = sub;
2279                 if (!ast_strlen_zero(l->language))
2280                         ast_string_field_set(tmp, language, l->language);
2281                 if (!ast_strlen_zero(l->accountcode))
2282                         ast_string_field_set(tmp, accountcode, l->accountcode);
2283                 if (l->amaflags)
2284                         tmp->amaflags = l->amaflags;
2285                 sub->owner = tmp;
2286                 ast_mutex_lock(&usecnt_lock);
2287                 usecnt++;
2288                 ast_mutex_unlock(&usecnt_lock);
2289                 ast_update_use_count();
2290                 tmp->callgroup = l->callgroup;
2291                 tmp->pickupgroup = l->pickupgroup;
2292                 ast_string_field_set(tmp, call_forward, l->call_forward);
2293                 strncpy(tmp->context, l->context, sizeof(tmp->context)-1);
2294                 strncpy(tmp->exten,l->exten, sizeof(tmp->exten)-1);
2295                 if (!ast_strlen_zero(l->cid_num)) {
2296                         tmp->cid.cid_num = strdup(l->cid_num);
2297                 }
2298                 if (!ast_strlen_zero(l->cid_name)) {
2299                         tmp->cid.cid_name = strdup(l->cid_name);
2300                 }
2301                 tmp->priority = 1;
2302                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2303
2304                 if (state != AST_STATE_DOWN) {
2305                         if (ast_pbx_start(tmp)) {
2306                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2307                                 ast_hangup(tmp);
2308                                 tmp = NULL;
2309                         }
2310                 }
2311         } else {
2312                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2313     }
2314     return tmp;
2315 }
2316
2317 static int handle_message(skinny_req *req, struct skinnysession *s)
2318 {
2319         struct skinny_subchannel *sub;
2320         struct ast_channel *c;
2321         struct ast_frame f = { 0, };    
2322         struct sockaddr_in sin;
2323         struct sockaddr_in us;
2324         struct skinny_line *lines;
2325         char name[16];
2326         char addr[4];
2327         char d;
2328         char iabuf[INET_ADDRSTRLEN];
2329         int digit;
2330         int res=0;
2331         int speedDialNum;
2332         int lineNumber;
2333         int stimulus;
2334         int stimulusInstance;
2335         int status;
2336         int port;
2337         int i;
2338         time_t timer;
2339         struct tm *cmtime;
2340         pthread_t t;
2341         button_defs_t *b, *buse;
2342         
2343         if ((!s->device) && (letohl(req->e) != REGISTER_MESSAGE && letohl(req->e) != ALARM_MESSAGE)) {
2344                 ast_log(LOG_WARNING, "Client sent message #%d without first registering.\n", req->e);
2345                 free(req);
2346                 return 0;
2347         }
2348
2349         switch(letohl(req->e))  {
2350         case ALARM_MESSAGE:
2351                 /* no response necessary */
2352                 break;
2353         case REGISTER_MESSAGE:
2354                 if (skinnydebug) {
2355                         ast_verbose("Device %s is attempting to register\n", req->data.reg.name);
2356                 }
2357                 res = skinny_register(req, s);  
2358                 if (!res) {
2359                         ast_log(LOG_ERROR, "Rejecting Device %s: Device not found\n", req->data.reg.name);
2360                         memcpy(&name, req->data.reg.name, sizeof(req->data.reg.name));
2361                         memset(req, 0, sizeof(skinny_req));
2362                         req->len = htolel(sizeof(register_rej_message)+4);
2363                         req->e = htolel(REGISTER_REJ_MESSAGE);
2364                         snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2365                         transmit_response(s, req);
2366                         break;
2367                 }
2368                 if (option_verbose > 2) {
2369                         ast_verbose(VERBOSE_PREFIX_3 "Device '%s' successfuly registered\n", s->device->name); 
2370                 }
2371                 memset(req, 0, SKINNY_MAX_PACKET);
2372                 req->len = htolel(sizeof(register_ack_message)+4);
2373                 req->e = htolel(REGISTER_ACK_MESSAGE);
2374                 req->data.regack.res[0] = '0';
2375                 req->data.regack.res[1] = '\0';
2376                 req->data.regack.keepAlive = htolel(keep_alive);
2377                 strncpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate) - 1); 
2378                 req->data.regack.res2[0] = '0';
2379                 req->data.regack.res2[1] = '\0';
2380                 req->data.regack.secondaryKeepAlive = htolel(keep_alive);
2381                 transmit_response(s, req);
2382                 if (skinnydebug) {
2383                         ast_verbose("Requesting capabilities\n");
2384                 }
2385                 memset(req, 0, SKINNY_MAX_PACKET);
2386                 req->len = htolel(4);
2387                 req->e = htolel(CAPABILITIES_REQ_MESSAGE);
2388                 transmit_response(s, req);
2389                 break;
2390         case UNREGISTER_MESSAGE:
2391                 /* XXX Acutally unregister the device */
2392                 break;
2393         case IP_PORT_MESSAGE:
2394                 /* no response necessary */
2395                 break;
2396         case STIMULUS_MESSAGE:
2397                 stimulus = letohl(req->data.stimulus.stimulus);
2398                 stimulusInstance = letohl(req->data.stimulus.stimulusInstance);
2399                 
2400                 switch(stimulus) {
2401                 case STIMULUS_REDIAL:
2402                         /* If we can keep an array of dialed frames we can implement a quick 
2403                            and dirty redial, feeding the frames we last got into the queue
2404                            function */
2405                         if (skinnydebug) {
2406                                 ast_verbose("Recieved Stimulus: Redial(%d)\n", stimulusInstance);
2407                         }
2408                         break;
2409                 case STIMULUS_SPEEDDIAL:
2410                         if (skinnydebug) {
2411                                 ast_verbose("Recieved Stimulus: SpeedDial(%d)\n", stimulusInstance);
2412                         }
2413                         break;
2414                 case STIMULUS_HOLD:
2415                         /* start moh? set RTP to 0.0.0.0? */
2416                         if (skinnydebug) {
2417                                 ast_verbose("Recieved Stimulus: Hold(%d)\n", stimulusInstance);
2418                         }
2419                         break;
2420                 case STIMULUS_TRANSFER:
2421                         if (skinnydebug) {
2422                                 ast_verbose("Recieved Stimulus: Transfer(%d)\n", stimulusInstance);
2423                         }
2424                         transmit_tone(s, SKINNY_DIALTONE);      
2425                         /* XXX figure out how to transfer */
2426                         break;
2427                 case STIMULUS_CONFERENCE:
2428                         if (skinnydebug) {
2429                                 ast_verbose("Recieved Stimulus: Transfer(%d)\n", stimulusInstance);
2430                         }
2431                         transmit_tone(s, SKINNY_DIALTONE);
2432                         /* XXX determine the best way to pull off a conference.  Meetme?  */
2433                         break;
2434                 case STIMULUS_VOICEMAIL:
2435                         if (skinnydebug) {
2436                                 ast_verbose("Recieved Stimulus: Voicemail(%d)\n", stimulusInstance);
2437                         }
2438                         /* XXX Find and dial voicemail extension */
2439                         break;
2440                 case STIMULUS_CALLPARK:
2441                         if (skinnydebug) {
2442                                 ast_verbose("Recieved Stimulus: Park Call(%d)\n", stimulusInstance);
2443                         }
2444                         /* XXX Park the call */
2445                         break;
2446                 case STIMULUS_FORWARDALL:
2447                         /* Why is DND under FORWARDALL ? */
2448
2449                         /* Do not disturb */
2450                         transmit_tone(s, SKINNY_DIALTONE);
2451                         if (s->device->lines->dnd != 0){
2452                                 if (option_verbose > 2) {
2453                                         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);
2454                                 }
2455                                 s->device->lines->dnd = 0;
2456                                 transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
2457                                 transmit_displaynotify(s, "DnD disabled",10);
2458                         } else {
2459                                 if (option_verbose > 2) {
2460                                         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);
2461                                 }
2462                                 s->device->lines->dnd = 1;
2463                                 transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_OFF);
2464                                 transmit_displaynotify(s, "DnD enabled",10);
2465                         }
2466                         break;
2467                 case STIMULUS_FORWARDBUSY:
2468                 case STIMULUS_FORWARDNOANSWER:
2469                         /* Gonna be fun, not */
2470                         if (skinnydebug) {
2471                                 ast_verbose("Recieved Stimulus: Forward (%d)\n", stimulusInstance);
2472                         }
2473                         break;
2474                 case STIMULUS_DISPLAY:
2475                         /* Not sure what this is */
2476                         if (skinnydebug) {
2477                                 ast_verbose("Recieved Stimulus: Display(%d)\n", stimulusInstance);
2478                         }
2479                         break;
2480                 case STIMULUS_LINE:
2481                         if (skinnydebug) {
2482                                 ast_verbose("Recieved Stimulus: Line(%d)\n", stimulusInstance);
2483                         }               
2484                         sub = find_subchannel_by_line(s->device->lines);
2485                         /* turn the speaker on */
2486                         transmit_speaker_mode(s, 1);  
2487                 break;
2488                 default:
2489                         ast_verbose("RECEIVED UNKNOWN STIMULUS:  %d(%d)\n", stimulus, stimulusInstance);                        
2490                         break;
2491                 }
2492                 break;
2493         case VERSION_REQ_MESSAGE:
2494                 if (skinnydebug) {
2495                         ast_verbose("Version Request\n");
2496                 }
2497                 memset(req, 0, SKINNY_MAX_PACKET);
2498                 req->len = htolel(sizeof(version_res_message)+4);
2499                 req->e = htolel(VERSION_RES_MESSAGE);
2500                 snprintf(req->data.version.version, sizeof(req->data.version.version), s->device->version_id);
2501                 transmit_response(s, req);
2502                 break;
2503         case SERVER_REQUEST_MESSAGE:
2504                 if (skinnydebug) {
2505                         ast_verbose("Recieved Server Request\n");
2506                 }
2507                 memset(req, 0, SKINNY_MAX_PACKET);
2508                 req->len = htolel(sizeof(server_res_message)+4);
2509                 req->e = htolel(SERVER_RES_MESSAGE);
2510                 memcpy(req->data.serverres.server[0].serverName, ourhost, 
2511                                 sizeof(req->data.serverres.server[0].serverName));
2512                 req->data.serverres.serverListenPort[0] = htolel(ourport);
2513                 req->data.serverres.serverIpAddr[0] = htolel(__ourip.s_addr);
2514                 transmit_response(s, req);      
2515                 break;
2516         case BUTTON_TEMPLATE_REQ_MESSAGE:
2517                 if (skinnydebug) {
2518                         ast_verbose("Buttontemplate requested\n");
2519                 }
2520                 sub = find_subchannel_by_line(s->device->lines);
2521                 memset(req, 0, SKINNY_MAX_PACKET);
2522                 req->e = htolel(BUTTON_TEMPLATE_RES_MESSAGE);   
2523                 req->len = htolel(sizeof(button_template_res_message)+4);
2524
2525                 /* Find a matching button definition, default to first in the
2526                    list */
2527                 buse = button_defs;
2528                 for(b=button_defs; b->type; b++) {
2529                         if (!strcmp(s->device->model, b->type)) {
2530                                 buse = b;
2531                         }
2532                 }
2533                 req->data.buttontemplate.buttonOffset = 0;
2534                 req->data.buttontemplate.buttonCount  = htolel(buse->num_buttons);
2535                 req->data.buttontemplate.totalButtonCount = htolel(buse->num_buttons);
2536                 for (i=0; i<42; i++) {
2537                         if (i < buse->num_buttons) {
2538                                 memcpy(&(req->data.buttontemplate.definition[i]),
2539                                         &(buse->button_def[i]),
2540                                         sizeof(button_definition));
2541                         } else {
2542                                 memcpy(&(req->data.buttontemplate.definition[i]),
2543                                         &(button_def_none),
2544                                         sizeof(button_definition));
2545                         }
2546                 }
2547
2548                 if (skinnydebug) {                      
2549                         ast_verbose("Sending %s template to %s@%s (%s)\n",
2550                                                 buse->type, 
2551                                                 sub->parent->name, 
2552                                                 sub->parent->parent->name, 
2553                                                 s->device->model);
2554                 }
2555                 transmit_response(s, req);
2556                 break;
2557         case SOFT_KEY_SET_REQ_MESSAGE:
2558                 if (skinnydebug)  {
2559                         ast_verbose("Received SoftKeySetReq\n");
2560                 }
2561                 memset(req, 0, SKINNY_MAX_PACKET);
2562                 req->len = htolel(sizeof(soft_key_sets)+4);
2563                 req->e = htolel(SOFT_KEY_SET_RES_MESSAGE);
2564                 req->data.softkeysets.softKeySetOffset = 0;
2565                 req->data.softkeysets.softKeySetCount = htolel(11);
2566                 req->data.softkeysets.totalSoftKeySetCount = htolel(11);        
2567                 /* XXX Wicked hack XXX */
2568                 memcpy(req->data.softkeysets.softKeySetDefinition, 
2569                            soft_key_set_hack, 
2570                            sizeof(req->data.softkeysets.softKeySetDefinition));
2571                 transmit_response(s,req);
2572                 break;
2573         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
2574                 if (skinnydebug) {
2575                         ast_verbose("Recieved SoftKey Template Request\n");
2576                 }
2577                 memset(req, 0, SKINNY_MAX_PACKET);
2578                 req->len = htolel(sizeof(soft_key_template)+4);
2579                 req->e = htolel(SOFT_KEY_TEMPLATE_RES_MESSAGE);
2580                 req->data.softkeytemplate.softKeyOffset = 0;
2581                 req->data.softkeytemplate.softKeyCount  = htolel(sizeof(soft_key_template_default) / sizeof(soft_key_template_definition));
2582                 req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(soft_key_template_definition)); 
2583                 memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
2584                            soft_key_template_default,
2585                            sizeof(soft_key_template_default));
2586                 transmit_response(s,req);
2587                 break;
2588         case TIME_DATE_REQ_MESSAGE:
2589                 if (skinnydebug) {
2590                         ast_verbose("Received Time/Date Request\n");
2591                 }
2592                 memset(req, 0, SKINNY_MAX_PACKET);
2593                 req->len = htolel(sizeof(definetimedate_message)+4);
2594                 req->e = htolel(DEFINETIMEDATE_MESSAGE);
2595                 timer=time(NULL);
2596                 cmtime = localtime(&timer);
2597                 req->data.definetimedate.year = htolel(cmtime->tm_year+1900);
2598                 req->data.definetimedate.month = htolel(cmtime->tm_mon+1);
2599                 req->data.definetimedate.dayofweek = htolel(cmtime->tm_wday);
2600                 req->data.definetimedate.day = htolel(cmtime->tm_mday);
2601                 req->data.definetimedate.hour = htolel(cmtime->tm_hour);
2602                 req->data.definetimedate.minute = htolel(cmtime->tm_min);
2603                 req->data.definetimedate.seconds = htolel(cmtime->tm_sec);
2604                 transmit_response(s, req);
2605                 break;
2606         case SPEED_DIAL_STAT_REQ_MESSAGE:
2607                 /* Not really sure how Speed Dial's are different than the 
2608                    Softkey templates */
2609                 speedDialNum = letohl(req->data.speeddialreq.speedDialNumber);
2610                 memset(req, 0, SKINNY_MAX_PACKET);
2611                 req->len = htolel(sizeof(speed_dial_stat_res_message)+4);
2612                 req->e = htolel(SPEED_DIAL_STAT_RES_MESSAGE);
2613 #if 0
2614                 /* XXX Do this right XXX */     
2615                 /* If the redial function works the way I think it will, a modification of it
2616                    can work here was well. Yikes. */
2617                 req->data.speeddialreq.speedDialNumber = speedDialNum;
2618                 snprintf(req->data.speeddial.speedDialDirNumber, sizeof(req->data.speeddial.speedDialDirNumber), "31337");
2619                 snprintf(req->data.speeddial.speedDialDisplayName,  sizeof(req->data.speeddial.speedDialDisplayName),"Asterisk Rules!");
2620 #endif  
2621                 transmit_response(s, req);
2622                 break;
2623         case LINE_STATE_REQ_MESSAGE:
2624                 lineNumber = letohl(req->data.line.lineNumber);
2625                 if (skinnydebug) {
2626                         ast_verbose("Received LineStateReq\n");
2627                 }
2628                 memset(req, 0, SKINNY_MAX_PACKET);
2629                 req->len = htolel(sizeof(line_stat_res_message)+4);
2630                 req->e = htolel(LINE_STAT_RES_MESSAGE); 
2631                 sub = find_subchannel_by_line(s->device->lines);
2632                 if (!sub) {
2633                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2634                         return 0;
2635                 }
2636                 lines = sub->parent;
2637                 ast_mutex_lock(&devicelock);
2638                 for (i=1; i < lineNumber; i++) {
2639                         lines = lines->next;
2640                 }
2641                 ast_mutex_unlock(&devicelock);
2642                 req->data.linestat.linenumber = letohl(lineNumber);             
2643                 memcpy(req->data.linestat.lineDirNumber, lines->name,
2644                                 sizeof(req->data.linestat.lineDirNumber));
2645                 memcpy(req->data.linestat.lineDisplayName, lines->label,
2646                                 sizeof(req->data.linestat.lineDisplayName)); 
2647                 transmit_response(s,req);
2648                 break;
2649         case CAPABILITIES_RES_MESSAGE:
2650                 if (skinnydebug) {
2651                         ast_verbose("Received CapabilitiesRes\n");      
2652                 }
2653                 /* XXX process the capabilites  */
2654                 break;
2655         case KEEP_ALIVE_MESSAGE:
2656                 memset(req, 0, SKINNY_MAX_PACKET);
2657                 req->len = htolel(4);
2658                 req->e = htolel(KEEP_ALIVE_ACK_MESSAGE);
2659                 transmit_response(s, req);
2660                 do_housekeeping(s);
2661                 break;
2662         case OFFHOOK_MESSAGE:
2663                 transmit_ringer_mode(s,SKINNY_RING_OFF);
2664                 transmit_lamp_indication(s, STIMULUS_LINE, s->device->lines->instance, SKINNY_LAMP_ON); 
2665                 sub = find_subchannel_by_line(s->device->lines);
2666                 if (!sub) {
2667                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2668                         return 0;
2669                 }
2670                 sub->parent->hookstate = SKINNY_OFFHOOK;
2671                 
2672                 if (sub->outgoing) {
2673                         /* We're answering a ringing call */
2674                         ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
2675                         transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2676                         transmit_tone(s, SKINNY_SILENCE);
2677                         transmit_callstate(s, s->device->lines->instance, SKINNY_CONNECTED, sub->callid);
2678                         start_rtp(sub);
2679                         ast_setstate(sub->owner, AST_STATE_UP);
2680                         /* XXX select the appropriate soft key here */
2681                 } else {        
2682                         if (!sub->owner) {      
2683                                 transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2684                                 if (skinnydebug) {
2685                                         ast_verbose("Attempting to Clear display on Skinny %s@%s\n",sub->parent->name, sub->parent->parent->name);
2686                                 }
2687                                 transmit_displaymessage(s, NULL); /* clear display */ 
2688                                 transmit_tone(s, SKINNY_DIALTONE);
2689                                 c = skinny_new(sub, AST_STATE_DOWN);                    
2690                                 if(c) {
2691                                         /* start the switch thread */
2692                                         if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
2693                                                 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
2694                                                 ast_hangup(c);
2695                                         }
2696                                 } else {
2697                                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", sub->parent->name, s->device->name);
2698                                 }
2699                         } else {
2700                                 ast_log(LOG_DEBUG, "Current sub [%s] already has owner\n", sub->owner->name);
2701                         }
2702                 }
2703                 break;
2704         case ONHOOK_MESSAGE:
2705                 sub = find_subchannel_by_line(s->device->lines);
2706                 if (sub->parent->hookstate == SKINNY_ONHOOK) {
2707                         /* Somthing else already put us back on hook */ 
2708                         break;
2709                 }
2710                 sub->cxmode = SKINNY_CX_RECVONLY;
2711                 sub->parent->hookstate = SKINNY_ONHOOK;
2712                 transmit_callstate(s, s->device->lines->instance, sub->parent->hookstate,sub->callid);
2713                 if (skinnydebug) {
2714                         ast_verbose("Skinny %s@%s went on hook\n",sub->parent->name, sub->parent->parent->name);
2715                 }
2716                 if (sub->parent->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
2717                         /* We're allowed to transfer, we have two active calls and */
2718                         /* we made at least one of the calls.  Let's try and transfer */
2719
2720 #if 0
2721                         if ((res = attempt_transfer(p)) < 0) {
2722                                  if (p->sub->next->owner) {
2723                                         sub->next->alreadygone = 1;
2724                                         ast_queue_hangup(sub->next->owner,1);
2725                                 }
2726                         } else if (res) {
2727                                 ast_log(LOG_WARNING, "Transfer attempt failed\n");
2728                                 return -1;
2729                         }
2730 #endif
2731                 } else {
2732                         /* Hangup the current call */
2733                         /* If there is another active call, skinny_hangup will ring the phone with the other call */
2734                         if (sub->owner) {
2735                                 sub->alreadygone = 1;
2736                                 ast_queue_hangup(sub->owner);
2737                         } else {
2738                                 ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n", 
2739                                    sub->parent->name, sub->parent->parent->name, sub->callid);
2740                         }
2741                 }
2742                 if ((sub->parent->hookstate == SKINNY_ONHOOK) && (!sub->next->rtp)) {
2743                         do_housekeeping(s);
2744                 }
2745                 break;
2746         case KEYPAD_BUTTON_MESSAGE:
2747                 digit = letohl(req->data.keypad.button);
2748                 if (skinnydebug) {
2749                         ast_verbose("Collected digit: [%d]\n", digit);
2750                 }
2751                 f.frametype = AST_FRAME_DTMF;
2752                 if (digit == 14) {
2753                         d = '*';
2754                 } else if (digit == 15) {
2755                         d = '#';
2756                 } else if (digit >=0 && digit <= 9) {
2757                         d = '0' + digit;
2758                 } else {
2759                         /* digit=10-13 (A,B,C,D ?), or
2760                          * digit is bad value
2761                          * 
2762                          * probably should not end up here, but set
2763                          * value for backward compatibility, and log
2764                          * a warning.
2765                          */
2766                         d = '0' + digit;
2767                         ast_log(LOG_WARNING, "Unsupported digit %d\n", digit);
2768                 }
2769                 f.subclass  = d;  
2770                 f.src = "skinny";
2771                 sub = find_subchannel_by_line(s->device->lines);                
2772                 if (sub->owner) {
2773                         /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
2774                         ast_queue_frame(sub->owner, &f);
2775                         if (sub->next->owner) {
2776                                 ast_queue_frame(sub->next->owner, &f);
2777                         }
2778                 } else {
2779                         ast_verbose("No owner: %s\n", s->device->lines->name);
2780                 }
2781                 break;
2782         case OPEN_RECIEVE_CHANNEL_ACK_MESSAGE:
2783                 ast_verbose("Recieved Open Recieve Channel Ack\n");
2784                 status = letohl(req->data.openrecievechannelack.status);
2785                 if (status) {
2786                         ast_log(LOG_ERROR, "Open Recieve Channel Failure\n");
2787                         break;
2788                 }
2789                 /* ENDIAN */
2790                 memcpy(addr, req->data.openrecievechannelack.ipAddr, sizeof(addr));
2791                 port = htolel(req->data.openrecievechannelack.port);
2792                 sin.sin_family = AF_INET;
2793                 /* I smell endian problems */
2794                 memcpy(&sin.sin_addr, addr, sizeof(sin.sin_addr));  
2795                 sin.sin_port = htons(port);
2796                 if (skinnydebug) {
2797                         ast_verbose("ipaddr = %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2798                 }
2799                 sub = find_subchannel_by_line(s->device->lines);
2800                 if (sub->rtp) {
2801                         ast_rtp_set_peer(sub->rtp, &sin);
2802                         ast_rtp_get_us(sub->rtp, &us);  
2803                 } else {
2804                         ast_log(LOG_ERROR, "No RTP structure, this is very bad\n");
2805                         break;
2806                 }
2807                 memset(req, 0, SKINNY_MAX_PACKET);
2808                 req->len = htolel(sizeof(start_media_transmission_message)+4);
2809                 req->e = htolel(START_MEDIA_TRANSMISSION_MESSAGE);
2810                 req->data.startmedia.conferenceId = 0;
2811                 req->data.startmedia.passThruPartyId = 0;
2812                 memcpy(req->data.startmedia.remoteIp, &s->device->ourip, 4); /* Endian? */
2813                 req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
2814                 req->data.startmedia.packetSize = htolel(20);
2815                 req->data.startmedia.payloadType = htolel(convert_cap(s->device->lines->capability));
2816                 req->data.startmedia.qualifier.precedence = htolel(127);
2817                 req->data.startmedia.qualifier.vad = 0;
2818                 req->data.startmedia.qualifier.packets = 0;
2819                 req->data.startmedia.qualifier.bitRate = 0;
2820                 transmit_response(s, req);
2821                 break;  
2822         default:
2823                 ast_verbose("RECEIVED UNKNOWN MESSAGE TYPE:  %x\n", letohl(req->e));
2824                 break;
2825         }
2826         free(req);
2827         return 1;
2828 }
2829
2830 static void destroy_session(struct skinnysession *s)
2831 {
2832         struct skinnysession *cur, *prev = NULL;
2833         ast_mutex_lock(&sessionlock);
2834         cur = sessions;
2835         while(cur) {
2836                 if (cur == s) {
2837                         break;
2838                 }
2839                 prev = cur;
2840                 cur = cur->next;
2841         }
2842         if (cur) {
2843                 if (prev) {
2844                         prev->next = cur->next;
2845                 } else {
2846                         sessions = cur->next;
2847                 }
2848                 if (s->fd > -1) {
2849                         close(s->fd);
2850                 }
2851                 ast_mutex_destroy(&s->lock);
2852                 free(s);
2853         } else {
2854                 ast_log(LOG_WARNING, "Trying to delete nonexistent session %p?\n", s);
2855         }
2856         ast_mutex_unlock(&sessionlock);
2857 }
2858
2859 static int get_input(struct skinnysession *s)  
2860 {  
2861         int res;  
2862         int dlen = 0;
2863         struct pollfd fds[1];  
2864  
2865         fds[0].fd = s->fd;
2866         fds[0].events = POLLIN;
2867         res = poll(fds, 1, -1);
2868  
2869         if (res < 0) {
2870                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
2871         } else if (res > 0) {
2872                 memset(s->inbuf,0,sizeof(s->inbuf));
2873                 res = read(s->fd, s->inbuf, 4);
2874                 if (res != 4) {
2875                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2876                         return -1;
2877                 }
2878                 dlen = letohl(*(int *)s->inbuf);
2879                 if (dlen+8 > sizeof(s->inbuf)) {
2880                         dlen = sizeof(s->inbuf) - 8;
2881                 }
2882                 *(int *)s->inbuf = htolel(dlen);
2883                 res = read(s->fd, s->inbuf+4, dlen+4);
2884                 ast_mutex_unlock(&s->lock);
2885                 if (res != (dlen+4)) {
2886                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2887                         return -1;
2888                 } 
2889         }  
2890         return res;  
2891 }   
2892
2893 static skinny_req *skinny_req_parse(struct skinnysession *s)
2894 {
2895         skinny_req *req;
2896         
2897         req = malloc(SKINNY_MAX_PACKET);
2898         if (!req) {
2899                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
2900                 return NULL;
2901         }
2902         memset(req, 0, sizeof(skinny_req));
2903         /* +8 to account for reserved and length fields */
2904         memcpy(req, s->inbuf, letohl(*(int*)(s->inbuf))+8); 
2905         if (letohl(req->e) < 0) {
2906                 ast_log(LOG_ERROR, "Event Message is NULL from socket %d, This is bad\n", s->fd);
2907                 free(req);
2908                 return NULL;
2909         }
2910         return req;
2911 }
2912
2913 static void *skinny_session(void *data)
2914 {
2915         int res;
2916         skinny_req *req;
2917         struct skinnysession *s = data;
2918         char iabuf[INET_ADDRSTRLEN];
2919         
2920         ast_verbose(VERBOSE_PREFIX_3 "Starting Skinny session from %s\n",  ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
2921         for (;;) {
2922                 res = 0;
2923                 res = get_input(s);
2924                 if (res < 0) {
2925                         break;
2926                 }
2927                 req = skinny_req_parse(s);
2928                 if (!req) {
2929                         return NULL;
2930                 }
2931                 res = handle_message(req, s);
2932                 if (res < 0) {
2933                         destroy_session(s);
2934                         return NULL;
2935                 } 
2936         }
2937         ast_log(LOG_NOTICE, "Skinny Session returned: %s\n", strerror(errno));
2938         destroy_session(s);
2939         return 0;
2940 }
2941
2942 static void *accept_thread(void *ignore)
2943 {
2944         int as;
2945         struct sockaddr_in sin;
2946         socklen_t sinlen;
2947         struct skinnysession *s;
2948         struct protoent *p;
2949         int arg = 1;
2950         pthread_attr_t attr;
2951
2952         pthread_attr_init(&attr);
2953         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2954
2955         for (;;) {
2956                 sinlen = sizeof(sin);
2957                 as = accept(skinnysock, (struct sockaddr *)&sin, &sinlen);
2958                 if (as < 0) {
2959                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
2960                         continue;
2961                 }
2962                 p = getprotobyname("tcp");
2963                 if(p) {
2964                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
2965                                 ast_log(LOG_WARNING, "Failed to set Skinny tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
2966                         }
2967                 }
2968                 s = malloc(sizeof(struct skinnysession));
2969                 if (!s) {
2970                         ast_log(LOG_WARNING, "Failed to allocate Skinny session: %s\n", strerror(errno));
2971                         continue;
2972                 } 
2973                 memset(s, 0, sizeof(struct skinnysession));
2974                 memcpy(&s->sin, &sin, sizeof(sin));
2975                 ast_mutex_init(&s->lock);
2976                 s->fd = as;
2977                 ast_mutex_lock(&sessionlock);
2978                 s->next = sessions;
2979                 sessions = s;
2980                 ast_mutex_unlock(&sessionlock);
2981                 
2982                 if (ast_pthread_create(&tcp_thread, NULL, skinny_session, s)) {
2983                         destroy_session(s);
2984                 }
2985         }
2986         if (skinnydebug) {
2987                 ast_verbose("killing accept thread\n");
2988         }
2989         close(as);
2990         return 0;
2991 }
2992
2993 static void *do_monitor(void *data)
2994 {
2995         int res;
2996
2997         /* This thread monitors all the interfaces which are not yet in use
2998            (and thus do not have a separate thread) indefinitely */
2999         /* From here on out, we die whenever asked */
3000         for(;;) {
3001                 pthread_testcancel();
3002                 /* Wait for sched or io */
3003                 res = ast_sched_wait(sched);
3004                 if ((res < 0) || (res > 1000)) {
3005                         res = 1000;
3006                 }
3007                 res = ast_io_wait(io, res);
3008                 ast_mutex_lock(&monlock);
3009                 if (res >= 0) {
3010                         ast_sched_runq(sched);
3011                 }
3012                 ast_mutex_unlock(&monlock);
3013         }
3014         /* Never reached */
3015         return NULL;
3016         
3017 }
3018
3019 static int restart_monitor(void)
3020 {
3021         /* If we're supposed to be stopped -- stay stopped */
3022         if (monitor_thread == AST_PTHREADT_STOP)
3023                 return 0;
3024         if (ast_mutex_lock(&monlock)) {
3025                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
3026                 return -1;
3027         }
3028         if (monitor_thread == pthread_self()) {
3029                 ast_mutex_unlock(&monlock);
3030                 ast_log(LOG_WARNING, "Cannot kill myself\n");
3031                 return -1;
3032         }
3033         if (monitor_thread != AST_PTHREADT_NULL) {
3034                 /* Wake up the thread */
3035                 pthread_kill(monitor_thread, SIGURG);
3036         } else {
3037                 /* Start a new monitor */
3038                 if (ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
3039                         ast_mutex_unlock(&monlock);
3040                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
3041                         return -1;
3042                 }
3043         }
3044         ast_mutex_unlock(&monlock);
3045         return 0;
3046 }
3047
3048 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause)
3049 {
3050         int oldformat;
3051         struct skinny_subchannel *sub;
3052         struct ast_channel *tmpc = NULL;
3053         char tmp[256];
3054         char *dest = data;
3055
3056         oldformat = format;
3057         format &= capability;
3058         if (!format) {
3059                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
3060                 return NULL;
3061         }
3062         strncpy(tmp, dest, sizeof(tmp) - 1);
3063         if (ast_strlen_zero(tmp)) {
3064                 ast_log(LOG_NOTICE, "Skinny channels require a device\n");
3065                 return NULL;
3066         }
3067         sub = find_subchannel_by_name(tmp);  
3068         if (!sub) {
3069                 ast_log(LOG_NOTICE, "No available lines on: %s\n", dest);
3070                 return NULL;
3071         }
3072         if (option_verbose > 2) {
3073                 ast_verbose(VERBOSE_PREFIX_3 "skinny_request(%s)\n", tmp);
3074                 ast_verbose(VERBOSE_PREFIX_3 "Skinny cw: %d, dnd: %d, so: %d, sno: %d\n", 
3075                         sub->parent->callwaiting, sub->parent->dnd, sub->owner ? 1 : 0, sub->next->owner ? 1: 0);
3076         }
3077         tmpc = skinny_new(sub->owner ? sub->next : sub, AST_STATE_DOWN);
3078         if (!tmpc) {
3079                 ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
3080         }
3081         restart_monitor();
3082         return tmpc;
3083 }
3084
3085 static int reload_config(void)
3086 {
3087         int on = 1;
3088         struct ast_config *cfg;
3089         struct ast_variable *v;
3090         int format;
3091         char *cat;
3092         char iabuf[INET_ADDRSTRLEN];
3093         struct skinny_device *d;
3094         int oldport = ntohs(bindaddr.sin_port);
3095
3096         if (gethostname(ourhost, sizeof(ourhost))) {
3097                 ast_log(LOG_WARNING, "Unable to get hostname, Skinny disabled\n");
3098                 return 0;
3099         }
3100         cfg = ast_config_load(config);
3101
3102         /* We *must* have a config file otherwise stop immediately */
3103         if (!cfg) {
3104                 ast_log(LOG_NOTICE, "Unable to load config %s, Skinny disabled\n", config);
3105                 return 0;
3106         }
3107         /* load the general section */
3108         memset(&bindaddr, 0, sizeof(bindaddr));
3109         v = ast_variable_browse(cfg, "general");
3110         while(v) {
3111                 /* Create the interface list */
3112                 if (!strcasecmp(v->name, "bindaddr")) {
3113                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
3114                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
3115                         } else {
3116                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
3117                         }
3118                 } else if (!strcasecmp(v->name, "keepAlive")) {
3119                         keep_alive = atoi(v->value);            
3120                 } else if (!strcasecmp(v->name, "dateFormat")) {
3121                         strncpy(date_format, v->value, sizeof(date_format) - 1);        
3122                 } else if (!strcasecmp(v->name, "allow")) {
3123                         format = ast_getformatbyname(v->value);
3124                         if (format < 1) {
3125                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
3126                         } else {
3127                                 capability |= format;
3128                         }       
3129                 } else if (!strcasecmp(v->name, "disallow")) {
3130                         format = ast_getformatbyname(v->value);
3131                         if (format < 1) {
3132                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
3133                         } else {
3134                                 capability &= ~format;
3135                         }
3136                 } else if (!strcasecmp(v->name, "port")) {
3137                         if (sscanf(v->value, "%d", &ourport) == 1) {
3138                                 bindaddr.sin_port = htons(ourport);
3139                         } else {
3140                                 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
3141                         }
3142                 }
3143                 v = v->next;
3144         }
3145         if (ntohl(bindaddr.sin_addr.s_addr)) {
3146                 memcpy(&__ourip, &bindaddr.sin_addr, sizeof(__ourip));
3147         } else {
3148                 hp = ast_gethostbyname(ourhost, &ahp);
3149                 if (!hp) {
3150                         ast_log(LOG_WARNING, "Unable to get our IP address, Skinny disabled\n");
3151                         ast_config_destroy(cfg);
3152                         return 0;
3153                 }
3154                 memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
3155         }
3156         if (!ntohs(bindaddr.sin_port)) {
3157                 bindaddr.sin_port = ntohs(DEFAULT_SKINNY_PORT);
3158         }
3159         bindaddr.sin_family = AF_INET;
3160         
3161         /* load the device sections */
3162         cat = ast_category_browse(cfg, NULL);
3163         while(cat) {
3164                 if (!strcasecmp(cat, "general")) {
3165                   /* Nothing to do */
3166 #if 0
3167                 } else if (!strncasecmp(cat, "paging-", 7)) {
3168                         p = build_paging_device(cat, ast_variable_browse(cfg, cat));
3169                         if (p) {
3170                         }
3171 #endif
3172                 } else {
3173                         d = build_device(cat, ast_variable_browse(cfg, cat));
3174                         if (d) {
3175                                 if (option_verbose > 2) {
3176                                         ast_verbose(VERBOSE_PREFIX_3 "Added device '%s'\n", d->name);
3177                                 }
3178                                 ast_mutex_lock(&devicelock);
3179                                 d->next = devices;
3180                                 devices = d;
3181                                 ast_mutex_unlock(&devicelock);
3182                         }
3183                 }
3184                 cat = ast_category_browse(cfg, cat);
3185         }
3186         ast_mutex_lock(&netlock);
3187         if ((skinnysock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
3188                 close(skinnysock);
3189                 skinnysock = -1;
3190         }
3191         if (skinnysock < 0) {
3192                 skinnysock = socket(AF_INET, SOCK_STREAM, 0);
3193                 if(setsockopt(skinnysock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
3194                         ast_log(LOG_ERROR, "Set Socket Options failed: errno %d, %s", errno, strerror(errno));
3195                         ast_config_destroy(cfg);
3196                         return 0;
3197                 }
3198                 if (skinnysock < 0) {
3199                         ast_log(LOG_WARNING, "Unable to create Skinny socket: %s\n", strerror(errno));
3200                 } else {
3201                         if (bind(skinnysock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
3202                                 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
3203                                                 ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port),
3204                                                         strerror(errno));
3205                                 close(skinnysock);
3206                                 skinnysock = -1;
3207                                 ast_config_destroy(cfg);
3208                                 return 0;
3209                         } 
3210                         if (listen(skinnysock,DEFAULT_SKINNY_BACKLOG)) {
3211                                         ast_log(LOG_WARNING, "Failed to start listening to %s:%d: %s\n",
3212                                                 ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port),
3213                                                         strerror(errno));
3214                                         close(skinnysock);
3215                                         skinnysock = -1;
3216                                         ast_config_destroy(cfg);
3217                                         return 0;
3218                         }
3219                         if (option_verbose > 1) {
3220                                 ast_verbose(VERBOSE_PREFIX_2 "Skinny listening on %s:%d\n", 
3221                                         ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port));
3222                         }
3223                         ast_pthread_create(&accept_t,NULL, accept_thread, NULL);
3224                 }
3225         }
3226         ast_mutex_unlock(&netlock);
3227         ast_config_destroy(cfg);
3228         return 0;
3229 }
3230
3231 void delete_devices(void)
3232 {
3233         struct skinny_device *d, *dlast;
3234         struct skinny_line *l, *llast;
3235         struct skinny_subchannel *sub, *slast;
3236         
3237         ast_mutex_lock(&devicelock);
3238         
3239         /* Delete all devices */
3240         for (d=devices;d;) {            
3241                 /* Delete all lines for this device */
3242                 for (l=d->lines;l;) {
3243                         /* Delete all subchannels for this line */
3244                         for (sub=l->sub;sub;) {
3245                                 slast = sub;
3246                                 sub = sub->next;
3247                                 ast_mutex_destroy(&slast->lock);
3248                                 free(slast);
3249                         }
3250                         llast = l;
3251                         l = l->next;
3252                         ast_mutex_destroy(&llast->lock);
3253                         free(llast);
3254                 }
3255                 dlast = d;
3256                 d = d->next;
3257                 free(dlast);
3258         }
3259         devices=NULL;
3260         ast_mutex_unlock(&devicelock);
3261 }
3262
3263 int reload(void)
3264 {
3265         delete_devices();
3266         reload_config();
3267         restart_monitor();
3268         return 0;
3269 }
3270
3271
3272 int load_module()
3273 {
3274         int res = 0;
3275
3276         for (; res < (sizeof(soft_key_template_default) / sizeof(soft_key_template_default[0])); res++) {
3277                 soft_key_template_default[res].softKeyEvent = htolel(soft_key_template_default[res].softKeyEvent);
3278         }
3279         /* load and parse config */
3280         res = reload_config();
3281         
3282         ast_rtp_proto_register(&skinny_rtp);
3283         ast_cli_register(&cli_show_devices);
3284         ast_cli_register(&cli_show_lines);
3285         ast_cli_register(&cli_debug);
3286         ast_cli_register(&cli_no_debug);
3287         sched = sched_context_create();
3288         if (!sched) {
3289                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
3290         }
3291         io = io_context_create();
3292         if (!io) {
3293                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
3294         }
3295         /* And start the monitor for the first time */
3296         restart_monitor();
3297
3298         /* Announce our presence to Asterisk */ 
3299         if (!res) {
3300                 /* Make sure we can register our skinny channel type */
3301                 if (ast_channel_register(&skinny_tech)) {
3302                         ast_log(LOG_ERROR, "Unable to register channel class 'Skinny'\n");
3303                         return -1;
3304                 }
3305         }
3306         return res;
3307 }
3308
3309 int unload_module()
3310 {
3311 #if 0
3312         struct skinny_session *session, s;
3313         struct skinny_subchannel *sub;
3314         struct skinny_line *line = session;
3315
3316         /* close all IP connections */
3317         if (!ast_mutex_lock(&devicelock)) {
3318                 /* Terminate tcp listener thread */
3319         } else {
3320                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
3321                 return -1;
3322         }
3323         if (!ast_mutex_lock(&monlock)) {
3324                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
3325                         pthread_cancel(monitor_thread);
3326                         pthread_kill(monitor_thread, SIGURG);
3327                         pthread_join(monitor_thread, NULL);
3328                 }
3329                 monitor_thread = AST_PTHREADT_STOP;
3330                 ast_mutex_unlock(&monlock);
3331         } else {
3332                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
3333                 return -1;
3334         }
3335         if (!ast_mutex_lock(&iflock)) {
3336                 /* Destroy all the interfaces and free their memory */
3337                 p = iflist;
3338                 while(p) {
3339                         pl = p;
3340                         p = p->next;
3341                         /* Free associated memory */
3342                         ast_mutex_destroy(&pl->lock);
3343                         free(pl);
3344                 }
3345                 iflist = NULL;
3346                 ast_mutex_unlock(&iflock);
3347         } else {
3348                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
3349                 return -1;
3350         }
3351
3352         ast_rtp_proto_register(&skinny_rtp);
3353         ast_channel_unregister(&skinny_tech);
3354         ast_cli_register(&cli_show_devices);
3355         ast_cli_register(&cli_show_lines);
3356         ast_cli_register(&cli_debug);
3357         ast_cli_register(&cli_no_debug);
3358
3359         return 0;
3360 #endif
3361         return -1;
3362 }
3363
3364 int usecount()
3365 {
3366         return usecnt;
3367 }
3368
3369 char *key()
3370 {
3371         return ASTERISK_GPL_KEY;
3372 }
3373
3374 char *description()
3375 {
3376         return (char *) desc;
3377 }