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