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