377448284510c038509f0af203c6196ee2feada5
[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
72 /************************************************************************************/
73 /*                         Skinny/Asterisk Protocol Settings                        */
74 /************************************************************************************/
75 static const char desc[] = "Skinny Client Control Protocol (Skinny)";
76 static const char tdesc[] = "Skinny Client Control Protocol (Skinny)";
77 static const char type[] = "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 = type,
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         if (fromnum)
1090                 ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
1091         if (toname)
1092                 ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
1093         if (tonum)
1094                 ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
1095
1096         req->data.callinfo.instance = htolel(instance);
1097         req->data.callinfo.reference = htolel(callid);
1098         req->data.callinfo.type = htolel(calltype);
1099
1100         transmit_response(s, req);
1101 }
1102
1103 static void transmit_connect(struct skinnysession *s)
1104 {
1105         skinny_req *req;
1106         struct skinny_line *l = s->device->lines;
1107
1108         req = req_alloc(sizeof(struct open_recieve_channel_message));
1109         if (!req) {
1110                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1111                 return;
1112         }       
1113         req->len = htolel(sizeof(struct open_recieve_channel_message));
1114         req->e = htolel(OPEN_RECIEVE_CHANNEL_MESSAGE);
1115         req->data.openrecievechannel.conferenceId = 0;
1116         req->data.openrecievechannel.partyId = 0;
1117         req->data.openrecievechannel.packets = htolel(20);
1118         req->data.openrecievechannel.capability = htolel(convert_cap(l->capability)); 
1119         req->data.openrecievechannel.echo = 0;
1120         req->data.openrecievechannel.bitrate = 0;
1121         transmit_response(s, req);
1122 }       
1123
1124 static void transmit_tone(struct skinnysession *s, int tone)
1125 {
1126         skinny_req *req;
1127
1128         if (tone > 0)
1129                 req = req_alloc(sizeof(struct start_tone_message));
1130         else 
1131                 req = req_alloc(4);
1132         if (!req) {
1133                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1134                 return;
1135         }       
1136         if (tone > 0) {
1137                 req->len = htolel(sizeof(start_tone_message)+4);
1138                 req->e = htolel(START_TONE_MESSAGE);
1139                 req->data.starttone.tone = htolel(tone); 
1140         } else {
1141                 req->len = htolel(4);
1142                 req->e = htolel(STOP_TONE_MESSAGE);
1143         }
1144         transmit_response(s, req);
1145 }
1146
1147 #if 0
1148 /* XXX need to properly deal with softkeys */
1149 static void transmit_selectsoftkeys(struct skinnysession *s, int instance, int callid, int softkey)
1150 {
1151         skinny_req *req;
1152         int memsize = sizeof(struct select_soft_keys_message);
1153
1154         req = req_alloc(memsize);
1155         if (!req) {
1156                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1157                 return;
1158         }       
1159         memset(req, 0, memsize);
1160         req->len = htolel(sizeof(select_soft_keys_message)+4);
1161         req->e = htolel(SELECT_SOFT_KEYS_MESSAGE);
1162         req->data.selectsoftkey.instance = htolel(instance);
1163         req->data.selectsoftkey.reference = htolel(callid);
1164         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
1165         transmit_response(s, req);
1166 }
1167 #endif
1168
1169 static void transmit_lamp_indication(struct skinnysession *s, int stimulus, int instance, int indication)
1170 {
1171         skinny_req *req;
1172
1173         req = req_alloc(sizeof(struct set_lamp_message));
1174         if (!req) {
1175                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1176                 return;
1177         }       
1178         req->len = htolel(sizeof(set_lamp_message)+4);
1179         req->e = htolel(SET_LAMP_MESSAGE);
1180         req->data.setlamp.stimulus = htolel(stimulus);
1181         req->data.setlamp.stimulusInstance = htolel(instance);
1182         req->data.setlamp.deviceStimulus = htolel(indication);
1183         transmit_response(s, req);
1184 }
1185
1186 static void transmit_ringer_mode(struct skinnysession *s, int mode)
1187 {
1188         skinny_req *req;
1189
1190         req = req_alloc(sizeof(struct set_ringer_message));
1191         if (!req) {
1192                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1193                 return;
1194         }
1195         req->len = htolel(sizeof(set_ringer_message)+4);
1196         req->e = htolel(SET_RINGER_MESSAGE); 
1197         req->data.setringer.ringerMode = htolel(mode); 
1198         transmit_response(s, req);
1199 }
1200
1201 static void transmit_displaymessage(struct skinnysession *s, char *text)
1202 {
1203         skinny_req *req;
1204
1205         if (text == 0) {
1206                 req = req_alloc(4);
1207                 req->len = htolel(4);
1208                 req->e = htolel(CLEAR_DISPLAY_MESSAGE);
1209         } else {
1210                 req = req_alloc(sizeof(struct displaytext_message));
1211
1212                 strncpy(req->data.displaytext.text, text, sizeof(req->data.displaytext.text)-1);
1213                 req->len = htolel(sizeof(displaytext_message) + 4);
1214                 req->e = htolel(DISPLAYTEXT_MESSAGE);
1215                 if (skinnydebug) {
1216                         ast_verbose("Displaying message '%s'\n", req->data.displaytext.text);
1217                 }
1218         }
1219
1220         if (!req) {
1221                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1222                 return;
1223         }
1224         transmit_response(s, req);
1225 }
1226
1227 static void transmit_displaynotify(struct skinnysession *s, char *text, int t)
1228 {
1229         skinny_req *req;
1230
1231         req = req_alloc(sizeof(struct display_notify_message));
1232
1233         if (!req) {
1234                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1235                 return;
1236         }
1237
1238         req->e = htolel(DISPLAY_NOTIFY_MESSAGE);
1239         req->len = htolel(sizeof(display_notify_message) + 4);
1240         strncpy(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage)-1);
1241         req->data.displaynotify.displayTimeout = htolel(t);
1242
1243         if (skinnydebug) {
1244                 ast_verbose("Displaying notify '%s'\n", text);
1245         }
1246         
1247         transmit_response(s, req);
1248 }
1249
1250 static void transmit_displaypromptstatus(struct skinnysession *s, char *text, int t, int instance, int callid)
1251 {
1252         skinny_req *req;
1253
1254         req = req_alloc(sizeof(struct display_prompt_status_message));
1255
1256         if (!req) {
1257                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1258                 return;
1259         }
1260
1261         req->e = htolel(DISPLAY_PROMPT_STATUS_MESSAGE);
1262         req->len = htolel(sizeof(display_prompt_status_message) + 4);
1263         strncpy(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage)-1);
1264         req->data.displaypromptstatus.messageTimeout = htolel(t);
1265         req->data.displaypromptstatus.lineInstance = htolel(instance);
1266         req->data.displaypromptstatus.callReference = htolel(callid);
1267
1268         if (skinnydebug) {
1269                 ast_verbose("Displaying Prompt Status '%s'\n", text);
1270         }
1271
1272         transmit_response(s, req);
1273 }
1274
1275 static void transmit_diallednumber(struct skinnysession *s, char *text, int instance, int callid)
1276 {
1277         skinny_req *req;
1278
1279         req = req_alloc(sizeof(struct dialled_number_message));
1280
1281         if (!req) {
1282                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
1283                 return;
1284         }
1285
1286         req->e = htolel(DIALLED_NUMBER_MESSAGE);
1287         req->len = htolel(sizeof(dialled_number_message) + 4);
1288         strncpy(req->data.diallednumber.dialledNumber, text, sizeof(req->data.diallednumber.dialledNumber)-1);
1289         req->data.diallednumber.lineInstance = htolel(instance);
1290         req->data.diallednumber.callReference = htolel(callid);
1291
1292         transmit_response(s, req);
1293 }
1294
1295 static int has_voicemail(struct skinny_line *l)
1296 {
1297         return ast_app_has_voicemail(l->mailbox, NULL);
1298 }
1299
1300
1301 static void do_housekeeping(struct skinnysession *s)
1302 {
1303         struct skinny_subchannel *sub;
1304         struct skinny_line *l = s->device->lines;
1305
1306         sub = find_subchannel_by_line(l);
1307         transmit_displaymessage(s, NULL);
1308
1309         if (skinnydebug) {
1310                 ast_verbose("Checking for voicemail Skinny %s@%s\n", sub->parent->name, sub->parent->parent->name);
1311         }
1312         if (has_voicemail(sub->parent)) {
1313                 int new;
1314                 int old;
1315                 ast_app_messagecount(sub->parent->mailbox, &new, &old);
1316                 if (skinnydebug) {
1317                         ast_verbose("Skinny %s@%s has voicemail! Yay!\n", sub->parent->name, sub->parent->parent->name);
1318                 }
1319                 transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
1320         } else {
1321                 transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
1322         }
1323
1324 }
1325
1326 /* I do not believe skinny can deal with video. 
1327    Anyone know differently? */
1328 static struct ast_rtp *skinny_get_vrtp_peer(struct ast_channel *chan)
1329 {
1330         return NULL;
1331 }
1332
1333 static struct ast_rtp *skinny_get_rtp_peer(struct ast_channel *chan)
1334 {
1335         struct skinny_subchannel *sub;
1336         sub = chan->tech_pvt;
1337         if (sub && sub->rtp)
1338                 return sub->rtp;
1339         return NULL;
1340 }
1341
1342 static int skinny_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
1343 {
1344         struct skinny_subchannel *sub;
1345         sub = chan->tech_pvt;
1346         if (sub) {
1347                 /* transmit_modify_with_sdp(sub, rtp); @@FIXME@@ if needed */
1348                 return 0;
1349         }
1350         return -1;
1351 }
1352
1353 static struct ast_rtp_protocol skinny_rtp = {
1354         .type = type,
1355         .get_rtp_info = skinny_get_rtp_peer,
1356         .get_vrtp_info =  skinny_get_vrtp_peer,
1357         .set_rtp_peer = skinny_set_rtp_peer,
1358 };
1359
1360 static int skinny_do_debug(int fd, int argc, char *argv[])
1361 {
1362         if (argc != 2)
1363                 return RESULT_SHOWUSAGE;
1364         skinnydebug = 1;
1365         ast_cli(fd, "Skinny Debugging Enabled\n");
1366         return RESULT_SUCCESS;
1367 }
1368
1369 static int skinny_no_debug(int fd, int argc, char *argv[])
1370 {
1371         if (argc != 3)
1372                 return RESULT_SHOWUSAGE;
1373         skinnydebug = 0;
1374         ast_cli(fd, "Skinny Debugging Disabled\n");
1375         return RESULT_SUCCESS;
1376 }
1377
1378 static int skinny_show_devices(int fd, int argc, char *argv[])
1379 {
1380         struct skinny_device  *d;
1381         struct skinny_line *l;
1382         int numlines = 0;
1383         char iabuf[INET_ADDRSTRLEN];
1384
1385         if (argc != 3) 
1386                 return RESULT_SHOWUSAGE;
1387
1388         ast_mutex_lock(&devicelock);
1389         d = devices;
1390
1391         ast_cli(fd, "Name                 DeviceId         IP              TypeId R Model  NL\n");
1392         ast_cli(fd, "-------------------- ---------------- --------------- ------ - ------ --\n");
1393         while(d) {
1394                 l = d->lines;
1395                 numlines = 0;
1396                 while(l) { numlines++; l = l->next; }
1397
1398                 ast_cli(fd, "%-20s %-16s %-16s %6X %c %-6s %2d\n", 
1399                                 d->name, 
1400                                 d->id, 
1401                                 ast_inet_ntoa(iabuf, sizeof(iabuf), d->addr.sin_addr), 
1402                                 d->type, 
1403                                 d->registered?'Y':'N', 
1404                                 d->model, 
1405                                 numlines);
1406
1407                 d = d->next;
1408         }
1409         ast_mutex_unlock(&devicelock);
1410
1411         return RESULT_SUCCESS;
1412 }
1413
1414 static int skinny_show_lines(int fd, int argc, char *argv[])
1415 {
1416                 
1417         struct skinny_device  *d;
1418         struct skinny_line *l;
1419
1420         if (argc != 3) 
1421                 return RESULT_SHOWUSAGE;
1422
1423         ast_mutex_lock(&devicelock);
1424         d = devices;
1425         while(d) {
1426                 l = d->lines;
1427                 while (l) {
1428                         ast_cli(fd, "%-20s %2d %-20s %-20s  %c  %c\n",
1429                                 l->parent->name,
1430                                 l->instance,
1431                                 l->name,
1432                                 l->label,
1433                                 l->sub->owner?'Y':'N',
1434                                 l->sub->rtp?'Y':'N');
1435
1436                         l = l->next;
1437                 }
1438                 d = d->next;
1439         }
1440         ast_mutex_unlock(&devicelock);
1441
1442         return RESULT_SUCCESS;
1443 }
1444
1445 static char show_devices_usage[] = 
1446 "Usage: skinny show devices\n"
1447 "       Lists all devices known to the Skinny subsystem.\n";
1448
1449 static char show_lines_usage[] = 
1450 "Usage: skinny show lines\n"
1451 "       Lists all lines known to the Skinny subsystem.\n";
1452
1453 static char debug_usage[] = 
1454 "Usage: skinny debug\n"
1455 "       Enables dumping of Skinny packets for debugging purposes\n";
1456
1457 static char no_debug_usage[] = 
1458 "Usage: skinny no debug\n"
1459 "       Disables dumping of Skinny packets for debugging purposes\n";
1460
1461 static struct ast_cli_entry  cli_show_devices =
1462         { { "skinny", "show", "devices", NULL }, skinny_show_devices, "Show defined Skinny devices", show_devices_usage };
1463
1464 static struct ast_cli_entry  cli_show_lines =
1465         { { "skinny", "show", "lines", NULL }, skinny_show_lines, "Show defined Skinny lines per device", show_lines_usage };
1466
1467 static struct ast_cli_entry  cli_debug =
1468         { { "skinny", "debug", NULL }, skinny_do_debug, "Enable Skinny debugging", debug_usage };
1469
1470 static struct ast_cli_entry  cli_no_debug =
1471         { { "skinny", "no", "debug", NULL }, skinny_no_debug, "Disable Skinny debugging", no_debug_usage };
1472
1473 #if 0
1474 static struct skinny_paging_device *build_paging_device(char *cat, struct ast_variable *v)
1475 {
1476         return NULL;
1477 }
1478 #endif
1479
1480 static struct skinny_device *build_device(char *cat, struct ast_variable *v)
1481 {
1482         struct skinny_device *d;
1483         struct skinny_line *l;
1484         struct skinny_subchannel *sub;
1485         int i=0, y=0;
1486         
1487         d = malloc(sizeof(struct skinny_device));
1488         if (d) {
1489                 memset(d, 0, sizeof(struct skinny_device));
1490                 strncpy(d->name, cat, sizeof(d->name) - 1);
1491                 while(v) {
1492                         if (!strcasecmp(v->name, "host")) {
1493                                         if (ast_get_ip(&d->addr, v->value)) {
1494                                                 free(d);
1495                                                 return NULL;
1496                                         }                               
1497                         } else if (!strcasecmp(v->name, "port")) {
1498                                 d->addr.sin_port = htons(atoi(v->value));
1499                         } else if (!strcasecmp(v->name, "device")) {
1500                         strncpy(d->id, v->value, sizeof(d->id)-1);
1501                         } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
1502                                 d->ha = ast_append_ha(v->name, v->value, d->ha);
1503                         } else if (!strcasecmp(v->name, "context")) {
1504                                 strncpy(context, v->value, sizeof(context) - 1);
1505                         } else if (!strcasecmp(v->name, "version")) {
1506                                 strncpy(d->version_id, v->value, sizeof(d->version_id) -1); 
1507                         } else if (!strcasecmp(v->name, "nat")) {
1508                                 nat = ast_true(v->value);
1509                 } else if (!strcasecmp(v->name, "model")) {
1510                                 strncpy(d->model, v->value, sizeof(d->model) - 1);
1511                         } else if (!strcasecmp(v->name, "callerid")) {
1512                                 if (!strcasecmp(v->value, "asreceived")) {
1513                                         cid_num[0] = '\0';
1514                                         cid_name[0] = '\0';
1515                                 } else {
1516                                         ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
1517                                 }
1518                         } else if (!strcasecmp(v->name, "language")) {
1519                                 strncpy(language, v->value, sizeof(language)-1);
1520                         } else if (!strcasecmp(v->name, "accountcode")) {
1521                                 strncpy(accountcode, v->value, sizeof(accountcode)-1);
1522                         } else if (!strcasecmp(v->name, "amaflags")) {
1523                                 y = ast_cdr_amaflags2int(v->value);
1524                                 if (y < 0) {
1525                                         ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
1526                                 } else {
1527                                 amaflags = y;
1528                                 }
1529                         } else if (!strcasecmp(v->name, "musiconhold")) {
1530                                 strncpy(musicclass, v->value, sizeof(musicclass)-1);
1531                         } else if (!strcasecmp(v->name, "callgroup")) {
1532                                 cur_callergroup = ast_get_group(v->value);
1533                         } else if (!strcasecmp(v->name, "pickupgroup")) {
1534                                 cur_pickupgroup = ast_get_group(v->value);
1535                         } else if (!strcasecmp(v->name, "immediate")) {
1536                                 immediate = ast_true(v->value);
1537                         } else if (!strcasecmp(v->name, "cancallforward")) {
1538                                 cancallforward = ast_true(v->value);
1539                         } else if (!strcasecmp(v->name, "mailbox")) {
1540                                 strncpy(mailbox, v->value, sizeof(mailbox) -1);
1541                         } else if (!strcasecmp(v->name, "callreturn")) {
1542                                 callreturn = ast_true(v->value);
1543                         } else if (!strcasecmp(v->name, "callwaiting")) {
1544                                 callwaiting = ast_true(v->value);
1545                         } else if (!strcasecmp(v->name, "transfer")) {
1546                                 transfer = ast_true(v->value);
1547                         } else if (!strcasecmp(v->name, "threewaycalling")) {
1548                                 threewaycalling = ast_true(v->value);
1549                         } else if (!strcasecmp(v->name, "mwiblink")) {
1550                                 mwiblink = ast_true(v->value);
1551                         } else if (!strcasecmp(v->name, "linelabel")) {
1552                                 strncpy(linelabel, v->value, sizeof(linelabel)-1);
1553                         } else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
1554                                 l = malloc(sizeof(struct skinny_line));;
1555                                 if (l) {
1556                                         memset(l, 0, sizeof(struct skinny_line));
1557                                         ast_mutex_init(&l->lock);
1558                                         strncpy(l->name, v->value, sizeof(l->name) - 1);
1559                                         
1560                                         /* XXX Should we check for uniqueness?? XXX */
1561
1562                                         strncpy(l->context, context, sizeof(l->context) - 1);
1563                                         strncpy(l->cid_num, cid_num, sizeof(l->cid_num) - 1);
1564                                         strncpy(l->cid_name, cid_name, sizeof(l->cid_name) - 1);
1565                                         strncpy(l->label, linelabel, sizeof(l->label) - 1);
1566                                         strncpy(l->language, language, sizeof(l->language) - 1);
1567                                         strncpy(l->musicclass, musicclass, sizeof(l->musicclass)-1);
1568                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1569                                         strncpy(l->mailbox, mailbox, sizeof(l->mailbox)-1);
1570                                         if (!ast_strlen_zero(mailbox)) {
1571                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting mailbox '%s' on %s@%s\n", mailbox, d->name, l->name);
1572                                         }
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
1634                 if (d->addr.sin_addr.s_addr && !ntohs(d->addr.sin_port))
1635                         d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
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
1669         if (!d)
1670                 return 0;
1671         
1672         return 1;
1673 }               
1674
1675 static void start_rtp(struct skinny_subchannel *sub)
1676 {
1677                 ast_mutex_lock(&sub->lock);
1678                 /* Allocate the RTP */
1679                 sub->rtp = ast_rtp_new(sched, io, 1, 0);
1680                 if (sub->rtp && sub->owner)
1681                         sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
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
1691 static void *skinny_ss(void *data)
1692 {
1693         struct ast_channel *chan = data;
1694         struct skinny_subchannel *sub = chan->tech_pvt;
1695         struct skinny_line *l = sub->parent;
1696         struct skinnysession *s = l->parent->session;
1697         char exten[AST_MAX_EXTENSION] = "";
1698         int len = 0;
1699         int timeout = firstdigittimeout;
1700         int res;
1701         int getforward=0;
1702     
1703         if (option_verbose > 2) {
1704                 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s@%s'\n", l->name, l->parent->name);
1705         }
1706         while(len < AST_MAX_EXTENSION-1) {
1707         res = ast_waitfordigit(chan, timeout);
1708         timeout = 0;
1709         if (res < 0) {
1710                 if (skinnydebug) {
1711                         ast_verbose("Skinny(%s@%s): waitfordigit returned < 0\n", l->name, l->parent->name);
1712                 }
1713                 ast_indicate(chan, -1);
1714                 ast_hangup(chan);
1715                 return NULL;
1716         } else if (res)  {
1717             exten[len++]=res;
1718             exten[len] = '\0';
1719         }
1720         if (!ast_ignore_pattern(chan->context, exten)) {
1721                         transmit_tone(s, SKINNY_SILENCE);
1722         } 
1723         if (ast_exists_extension(chan, chan->context, exten, 1, l->cid_num)) {
1724             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, l->cid_num)) {
1725                 if (getforward) {
1726                     /* Record this as the forwarding extension */
1727                     strncpy(l->call_forward, exten, sizeof(l->call_forward) - 1); 
1728                     if (option_verbose > 2) {
1729                         ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n", 
1730                                 l->call_forward, chan->name);
1731                     }
1732                     transmit_tone(s, SKINNY_DIALTONE); 
1733                     if (res) {
1734                             break;
1735                     }
1736                     usleep(500000);
1737                     ast_indicate(chan, -1);
1738                     sleep(1);
1739                     memset(exten, 0, sizeof(exten));
1740                     transmit_tone(s, SKINNY_DIALTONE); 
1741                     len = 0;
1742                     getforward = 0;
1743                 } else  {
1744                     strncpy(chan->exten, exten, sizeof(chan->exten)-1);
1745                     if (!ast_strlen_zero(l->cid_num)) {
1746                         if (!l->hidecallerid)
1747                             chan->cid.cid_num = strdup(l->cid_num);
1748                         chan->cid.cid_ani = strdup(l->cid_num);
1749                     }
1750                     ast_setstate(chan, AST_STATE_RING);
1751                     res = ast_pbx_run(chan);
1752                     if (res) {
1753                         ast_log(LOG_WARNING, "PBX exited non-zero\n");
1754                                                 transmit_tone(s, SKINNY_REORDER); 
1755                     }
1756                     return NULL;
1757                 }
1758             } 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                 
1779         } else if (!strcmp(exten,ast_pickup_ext())) {
1780             /* Scan all channels and see if any there
1781              * ringing channqels with that have call groups
1782              * that equal this channels pickup group  
1783              */
1784             if (ast_pickup_call(chan)) {
1785                 ast_log(LOG_WARNING, "No call pickup possible...\n");
1786                                 transmit_tone(s, SKINNY_REORDER);
1787             }
1788             ast_hangup(chan);
1789             return NULL;
1790             
1791         } else if (!l->hidecallerid && !strcmp(exten, "*67")) {
1792             if (option_verbose > 2) {
1793                 ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
1794             }
1795             /* Disable Caller*ID if enabled */
1796             l->hidecallerid = 1;
1797             if (chan->cid.cid_num)
1798                 free(chan->cid.cid_num);
1799             chan->cid.cid_num = NULL;
1800             
1801                         if (chan->cid.cid_name)
1802                 free(chan->cid.cid_name);
1803             chan->cid.cid_name = NULL;
1804                         
1805             transmit_tone(s, SKINNY_DIALTONE);
1806             len = 0;
1807             memset(exten, 0, sizeof(exten));
1808             timeout = firstdigittimeout;
1809         } else if (l->callreturn && !strcmp(exten, "*69")) {
1810             res = 0;
1811             if (!ast_strlen_zero(l->lastcallerid)) {
1812                 res = ast_say_digit_str(chan, l->lastcallerid, "", chan->language);
1813             }
1814             if (!res) {
1815                 transmit_tone(s, SKINNY_DIALTONE);
1816                         }
1817             break;
1818         } else if (!strcmp(exten, "*78")) {
1819             /* Do not disturb */
1820             if (option_verbose > 2) {
1821                 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %s\n", chan->name);
1822             }
1823             transmit_tone(s, SKINNY_DIALTONE);
1824             l->dnd = 1;
1825             getforward = 0;
1826             memset(exten, 0, sizeof(exten));
1827             len = 0;
1828         } else if (!strcmp(exten, "*79")) {
1829             /* Do not disturb */
1830             if (option_verbose > 2) {
1831                 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %s\n", chan->name);
1832             }
1833                         transmit_tone(s, SKINNY_DIALTONE);
1834             l->dnd = 0;
1835             getforward = 0;
1836             memset(exten, 0, sizeof(exten));
1837             len = 0;
1838         } else if (l->cancallforward && !strcmp(exten, "*72")) {
1839             transmit_tone(s, SKINNY_DIALTONE);
1840             getforward = 1;
1841             memset(exten, 0, sizeof(exten));
1842             len = 0;
1843         } else if (l->cancallforward && !strcmp(exten, "*73")) {
1844             if (option_verbose > 2) {
1845                 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %s\n", chan->name);
1846             }
1847             transmit_tone(s, SKINNY_DIALTONE); 
1848             memset(l->call_forward, 0, sizeof(l->call_forward));
1849             getforward = 0;
1850             memset(exten, 0, sizeof(exten));
1851             len = 0;
1852         } else if (!strcmp(exten, ast_parking_ext()) && 
1853                     sub->next->owner &&
1854                     ast_bridged_channel(sub->next->owner)) {
1855             /* This is a three way call, the main call being a real channel, 
1856                 and we're parking the first call. */
1857             ast_masq_park_call(ast_bridged_channel(sub->next->owner), chan, 0, NULL);
1858             if (option_verbose > 2) {
1859                 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
1860             }
1861             break;
1862         } else if (!ast_strlen_zero(l->lastcallerid) && !strcmp(exten, "*60")) {
1863             if (option_verbose > 2) {
1864                 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", l->lastcallerid);
1865             }
1866             res = ast_db_put("blacklist", l->lastcallerid, "1");
1867             if (!res) {
1868                 transmit_tone(s, SKINNY_DIALTONE);              
1869                 memset(exten, 0, sizeof(exten));
1870                 len = 0;
1871             }
1872         } else if (l->hidecallerid && !strcmp(exten, "*82")) {
1873             if (option_verbose > 2) {
1874                 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
1875             }
1876             /* Enable Caller*ID if enabled */
1877             l->hidecallerid = 0;
1878             if (chan->cid.cid_num)
1879                 free(chan->cid.cid_num);
1880             if (!ast_strlen_zero(l->cid_num))
1881                 chan->cid.cid_num = strdup(l->cid_num);
1882
1883             if (chan->cid.cid_name)
1884                 free(chan->cid.cid_name);
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                         sleep(3); /* hang out for 3 seconds to let congestion play */
1897                         break;
1898         }
1899         if (!timeout)
1900             timeout = gendigittimeout;
1901         if (len && !ast_ignore_pattern(chan->context, exten))
1902                         ast_indicate(chan, -1);
1903     }
1904         ast_hangup(chan);
1905         return NULL;
1906 }
1907
1908
1909
1910 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
1911 {
1912         int res = 0;
1913         int tone = 0;
1914         struct skinny_line *l;
1915         struct skinny_subchannel *sub;
1916         struct skinnysession *session;
1917         
1918         sub = ast->tech_pvt;
1919         l = sub->parent;
1920         session = l->parent->session;
1921
1922         if (!l->parent->registered) {
1923                 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
1924                 return -1;
1925         }
1926         
1927         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1928                 ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
1929                 return -1;
1930         }
1931
1932         if (skinnydebug) {
1933                 ast_verbose(VERBOSE_PREFIX_3 "skinny_call(%s)\n", ast->name);
1934         }
1935
1936         if (l->dnd) {
1937                 ast_queue_control(ast, AST_CONTROL_BUSY);
1938                 return -1;
1939         }
1940    
1941         switch (l->hookstate) {
1942         case SKINNY_OFFHOOK:
1943             tone = SKINNY_CALLWAITTONE;
1944             break;
1945         case SKINNY_ONHOOK:
1946                         tone = SKINNY_ALERT;
1947                         break;
1948         default:
1949             ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
1950             break;
1951         }
1952
1953         transmit_lamp_indication(session, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
1954         transmit_ringer_mode(session, SKINNY_RING_INSIDE);
1955         
1956         if (ast->cid.cid_num) { 
1957                 char ciddisplay[41];
1958                 char *work;
1959                 size_t size = sizeof(ciddisplay);
1960
1961                 /* We'll assume that if it is 10 numbers, it is a standard NANPA number
1962                    Why? Because I am bloody American, and I'm bigoted that way. */
1963
1964                 if (strlen(ast->cid.cid_num) == 10) {
1965                         ast_build_string(&work, &size, "(xxx)xxx-xxxx      %s",
1966                                          ast->cid.cid_name ? ast->cid.cid_name : "");
1967                         memcpy(&ciddisplay[1], ast->cid.cid_num, 3);
1968                         memcpy(&ciddisplay[5], &ast->cid.cid_num[3], 3);
1969                         memcpy(&ciddisplay[9], &ast->cid.cid_num[6], 4);
1970                 } else {
1971                         if (strlen(ast->cid.cid_num) < 41)
1972                                 ast_build_string(&work, &size, "%s -- %s", ast->cid.cid_num,
1973                                                  ast->cid.cid_name ? ast->cid.cid_name : "");
1974                         else
1975                                 strncpy(ciddisplay, "Number too long!", 15);
1976                 }
1977
1978                 if (skinnydebug)
1979                         ast_verbose("Trying to send: '%s'\n",ciddisplay);
1980
1981                 transmit_displaymessage(session, ciddisplay);
1982         } else
1983                 transmit_displaymessage(session, "Unknown Name");
1984
1985         transmit_tone(session, tone);
1986         transmit_callstate(session, l->instance, SKINNY_RINGIN, sub->callid);
1987         transmit_displaypromptstatus(session, "Ring-In", 0, l->instance, sub->callid);
1988         transmit_callinfo(session, ast->cid.cid_name, ast->cid.cid_num, l->cid_name, l->cid_num, l->instance, sub->callid, 1); /* 1 = incoming to phone */
1989
1990         /* XXX need to deal with softkeys */
1991
1992         ast_setstate(ast, AST_STATE_RINGING);
1993         ast_queue_control(ast, AST_CONTROL_RINGING);
1994
1995         sub->outgoing = 1;
1996
1997         return res;
1998 }
1999
2000
2001 static int skinny_hangup(struct ast_channel *ast)
2002 {
2003     struct skinny_subchannel *sub = ast->tech_pvt;
2004     struct skinny_line *l = sub->parent;
2005     struct skinnysession *s = l->parent->session;
2006
2007     if (skinnydebug) {
2008         ast_verbose("skinny_hangup(%s) on %s@%s\n", ast->name, l->name, l->parent->name);
2009     }
2010     if (!ast->tech_pvt) {
2011         ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
2012         return 0;
2013     }
2014
2015     if (l->parent->registered) {
2016         if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_OFFHOOK)) {
2017                         sub->parent->hookstate = SKINNY_ONHOOK;
2018                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2019                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2020                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
2021                 } else if ((sub->parent->type = TYPE_LINE) && (sub->parent->hookstate == SKINNY_ONHOOK)) {
2022                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2023                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF); 
2024                         transmit_ringer_mode(s, SKINNY_RING_OFF);
2025                         transmit_tone(s, SKINNY_SILENCE);
2026                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2027                         do_housekeeping(s);
2028                 } 
2029     }
2030     ast_mutex_lock(&sub->lock);
2031     sub->owner = NULL;
2032     ast->tech_pvt = NULL;
2033     sub->alreadygone = 0;
2034     sub->outgoing = 0;
2035     if (sub->rtp) {
2036         ast_rtp_destroy(sub->rtp);
2037         sub->rtp = NULL;
2038     }
2039     ast_mutex_unlock(&sub->lock);
2040     return 0;
2041 }
2042
2043 static int skinny_answer(struct ast_channel *ast)
2044 {
2045     int res = 0;
2046     struct skinny_subchannel *sub = ast->tech_pvt;
2047     struct skinny_line *l = sub->parent;
2048     struct skinnysession *s = l->parent->session;
2049
2050     sub->cxmode = SKINNY_CX_SENDRECV;
2051     if (!sub->rtp) {
2052                 start_rtp(sub);
2053     } 
2054     ast_verbose("skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, l->parent->name, sub->callid);
2055     if (ast->_state != AST_STATE_UP) {
2056         ast_setstate(ast, AST_STATE_UP);
2057     }
2058
2059     transmit_tone(s, SKINNY_NOTONE);
2060     transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
2061     transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
2062     return res;
2063 }
2064
2065 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
2066 {
2067         /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
2068         struct ast_frame *f;
2069         f = ast_rtp_read(sub->rtp);
2070         if (sub->owner) {
2071                 /* We already hold the channel lock */
2072                 if (f->frametype == AST_FRAME_VOICE) {
2073                         if (f->subclass != sub->owner->nativeformats) {
2074                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2075                                 sub->owner->nativeformats = f->subclass;
2076                                 ast_set_read_format(sub->owner, sub->owner->readformat);
2077                                 ast_set_write_format(sub->owner, sub->owner->writeformat);
2078                         }
2079                 }
2080         }
2081         return f;
2082 }
2083
2084 static struct ast_frame  *skinny_read(struct ast_channel *ast)
2085 {
2086         struct ast_frame *fr;
2087         struct skinny_subchannel *sub = ast->tech_pvt;
2088         ast_mutex_lock(&sub->lock);
2089         fr = skinny_rtp_read(sub);
2090         ast_mutex_unlock(&sub->lock);
2091         return fr;
2092 }
2093
2094 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
2095 {
2096         struct skinny_subchannel *sub = ast->tech_pvt;
2097         int res = 0;
2098         if (frame->frametype != AST_FRAME_VOICE) {
2099                 if (frame->frametype == AST_FRAME_IMAGE)
2100                         return 0;
2101                 else {
2102                         ast_log(LOG_WARNING, "Can't send %d type frames with skinny_write\n", frame->frametype);
2103                         return 0;
2104                 }
2105         } else {
2106                 if (!(frame->subclass & ast->nativeformats)) {
2107                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2108                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2109                         return -1;
2110                 }
2111         }
2112         if (sub) {
2113                 ast_mutex_lock(&sub->lock);
2114                 if (sub->rtp) {
2115                         res =  ast_rtp_write(sub->rtp, frame);
2116                 }
2117                 ast_mutex_unlock(&sub->lock);
2118         }
2119         return res;
2120 }
2121
2122 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2123 {
2124         struct skinny_subchannel *sub = newchan->tech_pvt;
2125         ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", oldchan->name, newchan->name);
2126         if (sub->owner != oldchan) {
2127                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
2128                 return -1;
2129         }
2130         sub->owner = newchan;
2131         return 0;
2132 }
2133
2134 static int skinny_senddigit(struct ast_channel *ast, char digit)
2135 {
2136 #if 0
2137         struct skinny_subchannel *sub = ast->tech_pvt;
2138         int tmp;
2139         /* not right */
2140         sprintf(tmp, "%d", digit);  
2141         transmit_tone(sub->parent->parent->session, digit);
2142 #endif
2143         return -1;
2144 }
2145
2146 static char *control2str(int ind) {
2147     static char tmp[100];
2148
2149     switch (ind) {
2150         case AST_CONTROL_HANGUP:
2151             return "Other end has hungup";
2152         case AST_CONTROL_RING:
2153             return "Local ring";
2154         case AST_CONTROL_RINGING:
2155             return "Remote end is ringing";
2156         case AST_CONTROL_ANSWER:
2157             return "Remote end has answered";
2158         case AST_CONTROL_BUSY:
2159             return "Remote end is busy";
2160         case AST_CONTROL_TAKEOFFHOOK:
2161             return "Make it go off hook";
2162         case AST_CONTROL_OFFHOOK:
2163             return "Line is off hook";
2164         case AST_CONTROL_CONGESTION:
2165             return "Congestion (circuits busy)";
2166         case AST_CONTROL_FLASH:
2167             return "Flash hook";
2168         case AST_CONTROL_WINK:
2169             return "Wink";
2170         case AST_CONTROL_OPTION:
2171             return "Set a low-level option";
2172         case AST_CONTROL_RADIO_KEY:
2173             return "Key Radio";
2174         case AST_CONTROL_RADIO_UNKEY:
2175             return "Un-Key Radio";
2176         case AST_CONTROL_PROGRESS:
2177             return "Remote end is making Progress";
2178         case AST_CONTROL_PROCEEDING:
2179             return "Remote end is proceeding";
2180         case AST_CONTROL_HOLD:
2181             return "Hold";
2182         case AST_CONTROL_UNHOLD:
2183             return "Unhold";
2184         case -1:
2185             return "Stop tone";
2186     }
2187     snprintf(tmp, 100, "UNKNOWN-%d", ind);
2188     return tmp;
2189 }
2190
2191
2192 static int skinny_indicate(struct ast_channel *ast, int ind)
2193 {
2194         struct skinny_subchannel *sub = ast->tech_pvt;
2195         struct skinny_line *l = sub->parent;
2196         struct skinnysession *s = l->parent->session;
2197
2198         if (skinnydebug) {
2199                 ast_verbose(VERBOSE_PREFIX_3 "Asked to indicate '%s' condition on channel %s\n", control2str(ind), ast->name);
2200         }
2201         switch(ind) {
2202         case AST_CONTROL_RINGING:
2203                 if (ast->_state != AST_STATE_UP) {
2204                         if (!sub->progress) {           
2205                                 transmit_tone(s, SKINNY_ALERT);
2206                                 transmit_callstate(s, l->instance, SKINNY_RINGOUT, sub->callid);
2207                                 transmit_diallednumber(s, ast->exten, l->instance, sub->callid);
2208                                 transmit_displaypromptstatus(s, "Ring Out", 0, l->instance, sub->callid);
2209                                 transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2210                                 sub->ringing = 1;
2211                                 break;
2212                         }
2213                 }
2214                 return -1;
2215         case AST_CONTROL_BUSY:
2216                 if (ast->_state != AST_STATE_UP) {              
2217                         transmit_tone(s, SKINNY_BUSYTONE);
2218                         transmit_callstate(s, l->instance, SKINNY_BUSY, sub->callid);
2219                         sub->alreadygone = 1;
2220                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2221                         break;
2222                 }
2223                 return -1;
2224         case AST_CONTROL_CONGESTION:
2225                 if (ast->_state != AST_STATE_UP) {              
2226                         transmit_tone(s, SKINNY_REORDER);
2227                         transmit_callstate(s, l->instance, SKINNY_CONGESTION, sub->callid);
2228                         sub->alreadygone = 1;
2229                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2230                         break;
2231                 }
2232                 return -1;
2233         case AST_CONTROL_PROGRESS:
2234                 if ((ast->_state != AST_STATE_UP) && !sub->progress && !sub->outgoing) {
2235                         transmit_tone(s, SKINNY_ALERT);
2236                         transmit_callstate(s, l->instance, SKINNY_PROGRESS, sub->callid);
2237                         transmit_displaypromptstatus(s, "Call Progress", 0, l->instance, sub->callid);
2238                         transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2239                         sub->progress = 1;
2240                         break;
2241                 }
2242                 return -1;  
2243         case -1:
2244                 transmit_tone(s, SKINNY_SILENCE);
2245                 break;          
2246         case AST_CONTROL_PROCEEDING:
2247                 break;
2248         default:
2249                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
2250                 return -1;
2251         }
2252         return 0;
2253 }
2254         
2255 static struct ast_channel *skinny_new(struct skinny_subchannel *sub, int state)
2256 {
2257         struct ast_channel *tmp;
2258         struct skinny_line *l = sub->parent;
2259         int fmt;
2260         l = sub->parent;
2261         tmp = ast_channel_alloc(1);
2262         if (tmp) {
2263                 tmp->tech = &skinny_tech;
2264                 tmp->nativeformats = l->capability;
2265                 if (!tmp->nativeformats)
2266                         tmp->nativeformats = capability;
2267                 fmt = ast_best_codec(tmp->nativeformats);
2268 ast_verbose("chan_skinny: skinny_new: tmp->nativeformats=%d fmt=%d\n", tmp->nativeformats, fmt);
2269                 snprintf(tmp->name, sizeof(tmp->name), "Skinny/%s@%s-%d", l->name, l->parent->name, sub->callid);
2270                 if (sub->rtp)
2271                         tmp->fds[0] = ast_rtp_fd(sub->rtp);
2272                 tmp->type = type;
2273                 ast_setstate(tmp, state);
2274                 if (state == AST_STATE_RING)
2275                         tmp->rings = 1;
2276                 tmp->writeformat = fmt;
2277                 tmp->rawwriteformat = fmt;
2278                 tmp->readformat = fmt;
2279                 tmp->rawreadformat = fmt;
2280                 tmp->tech_pvt = sub;
2281                 if (!ast_strlen_zero(l->language))
2282                         strncpy(tmp->language, l->language, sizeof(tmp->language)-1);
2283                 if (!ast_strlen_zero(l->accountcode))
2284                         strncpy(tmp->accountcode, l->accountcode, sizeof(tmp->accountcode)-1);
2285                 if (l->amaflags)
2286                         tmp->amaflags = l->amaflags;
2287                 sub->owner = tmp;
2288                 ast_mutex_lock(&usecnt_lock);
2289                 usecnt++;
2290                 ast_mutex_unlock(&usecnt_lock);
2291                 ast_update_use_count();
2292                 tmp->callgroup = l->callgroup;
2293                 tmp->pickupgroup = l->pickupgroup;
2294                 strncpy(tmp->call_forward, l->call_forward, sizeof(tmp->call_forward) - 1);
2295                 strncpy(tmp->context, l->context, sizeof(tmp->context)-1);
2296                 strncpy(tmp->exten,l->exten, sizeof(tmp->exten)-1);
2297                 if (!ast_strlen_zero(l->cid_num)) {
2298                         tmp->cid.cid_num = strdup(l->cid_num);
2299                 }
2300                 if (!ast_strlen_zero(l->cid_name)) {
2301                         tmp->cid.cid_name = strdup(l->cid_name);
2302                 }
2303                 tmp->priority = 1;
2304
2305                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2306
2307
2308                 if (state != AST_STATE_DOWN) {
2309                         if (ast_pbx_start(tmp)) {
2310                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2311                                 ast_hangup(tmp);
2312                                 tmp = NULL;
2313                         }
2314                 }
2315         } else {
2316                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2317     }
2318
2319         return tmp;
2320 }
2321
2322 static int handle_message(skinny_req *req, struct skinnysession *s)
2323 {
2324         struct skinny_subchannel *sub;
2325         struct ast_channel *c;
2326         struct ast_frame f = { 0, };    
2327         struct sockaddr_in sin;
2328         struct sockaddr_in us;
2329         struct skinny_line *lines;
2330         char name[16];
2331         char addr[4];
2332         char d;
2333         char iabuf[INET_ADDRSTRLEN];
2334         int digit;
2335         int res=0;
2336         int speedDialNum;
2337         int lineNumber;
2338         int stimulus;
2339         int stimulusInstance;
2340         int status;
2341         int port;
2342         int i;
2343         time_t timer;
2344         struct tm *cmtime;
2345         pthread_t t;
2346         button_defs_t *b, *buse;
2347         
2348         if ( (!s->device) && (letohl(req->e) != REGISTER_MESSAGE && letohl(req->e) != ALARM_MESSAGE)) {
2349                 ast_log(LOG_WARNING, "Client sent message #%d without first registering.\n", req->e);
2350                 free(req);
2351                 return 0;
2352         }
2353
2354         switch(letohl(req->e))  {
2355         case ALARM_MESSAGE:
2356                 /* no response necessary */
2357                 break;
2358         case REGISTER_MESSAGE:
2359                 if (skinnydebug) {
2360                         ast_verbose("Device %s is attempting to register\n", req->data.reg.name);
2361                 }
2362                 res = skinny_register(req, s);  
2363                 if (!res) {
2364                         ast_log(LOG_ERROR, "Rejecting Device %s: Device not found\n", req->data.reg.name);
2365                         memcpy(&name, req->data.reg.name, sizeof(req->data.reg.name));
2366                         memset(req, 0, sizeof(skinny_req));
2367                         req->len = htolel(sizeof(register_rej_message)+4);
2368                         req->e = htolel(REGISTER_REJ_MESSAGE);
2369                         snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2370                         transmit_response(s, req);
2371                         break;
2372                 }
2373                 if (option_verbose > 2) {
2374                         ast_verbose(VERBOSE_PREFIX_3 "Device '%s' successfuly registered\n", s->device->name); 
2375                 }
2376                 memset(req, 0, SKINNY_MAX_PACKET);
2377                 req->len = htolel(sizeof(register_ack_message)+4);
2378                 req->e = htolel(REGISTER_ACK_MESSAGE);
2379                 req->data.regack.res[0] = '0';
2380                 req->data.regack.res[1] = '\0';
2381                 req->data.regack.keepAlive = htolel(keep_alive);
2382                 strncpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate) - 1); 
2383                 req->data.regack.res2[0] = '0';
2384                 req->data.regack.res2[1] = '\0';
2385                 req->data.regack.secondaryKeepAlive = htolel(keep_alive);
2386                 transmit_response(s, req);
2387                 if (skinnydebug) {
2388                         ast_verbose("Requesting capabilities\n");
2389                 }
2390                 memset(req, 0, SKINNY_MAX_PACKET);
2391                 req->len = htolel(4);
2392                 req->e = htolel(CAPABILITIES_REQ_MESSAGE);
2393                 transmit_response(s, req);
2394                 break;
2395         case UNREGISTER_MESSAGE:
2396                 /* XXX Acutally unregister the device */
2397                 break;
2398         case IP_PORT_MESSAGE:
2399                 /* no response necessary */
2400                 break;
2401         case STIMULUS_MESSAGE:
2402                 stimulus = letohl(req->data.stimulus.stimulus);
2403                 stimulusInstance = letohl(req->data.stimulus.stimulusInstance);
2404                 
2405                 switch(stimulus) {
2406                 case STIMULUS_REDIAL:
2407                         /* If we can keep an array of dialed frames we can implement a quick 
2408                            and dirty redial, feeding the frames we last got into the queue
2409                            function */
2410
2411                         if (skinnydebug) {
2412                                 ast_verbose("Recieved Stimulus: Redial(%d)\n", stimulusInstance);
2413                         }
2414
2415
2416                         break;
2417                 case STIMULUS_SPEEDDIAL:
2418                         if (skinnydebug) {
2419                                 ast_verbose("Recieved Stimulus: SpeedDial(%d)\n", stimulusInstance);
2420                         }
2421                         break;
2422                 case STIMULUS_HOLD:
2423                         /* start moh? set RTP to 0.0.0.0? */
2424                         if (skinnydebug) {
2425                                 ast_verbose("Recieved Stimulus: Hold(%d)\n", stimulusInstance);
2426                         }
2427                         break;
2428                 case STIMULUS_TRANSFER:
2429                         if (skinnydebug) {
2430                                 ast_verbose("Recieved Stimulus: Transfer(%d)\n", stimulusInstance);
2431                         }
2432                         transmit_tone(s, SKINNY_DIALTONE);
2433                                 
2434                         /* figure out how to transfer */
2435
2436                         break;
2437                 case STIMULUS_CONFERENCE:
2438                         if (skinnydebug) {
2439                                 ast_verbose("Recieved Stimulus: Transfer(%d)\n", stimulusInstance);
2440                         }
2441                         transmit_tone(s, SKINNY_DIALTONE);
2442
2443                         /* figure out how to bridge n' stuff */
2444                                 
2445
2446                         break;
2447                 case STIMULUS_VOICEMAIL:
2448                         if (skinnydebug) {
2449                                 ast_verbose("Recieved Stimulus: Voicemail(%d)\n", stimulusInstance);
2450                         }
2451                                 
2452                         /* Dial Voicemail */
2453
2454                         break;
2455                 case STIMULUS_CALLPARK:
2456                         if (skinnydebug) {
2457                                 ast_verbose("Recieved Stimulus: Park Call(%d)\n", stimulusInstance);
2458                         }
2459
2460                         break;
2461                 case STIMULUS_FORWARDALL:
2462                         /* Do not disturb */
2463                         transmit_tone(s, SKINNY_DIALTONE);
2464                         if(s->device->lines->dnd != 0){
2465                                 if (option_verbose > 2) {
2466                                         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);
2467                                 }
2468                                 s->device->lines->dnd = 0;
2469                                 transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
2470                                 transmit_displaynotify(s, "DnD disabled",10);
2471                         }else{
2472                                 if (option_verbose > 2) {
2473                                         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);
2474                                 }
2475                                 s->device->lines->dnd = 1;
2476                                 transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_OFF);
2477                                 transmit_displaynotify(s, "DnD enabled",10);
2478                         }
2479                         break;
2480                 case STIMULUS_FORWARDBUSY:
2481                 case STIMULUS_FORWARDNOANSWER:
2482                         /* Gonna be fun, not */
2483                         if (skinnydebug) {
2484                                 ast_verbose("Recieved Stimulus: Forward (%d)\n", stimulusInstance);
2485                         }
2486                         break;
2487                 case STIMULUS_DISPLAY:
2488                         /* Not sure what this is */
2489                         if (skinnydebug) {
2490                                 ast_verbose("Recieved Stimulus: Display(%d)\n", stimulusInstance);
2491                         }
2492                         break;
2493                 case STIMULUS_LINE:
2494                         if (skinnydebug) {
2495                                 ast_verbose("Recieved Stimulus: Line(%d)\n", stimulusInstance);
2496                         }               
2497                         sub = find_subchannel_by_line(s->device->lines);
2498                         /* turn the speaker on */
2499                         transmit_speaker_mode(s, 1);  
2500                 break;
2501                 default:
2502                         ast_verbose("RECEIVED UNKNOWN STIMULUS:  %d(%d)\n", stimulus, stimulusInstance);                        
2503                         break;
2504                 }
2505                 break;
2506         case VERSION_REQ_MESSAGE:
2507                 if (skinnydebug) {
2508                         ast_verbose("Version Request\n");
2509                 }
2510                 memset(req, 0, SKINNY_MAX_PACKET);
2511                 req->len = htolel(sizeof(version_res_message)+4);
2512                 req->e = htolel(VERSION_RES_MESSAGE);
2513                 snprintf(req->data.version.version, sizeof(req->data.version.version), s->device->version_id);
2514                 transmit_response(s, req);
2515                 break;
2516         case SERVER_REQUEST_MESSAGE:
2517                 if (skinnydebug) {
2518                         ast_verbose("Recieved Server Request\n");
2519                 }
2520                 memset(req, 0, SKINNY_MAX_PACKET);
2521                 req->len = htolel(sizeof(server_res_message)+4);
2522                 req->e = htolel(SERVER_RES_MESSAGE);
2523                 memcpy(req->data.serverres.server[0].serverName, ourhost, 
2524                                 sizeof(req->data.serverres.server[0].serverName));
2525                 req->data.serverres.serverListenPort[0] = htolel(ourport);
2526                 req->data.serverres.serverIpAddr[0] = htolel(__ourip.s_addr);
2527                 transmit_response(s, req);      
2528                 break;
2529         case BUTTON_TEMPLATE_REQ_MESSAGE:
2530                 if (skinnydebug) {
2531                         ast_verbose("Buttontemplate requested\n");
2532                 }
2533
2534                 sub = find_subchannel_by_line(s->device->lines);
2535
2536                 memset(req, 0, SKINNY_MAX_PACKET);
2537                 req->e = htolel(BUTTON_TEMPLATE_RES_MESSAGE);   
2538                 req->len = htolel(sizeof(button_template_res_message)+4);
2539
2540                 /* Find a matching button definition, default to first in the
2541                    list */
2542                 buse = button_defs;
2543                 for(b=button_defs; b->type; b++) {
2544                         if (!strcmp(s->device->model, b->type)) {
2545                                 buse = b;
2546                         }
2547                 }
2548
2549                 req->data.buttontemplate.buttonOffset = 0;
2550                 req->data.buttontemplate.buttonCount  = htolel(buse->num_buttons);
2551                 req->data.buttontemplate.totalButtonCount = htolel(buse->num_buttons);
2552                 for (i=0; i<42; i++) {
2553                         if (i < buse->num_buttons) {
2554                                 memcpy(&(req->data.buttontemplate.definition[i]),
2555                                         &(buse->button_def[i]),
2556                                         sizeof(button_definition));
2557                         } else {
2558                                 memcpy(&(req->data.buttontemplate.definition[i]),
2559                                         &(button_def_none),
2560                                         sizeof(button_definition));
2561                         }
2562                 }
2563
2564                 if(skinnydebug){                        
2565                         ast_verbose("Sending %s template to %s@%s (%s)\n",
2566                                                 buse->type, 
2567                                                 sub->parent->name, 
2568                                                 sub->parent->parent->name, 
2569                                                 s->device->model);
2570                 }
2571
2572                 transmit_response(s, req);
2573                 break;
2574         case SOFT_KEY_SET_REQ_MESSAGE:
2575                 if (skinnydebug)  {
2576                         ast_verbose("Received SoftKeySetReq\n");
2577                 }
2578                 memset(req, 0, SKINNY_MAX_PACKET);
2579                 req->len = htolel(sizeof(soft_key_sets)+4);
2580                 req->e = htolel(SOFT_KEY_SET_RES_MESSAGE);
2581                 req->data.softkeysets.softKeySetOffset          = 0;
2582                 req->data.softkeysets.softKeySetCount           = htolel(11);
2583                 req->data.softkeysets.totalSoftKeySetCount  = htolel(11);       
2584                 /* XXX Wicked hack XXX */
2585                 memcpy(req->data.softkeysets.softKeySetDefinition, 
2586                            soft_key_set_hack, 
2587                            sizeof(req->data.softkeysets.softKeySetDefinition));
2588                 transmit_response(s,req);
2589                 break;
2590         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
2591                 if (skinnydebug) {
2592                         ast_verbose("Recieved SoftKey Template Request\n");
2593                 }
2594                 memset(req, 0, SKINNY_MAX_PACKET);
2595                 req->len = htolel(sizeof(soft_key_template)+4);
2596                 req->e = htolel(SOFT_KEY_TEMPLATE_RES_MESSAGE);
2597                 req->data.softkeytemplate.softKeyOffset         = 0;
2598                 req->data.softkeytemplate.softKeyCount          = htolel(sizeof(soft_key_template_default) / sizeof(soft_key_template_definition));
2599                 req->data.softkeytemplate.totalSoftKeyCount     = htolel(sizeof(soft_key_template_default) / sizeof(soft_key_template_definition)); 
2600                 memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
2601                            soft_key_template_default,
2602                            sizeof(soft_key_template_default));
2603                 transmit_response(s,req);
2604                 break;
2605         case TIME_DATE_REQ_MESSAGE:
2606                 if (skinnydebug) {
2607                         ast_verbose("Received Time/Date Request\n");
2608                 }
2609                 memset(req, 0, SKINNY_MAX_PACKET);
2610                 req->len = htolel(sizeof(definetimedate_message)+4);
2611                 req->e = htolel(DEFINETIMEDATE_MESSAGE);
2612                 timer=time(NULL);
2613                 cmtime = localtime(&timer);
2614                 req->data.definetimedate.year = htolel(cmtime->tm_year+1900);
2615                 req->data.definetimedate.month = htolel(cmtime->tm_mon+1);
2616                 req->data.definetimedate.dayofweek = htolel(cmtime->tm_wday);
2617                 req->data.definetimedate.day = htolel(cmtime->tm_mday);
2618                 req->data.definetimedate.hour = htolel(cmtime->tm_hour);
2619                 req->data.definetimedate.minute = htolel(cmtime->tm_min);
2620                 req->data.definetimedate.seconds = htolel(cmtime->tm_sec);
2621                 transmit_response(s, req);
2622                 break;
2623         case SPEED_DIAL_STAT_REQ_MESSAGE:
2624                 /* Not really sure how Speed Dial's are different than the 
2625                    Softkey templates */
2626                 speedDialNum = letohl(req->data.speeddialreq.speedDialNumber);
2627                 memset(req, 0, SKINNY_MAX_PACKET);
2628                 req->len = htolel(sizeof(speed_dial_stat_res_message)+4);
2629                 req->e = htolel(SPEED_DIAL_STAT_RES_MESSAGE);
2630 #if 0
2631                 /* XXX Do this right XXX */     
2632                 /* If the redial function works the way I think it will, a modification of it
2633                    can work here was well. Yikes. */
2634                 req->data.speeddialreq.speedDialNumber = speedDialNum;
2635                 snprintf(req->data.speeddial.speedDialDirNumber, sizeof(req->data.speeddial.speedDialDirNumber), "31337");
2636                 snprintf(req->data.speeddial.speedDialDisplayName,  sizeof(req->data.speeddial.speedDialDisplayName),"Asterisk Rules!");
2637 #endif  
2638                 transmit_response(s, req);
2639                 break;
2640         case LINE_STATE_REQ_MESSAGE:
2641                 lineNumber = letohl(req->data.line.lineNumber);
2642                 if (skinnydebug) {
2643                         ast_verbose("Received LineStateReq\n");
2644                 }
2645                 memset(req, 0, SKINNY_MAX_PACKET);
2646                 req->len = htolel(sizeof(line_stat_res_message)+4);
2647                 req->e = htolel(LINE_STAT_RES_MESSAGE); 
2648                 sub = find_subchannel_by_line(s->device->lines);
2649                 if (!sub) {
2650                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2651                         return 0;
2652                 }
2653                 lines = sub->parent;
2654                 ast_mutex_lock(&devicelock);
2655                 for (i=1; i < lineNumber; i++) {
2656                         lines = lines->next;
2657                 }
2658                 ast_mutex_unlock(&devicelock);
2659                 req->data.linestat.linenumber = letohl(lineNumber);             
2660                 memcpy(req->data.linestat.lineDirNumber, lines->name,
2661                                 sizeof(req->data.linestat.lineDirNumber));
2662                 memcpy(req->data.linestat.lineDisplayName, lines->label,
2663                                 sizeof(req->data.linestat.lineDisplayName)); 
2664                 transmit_response(s,req);
2665                 break;
2666         case CAPABILITIES_RES_MESSAGE:
2667                 if (skinnydebug) {
2668                         ast_verbose("Received CapabilitiesRes\n");      
2669                 }
2670                 /* XXX process the capabilites  */
2671                 break;
2672         case KEEP_ALIVE_MESSAGE:
2673                 memset(req, 0, SKINNY_MAX_PACKET);
2674                 req->len = htolel(4);
2675                 req->e = htolel(KEEP_ALIVE_ACK_MESSAGE);
2676                 transmit_response(s, req);
2677                 do_housekeeping(s);
2678
2679                 break;
2680         case OFFHOOK_MESSAGE:
2681                 transmit_ringer_mode(s,SKINNY_RING_OFF);
2682                 transmit_lamp_indication(s, STIMULUS_LINE, s->device->lines->instance, SKINNY_LAMP_ON); 
2683                 
2684                 sub = find_subchannel_by_line(s->device->lines);
2685                 if (!sub) {
2686                         ast_log(LOG_NOTICE, "No available lines on: %s\n", s->device->name);
2687                         return 0;
2688                 }
2689                 sub->parent->hookstate = SKINNY_OFFHOOK;
2690                 
2691                 if (sub->outgoing) {
2692                         /* We're answering a ringing call */
2693                         ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
2694                         transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2695                         transmit_tone(s, SKINNY_SILENCE);
2696                         transmit_callstate(s, s->device->lines->instance, SKINNY_CONNECTED, sub->callid);
2697                         start_rtp(sub);
2698                         ast_setstate(sub->owner, AST_STATE_UP);
2699                         /* XXX select the appropriate soft key here */
2700                 } else {        
2701                         if (!sub->owner) {      
2702                                 transmit_callstate(s, s->device->lines->instance, SKINNY_OFFHOOK, sub->callid);
2703                                 if (skinnydebug) {
2704                                         ast_verbose("Attempting to Clear display on Skinny %s@%s\n",sub->parent->name, sub->parent->parent->name);
2705                                 }
2706                                 transmit_displaymessage(s, NULL); /* clear display */ 
2707                                 transmit_tone(s, SKINNY_DIALTONE);
2708                                 c = skinny_new(sub, AST_STATE_DOWN);                    
2709                                 if(c) {
2710                                         /* start switch */
2711                                         if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
2712                                                 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
2713                                                 ast_hangup(c);
2714                                         }
2715                                 } else {
2716                                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", sub->parent->name, s->device->name);
2717                                 }
2718                                 
2719                         } else {
2720                                 ast_log(LOG_DEBUG, "Current sub [%s] already has owner\n", sub->owner->name);
2721                         }
2722                 }
2723                 break;
2724         case ONHOOK_MESSAGE:
2725                 sub = find_subchannel_by_line(s->device->lines);
2726                 if (sub->parent->hookstate == SKINNY_ONHOOK) {
2727                         /* Somthing else already put us back on hook */ 
2728                         break;
2729                 }
2730                 sub->cxmode = SKINNY_CX_RECVONLY;
2731                 sub->parent->hookstate = SKINNY_ONHOOK;
2732                 transmit_callstate(s, s->device->lines->instance, sub->parent->hookstate,sub->callid);
2733
2734                 if (skinnydebug) {
2735                         ast_verbose("Skinny %s@%s went on hook\n",sub->parent->name, sub->parent->parent->name);
2736                 }
2737
2738                 if (sub->parent->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
2739                         /* We're allowed to transfer, we have two active calls and */
2740                         /* we made at least one of the calls.  Let's try and transfer */
2741
2742 #if 0
2743                         if ((res = attempt_transfer(p)) < 0) {
2744                                  if (p->sub->next->owner) {
2745                                         sub->next->alreadygone = 1;
2746                                         ast_queue_hangup(sub->next->owner,1);
2747                                 }
2748                         } else if (res) {
2749                                 ast_log(LOG_WARNING, "Transfer attempt failed\n");
2750                                 return -1;
2751                         }
2752 #endif
2753                 } else {
2754                         /* Hangup the current call */
2755                         /* If there is another active call, skinny_hangup will ring the phone with the other call */
2756                         if (sub->owner) {
2757                                 sub->alreadygone = 1;
2758                                 ast_queue_hangup(sub->owner);
2759                         } else {
2760                                 ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n", 
2761                                    sub->parent->name, sub->parent->parent->name, sub->callid);
2762                         }
2763                 }
2764
2765                 if ((sub->parent->hookstate == SKINNY_ONHOOK) && (!sub->next->rtp)) {
2766                         do_housekeeping(s);
2767                 }
2768
2769                 break;
2770
2771         case KEYPAD_BUTTON_MESSAGE:
2772                 digit = letohl(req->data.keypad.button);
2773                 if (skinnydebug) {
2774                         ast_verbose("Collected digit: [%d]\n", digit);
2775                 }
2776                 f.frametype = AST_FRAME_DTMF;
2777                 if (digit == 14) {
2778                         d = '*';
2779                 } else if (digit == 15) {
2780                         d = '#';
2781                 } else if (digit >=0 && digit <= 9) {
2782                         d = '0' + digit;
2783                 } else {
2784                         /* digit=10-13 (A,B,C,D ?), or
2785                          * digit is bad value
2786                          * 
2787                          * probably should not end up here, but set
2788                          * value for backward compatibility, and log
2789                          * a warning.
2790                          */
2791                         d = '0' + digit;
2792                         ast_log(LOG_WARNING, "Unsupported digit %d\n", digit);
2793                 }
2794                 f.subclass  = d;  
2795                 f.src = "skinny";
2796
2797                 sub = find_subchannel_by_line(s->device->lines);                
2798
2799                 if (sub->owner) {
2800                         /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
2801                         ast_queue_frame(sub->owner, &f);
2802                         if (sub->next->owner) {
2803                                 ast_queue_frame(sub->next->owner, &f);
2804                         }
2805                 } else {
2806                         ast_verbose("No owner: %s\n", s->device->lines->name);
2807                 }
2808                 break;
2809         case OPEN_RECIEVE_CHANNEL_ACK_MESSAGE:
2810                 ast_verbose("Recieved Open Recieve Channel Ack\n");
2811                 status = letohl(req->data.openrecievechannelack.status);
2812                 if (status) {
2813                         ast_log(LOG_ERROR, "Open Recieve Channel Failure\n");
2814                         break;
2815                 }
2816                 /* ENDIAN */
2817                 memcpy(addr, req->data.openrecievechannelack.ipAddr, sizeof(addr));
2818                 port = htolel(req->data.openrecievechannelack.port);
2819                                 
2820                 sin.sin_family = AF_INET;
2821                 /* I smell endian problems */
2822                 memcpy(&sin.sin_addr, addr, sizeof(sin.sin_addr));  
2823                 sin.sin_port = htons(port);
2824
2825                 ast_verbose("ipaddr = %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
2826         
2827                 sub = find_subchannel_by_line(s->device->lines);
2828                 if (sub->rtp) {
2829                         ast_rtp_set_peer(sub->rtp, &sin);
2830                         ast_rtp_get_us(sub->rtp, &us);  
2831                 } else {
2832                         ast_log(LOG_ERROR, "No RTP structure, this is very bad\n");
2833                         break;
2834                 }
2835                 memset(req, 0, SKINNY_MAX_PACKET);
2836                 req->len = htolel(sizeof(start_media_transmission_message)+4);
2837                 req->e = htolel(START_MEDIA_TRANSMISSION_MESSAGE);
2838                 req->data.startmedia.conferenceId = 0;
2839                 req->data.startmedia.passThruPartyId = 0;
2840                 memcpy(req->data.startmedia.remoteIp, &s->device->ourip, 4); /* Endian? */
2841                 req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
2842                 req->data.startmedia.packetSize = htolel(20);
2843                 req->data.startmedia.payloadType = htolel(convert_cap(s->device->lines->capability));
2844                 req->data.startmedia.qualifier.precedence = htolel(127);
2845                 req->data.startmedia.qualifier.vad = 0;
2846                 req->data.startmedia.qualifier.packets = 0;
2847                 req->data.startmedia.qualifier.bitRate = 0;
2848                 transmit_response(s, req);
2849                 break;  
2850         default:
2851                 ast_verbose("RECEIVED UNKNOWN MESSAGE TYPE:  %x\n", letohl(req->e));
2852                 break;
2853         }
2854
2855         free(req);
2856         return 1;
2857
2858 }
2859
2860 static void destroy_session(struct skinnysession *s)
2861 {
2862         struct skinnysession *cur, *prev = NULL;
2863         ast_mutex_lock(&sessionlock);
2864         cur = sessions;
2865         while(cur) {
2866                 if (cur == s)
2867                         break;
2868                 prev = cur;
2869                 cur = cur->next;
2870         }
2871         if (cur) {
2872                 if (prev)
2873                         prev->next = cur->next;
2874                 else
2875                         sessions = cur->next;
2876                 if (s->fd > -1)
2877                         close(s->fd);
2878                 ast_mutex_destroy(&s->lock);
2879                 free(s);
2880         } else
2881                 ast_log(LOG_WARNING, "Trying to delete nonexistent session %p?\n", s);
2882         ast_mutex_unlock(&sessionlock);
2883 }
2884
2885 static int get_input(struct skinnysession *s)  
2886 {  
2887         int res;  
2888         int dlen = 0;
2889         struct pollfd fds[1];  
2890  
2891         fds[0].fd = s->fd;
2892         fds[0].events = POLLIN;
2893         res = poll(fds, 1, -1);
2894  
2895         if (res < 0) {
2896                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
2897         } else if (res > 0) {
2898                 memset(s->inbuf,0,sizeof(s->inbuf));
2899                 res = read(s->fd, s->inbuf, 4);
2900                 if (res != 4) {
2901                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2902                         return -1;
2903                 }
2904                 dlen = letohl(*(int *)s->inbuf);
2905                 if (dlen+8 > sizeof(s->inbuf))
2906                         dlen = sizeof(s->inbuf) - 8;
2907                 *(int *)s->inbuf = htolel(dlen);
2908                 res = read(s->fd, s->inbuf+4, dlen+4);
2909                 ast_mutex_unlock(&s->lock);
2910                 if (res != (dlen+4)) {
2911                         ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
2912                         return -1;
2913                 } 
2914         }  
2915         return res;  
2916 }   
2917
2918 static skinny_req *skinny_req_parse(struct skinnysession *s)
2919 {
2920         skinny_req *req;
2921         
2922         req = malloc(SKINNY_MAX_PACKET);
2923         if (!req) {
2924                 ast_log(LOG_ERROR, "Unable to allocate skinny_request, this is bad\n");
2925                 return NULL;
2926         }
2927         memset(req, 0, sizeof(skinny_req));
2928         /* +8 to account for reserved and length fields */
2929         memcpy(req, s->inbuf, letohl(*(int*)(s->inbuf))+8); 
2930         if (letohl(req->e) < 0) {
2931                 ast_log(LOG_ERROR, "Event Message is NULL from socket %d, This is bad\n", s->fd);
2932                 free(req);
2933                 return NULL;
2934         }
2935         return req;
2936 }
2937
2938 static void *skinny_session(void *data)
2939 {
2940         int res;
2941         skinny_req *req;
2942         struct skinnysession *s = data;
2943         char iabuf[INET_ADDRSTRLEN];
2944         
2945         ast_verbose(VERBOSE_PREFIX_3 "Starting Skinny session from %s\n",  ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
2946
2947         for (;;) {
2948                 res = 0;
2949                 res = get_input(s);
2950                 if (res < 0)
2951                         break;
2952                 req = skinny_req_parse(s);
2953                 if (!req) {
2954                         return NULL;
2955                 }
2956                 res = handle_message(req, s);
2957                 if (res < 0) {
2958                         destroy_session(s);
2959                         return NULL;
2960                 } 
2961         }
2962         ast_log(LOG_NOTICE, "Skinny Session returned: %s\n", strerror(errno));
2963         destroy_session(s);
2964         return 0;
2965 }
2966
2967 static void *accept_thread(void *ignore)
2968 {
2969         int as;
2970         struct sockaddr_in sin;
2971         socklen_t sinlen;
2972         struct skinnysession *s;
2973         struct protoent *p;
2974         int arg = 1;
2975         pthread_attr_t attr;
2976
2977         pthread_attr_init(&attr);
2978         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2979
2980         for (;;) {
2981                 sinlen = sizeof(sin);
2982                 as = accept(skinnysock, (struct sockaddr *)&sin, &sinlen);
2983                 if (as < 0) {
2984                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
2985                         continue;
2986                 }
2987                 p = getprotobyname("tcp");
2988                 if(p) {
2989                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
2990                                 ast_log(LOG_WARNING, "Failed to set Skinny tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
2991                         }
2992                 }
2993                 s = malloc(sizeof(struct skinnysession));
2994                 if (!s) {
2995                         ast_log(LOG_WARNING, "Failed to allocate Skinny session: %s\n", strerror(errno));
2996                         continue;
2997                 } 
2998                 memset(s, 0, sizeof(struct skinnysession));
2999                 memcpy(&s->sin, &sin, sizeof(sin));
3000                 ast_mutex_init(&s->lock);
3001                 s->fd = as;
3002                 ast_mutex_lock(&sessionlock);
3003                 s->next = sessions;
3004                 sessions = s;
3005                 ast_mutex_unlock(&sessionlock);
3006                 
3007                 if (ast_pthread_create(&tcp_thread, NULL, skinny_session, s)) {
3008                         destroy_session(s);
3009                 }
3010         }
3011         
3012         
3013         if (skinnydebug) {
3014                 ast_verbose("killing accept thread\n");
3015         }
3016         close(as);
3017         return 0;
3018 }
3019
3020 static void *do_monitor(void *data)
3021 {
3022         int res;
3023
3024         /* This thread monitors all the interfaces which are not yet in use
3025            (and thus do not have a separate thread) indefinitely */
3026         /* From here on out, we die whenever asked */
3027         for(;;) {
3028                 pthread_testcancel();
3029                 /* Wait for sched or io */
3030                 res = ast_sched_wait(sched);
3031                 if ((res < 0) || (res > 1000)) {
3032                         res = 1000;
3033                 }
3034                 res = ast_io_wait(io, res);
3035                 ast_mutex_lock(&monlock);
3036                 if (res >= 0) {
3037                         ast_sched_runq(sched);
3038                 }
3039                 ast_mutex_unlock(&monlock);
3040         }
3041         /* Never reached */
3042         return NULL;
3043         
3044 }
3045
3046 static int restart_monitor(void)
3047 {
3048         /* If we're supposed to be stopped -- stay stopped */
3049         if (monitor_thread == AST_PTHREADT_STOP)
3050                 return 0;
3051         if (ast_mutex_lock(&monlock)) {
3052                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
3053                 return -1;
3054         }
3055         if (monitor_thread == pthread_self()) {
3056                 ast_mutex_unlock(&monlock);
3057                 ast_log(LOG_WARNING, "Cannot kill myself\n");
3058                 return -1;
3059         }
3060         if (monitor_thread != AST_PTHREADT_NULL) {
3061                 /* Wake up the thread */
3062                 pthread_kill(monitor_thread, SIGURG);
3063         } else {
3064                 /* Start a new monitor */
3065                 if (ast_pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
3066                         ast_mutex_unlock(&monlock);
3067                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
3068                         return -1;
3069                 }
3070         }
3071         ast_mutex_unlock(&monlock);
3072         return 0;
3073 }
3074
3075 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause)
3076 {
3077         int oldformat;
3078         struct skinny_subchannel *sub;
3079         struct ast_channel *tmpc = NULL;
3080         char tmp[256];
3081         char *dest = data;
3082
3083         oldformat = format;
3084         format &= capability;
3085         if (!format) {
3086                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
3087                 return NULL;
3088         }
3089         
3090         strncpy(tmp, dest, sizeof(tmp) - 1);
3091         if (ast_strlen_zero(tmp)) {
3092                 ast_log(LOG_NOTICE, "Skinny channels require a device\n");
3093                 return NULL;
3094         }
3095         
3096         sub = find_subchannel_by_name(tmp);  
3097         if (!sub) {
3098                 ast_log(LOG_NOTICE, "No available lines on: %s\n", dest);
3099                 return NULL;
3100         }
3101         
3102         if (option_verbose > 2) {
3103                 ast_verbose(VERBOSE_PREFIX_3 "skinny_request(%s)\n", tmp);
3104                 ast_verbose(VERBOSE_PREFIX_3 "Skinny cw: %d, dnd: %d, so: %d, sno: %d\n", 
3105                         sub->parent->callwaiting, sub->parent->dnd, sub->owner ? 1 : 0, sub->next->owner ? 1: 0);
3106         }
3107         tmpc = skinny_new(sub->owner ? sub->next : sub, AST_STATE_DOWN);
3108         if (!tmpc) {
3109                 ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
3110         }
3111         restart_monitor();
3112
3113         /* and finish */        
3114         return tmpc;
3115 }
3116
3117 static int reload_config(void)
3118 {
3119         int on=1;
3120         struct ast_config *cfg;
3121         struct ast_variable *v;
3122         int format;
3123         char *cat;
3124         char iabuf[INET_ADDRSTRLEN];
3125         struct skinny_device *d;
3126         int oldport = ntohs(bindaddr.sin_port);
3127
3128         if (gethostname(ourhost, sizeof(ourhost))) {
3129                 ast_log(LOG_WARNING, "Unable to get hostname, Skinny disabled\n");
3130                 return 0;
3131         }
3132         cfg = ast_config_load(config);
3133
3134         /* We *must* have a config file otherwise stop immediately */
3135         if (!cfg) {
3136                 ast_log(LOG_NOTICE, "Unable to load config %s, Skinny disabled\n", config);
3137                 return 0;
3138         }
3139
3140         /* load the general section */
3141         memset(&bindaddr, 0, sizeof(bindaddr));
3142         v = ast_variable_browse(cfg, "general");
3143         while(v) {
3144                 /* Create the interface list */
3145                 if (!strcasecmp(v->name, "bindaddr")) {
3146                         if (!(hp = ast_gethostbyname(v->value, &ahp))) {
3147                                 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
3148                         } else {
3149                                 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
3150                         }
3151                 } else if (!strcasecmp(v->name, "keepAlive")) {
3152                         keep_alive = atoi(v->value);            
3153                 } else if (!strcasecmp(v->name, "dateFormat")) {
3154                         strncpy(date_format, v->value, sizeof(date_format) - 1);        
3155                 } else if (!strcasecmp(v->name, "allow")) {
3156                         format = ast_getformatbyname(v->value);
3157                         if (format < 1) 
3158                                 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
3159                         else
3160                                 capability |= format;
3161                 } else if (!strcasecmp(v->name, "disallow")) {
3162                         format = ast_getformatbyname(v->value);
3163                         if (format < 1) 
3164                                 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
3165                         else
3166                                 capability &= ~format;
3167                 } else if (!strcasecmp(v->name, "port")) {
3168                         if (sscanf(v->value, "%d", &ourport) == 1) {
3169                                 bindaddr.sin_port = htons(ourport);
3170                         } else {
3171                                 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
3172                         }
3173                 }
3174                 v = v->next;
3175         }
3176
3177         if (ntohl(bindaddr.sin_addr.s_addr)) {
3178                 memcpy(&__ourip, &bindaddr.sin_addr, sizeof(__ourip));
3179         } else {
3180                 hp = ast_gethostbyname(ourhost, &ahp);
3181                 if (!hp) {
3182                         ast_log(LOG_WARNING, "Unable to get our IP address, Skinny disabled\n");
3183                         ast_config_destroy(cfg);
3184                         return 0;
3185                 }
3186                 memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
3187         }
3188         if (!ntohs(bindaddr.sin_port)) {
3189                 bindaddr.sin_port = ntohs(DEFAULT_SKINNY_PORT);
3190         }
3191         bindaddr.sin_family = AF_INET;
3192         
3193         /* load the device sections */
3194         cat = ast_category_browse(cfg, NULL);
3195         while(cat) {
3196                 if (!strcasecmp(cat, "general")) {
3197                   /* Nothing to do */
3198 #if 0
3199                 } else if (!strncasecmp(cat, "paging-", 7)) {
3200                         p = build_paging_device(cat, ast_variable_browse(cfg, cat));
3201                         if (p) {
3202                         }
3203 #endif
3204                 } else {
3205                         d = build_device(cat, ast_variable_browse(cfg, cat));
3206                         if (d) {
3207                                 if (option_verbose > 2) {
3208                                         ast_verbose(VERBOSE_PREFIX_3 "Added device '%s'\n", d->name);
3209                 }
3210                                 ast_mutex_lock(&devicelock);
3211                                 d->next = devices;
3212                                 devices = d;
3213                                 ast_mutex_unlock(&devicelock);
3214                         }
3215                 }
3216                 cat = ast_category_browse(cfg, cat);
3217         }
3218         ast_mutex_lock(&netlock);
3219         if ((skinnysock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
3220                 close(skinnysock);
3221                 skinnysock = -1;
3222         }
3223         if (skinnysock < 0) {
3224                 skinnysock = socket(AF_INET, SOCK_STREAM, 0);
3225                 if(setsockopt(skinnysock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
3226                         ast_log(LOG_ERROR, "Set Socket Options failed: errno %d, %s", errno, strerror(errno));
3227                         ast_config_destroy(cfg);
3228                         return 0;
3229                 }
3230
3231                 if (skinnysock < 0) {
3232                         ast_log(LOG_WARNING, "Unable to create Skinny socket: %s\n", strerror(errno));
3233                 } else {
3234                         if (bind(skinnysock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
3235                                 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
3236                                                 ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port),
3237                                                         strerror(errno));
3238                                 close(skinnysock);
3239                                 skinnysock = -1;
3240                                 ast_config_destroy(cfg);
3241                                 return 0;
3242                         } 
3243
3244                         if (listen(skinnysock,DEFAULT_SKINNY_BACKLOG)) {
3245                                         ast_log(LOG_WARNING, "Failed to start listening to %s:%d: %s\n",
3246                                                 ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port),
3247                                                         strerror(errno));
3248                                         close(skinnysock);
3249                                         skinnysock = -1;
3250                                         ast_config_destroy(cfg);
3251                                         return 0;
3252                         }
3253                 
3254                         if (option_verbose > 1)
3255                                 ast_verbose(VERBOSE_PREFIX_2 "Skinny listening on %s:%d\n", 
3256                                         ast_inet_ntoa(iabuf, sizeof(iabuf), bindaddr.sin_addr), ntohs(bindaddr.sin_port));
3257
3258                         ast_pthread_create(&accept_t,NULL, accept_thread, NULL);
3259                 }
3260         }
3261         ast_mutex_unlock(&netlock);
3262
3263         /* and unload the configuration when were done */
3264         ast_config_destroy(cfg);
3265
3266         return 0;
3267 }
3268
3269 void delete_devices(void)
3270 {
3271         struct skinny_device *d, *dlast;
3272         struct skinny_line *l, *llast;
3273         struct skinny_subchannel *sub, *slast;
3274         
3275         ast_mutex_lock(&devicelock);
3276         
3277         /* Delete all devices */
3278         for (d=devices;d;) {
3279                 
3280                 /* Delete all lines for this device */
3281                 for (l=d->lines;l;) {
3282                         /* Delete all subchannels for this line */
3283                         for (sub=l->sub;sub;) {
3284                                 slast = sub;
3285                                 sub = sub->next;
3286                                 ast_mutex_destroy(&slast->lock);
3287                                 free(slast);
3288                         }
3289                         llast = l;
3290                         l = l->next;
3291                         ast_mutex_destroy(&llast->lock);
3292                         free(llast);
3293                 }
3294                 dlast = d;
3295                 d = d->next;
3296                 free(dlast);
3297         }
3298         devices=NULL;
3299         ast_mutex_unlock(&devicelock);
3300 }
3301
3302 int reload(void)
3303 {
3304         delete_devices();
3305         reload_config();
3306         restart_monitor();
3307
3308         return 0;
3309 }
3310
3311
3312 int load_module()
3313 {
3314         int res = 0;
3315
3316         for (; res < (sizeof(soft_key_template_default) / sizeof(soft_key_template_default[0])); res++)
3317                 soft_key_template_default[res].softKeyEvent = htolel(soft_key_template_default[res].softKeyEvent);
3318
3319         /* load and parse config */
3320         res = reload_config();
3321         
3322         /* Announce our presence to Asterisk */ 
3323         if (!res) {
3324                 /* Make sure we can register our skinny channel type */
3325                 if (ast_channel_register(&skinny_tech)) {
3326                         ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
3327                         return -1;
3328                 }
3329         }
3330         ast_rtp_proto_register(&skinny_rtp);
3331         ast_cli_register(&cli_show_devices);
3332         ast_cli_register(&cli_show_lines);
3333         ast_cli_register(&cli_debug);
3334         ast_cli_register(&cli_no_debug);
3335         sched = sched_context_create();
3336         if (!sched) {
3337                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
3338         }
3339         io = io_context_create();
3340         if (!io) {
3341                 ast_log(LOG_WARNING, "Unable to create I/O context\n");
3342         }
3343         /* And start the monitor for the first time */
3344         restart_monitor();
3345         return res;
3346 }
3347
3348 int unload_module()
3349 {
3350 #if 0
3351         struct skinny_session *session, s;
3352         struct skinny_subchannel *sub;
3353         struct skinny_line *line = session;
3354
3355         /* close all IP connections */
3356         if (!ast_mutex_lock(&devicelock)) {
3357                 /* Terminate tcp listener thread */
3358                 
3359
3360         } else {
3361                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
3362                 return -1;
3363         }
3364         if (!ast_mutex_lock(&monlock)) {
3365                 if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
3366                         pthread_cancel(monitor_thread);
3367                         pthread_kill(monitor_thread, SIGURG);
3368                         pthread_join(monitor_thread, NULL);
3369                 }
3370                 monitor_thread = AST_PTHREADT_STOP;
3371                 ast_mutex_unlock(&monlock);
3372         } else {
3373                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
3374                 return -1;
3375         }
3376         if (!ast_mutex_lock(&iflock)) {
3377                 /* Destroy all the interfaces and free their memory */
3378                 p = iflist;
3379                 while(p) {
3380                         pl = p;
3381                         p = p->next;
3382                         /* Free associated memory */
3383                         ast_mutex_destroy(&pl->lock);
3384                         free(pl);
3385                 }
3386                 iflist = NULL;
3387                 ast_mutex_unlock(&iflock);
3388         } else {
3389                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
3390                 return -1;
3391         }
3392
3393         ast_rtp_proto_register(&skinny_rtp);
3394         ast_channel_unregister(&skinny_tech);
3395         ast_cli_register(&cli_show_devices);
3396         ast_cli_register(&cli_show_lines);
3397         ast_cli_register(&cli_debug);
3398         ast_cli_register(&cli_no_debug);
3399
3400         return 0;
3401 #endif
3402         return -1;
3403 }
3404
3405 int usecount()
3406 {
3407         return usecnt;
3408 }
3409
3410 char *key()
3411 {
3412         return ASTERISK_GPL_KEY;
3413 }
3414
3415 char *description()
3416 {
3417         return (char *) desc;
3418 }