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