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