f55002d641a3c98535570225ba8242705106a711
[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_7921              365
825 #define SKINNY_DEVICE_7905              20000
826 #define SKINNY_DEVICE_7920              30002
827 #define SKINNY_DEVICE_7970              30006
828 #define SKINNY_DEVICE_7912              30007
829 #define SKINNY_DEVICE_7902              30008
830 #define SKINNY_DEVICE_CIPC              30016   /* Cisco IP Communicator */
831 #define SKINNY_DEVICE_7961              30018
832 #define SKINNY_DEVICE_7936              30019
833 #define SKINNY_DEVICE_SCCPGATEWAY_AN    30027   /* ??? */
834 #define SKINNY_DEVICE_SCCPGATEWAY_BRI   30028   /* ??? */
835
836 #define SKINNY_SPEAKERON 1
837 #define SKINNY_SPEAKEROFF 2
838
839 #define SKINNY_MICON 1
840 #define SKINNY_MICOFF 2
841
842 #define SKINNY_OFFHOOK 1
843 #define SKINNY_ONHOOK 2
844 #define SKINNY_RINGOUT 3
845 #define SKINNY_RINGIN 4
846 #define SKINNY_CONNECTED 5
847 #define SKINNY_BUSY 6
848 #define SKINNY_CONGESTION 7
849 #define SKINNY_HOLD 8
850 #define SKINNY_CALLWAIT 9
851 #define SKINNY_TRANSFER 10
852 #define SKINNY_PARK 11
853 #define SKINNY_PROGRESS 12
854 #define SKINNY_CALLREMOTEMULTILINE 13
855 #define SKINNY_INVALID 14
856
857 #define SKINNY_SILENCE          0x00
858 #define SKINNY_DIALTONE         0x21
859 #define SKINNY_BUSYTONE         0x23
860 #define SKINNY_ALERT            0x24
861 #define SKINNY_REORDER          0x25
862 #define SKINNY_CALLWAITTONE     0x2D
863 #define SKINNY_NOTONE           0x7F
864
865 #define SKINNY_LAMP_OFF 1
866 #define SKINNY_LAMP_ON 2
867 #define SKINNY_LAMP_WINK 3
868 #define SKINNY_LAMP_FLASH 4
869 #define SKINNY_LAMP_BLINK 5
870
871 #define SKINNY_RING_OFF 1
872 #define SKINNY_RING_INSIDE 2
873 #define SKINNY_RING_OUTSIDE 3
874 #define SKINNY_RING_FEATURE 4
875
876 #define TYPE_TRUNK 1
877 #define TYPE_LINE 2
878
879 /* Skinny rtp stream modes. Do we really need this? */
880 #define SKINNY_CX_SENDONLY      0
881 #define SKINNY_CX_RECVONLY      1
882 #define SKINNY_CX_SENDRECV      2
883 #define SKINNY_CX_CONF          3
884 #define SKINNY_CX_CONFERENCE    3
885 #define SKINNY_CX_MUTE          4
886 #define SKINNY_CX_INACTIVE      4
887
888 #if 0
889 static char *skinny_cxmodes[] = {
890         "sendonly",
891         "recvonly",
892         "sendrecv",
893         "confrnce",
894         "inactive"
895 };
896 #endif
897
898 /* driver scheduler */
899 static struct sched_context *sched = NULL;
900 static struct io_context *io;
901
902 /* Protect the monitoring thread, so only one process can kill or start it, and not
903    when it's doing something critical. */
904 AST_MUTEX_DEFINE_STATIC(monlock);
905 /* Protect the network socket */
906 AST_MUTEX_DEFINE_STATIC(netlock);
907 /* Protect the session list */
908 AST_MUTEX_DEFINE_STATIC(sessionlock);
909 /* Protect the device list */
910 AST_MUTEX_DEFINE_STATIC(devicelock);
911 #if 0
912 /* Protect the paging device list */
913 AST_MUTEX_DEFINE_STATIC(pagingdevicelock);
914 #endif
915
916 /* This is the thread for the monitor which checks for input on the channels
917    which are not currently in use. */
918 static pthread_t monitor_thread = AST_PTHREADT_NULL;
919
920 /* Wait up to 16 seconds for first digit */
921 static int firstdigittimeout = 16000;
922
923 /* How long to wait for following digits */
924 static int gendigittimeout = 8000;
925
926 /* How long to wait for an extra digit, if there is an ambiguous match */
927 static int matchdigittimeout = 3000;
928
929 struct skinny_subchannel {
930         ast_mutex_t lock;
931         struct ast_channel *owner;
932         struct ast_rtp *rtp;
933         struct ast_rtp *vrtp;
934         unsigned int callid;
935         /* time_t lastouttime; */                       /* Unused */
936         int progress;
937         int ringing;
938         int onhold;
939         /* int lastout; */                              /* Unused */
940         int cxmode;
941         int nat;
942         int outgoing;
943         int alreadygone;
944
945         struct skinny_subchannel *next;
946         struct skinny_line *parent;
947 };
948
949 struct skinny_line {
950         ast_mutex_t lock;
951         char name[80];
952         char label[24];                                 /* Label that shows next to the line buttons */
953         char accountcode[AST_MAX_ACCOUNT_CODE];
954         char exten[AST_MAX_EXTENSION];                  /* Extension where to start */
955         char context[AST_MAX_CONTEXT];
956         char language[MAX_LANGUAGE];
957         char cid_num[AST_MAX_EXTENSION];                /* Caller*ID */
958         char cid_name[AST_MAX_EXTENSION];               /* Caller*ID */
959         char lastcallerid[AST_MAX_EXTENSION];           /* Last Caller*ID */
960         char call_forward[AST_MAX_EXTENSION];
961         char mailbox[AST_MAX_EXTENSION];
962         char vmexten[AST_MAX_EXTENSION];
963         char regexten[AST_MAX_EXTENSION];               /* Extension for auto-extensions */
964         char regcontext[AST_MAX_CONTEXT];               /* Context for auto-extensions */
965         char mohinterpret[MAX_MUSICCLASS];
966         char mohsuggest[MAX_MUSICCLASS];
967         char lastnumberdialed[AST_MAX_EXTENSION];       /* Last number that was dialed - used for redial */
968         int curtone;                                    /* Current tone being played */
969         ast_group_t callgroup;
970         ast_group_t pickupgroup;
971         int callwaiting;
972         int transfer;
973         int threewaycalling;
974         int mwiblink;
975         int cancallforward;
976         int callreturn;
977         int dnd; /* How does this affect callwait?  Do we just deny a skinny_request if we're dnd? */
978         int hascallerid;
979         int hidecallerid;
980         int amaflags;
981         int type;
982         int instance;
983         int group;
984         int needdestroy;
985         int capability;
986         int nonCodecCapability;
987         int onhooktime;
988         int msgstate;                                   /* voicemail message state */
989         int immediate;
990         int hookstate;
991         int nat;
992
993         struct ast_codec_pref prefs;
994         struct skinny_subchannel *sub;
995         struct skinny_line *next;
996         struct skinny_device *parent;
997 };
998
999 struct skinny_speeddial {
1000         ast_mutex_t lock;
1001         char label[42];
1002         char context[AST_MAX_CONTEXT];
1003         char exten[AST_MAX_EXTENSION];
1004         int instance;
1005         int stateid;
1006         int laststate;
1007         int isHint;
1008
1009         struct skinny_speeddial *next;
1010         struct skinny_device *parent;
1011 };
1012
1013 struct skinny_addon {
1014         ast_mutex_t lock;
1015         char type[10];
1016
1017         struct skinny_addon *next;
1018         struct skinny_device *parent;
1019 };
1020
1021 static struct skinny_device {
1022         /* A device containing one or more lines */
1023         char name[80];
1024         char id[16];
1025         char version_id[16];
1026         char exten[AST_MAX_EXTENSION];          /* Cruddy variable name, pick a better one */
1027         int type;
1028         int registered;
1029         int lastlineinstance;
1030         int lastcallreference;
1031         int capability;
1032         struct sockaddr_in addr;
1033         struct in_addr ourip;
1034         struct skinny_line *lines;
1035         struct skinny_speeddial *speeddials;
1036         struct skinny_addon *addons;
1037         struct ast_codec_pref prefs;
1038         struct ast_ha *ha;
1039         struct skinnysession *session;
1040         struct skinny_device *next;
1041 } *devices = NULL;
1042
1043 struct skinny_paging_device {
1044         char name[80];
1045         char id[16];
1046         struct skinny_device ** devices;
1047         struct skinny_paging_device *next;
1048 };
1049
1050 static struct skinnysession {
1051         pthread_t t;
1052         ast_mutex_t lock;
1053         struct sockaddr_in sin;
1054         int fd;
1055         char inbuf[SKINNY_MAX_PACKET];
1056         char outbuf[SKINNY_MAX_PACKET];
1057         struct skinny_device *device;
1058         struct skinnysession *next;
1059 } *sessions = NULL;
1060
1061 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause);
1062 static int skinny_devicestate(void *data);
1063 static int skinny_call(struct ast_channel *ast, char *dest, int timeout);
1064 static int skinny_hangup(struct ast_channel *ast);
1065 static int skinny_answer(struct ast_channel *ast);
1066 static struct ast_frame *skinny_read(struct ast_channel *ast);
1067 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1068 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1069 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1070 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1071 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1072 static int handle_time_date_req_message(struct skinny_req *req, struct skinnysession *s);
1073
1074 static const struct ast_channel_tech skinny_tech = {
1075         .type = "Skinny",
1076         .description = tdesc,
1077         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1078         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1079         .requester = skinny_request,
1080         .devicestate = skinny_devicestate,
1081         .call = skinny_call,
1082         .hangup = skinny_hangup,
1083         .answer = skinny_answer,
1084         .read = skinny_read,
1085         .write = skinny_write,
1086         .indicate = skinny_indicate,
1087         .fixup = skinny_fixup,
1088         .send_digit_begin = skinny_senddigit_begin,
1089         .send_digit_end = skinny_senddigit_end,
1090 /*      .bridge = ast_rtp_bridge, */
1091 };
1092
1093 static int skinny_extensionstate_cb(char *context, char* exten, int state, void *data);
1094
1095 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1096 {
1097         struct skinny_device *d = s->device;
1098         struct skinny_addon *a = d->addons;
1099         int i;
1100
1101         switch (d->type) {
1102                 case SKINNY_DEVICE_30SPPLUS:
1103                 case SKINNY_DEVICE_30VIP:
1104                         /* 13 rows, 2 columns */
1105                         for (i = 0; i < 4; i++)
1106                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1107                         (btn++)->buttonDefinition = BT_REDIAL;
1108                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1109                         (btn++)->buttonDefinition = BT_CALLPARK;
1110                         (btn++)->buttonDefinition = BT_FORWARDALL;
1111                         (btn++)->buttonDefinition = BT_CONFERENCE;
1112                         for (i = 0; i < 4; i++)
1113                                 (btn++)->buttonDefinition = BT_NONE;
1114                         for (i = 0; i < 13; i++)
1115                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1116                         
1117                         break;
1118                 case SKINNY_DEVICE_12SPPLUS:
1119                 case SKINNY_DEVICE_12SP:
1120                 case SKINNY_DEVICE_12:
1121                         /* 6 rows, 2 columns */
1122                         for (i = 0; i < 2; i++)
1123                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1124                         for (i = 0; i < 4; i++)
1125                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1126                         (btn++)->buttonDefinition = BT_HOLD;
1127                         (btn++)->buttonDefinition = BT_REDIAL;
1128                         (btn++)->buttonDefinition = BT_TRANSFER;
1129                         (btn++)->buttonDefinition = BT_FORWARDALL;
1130                         (btn++)->buttonDefinition = BT_CALLPARK;
1131                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1132                         break;
1133                 case SKINNY_DEVICE_7910:
1134                         (btn++)->buttonDefinition = BT_LINE;
1135                         (btn++)->buttonDefinition = BT_HOLD;
1136                         (btn++)->buttonDefinition = BT_TRANSFER;
1137                         (btn++)->buttonDefinition = BT_DISPLAY;
1138                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1139                         (btn++)->buttonDefinition = BT_CONFERENCE;
1140                         (btn++)->buttonDefinition = BT_FORWARDALL;
1141                         for (i = 0; i < 2; i++)
1142                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1143                         (btn++)->buttonDefinition = BT_REDIAL;
1144                         break;
1145                 case SKINNY_DEVICE_7960:
1146                 case SKINNY_DEVICE_7961:
1147                 case SKINNY_DEVICE_7961GE:
1148                         for (i = 0; i < 6; i++)
1149                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1150                         break;
1151                 case SKINNY_DEVICE_7940:
1152                 case SKINNY_DEVICE_7941:
1153                 case SKINNY_DEVICE_7941GE:
1154                         for (i = 0; i < 2; i++)
1155                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1156                         break;
1157                 case SKINNY_DEVICE_7935:
1158                 case SKINNY_DEVICE_7936:
1159                         for (i = 0; i < 2; i++)
1160                                 (btn++)->buttonDefinition = BT_LINE;
1161                         break;
1162                 case SKINNY_DEVICE_ATA186:
1163                         (btn++)->buttonDefinition = BT_LINE;
1164                         break;
1165                 case SKINNY_DEVICE_7970:
1166                 case SKINNY_DEVICE_7971:
1167                 case SKINNY_DEVICE_CIPC:
1168                         for (i = 0; i < 8; i++)
1169                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1170                         break;
1171                 case SKINNY_DEVICE_7985:
1172                         /* XXX I have no idea what the buttons look like on these. */
1173                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1174                         break;
1175                 case SKINNY_DEVICE_7912:
1176                 case SKINNY_DEVICE_7911:
1177                 case SKINNY_DEVICE_7905:
1178                         (btn++)->buttonDefinition = BT_LINE;
1179                         (btn++)->buttonDefinition = BT_HOLD;
1180                         break;
1181                 case SKINNY_DEVICE_7920:
1182                 case SKINNY_DEVICE_7921:
1183                         /* XXX I don't know if this is right. */
1184                         for (i = 0; i < 4; i++)
1185                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1186                         break;
1187                 case SKINNY_DEVICE_7902:
1188                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1189                         break;
1190                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1191                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1192                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1193                         break;
1194                 default:
1195                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1196                         break;
1197         }
1198
1199         for (a = d->addons; a; a = a->next) {
1200                 if (!strcasecmp(a->type, "7914")) {
1201                         for (i = 0; i < 14; i++)
1202                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1203                 } else {
1204                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1205                 }
1206         }
1207
1208         return btn;
1209 }
1210
1211 static struct skinny_req *req_alloc(size_t size, int response_message)
1212 {
1213         struct skinny_req *req;
1214
1215         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1216                 return NULL;
1217
1218         req->len = htolel(size+4);
1219         req->e = htolel(response_message);
1220
1221         return req;
1222 }
1223
1224 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1225 {
1226         struct skinny_line *l;
1227
1228         /*Dialing from on hook or on a 7920 uses instance 0 in requests
1229           but we need to start looking at instance 1 */
1230
1231         if (!instance)
1232                 instance = 1;
1233
1234         for (l = d->lines; l; l = l->next) {
1235                 if (l->instance == instance)
1236                         break;
1237         }
1238
1239         if (!l) {
1240                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1241         }
1242         return l;
1243 }
1244
1245 static struct skinny_line *find_line_by_name(const char *dest)
1246 {
1247         struct skinny_line *l;
1248         struct skinny_device *d;
1249         char line[256];
1250         char *at;
1251         char *device;
1252
1253         ast_copy_string(line, dest, sizeof(line));
1254         at = strchr(line, '@');
1255         if (!at) {
1256                 ast_log(LOG_NOTICE, "Device '%s' has no @ (at) sign!\n", dest);
1257                 return NULL;
1258         }
1259         *at++ = '\0';
1260         device = at;
1261         ast_mutex_lock(&devicelock);
1262         for (d = devices; d; d = d->next) {
1263                 if (!strcasecmp(d->name, device)) {
1264                         if (skinnydebug)
1265                                 ast_verbose("Found device: %s\n", d->name);
1266                         /* Found the device */
1267                         for (l = d->lines; l; l = l->next) {
1268                                 /* Search for the right line */
1269                                 if (!strcasecmp(l->name, line)) {
1270                                         ast_mutex_unlock(&devicelock);
1271                                         return l;
1272                                 }
1273                         }
1274                 }
1275         }
1276         /* Device not found */
1277         ast_mutex_unlock(&devicelock);
1278         return NULL;
1279 }
1280
1281 /* It's quicker/easier to find the subchannel when we know the instance number too */
1282 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
1283 {
1284         struct skinny_line *l = find_line_by_instance(d, instance);
1285         struct skinny_subchannel *sub;
1286
1287         if (!l) {
1288                 return NULL;
1289         }
1290
1291         /* 7920 phones set call reference to 0, so use the first
1292            sub-channel on the list.
1293            This MIGHT need more love to be right */
1294         if (!reference)
1295                 sub = l->sub;
1296         else {
1297                 for (sub = l->sub; sub; sub = sub->next) {
1298                         if (sub->callid == reference)
1299                                 break;
1300                 }
1301         }
1302         if (!sub) {
1303                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
1304         }
1305         return sub;
1306 }
1307
1308 /* Find the subchannel when we only have the callid - this shouldn't happen often */
1309 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
1310 {
1311         struct skinny_line *l;
1312         struct skinny_subchannel *sub = NULL;
1313
1314         for (l = d->lines; l; l = l->next) {
1315                 for (sub = l->sub; sub; sub = sub->next) {
1316                         if (sub->callid == reference)
1317                                 break;
1318                 }
1319                 if (sub)
1320                         break;
1321         }
1322
1323         if (!l) {
1324                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
1325         } else {
1326                 if (!sub) {
1327                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
1328                 }
1329         }
1330         return sub;
1331 }
1332
1333 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
1334 {
1335         struct skinny_speeddial *sd;
1336
1337         for (sd = d->speeddials; sd; sd = sd->next) {
1338                 if (sd->isHint == isHint && sd->instance == instance)
1339                         break;
1340         }
1341
1342         if (!sd) {
1343                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
1344         }
1345         return sd;
1346 }
1347
1348 static int codec_skinny2ast(enum skinny_codecs skinnycodec)
1349 {
1350         switch (skinnycodec) {
1351         case SKINNY_CODEC_ALAW:
1352                 return AST_FORMAT_ALAW;
1353         case SKINNY_CODEC_ULAW:
1354                 return AST_FORMAT_ULAW;
1355         case SKINNY_CODEC_G723_1:
1356                 return AST_FORMAT_G723_1;
1357         case SKINNY_CODEC_G729A:
1358                 return AST_FORMAT_G729A;
1359         case SKINNY_CODEC_G726_32:
1360                 return AST_FORMAT_G726_AAL2; /* XXX Is this right? */
1361         case SKINNY_CODEC_H261:
1362                 return AST_FORMAT_H261;
1363         case SKINNY_CODEC_H263:
1364                 return AST_FORMAT_H263;
1365         default:
1366                 return 0;
1367         }
1368 }
1369
1370 static int codec_ast2skinny(int astcodec)
1371 {
1372         switch (astcodec) {
1373         case AST_FORMAT_ALAW:
1374                 return SKINNY_CODEC_ALAW;
1375         case AST_FORMAT_ULAW:
1376                 return SKINNY_CODEC_ULAW;
1377         case AST_FORMAT_G723_1:
1378                 return SKINNY_CODEC_G723_1;
1379         case AST_FORMAT_G729A:
1380                 return SKINNY_CODEC_G729A;
1381         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
1382                 return SKINNY_CODEC_G726_32;
1383         case AST_FORMAT_H261:
1384                 return SKINNY_CODEC_H261;
1385         case AST_FORMAT_H263:
1386                 return SKINNY_CODEC_H263;
1387         default:
1388                 return 0;
1389         }
1390 }
1391
1392 static void cleanup_stale_contexts(char *new, char *old)
1393 {
1394         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
1395
1396         while ((oldcontext = strsep(&old, "&"))) {
1397                 stalecontext = '\0';
1398                 ast_copy_string(newlist, new, sizeof(newlist));
1399                 stringp = newlist;
1400                 while ((newcontext = strsep(&stringp, "&"))) {
1401                         if (strcmp(newcontext, oldcontext) == 0) {
1402                                 /* This is not the context you're looking for */
1403                                 stalecontext = '\0';
1404                                 break;
1405                         } else if (strcmp(newcontext, oldcontext)) {
1406                                 stalecontext = oldcontext;
1407                         }
1408                         
1409                 }
1410                 if (stalecontext)
1411                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
1412         }
1413 }
1414
1415 static void register_exten(struct skinny_line *l)
1416 {
1417         char multi[256];
1418         char *stringp, *ext, *context;
1419
1420         if (ast_strlen_zero(regcontext))
1421                 return;
1422
1423         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1424         stringp = multi;
1425         while ((ext = strsep(&stringp, "&"))) {
1426                 if ((context = strchr(ext, '@'))) {
1427                         *context++ = '\0';      /* split ext@context */
1428                         if (!ast_context_find(context)) {
1429                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1430                                 continue;
1431                         }
1432                 } else {
1433                         context = regcontext;
1434                 }
1435                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
1436                          ast_strdup(l->name), ast_free, "Skinny");
1437         }
1438 }
1439
1440 static void unregister_exten(struct skinny_line *l)
1441 {
1442         char multi[256];
1443         char *stringp, *ext, *context;
1444
1445         if (ast_strlen_zero(regcontext))
1446                 return;
1447
1448         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1449         stringp = multi;
1450         while ((ext = strsep(&stringp, "&"))) {
1451                 if ((context = strchr(ext, '@'))) {
1452                         *context++ = '\0';      /* split ext@context */
1453                         if (!ast_context_find(context)) {
1454                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1455                                 continue;
1456                         }
1457                 } else {
1458                         context = regcontext;
1459                 }
1460                 ast_context_remove_extension(context, ext, 1, NULL);
1461         }
1462 }
1463
1464 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
1465 {
1466         struct skinny_device *d;
1467         struct skinny_line *l;
1468         struct skinny_speeddial *sd;
1469         struct sockaddr_in sin;
1470         socklen_t slen;
1471
1472         ast_mutex_lock(&devicelock);
1473         for (d = devices; d; d = d->next) {
1474                 if (!strcasecmp(req->data.reg.name, d->id)
1475                                 && ast_apply_ha(d->ha, &(s->sin))) {
1476                         s->device = d;
1477                         d->type = letohl(req->data.reg.type);
1478                         if (ast_strlen_zero(d->version_id)) {
1479                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
1480                         }
1481                         d->registered = 1;
1482                         d->session = s;
1483
1484                         slen = sizeof(sin);
1485                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
1486                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
1487                                 sin.sin_addr = __ourip;
1488                         }
1489                         d->ourip = sin.sin_addr;
1490
1491                         for (sd = d->speeddials; sd; sd = sd->next) {
1492                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd);
1493                         }
1494                         for (l = d->lines; l; l = l->next) {
1495                                 register_exten(l);
1496                                 ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
1497                         }
1498                         break;
1499                 }
1500         }
1501         ast_mutex_unlock(&devicelock);
1502         if (!d) {
1503                 return 0;
1504         }
1505         return 1;
1506 }
1507
1508 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
1509 {
1510         struct skinny_device *d;
1511         struct skinny_line *l;
1512         struct skinny_speeddial *sd;
1513
1514         d = s->device;
1515
1516         if (d) {
1517                 d->session = NULL;
1518                 d->registered = 0;
1519
1520                 for (sd = d->speeddials; sd; sd = sd->next) {
1521                         if (sd->stateid > -1)
1522                                 ast_extension_state_del(sd->stateid, NULL);
1523                 }
1524                 for (l = d->lines; l; l = l->next) {
1525                         unregister_exten(l);
1526                         ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
1527                 }
1528         }
1529
1530         return -1; /* main loop will destroy the session */
1531 }
1532
1533 static int transmit_response(struct skinnysession *s, struct skinny_req *req)
1534 {
1535         int res = 0;
1536
1537         if (!s) {
1538                 ast_log(LOG_WARNING, "Asked to transmit to a non-existant session!\n");
1539                 return -1;
1540         }
1541
1542         ast_mutex_lock(&s->lock);
1543
1544         if (skinnydebug)
1545                 ast_log(LOG_VERBOSE, "writing packet type %04X (%d bytes) to socket %d\n", letohl(req->e), letohl(req->len)+8, s->fd);
1546
1547         if (letohl(req->len > SKINNY_MAX_PACKET) || letohl(req->len < 0)) {
1548                 ast_log(LOG_WARNING, "transmit_response: the length of the request is out of bounds\n");
1549                 return -1;
1550         }
1551
1552         memset(s->outbuf,0,sizeof(s->outbuf));
1553         memcpy(s->outbuf, req, skinny_header_size);
1554         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
1555
1556         res = write(s->fd, s->outbuf, letohl(req->len)+8);
1557
1558         if (res != letohl(req->len)+8) {
1559                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
1560                 if (res == -1) {
1561                         if (skinnydebug)
1562                                 ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
1563                         skinny_unregister(NULL, s);
1564                 }
1565                 
1566         }
1567         
1568         ast_mutex_unlock(&s->lock);
1569         return 1;
1570 }
1571
1572 static void transmit_speaker_mode(struct skinnysession *s, int mode)
1573 {
1574         struct skinny_req *req;
1575
1576         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
1577                 return;
1578
1579         req->data.setspeaker.mode = htolel(mode);
1580         transmit_response(s, req);
1581 }
1582 /*
1583 static void transmit_microphone_mode(struct skinnysession *s, int mode)
1584 {
1585         struct skinny_req *req;
1586
1587         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
1588                 return;
1589
1590         req->data.setmicrophone.mode = htolel(mode);
1591         transmit_response(s, req);
1592 }
1593 */
1594 static void transmit_callstate(struct skinnysession *s, int instance, int state, unsigned callid)
1595 {
1596         struct skinny_req *req;
1597
1598         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
1599                 return;
1600
1601         if (state == SKINNY_ONHOOK) {
1602                 transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
1603         }
1604         req->data.callstate.callState = htolel(state);
1605         req->data.callstate.lineInstance = htolel(instance);
1606         req->data.callstate.callReference = htolel(callid);
1607         transmit_response(s, req);
1608         if (state == SKINNY_OFFHOOK) {
1609                 if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
1610                         return;
1611
1612                 req->data.activatecallplane.lineInstance = htolel(instance);
1613                 transmit_response(s, req);
1614         } else if (state == SKINNY_ONHOOK) {
1615                 if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
1616                         return;
1617
1618                 req->data.activatecallplane.lineInstance = htolel(instance);
1619                 transmit_response(s, req);
1620
1621                 if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
1622                         return;
1623
1624                 req->data.closereceivechannel.conferenceId = 0;
1625                 req->data.closereceivechannel.partyId = htolel(callid);
1626                 transmit_response(s, req);
1627
1628                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
1629                         return;
1630
1631                 req->data.stopmedia.conferenceId = 0;
1632                 req->data.stopmedia.passThruPartyId = htolel(callid);
1633                 transmit_response(s, req);
1634         }
1635 }
1636
1637 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)
1638 {
1639         struct skinny_req *req;
1640
1641         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
1642                 return;
1643
1644         if (skinnydebug)
1645                         ast_verbose("Setting Callinfo to %s(%s) from %s(%s) on %s(%d)\n", fromname, fromnum, toname, tonum, s->device->name, instance);
1646
1647         if (fromname) {
1648                 ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
1649         }
1650         if (fromnum) {
1651                 ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
1652         }
1653         if (toname) {
1654                 ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
1655         }
1656         if (tonum) {
1657                 ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
1658         }
1659         req->data.callinfo.instance = htolel(instance);
1660         req->data.callinfo.reference = htolel(callid);
1661         req->data.callinfo.type = htolel(calltype);
1662         transmit_response(s, req);
1663 }
1664
1665 static void transmit_connect(struct skinnysession *s, struct skinny_subchannel *sub)
1666 {
1667         struct skinny_req *req;
1668         struct skinny_line *l = sub->parent;
1669         struct ast_format_list fmt;
1670
1671         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
1672                 return;
1673
1674         fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
1675
1676         req->data.openreceivechannel.conferenceId = htolel(0);
1677         req->data.openreceivechannel.partyId = htolel(sub->callid);
1678         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
1679         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(fmt.bits));
1680         req->data.openreceivechannel.echo = htolel(0);
1681         req->data.openreceivechannel.bitrate = htolel(0);
1682         transmit_response(s, req);
1683 }
1684
1685 static void transmit_tone(struct skinnysession *s, int tone)
1686 {
1687         struct skinny_req *req;
1688
1689         if (tone == SKINNY_NOTONE) {
1690                 /* This is bad, mmm'kay? */
1691                 return;
1692         }
1693
1694         if (tone > 0) {
1695                 if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
1696                         return;
1697         } else {
1698                 if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
1699                         return;
1700         }
1701
1702         if (tone > 0) {
1703                 req->data.starttone.tone = htolel(tone);
1704         }
1705         transmit_response(s, req);
1706 }
1707
1708 static void transmit_selectsoftkeys(struct skinnysession *s, int instance, int callid, int softkey)
1709 {
1710         struct skinny_req *req;
1711
1712         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
1713                 return;
1714
1715         req->data.selectsoftkey.instance = htolel(instance);
1716         req->data.selectsoftkey.reference = htolel(callid);
1717         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
1718         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
1719         transmit_response(s, req);
1720 }
1721
1722 static void transmit_lamp_indication(struct skinnysession *s, int stimulus, int instance, int indication)
1723 {
1724         struct skinny_req *req;
1725
1726         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
1727                 return;
1728
1729         req->data.setlamp.stimulus = htolel(stimulus);
1730         req->data.setlamp.stimulusInstance = htolel(instance);
1731         req->data.setlamp.deviceStimulus = htolel(indication);
1732         transmit_response(s, req);
1733 }
1734
1735 static void transmit_ringer_mode(struct skinnysession *s, int mode)
1736 {
1737         struct skinny_req *req;
1738
1739         if (skinnydebug)
1740                 ast_verbose("Setting ringer mode to '%d'.\n", mode);
1741
1742         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
1743                 return;
1744
1745         req->data.setringer.ringerMode = htolel(mode);
1746         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
1747            Note: The phone will always show as ringing on the display.
1748
1749            1: phone will audibly ring over and over
1750            2: phone will audibly ring only once
1751            any other value, will NOT cause the phone to audibly ring
1752         */
1753         req->data.setringer.unknown1 = htolel(1);
1754         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
1755            Perhaps a packet capture can shed some light on this. */
1756         req->data.setringer.unknown2 = htolel(1);
1757         transmit_response(s, req);
1758 }
1759
1760 static void transmit_displaymessage(struct skinnysession *s, const char *text)
1761 {
1762         struct skinny_req *req;
1763
1764         if (text == 0) {
1765                 if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
1766                         return;
1767
1768                 if (skinnydebug)
1769                         ast_verbose("Clearing Display\n");
1770         } else {
1771                 if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
1772                         return;
1773
1774                 ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
1775                 if (skinnydebug)
1776                         ast_verbose("Displaying message '%s'\n", req->data.displaytext.text);
1777         }
1778
1779         transmit_response(s, req);
1780 }
1781
1782 static void transmit_displaynotify(struct skinnysession *s, const char *text, int t)
1783 {
1784         struct skinny_req *req;
1785
1786         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
1787                 return;
1788
1789         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
1790         req->data.displaynotify.displayTimeout = htolel(t);
1791
1792         if (skinnydebug)
1793                 ast_verbose("Displaying notify '%s'\n", text);
1794
1795         transmit_response(s, req);
1796 }
1797
1798 static void transmit_displaypromptstatus(struct skinnysession *s, const char *text, int t, int instance, int callid)
1799 {
1800         struct skinny_req *req;
1801
1802         if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
1803                 return;
1804
1805         ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
1806         req->data.displaypromptstatus.messageTimeout = htolel(t);
1807         req->data.displaypromptstatus.lineInstance = htolel(instance);
1808         req->data.displaypromptstatus.callReference = htolel(callid);
1809
1810         if (skinnydebug)
1811                 ast_verbose("Displaying Prompt Status '%s'\n", text);
1812
1813         transmit_response(s, req);
1814 }
1815
1816 static void transmit_dialednumber(struct skinnysession *s, const char *text, int instance, int callid)
1817 {
1818         struct skinny_req *req;
1819
1820         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
1821                 return;
1822
1823         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
1824         req->data.dialednumber.lineInstance = htolel(instance);
1825         req->data.dialednumber.callReference = htolel(callid);
1826
1827         transmit_response(s, req);
1828 }
1829
1830 static int skinny_extensionstate_cb(char *context, char *exten, int state, void *data)
1831 {
1832         struct skinny_speeddial *sd = data;
1833         struct skinny_device *d = sd->parent;
1834         struct skinnysession *s = d->session;
1835         char hint[AST_MAX_EXTENSION];
1836         int callstate = SKINNY_CALLREMOTEMULTILINE;
1837         int lamp = SKINNY_LAMP_OFF;
1838
1839         switch (state) {
1840         case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
1841         case AST_EXTENSION_REMOVED:     /* Extension is gone */
1842                 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);
1843                 sd->stateid = -1;
1844                 callstate = SKINNY_ONHOOK;
1845                 lamp = SKINNY_LAMP_OFF;
1846                 break;
1847         case AST_EXTENSION_RINGING:
1848         case AST_EXTENSION_UNAVAILABLE:
1849                 callstate = SKINNY_RINGIN;
1850                 lamp = SKINNY_LAMP_BLINK;
1851                 break;
1852         case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
1853         case AST_EXTENSION_INUSE:
1854                 callstate = SKINNY_CALLREMOTEMULTILINE;
1855                 lamp = SKINNY_LAMP_ON;
1856                 break;
1857         case AST_EXTENSION_ONHOLD:
1858                 callstate = SKINNY_HOLD;
1859                 lamp = SKINNY_LAMP_WINK;
1860                 break;
1861         case AST_EXTENSION_NOT_INUSE:
1862         default:
1863                 callstate = SKINNY_ONHOOK;
1864                 lamp = SKINNY_LAMP_OFF;
1865                 break;
1866         }
1867
1868         if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
1869                 /* If they are not registered, we will override notification and show no availability */
1870                 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
1871                         callstate = SKINNY_ONHOOK;
1872                         lamp = SKINNY_LAMP_FLASH;
1873                 }
1874         }
1875
1876         transmit_lamp_indication(s, STIMULUS_LINE, sd->instance, lamp);
1877         transmit_callstate(s, sd->instance, callstate, 0);
1878         sd->laststate = state;
1879
1880         return 0;
1881 }
1882
1883 static int has_voicemail(struct skinny_line *l)
1884 {
1885         return ast_app_has_voicemail(l->mailbox, NULL);
1886 }
1887
1888 static void do_housekeeping(struct skinnysession *s)
1889 {
1890         int new;
1891         int old;
1892         int device_lamp = 0;
1893         struct skinny_device *d = s->device;
1894         struct skinny_line *l;
1895
1896         /* Update time on device */
1897         handle_time_date_req_message(NULL, s);
1898
1899         /* Set MWI on individual lines */
1900         for (l = d->lines; l; l = l->next) {
1901                 if (has_voicemail(l)) {
1902                         if (skinnydebug)
1903                                 ast_verbose("Checking for voicemail Skinny %s@%s\n", l->name, d->name);
1904                         ast_app_inboxcount(l->mailbox, &new, &old);
1905                         if (skinnydebug)
1906                                 ast_verbose("Skinny %s@%s has voicemail!\n", l->name, d->name);
1907                         transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
1908                         device_lamp++;
1909                 } else {
1910                         transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
1911                 }
1912         }
1913         /* If at least one line has VM, turn the device level lamp on */
1914         if (device_lamp)
1915                 transmit_lamp_indication(s, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_ON);
1916         else
1917                 transmit_lamp_indication(s, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
1918 }
1919
1920 /* I do not believe skinny can deal with video.
1921    Anyone know differently? */
1922 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
1923 static enum ast_rtp_get_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
1924 {
1925         struct skinny_subchannel *sub = NULL;
1926
1927         if (!(sub = c->tech_pvt) || !(sub->vrtp))
1928                 return AST_RTP_GET_FAILED;
1929
1930         *rtp = sub->vrtp;
1931
1932         return AST_RTP_TRY_NATIVE;
1933 }
1934
1935 static enum ast_rtp_get_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
1936 {
1937         struct skinny_subchannel *sub = NULL;
1938
1939         if (!(sub = c->tech_pvt) || !(sub->rtp))
1940                 return AST_RTP_GET_FAILED;
1941
1942         *rtp = sub->rtp;
1943
1944         return AST_RTP_TRY_NATIVE;
1945 }
1946
1947 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)
1948 {
1949         struct skinny_subchannel *sub;
1950         sub = c->tech_pvt;
1951         if (sub) {
1952                 /* transmit_modify_with_sdp(sub, rtp); @@FIXME@@ if needed */
1953                 return 0;
1954         }
1955         return -1;
1956 }
1957
1958 static struct ast_rtp_protocol skinny_rtp = {
1959         .type = "Skinny",
1960         .get_rtp_info = skinny_get_rtp_peer,
1961         .get_vrtp_info = skinny_get_vrtp_peer,
1962         .set_rtp_peer = skinny_set_rtp_peer,
1963 };
1964
1965 static int skinny_do_debug(int fd, int argc, char *argv[])
1966 {
1967         if (argc != 3) {
1968                 return RESULT_SHOWUSAGE;
1969         }
1970         skinnydebug = 1;
1971         ast_cli(fd, "Skinny Debugging Enabled\n");
1972         return RESULT_SUCCESS;
1973 }
1974
1975 static int skinny_no_debug(int fd, int argc, char *argv[])
1976 {
1977         if (argc != 4) {
1978                 return RESULT_SHOWUSAGE;
1979         }
1980         skinnydebug = 0;
1981         ast_cli(fd, "Skinny Debugging Disabled\n");
1982         return RESULT_SUCCESS;
1983 }
1984
1985 static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
1986 {
1987         struct skinny_device *d;
1988
1989         char *result = NULL;
1990         int wordlen = strlen(word);
1991         int which = 0;
1992
1993         if (pos == 2) {
1994                 for (d = devices; d && !result; d = d->next) {
1995                         if (!strncasecmp(word, d->id, wordlen) && ++which > state)
1996                                 result = ast_strdup(d->id);
1997                 }
1998         }
1999
2000         return result;
2001 }
2002
2003 static int skinny_reset_device(int fd, int argc, char *argv[])
2004 {
2005         struct skinny_device *d;
2006         struct skinny_req *req;
2007
2008         if (argc < 3 || argc > 4) {
2009                 return RESULT_SHOWUSAGE;
2010         }
2011         ast_mutex_lock(&devicelock);
2012
2013         for (d = devices; d; d = d->next) {
2014                 int fullrestart = 0;
2015                 if (!strcasecmp(argv[2], d->id) || !strcasecmp(argv[2], "all")) {
2016                         if (!(d->session))
2017                                 continue;
2018
2019                         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
2020                                 continue;
2021
2022                         if (argc == 4 && !strcasecmp(argv[3], "restart"))
2023                                 fullrestart = 1;
2024
2025                         if (fullrestart)
2026                                 req->data.reset.resetType = 2;
2027                         else
2028                                 req->data.reset.resetType = 1;
2029
2030                         if (option_verbose > 2)
2031                                 ast_verbose(VERBOSE_PREFIX_3 "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
2032                         transmit_response(d->session, req);
2033                 }
2034         }
2035         ast_mutex_unlock(&devicelock);
2036         return RESULT_SUCCESS;
2037 }
2038
2039 static char *device2str(int type)
2040 {
2041         char *tmp;
2042
2043         switch (type) {
2044         case SKINNY_DEVICE_NONE:
2045                 return "No Device";
2046         case SKINNY_DEVICE_30SPPLUS:
2047                 return "30SP Plus";
2048         case SKINNY_DEVICE_12SPPLUS:
2049                 return "12SP Plus";
2050         case SKINNY_DEVICE_12SP:
2051                 return "12SP";
2052         case SKINNY_DEVICE_12:
2053                 return "12";
2054         case SKINNY_DEVICE_30VIP:
2055                 return "30VIP";
2056         case SKINNY_DEVICE_7910:
2057                 return "7910";
2058         case SKINNY_DEVICE_7960:
2059                 return "7960";
2060         case SKINNY_DEVICE_7940:
2061                 return "7940";
2062         case SKINNY_DEVICE_7935:
2063                 return "7935";
2064         case SKINNY_DEVICE_ATA186:
2065                 return "ATA186";
2066         case SKINNY_DEVICE_7941:
2067                 return "7941";
2068         case SKINNY_DEVICE_7971:
2069                 return "7971";
2070         case SKINNY_DEVICE_7985:
2071                 return "7985";
2072         case SKINNY_DEVICE_7911:
2073                 return "7911";
2074         case SKINNY_DEVICE_7961GE:
2075                 return "7961GE";
2076         case SKINNY_DEVICE_7941GE:
2077                 return "7941GE";
2078         case SKINNY_DEVICE_7921:
2079                 return "7921";
2080         case SKINNY_DEVICE_7905:
2081                 return "7905";
2082         case SKINNY_DEVICE_7920:
2083                 return "7920";
2084         case SKINNY_DEVICE_7970:
2085                 return "7970";
2086         case SKINNY_DEVICE_7912:
2087                 return "7912";
2088         case SKINNY_DEVICE_7902:
2089                 return "7902";
2090         case SKINNY_DEVICE_CIPC:
2091                 return "IP Communicator";
2092         case SKINNY_DEVICE_7961:
2093                 return "7961";
2094         case SKINNY_DEVICE_7936:
2095                 return "7936";
2096         case SKINNY_DEVICE_SCCPGATEWAY_AN:
2097                 return "SCCPGATEWAY_AN";
2098         case SKINNY_DEVICE_SCCPGATEWAY_BRI:
2099                 return "SCCPGATEWAY_BRI";
2100         case SKINNY_DEVICE_UNKNOWN:
2101                 return "Unknown";
2102         default:
2103                 if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
2104                         return "Unknown";
2105                 snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
2106                 return tmp;
2107         }
2108 }
2109
2110 static int skinny_show_devices(int fd, int argc, char *argv[])
2111 {
2112         struct skinny_device *d;
2113         struct skinny_line *l;
2114         int numlines = 0;
2115
2116         if (argc != 3) {
2117                 return RESULT_SHOWUSAGE;
2118         }
2119         ast_mutex_lock(&devicelock);
2120
2121         ast_cli(fd, "Name                 DeviceId         IP              Type            R NL\n");
2122         ast_cli(fd, "-------------------- ---------------- --------------- --------------- - --\n");
2123         for (d = devices; d; d = d->next) {
2124                 numlines = 0;
2125                 for (l = d->lines; l; l = l->next) {
2126                         numlines++;
2127                 }
2128
2129                 ast_cli(fd, "%-20s %-16s %-15s %-15s %c %2d\n",
2130                                 d->name,
2131                                 d->id,
2132                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
2133                                 device2str(d->type),
2134                                 d->registered?'Y':'N',
2135                                 numlines);
2136         }
2137         ast_mutex_unlock(&devicelock);
2138         return RESULT_SUCCESS;
2139 }
2140
2141 static int skinny_show_lines(int fd, int argc, char *argv[])
2142 {
2143         struct skinny_device *d;
2144         struct skinny_line *l;
2145
2146         if (argc != 3) {
2147                 return RESULT_SHOWUSAGE;
2148         }
2149         ast_mutex_lock(&devicelock);
2150
2151         ast_cli(fd, "Device Name          Instance Name                 Label               \n");
2152         ast_cli(fd, "-------------------- -------- -------------------- --------------------\n");
2153         for (d = devices; d; d = d->next) {
2154                 for (l = d->lines; l; l = l->next) {
2155                         ast_cli(fd, "%-20s %8d %-20s %-20s\n",
2156                                 d->name,
2157                                 l->instance,
2158                                 l->name,
2159                                 l->label);
2160                 }
2161         }
2162
2163         ast_mutex_unlock(&devicelock);
2164         return RESULT_SUCCESS;
2165 }
2166
2167 static const char show_devices_usage[] =
2168 "Usage: skinny show devices\n"
2169 "       Lists all devices known to the Skinny subsystem.\n";
2170
2171 static const char show_lines_usage[] =
2172 "Usage: skinny show lines\n"
2173 "       Lists all lines known to the Skinny subsystem.\n";
2174
2175 static const char debug_usage[] =
2176 "Usage: skinny set debug\n"
2177 "       Enables dumping of Skinny packets for debugging purposes\n";
2178
2179 static const char no_debug_usage[] =
2180 "Usage: skinny set debug off\n"
2181 "       Disables dumping of Skinny packets for debugging purposes\n";
2182
2183 static const char reset_usage[] =
2184 "Usage: skinny reset <DeviceId|all> [restart]\n"
2185 "       Causes a Skinny device to reset itself, optionally with a full restart\n";
2186
2187 static struct ast_cli_entry cli_skinny[] = {
2188         { { "skinny", "show", "devices", NULL },
2189         skinny_show_devices, "List defined Skinny devices",
2190         show_devices_usage },
2191
2192         { { "skinny", "show", "lines", NULL },
2193         skinny_show_lines, "List defined Skinny lines per device",
2194         show_lines_usage },
2195
2196         { { "skinny", "set", "debug", NULL },
2197         skinny_do_debug, "Enable Skinny debugging",
2198         debug_usage },
2199
2200         { { "skinny", "set", "debug", "off", NULL },
2201         skinny_no_debug, "Disable Skinny debugging",
2202         no_debug_usage },
2203
2204         { { "skinny", "reset", NULL },
2205         skinny_reset_device, "Reset Skinny device(s)",
2206         reset_usage, complete_skinny_reset },
2207 };
2208
2209 #if 0
2210 static struct skinny_paging_device *build_paging_device(const char *cat, struct ast_variable *v)
2211 {
2212         return NULL;
2213 }
2214 #endif
2215
2216 static struct skinny_device *build_device(const char *cat, struct ast_variable *v)
2217 {
2218         struct skinny_device *d;
2219         struct skinny_line *l;
2220         struct skinny_speeddial *sd;
2221         struct skinny_addon *a;
2222         char device_vmexten[AST_MAX_EXTENSION];
2223         int lineInstance = 1;
2224         int speeddialInstance = 1;
2225         int y = 0;
2226
2227         if (!(d = ast_calloc(1, sizeof(*d)))) {
2228                 return NULL;
2229         } else {
2230                 ast_copy_string(d->name, cat, sizeof(d->name));
2231                 d->lastlineinstance = 1;
2232                 d->capability = default_capability;
2233                 d->prefs = default_prefs;
2234                 if (!ast_strlen_zero(vmexten))
2235                         ast_copy_string(device_vmexten, vmexten, sizeof(device_vmexten));
2236                 while(v) {
2237                         if (!strcasecmp(v->name, "host")) {
2238                                 if (ast_get_ip(&d->addr, v->value)) {
2239                                         ast_free(d);
2240                                         return NULL;
2241                                 }
2242                         } else if (!strcasecmp(v->name, "port")) {
2243                                 d->addr.sin_port = htons(atoi(v->value));
2244                         } else if (!strcasecmp(v->name, "device")) {
2245                                 ast_copy_string(d->id, v->value, sizeof(d->id));
2246                         } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
2247                                 d->ha = ast_append_ha(v->name, v->value, d->ha, NULL);
2248                         } else if (!strcasecmp(v->name, "vmexten")) {
2249                                 ast_copy_string(device_vmexten, v->value, sizeof(device_vmexten));
2250                         } else if (!strcasecmp(v->name, "context")) {
2251                                 ast_copy_string(context, v->value, sizeof(context));
2252                         } else if (!strcasecmp(v->name, "regexten")) {
2253                                 ast_copy_string(regexten, v->value, sizeof(regexten));
2254                         } else if (!strcasecmp(v->name, "allow")) {
2255                                 ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 1);
2256                         } else if (!strcasecmp(v->name, "disallow")) {
2257                                 ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 0);
2258                         } else if (!strcasecmp(v->name, "version")) {
2259                                 ast_copy_string(d->version_id, v->value, sizeof(d->version_id));
2260                         } else if (!strcasecmp(v->name, "nat")) {
2261                                 nat = ast_true(v->value);
2262                         } else if (!strcasecmp(v->name, "callerid")) {
2263                                 if (!strcasecmp(v->value, "asreceived")) {
2264                                         cid_num[0] = '\0';
2265                                         cid_name[0] = '\0';
2266                                 } else {
2267                                         ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
2268                                 }
2269                         } else if (!strcasecmp(v->name, "language")) {
2270                                 ast_copy_string(language, v->value, sizeof(language));
2271                         } else if (!strcasecmp(v->name, "accountcode")) {
2272                                 ast_copy_string(accountcode, v->value, sizeof(accountcode));
2273                         } else if (!strcasecmp(v->name, "amaflags")) {
2274                                 y = ast_cdr_amaflags2int(v->value);
2275                                 if (y < 0) {
2276                                         ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
2277                                 } else {
2278                                         amaflags = y;
2279                                 }
2280                         } else if (!strcasecmp(v->name, "mohinterpret") || !strcasecmp(v->name, "musiconhold")) {
2281                                 ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
2282                         } else if (!strcasecmp(v->name, "mohsuggest")) {
2283                                 ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
2284                         } else if (!strcasecmp(v->name, "callgroup")) {
2285                                 cur_callergroup = ast_get_group(v->value);
2286                         } else if (!strcasecmp(v->name, "pickupgroup")) {
2287                                 cur_pickupgroup = ast_get_group(v->value);
2288                         } else if (!strcasecmp(v->name, "immediate")) {
2289                                 immediate = ast_true(v->value);
2290                         } else if (!strcasecmp(v->name, "cancallforward")) {
2291                                 cancallforward = ast_true(v->value);
2292                         } else if (!strcasecmp(v->name, "mailbox")) {
2293                                 ast_copy_string(mailbox, v->value, sizeof(mailbox));
2294                         } else if (!strcasecmp(v->name, "callreturn")) {
2295                                 callreturn = ast_true(v->value);
2296                         } else if (!strcasecmp(v->name, "callwaiting")) {
2297                                 callwaiting = ast_true(v->value);
2298                         } else if (!strcasecmp(v->name, "transfer")) {
2299                                 transfer = ast_true(v->value);
2300                         } else if (!strcasecmp(v->name, "threewaycalling")) {
2301                                 threewaycalling = ast_true(v->value);
2302                         } else if (!strcasecmp(v->name, "mwiblink")) {
2303                                 mwiblink = ast_true(v->value);
2304                         } else if (!strcasecmp(v->name, "linelabel")) {
2305                                 ast_copy_string(linelabel, v->value, sizeof(linelabel));
2306                         } else if (!strcasecmp(v->name, "speeddial")) {
2307                                 if (!(sd = ast_calloc(1, sizeof(*sd)))) {
2308                                         return NULL;
2309                                 } else {
2310                                         char *stringp, *exten, *context, *label;
2311                                         stringp = v->value;
2312                                         exten = strsep(&stringp, ",");
2313                                         if ((context = strchr(exten, '@'))) {
2314                                                 *context++ = '\0';
2315                                         }
2316                                         label = stringp;
2317                                         ast_mutex_init(&sd->lock);
2318                                         ast_copy_string(sd->exten, exten, sizeof(sd->exten));
2319                                         if (!ast_strlen_zero(context)) {
2320                                                 sd->isHint = 1;
2321                                                 sd->instance = lineInstance++;
2322                                                 ast_copy_string(sd->context, context, sizeof(sd->context));
2323                                         } else {
2324                                                 sd->isHint = 0;
2325                                                 sd->instance = speeddialInstance++;
2326                                                 sd->context[0] = '\0';
2327                                         }
2328                                         ast_copy_string(sd->label, S_OR(label, exten), sizeof(sd->label));
2329
2330                                         sd->parent = d;
2331
2332                                         sd->next = d->speeddials;
2333                                         d->speeddials = sd;
2334                                 }
2335                         } else if (!strcasecmp(v->name, "addon")) {
2336                                 if (!(a = ast_calloc(1, sizeof(*a)))) {
2337                                         return NULL;
2338                                 } else {
2339                                         ast_mutex_init(&a->lock);
2340                                         ast_copy_string(a->type, v->value, sizeof(a->type));
2341
2342                                         a->next = d->addons;
2343                                         d->addons = a;
2344                                 }
2345                         } else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
2346                                 if (!(l = ast_calloc(1, sizeof(*l)))) {
2347                                         return NULL;
2348                                 } else {
2349                                         ast_mutex_init(&l->lock);
2350                                         ast_copy_string(l->name, v->value, sizeof(l->name));
2351
2352                                         /* XXX Should we check for uniqueness?? XXX */
2353                                         ast_copy_string(l->context, context, sizeof(l->context));
2354                                         ast_copy_string(l->cid_num, cid_num, sizeof(l->cid_num));
2355                                         ast_copy_string(l->cid_name, cid_name, sizeof(l->cid_name));
2356                                         ast_copy_string(l->label, linelabel, sizeof(l->label));
2357                                         ast_copy_string(l->language, language, sizeof(l->language));
2358                                         ast_copy_string(l->mohinterpret, mohinterpret, sizeof(l->mohinterpret));
2359                                         ast_copy_string(l->mohsuggest, mohsuggest, sizeof(l->mohsuggest));
2360                                         ast_copy_string(l->regexten, regexten, sizeof(l->regexten));
2361                                         ast_copy_string(l->mailbox, mailbox, sizeof(l->mailbox));
2362                                         if (!ast_strlen_zero(mailbox)) {
2363                                                 if (option_verbose > 2)
2364                                                         ast_verbose(VERBOSE_PREFIX_3 "Setting mailbox '%s' on %s@%s\n", mailbox, d->name, l->name);
2365                                         }
2366                                         if (!ast_strlen_zero(device_vmexten))
2367                                                 ast_copy_string(l->vmexten, device_vmexten, sizeof(vmexten));
2368                                         l->msgstate = -1;
2369                                         l->capability = d->capability;
2370                                         l->prefs = d->prefs;
2371                                         l->parent = d;
2372                                         if (!strcasecmp(v->name, "trunk")) {
2373                                                 l->type = TYPE_TRUNK;
2374                                         } else {
2375                                                 l->type = TYPE_LINE;
2376                                         }
2377                                         l->immediate = immediate;
2378                                         l->callgroup = cur_callergroup;
2379                                         l->pickupgroup = cur_pickupgroup;
2380                                         l->callreturn = callreturn;
2381                                         l->cancallforward = cancallforward;
2382                                         l->callwaiting = callwaiting;
2383                                         l->transfer = transfer;
2384                                         l->threewaycalling = threewaycalling;
2385                                         l->mwiblink = mwiblink;
2386                                         l->onhooktime = time(NULL);
2387                                         l->instance = lineInstance++;
2388                                         /* ASSUME we're onhook at this point */
2389                                         l->hookstate = SKINNY_ONHOOK;
2390                                         l->nat = nat;
2391
2392                                         l->next = d->lines;
2393                                         d->lines = l;
2394                                 }
2395                         } else {
2396                                 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
2397                         }
2398                         v = v->next;
2399                 }
2400
2401                 if (!d->lines) {
2402                         ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
2403                         return NULL;
2404                 }
2405                 if (/*d->addr.sin_addr.s_addr && */!ntohs(d->addr.sin_port)) {
2406                         d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
2407                 }
2408 #if 0
2409                 /* I don't think we need this anymore at all, since d->ourip is set in skinny_register now */
2410                 if (d->addr.sin_addr.s_addr) {
2411                         /* XXX See note above, in 'host' option. */
2412                         if (ast_ouraddrfor(&d->addr.sin_addr, &d->ourip)) {
2413                                 d->ourip = __ourip;
2414                         }
2415                 } else {
2416                         d->ourip = __ourip;
2417                 }
2418 #endif
2419         }
2420         return d;
2421 }
2422
2423 static void start_rtp(struct skinny_subchannel *sub)
2424 {
2425         struct skinny_line *l = sub->parent;
2426         struct skinny_device *d = l->parent;
2427         int hasvideo = 0;
2428
2429         ast_mutex_lock(&sub->lock);
2430         /* Allocate the RTP */
2431         sub->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2432         if (hasvideo)
2433                 sub->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2434         
2435         if (sub->rtp && sub->owner) {
2436                 sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
2437                 sub->owner->fds[1] = ast_rtcp_fd(sub->rtp);
2438         }
2439         if (hasvideo && sub->vrtp && sub->owner) {
2440                 sub->owner->fds[2] = ast_rtp_fd(sub->vrtp);
2441                 sub->owner->fds[3] = ast_rtcp_fd(sub->vrtp);
2442         }
2443         if (sub->rtp) {
2444                 ast_rtp_setnat(sub->rtp, l->nat);
2445         }
2446         if (sub->vrtp) {
2447                 ast_rtp_setnat(sub->vrtp, l->nat);
2448         }
2449         /* Set Frame packetization */
2450         if (sub->rtp)
2451                 ast_rtp_codec_setpref(sub->rtp, &l->prefs);
2452
2453         /* Create the RTP connection */
2454         transmit_connect(d->session, sub);
2455         ast_mutex_unlock(&sub->lock);
2456 }
2457
2458 static void *skinny_newcall(void *data)
2459 {
2460         struct ast_channel *c = data;
2461         struct skinny_subchannel *sub = c->tech_pvt;
2462         struct skinny_line *l = sub->parent;
2463         struct skinny_device *d = l->parent;
2464         struct skinnysession *s = d->session;
2465         int res = 0;
2466
2467         ast_copy_string(l->lastnumberdialed, c->exten, sizeof(l->lastnumberdialed));
2468         ast_set_callerid(c,
2469                 l->hidecallerid ? "" : l->cid_num,
2470                 l->hidecallerid ? "" : l->cid_name,
2471                 c->cid.cid_ani ? NULL : l->cid_num);
2472         ast_setstate(c, AST_STATE_RING);
2473         res = ast_pbx_run(c);
2474         if (res) {
2475                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2476                 transmit_tone(s, SKINNY_REORDER);
2477         }
2478         return NULL;
2479 }
2480
2481 static void *skinny_ss(void *data)
2482 {
2483         struct ast_channel *c = data;
2484         struct skinny_subchannel *sub = c->tech_pvt;
2485         struct skinny_line *l = sub->parent;
2486         struct skinny_device *d = l->parent;
2487         struct skinnysession *s = d->session;
2488         int len = 0;
2489         int timeout = firstdigittimeout;
2490         int res = 0;
2491         int getforward=0;
2492         int loop_pause = 100;
2493
2494         if (option_verbose > 2)
2495                 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s@%s'\n", l->name, d->name);
2496
2497         len = strlen(d->exten);
2498
2499         while (len < AST_MAX_EXTENSION-1) {
2500                 res = 1;  /* Assume that we will get a digit */
2501                 while (strlen(d->exten) == len){
2502                         ast_safe_sleep(c, loop_pause);
2503                         timeout -= loop_pause;
2504                         if ( (timeout -= loop_pause) <= 0){
2505                                  res = 0;
2506                                  break;
2507                         }
2508                 res = 1;
2509                 }
2510
2511                 timeout = 0;
2512                 len = strlen(d->exten);
2513
2514                 if (!ast_ignore_pattern(c->context, d->exten)) {
2515                         transmit_tone(s, SKINNY_SILENCE);
2516                 }
2517                 if (ast_exists_extension(c, c->context, d->exten, 1, l->cid_num)) {
2518                         if (!res || !ast_matchmore_extension(c, c->context, d->exten, 1, l->cid_num)) {
2519                                 if (getforward) {
2520                                         /* Record this as the forwarding extension */
2521                                         ast_copy_string(l->call_forward, d->exten, sizeof(l->call_forward));
2522                                         if (option_verbose > 2)
2523                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n",
2524                                                         l->call_forward, c->name);
2525                                         transmit_tone(s, SKINNY_DIALTONE);
2526                                         if (res) {
2527                                                 break;
2528                                         }
2529                                         ast_safe_sleep(c, 500);
2530                                         ast_indicate(c, -1);
2531                                         ast_safe_sleep(c, 1000);
2532                                         memset(d->exten, 0, sizeof(d->exten));
2533                                         transmit_tone(s, SKINNY_DIALTONE);
2534                                         len = 0;
2535                                         getforward = 0;
2536                                 } else {
2537                                         ast_copy_string(c->exten, d->exten, sizeof(c->exten));
2538                                         ast_copy_string(l->lastnumberdialed, d->exten, sizeof(l->lastnumberdialed));
2539                                         memset(d->exten, 0, sizeof(d->exten));
2540                                         skinny_newcall(c);
2541                                         return NULL;
2542                                 }
2543                         } else {
2544                                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
2545                                    so just set the timeout to matchdigittimeout and wait some more */
2546                                 timeout = matchdigittimeout;
2547                         }
2548                 } else if (res == 0) {
2549                         ast_debug(1, "Not enough digits (%s) (and no ambiguous match)...\n", d->exten);
2550                         memset(d->exten, 0, sizeof(d->exten));
2551                         transmit_tone(s, SKINNY_REORDER);
2552                         if (sub->owner && sub->owner->_state != AST_STATE_UP) {
2553                                 ast_indicate(c, -1);
2554                                 ast_hangup(c);
2555                         }
2556                         return NULL;
2557                 } else if (!ast_canmatch_extension(c, c->context, d->exten, 1, c->cid.cid_num) &&
2558                            ((d->exten[0] != '*') || (!ast_strlen_zero(d->exten) > 2))) {
2559                         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);
2560                         memset(d->exten, 0, sizeof(d->exten));
2561                         transmit_tone(s, SKINNY_REORDER);
2562                         /* hang out for 3 seconds to let congestion play */
2563                         ast_safe_sleep(c, 3000);
2564                         break;
2565                 }
2566                 if (!timeout) {
2567                         timeout = gendigittimeout;
2568                 }
2569                 if (len && !ast_ignore_pattern(c->context, d->exten)) {
2570                         ast_indicate(c, -1);
2571                 }
2572         }
2573         if (c)
2574                 ast_hangup(c);
2575         memset(d->exten, 0, sizeof(d->exten));
2576         return NULL;
2577 }
2578
2579
2580
2581 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
2582 {
2583         int res = 0;
2584         int tone = 0;
2585         struct skinny_subchannel *sub = ast->tech_pvt;
2586         struct skinny_line *l = sub->parent;
2587         struct skinny_device *d = l->parent;
2588         struct skinnysession *s = d->session;
2589
2590         if (!d->registered) {
2591                 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
2592                 return -1;
2593         }
2594
2595         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2596                 ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
2597                 return -1;
2598         }
2599
2600         if (skinnydebug)
2601                 ast_verbose(VERBOSE_PREFIX_3 "skinny_call(%s)\n", ast->name);
2602
2603         if (l->dnd) {
2604                 ast_queue_control(ast, AST_CONTROL_BUSY);
2605                 return -1;
2606         }
2607
2608         switch (l->hookstate) {
2609         case SKINNY_OFFHOOK:
2610                 tone = SKINNY_CALLWAITTONE;
2611                 break;
2612         case SKINNY_ONHOOK:
2613                 tone = SKINNY_ALERT;
2614                 break;
2615         default:
2616                 ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
2617                 break;
2618         }
2619
2620         transmit_callstate(s, l->instance, SKINNY_RINGIN, sub->callid);
2621         transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGIN);
2622         transmit_displaypromptstatus(s, "Ring-In", 0, l->instance, sub->callid);
2623         transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
2624         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
2625         transmit_ringer_mode(s, SKINNY_RING_INSIDE);
2626
2627         ast_setstate(ast, AST_STATE_RINGING);
2628         ast_queue_control(ast, AST_CONTROL_RINGING);
2629         sub->outgoing = 1;
2630         return res;
2631 }
2632
2633 static int skinny_hangup(struct ast_channel *ast)
2634 {
2635         struct skinny_subchannel *sub = ast->tech_pvt;
2636         struct skinny_line *l;
2637         struct skinny_device *d;
2638         struct skinnysession *s;
2639
2640         if (!sub) {
2641                 ast_debug(1, "Asked to hangup channel not connected\n");
2642                 return 0;
2643         }
2644         l = sub->parent;
2645         d = l->parent;
2646         s = d->session;
2647         if (skinnydebug)
2648                 ast_verbose("skinny_hangup(%s) on %s@%s\n", ast->name, l->name, d->name);
2649
2650         if (d->registered) {
2651                 if ((l->type = TYPE_LINE) && (l->hookstate == SKINNY_OFFHOOK)) {
2652                         l->hookstate = SKINNY_ONHOOK;
2653                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2654                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2655                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
2656                 } else if ((l->type = TYPE_LINE) && (l->hookstate == SKINNY_ONHOOK)) {
2657                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2658                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
2659                         transmit_ringer_mode(s, SKINNY_RING_OFF);
2660                         transmit_tone(s, SKINNY_SILENCE);
2661                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2662                         do_housekeeping(s);
2663                 }
2664         }
2665         ast_mutex_lock(&sub->lock);
2666         sub->owner = NULL;
2667         ast->tech_pvt = NULL;
2668         sub->alreadygone = 0;
2669         sub->outgoing = 0;
2670         if (sub->rtp) {
2671                 ast_rtp_destroy(sub->rtp);
2672                 sub->rtp = NULL;
2673         }
2674         ast_mutex_unlock(&sub->lock);
2675         return 0;
2676 }
2677
2678 static int skinny_answer(struct ast_channel *ast)
2679 {
2680         int res = 0;
2681         struct skinny_subchannel *sub = ast->tech_pvt;
2682         struct skinny_line *l = sub->parent;
2683         struct skinny_device *d = l->parent;
2684         struct skinnysession *s = d->session;
2685
2686         sub->cxmode = SKINNY_CX_SENDRECV;
2687         if (!sub->rtp) {
2688                 start_rtp(sub);
2689         }
2690         if (skinnydebug)
2691                 ast_verbose("skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, d->name, sub->callid);
2692         if (ast->_state != AST_STATE_UP) {
2693                 ast_setstate(ast, AST_STATE_UP);
2694         }
2695
2696         transmit_tone(s, SKINNY_SILENCE);
2697         /* order matters here...
2698            for some reason, transmit_callinfo must be before transmit_callstate,
2699            or you won't get keypad messages in some situations. */
2700         transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2);
2701         transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
2702         transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
2703         transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
2704         return res;
2705 }
2706
2707 /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
2708 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
2709 {
2710         struct ast_channel *ast = sub->owner;
2711         struct ast_frame *f;
2712
2713         if (!sub->rtp) {
2714                 /* We have no RTP allocated for this channel */
2715                 return &ast_null_frame;
2716         }
2717
2718         switch(ast->fdno) {
2719         case 0:
2720                 f = ast_rtp_read(sub->rtp);     /* RTP Audio */
2721                 break;
2722         case 1:
2723                 f = ast_rtcp_read(sub->rtp);    /* RTCP Control Channel */
2724                 break;
2725         case 2:
2726                 f = ast_rtp_read(sub->vrtp);    /* RTP Video */
2727                 break;
2728         case 3:
2729                 f = ast_rtcp_read(sub->vrtp);   /* RTCP Control Channel for video */
2730                 break;
2731 #if 0
2732         case 5:
2733                 /* Not yet supported */
2734                 f = ast_udptl_read(sub->udptl); /* UDPTL for T.38 */
2735                 break;
2736 #endif
2737         default:
2738                 f = &ast_null_frame;
2739         }
2740
2741         if (ast) {
2742                 /* We already hold the channel lock */
2743                 if (f->frametype == AST_FRAME_VOICE) {
2744                         if (f->subclass != ast->nativeformats) {
2745                                 ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
2746                                 ast->nativeformats = f->subclass;
2747                                 ast_set_read_format(ast, ast->readformat);
2748                                 ast_set_write_format(ast, ast->writeformat);
2749                         }
2750                 }
2751         }
2752         return f;
2753 }
2754
2755 static struct ast_frame *skinny_read(struct ast_channel *ast)
2756 {
2757         struct ast_frame *fr;
2758         struct skinny_subchannel *sub = ast->tech_pvt;
2759         ast_mutex_lock(&sub->lock);
2760         fr = skinny_rtp_read(sub);
2761         ast_mutex_unlock(&sub->lock);
2762         return fr;
2763 }
2764
2765 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
2766 {
2767         struct skinny_subchannel *sub = ast->tech_pvt;
2768         int res = 0;
2769         if (frame->frametype != AST_FRAME_VOICE) {
2770                 if (frame->frametype == AST_FRAME_IMAGE) {
2771                         return 0;
2772                 } else {
2773                         ast_log(LOG_WARNING, "Can't send %d type frames with skinny_write\n", frame->frametype);
2774                         return 0;
2775                 }
2776         } else {
2777                 if (!(frame->subclass & ast->nativeformats)) {
2778                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2779                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2780                         return -1;
2781                 }
2782         }
2783         if (sub) {
2784                 ast_mutex_lock(&sub->lock);
2785                 if (sub->rtp) {
2786                         res = ast_rtp_write(sub->rtp, frame);
2787                 }
2788                 ast_mutex_unlock(&sub->lock);
2789         }
2790         return res;
2791 }
2792
2793 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2794 {
2795         struct skinny_subchannel *sub = newchan->tech_pvt;
2796         ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", oldchan->name, newchan->name);
2797         if (sub->owner != oldchan) {
2798                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
2799                 return -1;
2800         }
2801         sub->owner = newchan;
2802         return 0;
2803 }
2804
2805 static int skinny_senddigit_begin(struct ast_channel *ast, char digit)
2806 {
2807         return -1; /* Start inband indications */
2808 }
2809
2810 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
2811 {
2812 #if 0
2813         struct skinny_subchannel *sub = ast->tech_pvt;
2814         struct skinny_line *l = sub->parent;
2815         struct skinny_device *d = l->parent;
2816         int tmp;
2817         /* not right */
2818         sprintf(tmp, "%d", digit);
2819         transmit_tone(d->session, digit);
2820 #endif
2821         return -1; /* Stop inband indications */
2822 }
2823
2824 static char *control2str(int ind) {
2825         char *tmp;
2826
2827         switch (ind) {
2828         case AST_CONTROL_HANGUP:
2829                 return "Other end has hungup";
2830         case AST_CONTROL_RING:
2831                 return "Local ring";
2832         case AST_CONTROL_RINGING:
2833                 return "Remote end is ringing";
2834         case AST_CONTROL_ANSWER:
2835                 return "Remote end has answered";
2836         case AST_CONTROL_BUSY:
2837                 return "Remote end is busy";
2838         case AST_CONTROL_TAKEOFFHOOK:
2839                 return "Make it go off hook";
2840         case AST_CONTROL_OFFHOOK:
2841                 return "Line is off hook";
2842         case AST_CONTROL_CONGESTION:
2843                 return "Congestion (circuits busy)";
2844         case AST_CONTROL_FLASH:
2845                 return "Flash hook";
2846         case AST_CONTROL_WINK:
2847                 return "Wink";
2848         case AST_CONTROL_OPTION:
2849                 return "Set a low-level option";
2850         case AST_CONTROL_RADIO_KEY:
2851                 return "Key Radio";
2852         case AST_CONTROL_RADIO_UNKEY:
2853                 return "Un-Key Radio";
2854         case AST_CONTROL_PROGRESS:
2855                 return "Remote end is making Progress";
2856         case AST_CONTROL_PROCEEDING:
2857                 return "Remote end is proceeding";
2858         case AST_CONTROL_HOLD:
2859                 return "Hold";
2860         case AST_CONTROL_UNHOLD:
2861                 return "Unhold";
2862         case -1:
2863                 return "Stop tone";
2864         default:
2865                 if (!(tmp = ast_threadstorage_get(&control2str_threadbuf, CONTROL2STR_BUFSIZE)))
2866                         return "Unknown";
2867                 snprintf(tmp, CONTROL2STR_BUFSIZE, "UNKNOWN-%d", ind);
2868                 return tmp;
2869         }
2870 }
2871
2872
2873 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
2874 {
2875         struct skinny_subchannel *sub = ast->tech_pvt;
2876         struct skinny_line *l = sub->parent;
2877         struct skinny_device *d = l->parent;
2878         struct skinnysession *s = d->session;
2879
2880         if (skinnydebug)
2881                 ast_verbose(VERBOSE_PREFIX_3 "Asked to indicate '%s' condition on channel %s\n", control2str(ind), ast->name);
2882         switch(ind) {
2883         case AST_CONTROL_RINGING:
2884                 if (ast->_state != AST_STATE_UP) {
2885                         if (!sub->progress) {
2886                                 transmit_tone(s, SKINNY_ALERT);
2887                                 transmit_callstate(s, l->instance, SKINNY_RINGOUT, sub->callid);
2888                                 transmit_dialednumber(s, ast->exten, l->instance, sub->callid);
2889                                 transmit_displaypromptstatus(s, "Ring Out", 0, l->instance, sub->callid);
2890                                 transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2891                                 sub->ringing = 1;
2892                                 break;
2893                         }
2894                 }
2895                 return -1;
2896         case AST_CONTROL_BUSY:
2897                 if (ast->_state != AST_STATE_UP) {
2898                         transmit_tone(s, SKINNY_BUSYTONE);
2899                         transmit_callstate(s, l->instance, SKINNY_BUSY, sub->callid);
2900                         sub->alreadygone = 1;
2901                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2902                         break;
2903                 }
2904                 return -1;
2905         case AST_CONTROL_CONGESTION:
2906                 if (ast->_state != AST_STATE_UP) {
2907                         transmit_tone(s, SKINNY_REORDER);
2908                         transmit_callstate(s, l->instance, SKINNY_CONGESTION, sub->callid);
2909                         sub->alreadygone = 1;
2910                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2911                         break;
2912                 }
2913                 return -1;
2914         case AST_CONTROL_PROGRESS:
2915                 if ((ast->_state != AST_STATE_UP) && !sub->progress && !sub->outgoing) {
2916                         transmit_tone(s, SKINNY_ALERT);
2917                         transmit_callstate(s, l->instance, SKINNY_PROGRESS, sub->callid);
2918                         transmit_displaypromptstatus(s, "Call Progress", 0, l->instance, sub->callid);
2919                         transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2920                         sub->progress = 1;
2921                         break;
2922                 }
2923                 return -1;
2924         case -1:
2925                 transmit_tone(s, SKINNY_SILENCE);
2926                 break;
2927         case AST_CONTROL_HOLD:
2928                 ast_moh_start(ast, data, l->mohinterpret);
2929                 break;
2930         case AST_CONTROL_UNHOLD:
2931                 ast_moh_stop(ast);
2932                 break;
2933         case AST_CONTROL_PROCEEDING:
2934                 break;
2935         default:
2936                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
2937                 return -1;
2938         }
2939         return 0;
2940 }
2941
2942 static struct ast_channel *skinny_new(struct skinny_line *l, int state)
2943 {
2944         struct ast_channel *tmp;
2945         struct skinny_subchannel *sub;
2946         struct skinny_device *d = l->parent;
2947         int fmt;
2948
2949         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);
2950         if (!tmp) {
2951                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2952                 return NULL;
2953         } else {
2954                 sub = ast_calloc(1, sizeof(*sub));
2955                 if (!sub) {
2956                         ast_log(LOG_WARNING, "Unable to allocate Skinny subchannel\n");
2957                         return NULL;
2958                 } else {
2959                         ast_mutex_init(&sub->lock);
2960
2961                         sub->owner = tmp;
2962                         sub->callid = callnums++;
2963                         d->lastlineinstance = l->instance;
2964                         d->lastcallreference = sub->callid;
2965                         sub->cxmode = SKINNY_CX_INACTIVE;
2966                         sub->nat = l->nat;
2967                         sub->parent = l;
2968                         sub->onhold = 0;
2969
2970                         sub->next = l->sub;
2971                         l->sub = sub;
2972                 }
2973                 tmp->tech = &skinny_tech;
2974                 tmp->tech_pvt = sub;
2975                 tmp->nativeformats = l->capability;
2976                 if (!tmp->nativeformats)
2977                         tmp->nativeformats = default_capability;
2978                 fmt = ast_best_codec(tmp->nativeformats);
2979                 if (skinnydebug)
2980                         ast_verbose("skinny_new: tmp->nativeformats=%d fmt=%d\n", tmp->nativeformats, fmt);
2981                 if (sub->rtp) {
2982                         tmp->fds[0] = ast_rtp_fd(sub->rtp);
2983                 }
2984                 if (state == AST_STATE_RING) {
2985                         tmp->rings = 1;
2986                 }
2987                 tmp->writeformat = fmt;
2988                 tmp->rawwriteformat = fmt;
2989                 tmp->readformat = fmt;
2990                 tmp->rawreadformat = fmt;
2991                 if (!ast_strlen_zero(l->language))
2992                         ast_string_field_set(tmp, language, l->language);
2993                 if (!ast_strlen_zero(l->accountcode))
2994                         ast_string_field_set(tmp, accountcode, l->accountcode);
2995                 if (l->amaflags)
2996                         tmp->amaflags = l->amaflags;
2997
2998                 ast_module_ref(ast_module_info->self);
2999                 tmp->callgroup = l->callgroup;
3000                 tmp->pickupgroup = l->pickupgroup;
3001                 ast_string_field_set(tmp, call_forward, l->call_forward);
3002                 ast_copy_string(tmp->context, l->context, sizeof(tmp->context));
3003                 ast_copy_string(tmp->exten, l->exten, sizeof(tmp->exten));
3004
3005                 /* Don't use ast_set_callerid() here because it will
3006                  * generate a needless NewCallerID event */
3007                 tmp->cid.cid_num = ast_strdup(l->cid_num);
3008                 tmp->cid.cid_ani = ast_strdup(l->cid_num);
3009                 tmp->cid.cid_name = ast_strdup(l->cid_name);
3010
3011                 tmp->priority = 1;
3012                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3013
3014                 if (sub->rtp)
3015                         ast_jb_configure(tmp, &global_jbconf);
3016
3017                 if (state != AST_STATE_DOWN) {
3018                         if (ast_pbx_start(tmp)) {
3019                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3020                                 ast_hangup(tmp);
3021                                 tmp = NULL;
3022                         }
3023                 }
3024         }
3025         return tmp;
3026 }
3027
3028 static int skinny_hold(struct skinny_subchannel *sub)
3029 {
3030         struct skinny_line *l = sub->parent;
3031         struct skinny_device *d = l->parent;
3032         struct skinnysession *s = d->session;
3033         struct skinny_req *req;
3034
3035         /* Channel needs to be put on hold */
3036         if (skinnydebug)
3037                 ast_verbose("Putting on Hold(%d)\n", l->instance);
3038
3039         ast_queue_control_data(sub->owner, AST_CONTROL_HOLD,
3040                 S_OR(l->mohsuggest, NULL),
3041                 !ast_strlen_zero(l->mohsuggest) ? strlen(l->mohsuggest) + 1 : 0);
3042
3043         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
3044                 return 0;
3045
3046         req->data.activatecallplane.lineInstance = htolel(l->instance);
3047         transmit_response(s, req);
3048
3049         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
3050                 return 0;
3051
3052         req->data.closereceivechannel.conferenceId = htolel(0);
3053         req->data.closereceivechannel.partyId = htolel(sub->callid);
3054         transmit_response(s, req);
3055
3056         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
3057                 return 0;
3058
3059         req->data.stopmedia.conferenceId = htolel(0);
3060         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
3061         transmit_response(s, req);
3062
3063         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_WINK);
3064         sub->onhold = 1;
3065         return 1;
3066 }
3067
3068 static int skinny_unhold(struct skinny_subchannel *sub)
3069 {
3070         struct skinny_line *l = sub->parent;
3071         struct skinny_device *d = l->parent;
3072         struct skinnysession *s = d->session;
3073         struct skinny_req *req;
3074
3075         /* Channel is on hold, so we will unhold */
3076         if (skinnydebug)
3077                 ast_verbose("Taking off Hold(%d)\n", l->instance);
3078
3079         ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
3080
3081         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
3082                 return 0;
3083
3084         req->data.activatecallplane.lineInstance = htolel(l->instance);
3085         transmit_response(s, req);
3086
3087         transmit_connect(s, sub);
3088         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3089         sub->onhold = 0;
3090         return 1;
3091 }
3092
3093 static int handle_keep_alive_message(struct skinny_req *req, struct skinnysession *s)
3094 {
3095         if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
3096                 return -1;
3097
3098         transmit_response(s, req);
3099         do_housekeeping(s);
3100         return 1;
3101 }
3102
3103 static int handle_register_message(struct skinny_req *req, struct skinnysession *s)
3104 {
3105         char name[16];
3106         int res;
3107
3108         memcpy(&name, req->data.reg.name, sizeof(name));
3109
3110         res = skinny_register(req, s);
3111         if (!res) {
3112                 ast_log(LOG_ERROR, "Rejecting Device %s: Device not found\n", name);
3113                 if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
3114                         return -1;
3115
3116                 snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
3117                 transmit_response(s, req);
3118                 return 0;
3119         }
3120         if (option_verbose > 2)
3121                 ast_verbose(VERBOSE_PREFIX_3 "Device '%s' successfully registered\n", name);
3122
3123         if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
3124                 return -1;
3125
3126         req->data.regack.res[0] = '0';
3127         req->data.regack.res[1] = '\0';
3128         req->data.regack.keepAlive = htolel(keep_alive);
3129         ast_copy_string(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate));
3130         req->data.regack.res2[0] = '0';
3131         req->data.regack.res2[1] = '\0';
3132         req->data.regack.secondaryKeepAlive = htolel(keep_alive);
3133         transmit_response(s, req);
3134         if (skinnydebug)
3135                 ast_verbose("Requesting capabilities\n");
3136
3137         if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
3138                 return -1;
3139
3140         transmit_response(s, req);
3141
3142         return res;
3143 }
3144
3145 static int handle_ip_port_message(struct skinny_req *req, struct skinnysession *s)
3146 {
3147         /* no response necessary */
3148         return 1;
3149 }
3150
3151 static int handle_keypad_button_message(struct skinny_req *req, struct skinnysession *s)
3152 {
3153         struct skinny_subchannel *sub = NULL;
3154         struct skinny_line *l;
3155         struct skinny_device *d = s->device;
3156         struct ast_frame f = { 0, };
3157         char dgt;
3158         int digit;
3159         int lineInstance;
3160         int callReference;
3161
3162         digit = letohl(req->data.keypad.button);
3163         lineInstance = letohl(req->data.keypad.lineInstance);
3164         callReference = letohl(req->data.keypad.callReference);
3165
3166         if (digit == 14) {
3167                 dgt = '*';
3168         } else if (digit == 15) {
3169                 dgt = '#';
3170         } else if (digit >= 0 && digit <= 9) {
3171                 dgt = '0' + digit;
3172         } else {
3173                 /* digit=10-13 (A,B,C,D ?), or
3174                  * digit is bad value
3175                  *
3176                  * probably should not end up here, but set
3177                  * value for backward compatibility, and log
3178                  * a warning.
3179                  */
3180                 dgt = '0' + digit;
3181                 ast_log(LOG_WARNING, "Unsupported digit %d\n", digit);
3182         }
3183
3184         f.subclass = dgt;
3185
3186         f.src = "skinny";
3187
3188         if (lineInstance && callReference)
3189                 sub = find_subchannel_by_instance_reference(d, lineInstance, callReference);
3190         else
3191                 sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
3192
3193         if (!sub)
3194                 return 0;
3195
3196         l = sub->parent;
3197         if (sub->owner) {
3198                 if (sub->owner->_state == 0) {
3199                         f.frametype = AST_FRAME_DTMF_BEGIN;
3200                         ast_queue_frame(sub->owner, &f);
3201                 }
3202                 /* XXX MUST queue this frame to all lines in threeway call if threeway call is active */
3203                 f.frametype = AST_FRAME_DTMF_END;
3204                 ast_queue_frame(sub->owner, &f);
3205                 /* XXX This seriously needs to be fixed */
3206                 if (sub->next && sub->next->owner) {
3207                         if (sub->owner->_state == 0) {
3208                                 f.frametype = AST_FRAME_DTMF_BEGIN;
3209                                 ast_queue_frame(sub->next->owner, &f);
3210                         }
3211                         f.frametype = AST_FRAME_DTMF_END;
3212                         ast_queue_frame(sub->next->owner, &f);
3213                 }
3214         } else {
3215                 if (skinnydebug)
3216                         ast_verbose("No owner: %s\n", l->name);
3217         }
3218         return 1;
3219 }
3220
3221 static int handle_stimulus_message(struct skinny_req *req, struct skinnysession *s)
3222 {
3223         struct skinny_device *d = s->device;
3224         struct skinny_line *l;
3225         struct skinny_subchannel *sub;
3226         /*struct skinny_speeddial *sd;*/
3227         struct ast_channel *c;
3228         pthread_t t;
3229         int event;
3230         int instance;
3231         int unknown1;
3232         /*int res = 0;*/
3233
3234         event = letohl(req->data.stimulus.stimulus);
3235         instance = letohl(req->data.stimulus.stimulusInstance);
3236         unknown1 = letohl(req->data.stimulus.unknown1); /* No clue.. */
3237         if (skinnydebug)
3238                 ast_verbose("unknown1 in handle_stimulus_message is '%d'\n", unknown1);
3239
3240         sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
3241
3242         if (!sub) {
3243                 l = find_line_by_instance(d, d->lastlineinstance);
3244                 if (!l) {
3245                         return 0;
3246                 }
3247         } else {
3248                 l = sub->parent;
3249         }
3250
3251         switch(event) {
3252         case STIMULUS_REDIAL:
3253                 if (skinnydebug)
3254                         ast_verbose("Received Stimulus: Redial(%d)\n", instance);
3255
3256                 c = skinny_new(l, AST_STATE_DOWN);
3257                 if (!c) {
3258                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
3259                 } else {
3260                         sub = c->tech_pvt;
3261                         l = sub->parent;
3262                         if (l->hookstate == SKINNY_ONHOOK) {
3263                                 l->hookstate = SKINNY_OFFHOOK;
3264                                 transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3265                         }
3266                         if (skinnydebug)
3267                                 ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
3268                         transmit_displaymessage(s, NULL); /* clear display */
3269                         transmit_tone(s, SKINNY_DIALTONE);
3270
3271                         if (ast_strlen_zero(l->lastnumberdialed)) {
3272                                 ast_log(LOG_WARNING, "Attempted redial, but no previously dialed number found.\n");
3273                                 return 0;
3274                         }
3275                         if (!ast_ignore_pattern(c->context, l->lastnumberdialed)) {
3276                                 transmit_tone(s, SKINNY_SILENCE);
3277                         }
3278                         ast_copy_string(c->exten, l->lastnumberdialed, sizeof(c->exten));
3279                         if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
3280                                 ast_log(LOG_WARNING, "Unable to create new call thread: %s\n", strerror(errno));
3281                                 ast_hangup(c);
3282                         }
3283                 }
3284                 break;
3285         case STIMULUS_SPEEDDIAL:
3286             {
3287                 struct skinny_speeddial *sd;
3288
3289                 if (skinnydebug)
3290                         ast_verbose("Received Stimulus: SpeedDial(%d)\n", instance);
3291                 if (!(sd = find_speeddial_by_instance(d, instance, 0))) {
3292                         return 0;
3293                 }
3294
3295                 if (!sub || !sub->owner)
3296                         c = skinny_new(l, AST_STATE_DOWN);
3297                 else
3298                         c = sub->owner;
3299
3300                 if (!c) {
3301                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
3302                 } else {
3303                         sub = c->tech_pvt;
3304                         l = sub->parent;
3305                         if (l->hookstate == SKINNY_ONHOOK) {
3306                                 l->hookstate = SKINNY_OFFHOOK;
3307                                 transmit_speaker_mode(s, SKINNY_SPEAKERON);
3308                                 transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3309                         }
3310                         if (skinnydebug)
3311                                 ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
3312                         transmit_displaymessage(s, NULL); /* clear display */
3313                         transmit_tone(s, SKINNY_DIALTONE);
3314
3315                         if (!ast_ignore_pattern(c->context, sd->exten)) {
3316                                 transmit_tone(s, SKINNY_SILENCE);
3317                         }
3318                         if (ast_exists_extension(c, c->context, sd->exten, 1, l->cid_num)) {
3319                                 ast_copy_string(c->exten, sd->exten, sizeof(c->exten));
3320                                 ast_copy_string(l->lastnumberdialed, sd->exten, sizeof(l->lastnumberdialed));
3321
3322                                 if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
3323                                         ast_log(LOG_WARNING, "Unable to create new call thread: %s\n", strerror(errno));
3324                                         ast_hangup(c);
3325                                 }
3326                                 break;
3327                         }
3328                 }
3329             }
3330                 break;
3331         case STIMULUS_HOLD:
3332                 if (skinnydebug)
3333                         ast_verbose("Received Stimulus: Hold(%d)\n", instance);
3334
3335                 if (!sub)
3336                         break;
3337
3338                 if (sub->onhold) {
3339                         skinny_unhold(sub);
3340                 } else {
3341                         skinny_hold(sub);
3342                 }
3343                 break;
3344         case STIMULUS_TRANSFER:
3345                 if (skinnydebug)
3346                         ast_verbose("Received Stimulus: Transfer(%d)\n", instance);
3347                 transmit_tone(s, SKINNY_DIALTONE);
3348                 /* XXX figure out how to transfer */
3349                 break;
3350         case STIMULUS_CONFERENCE:
3351                 if (skinnydebug)
3352                         ast_verbose("Received Stimulus: Conference(%d)\n", instance);
3353                 transmit_tone(s, SKINNY_DIALTONE);
3354                 /* XXX determine the best way to pull off a conference.  Meetme? */
3355                 break;
3356         case STIMULUS_VOICEMAIL:
3357                 if (skinnydebug)
3358                         ast_verbose("Received Stimulus: Voicemail(%d)\n", instance);
3359
3360                 if (!sub || !sub->owner) {
3361                         c = skinny_new(l, AST_STATE_DOWN);
3362                 } else {
3363                         c = sub->owner;
3364                 }
3365                 if (!c) {
3366                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
3367                 } else {
3368                         sub = c->tech_pvt;
3369                         l = sub->parent;
3370
3371                         if (ast_strlen_zero(l->vmexten))  /* Exit the call if no VM pilot */
3372                                 break;
3373
3374                         if (l->hookstate == SKINNY_ONHOOK){
3375                                 l->hookstate = SKINNY_OFFHOOK;
3376                                 transmit_speaker_mode(s, SKINNY_SPEAKERON);
3377                                 transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3378                         }
3379
3380                         if (skinnydebug)
3381                                 ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
3382
3383                         transmit_displaymessage(s, NULL); /* clear display */
3384                         transmit_tone(s, SKINNY_DIALTONE);
3385
3386                         if (!ast_ignore_pattern(c->context, vmexten)) {
3387                                 transmit_tone(s, SKINNY_SILENCE);
3388                         }
3389
3390                         if (ast_exists_extension(c, c->context, l->vmexten, 1, l->cid_num)) {
3391                                 ast_copy_string(c->exten, l->vmexten, sizeof(c->exten));
3392                                 ast_copy_string(l->lastnumberdialed, l->vmexten, sizeof(l->lastnumberdialed));
3393                                 if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
3394                                         ast_log(LOG_WARNING, "Unable to create new call thread: %s\n", strerror(errno));
3395                                         ast_hangup(c);
3396                                 }
3397                                 break;
3398                         }
3399                 }
3400                 break;
3401         case STIMULUS_CALLPARK:
3402                 if (skinnydebug)
3403                         ast_verbose("Received Stimulus: Park Call(%d)\n", instance);
3404                 /* XXX Park the call */
3405                 break;
3406         case STIMULUS_FORWARDALL:
3407                 if (skinnydebug)
3408                         ast_verbose("Received Stimulus: Forward All(%d)\n", instance);
3409                 /* Why is DND under FORWARDALL? */
3410                 /* Because it's the same thing. */
3411
3412                 /* Do not disturb */
3413                 transmit_tone(s, SKINNY_DIALTONE);
3414                 if (l->dnd != 0){
3415                         if (option_verbose > 2)
3416                                 ast_verbose(VERBOSE_PREFIX_3 "Disabling DND on %s@%s\n", l->name, d->name);
3417                         l->dnd = 0;
3418                         transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
3419                         transmit_displaynotify(s, "DnD disabled", 10);
3420                 } else {
3421                         if (option_verbose > 2)
3422                                 ast_verbose(VERBOSE_PREFIX_3 "Enabling DND on %s@%s\n", l->name, d->name);
3423                         l->dnd = 1;
3424                         transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_OFF);
3425                         transmit_displaynotify(s, "DnD enabled", 10);
3426                 }
3427                 break;
3428         case STIMULUS_FORWARDBUSY:
3429                 if (skinnydebug)
3430                         ast_verbose("Received Stimulus: Forward Busy (%d)\n", instance);
3431                 break;
3432         case STIMULUS_FORWARDNOANSWER:
3433                 if (skinnydebug)
3434                         ast_verbose("Received Stimulus: Forward No Answer (%d)\n", instance);
3435                 break;
3436         case STIMULUS_DISPLAY:
3437                 /* Not sure what this is */
3438                 if (skinnydebug)
3439                         ast_verbose("Received Stimulus: Display(%d)\n", instance);
3440                 break;
3441         case STIMULUS_LINE:
3442                 if (skinnydebug)
3443                         ast_verbose("Received Stimulus: Line(%d)\n", instance);
3444
3445                 l = find_line_by_instance(d, instance);
3446
3447                 if (!l) {
3448                         return 0;
3449                 }
3450
3451                 /* turn the speaker on */
3452                 transmit_speaker_mode(s, SKINNY_SPEAKERON);
3453                 transmit_ringer_mode(s, SKINNY_RING_OFF);
3454                 transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3455
3456                 l->hookstate = SKINNY_OFFHOOK;
3457
3458                 ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
3459
3460                 if (sub && sub->outgoing) {
3461                         /* We're answering a ringing call */
3462                         ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
3463                         transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3464                         transmit_tone(s, SKINNY_SILENCE);
3465                         transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
3466                         transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
3467                         transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
3468                         start_rtp(sub);
3469                         ast_setstate(sub->owner, AST_STATE_UP);
3470                 } else {
3471                         if (sub && sub->owner) {
3472                                 ast_debug(1, "Current subchannel [%s] already has owner\n", sub->owner->name);
3473                         } else {
3474                                 c = skinny_new(l, AST_STATE_DOWN);
3475                                 if (c) {
3476                                         sub = c->tech_pvt;
3477                                         transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3478                                         if (skinnydebug)
3479                                                 ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
3480                                         transmit_displaymessage(s, NULL); /* clear display */
3481                                         transmit_tone(s, SKINNY_DIALTONE);
3482                                         transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
3483
3484                                         /* start the switch thread */
3485                                         if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
3486                                                 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
3487                                                 ast_hangup(c);
3488                                         }
3489                                 } else {
3490                                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
3491                                 }
3492                         }
3493                 }
3494                 break;
3495         default:
3496                 if (skinnydebug)
3497                         ast_verbose("RECEIVED UNKNOWN STIMULUS:  %d(%d)\n", event, instance);
3498                 break;
3499         }
3500         ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
3501
3502         return 1;
3503 }
3504
3505 static int handle_offhook_message(struct skinny_req *req, struct skinnysession *s)
3506 {
3507         struct skinny_device *d = s->device;
3508         struct skinny_line *l;
3509         struct skinny_subchannel *sub;
3510         struct ast_channel *c;
3511         pthread_t t;
3512         int unknown1;
3513         int unknown2;
3514
3515         unknown1 = letohl(req->data.offhook.unknown1);
3516         unknown2 = letohl(req->data.offhook.unknown2);
3517
3518         sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
3519
3520         if (!sub) {
3521                 l = find_line_by_instance(d, d->lastlineinstance);
3522                 if (!l) {
3523                         return 0;
3524                 }
3525         } else {
3526                 l = sub->parent;
3527         }
3528
3529         transmit_ringer_mode(s, SKINNY_RING_OFF);
3530         l->hookstate = SKINNY_OFFHOOK;
3531
3532         ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
3533
3534         if (sub && sub->onhold) {
3535                 return 1;
3536         }
3537
3538         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3539
3540         if (sub && sub->outgoing) {
3541                 /* We're answering a ringing call */
3542                 ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
3543                 transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3544                 transmit_tone(s, SKINNY_SILENCE);
3545                 transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
3546                 transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
3547                 start_rtp(sub);
3548                 ast_setstate(sub->owner, AST_STATE_UP);
3549         } else {
3550                 if (sub && sub->owner) {
3551                         ast_debug(1, "Current sub [%s] already has owner\n", sub->owner->name);
3552                 } else {
3553                         c = skinny_new(l, AST_STATE_DOWN);
3554                         if (c) {
3555                                 sub = c->tech_pvt;
3556                                 transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3557                                 if (skinnydebug)
3558                                         ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
3559                                 transmit_displaymessage(s, NULL); /* clear display */
3560                                 transmit_tone(s, SKINNY_DIALTONE);
3561                                 transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
3562
3563                                 /* start the switch thread */
3564                                 if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
3565                                         ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
3566                                         ast_hangup(c);
3567                                 }
3568                         } else {
3569                                 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
3570                         }
3571                 }
3572         }
3573         return 1;
3574 }
3575
3576 static int handle_onhook_message(struct skinny_req *req, struct skinnysession *s)
3577 {
3578         struct skinny_device *d = s->device;
3579         struct skinny_line *l;
3580         struct skinny_subchannel *sub;
3581         int unknown1;
3582         int unknown2;
3583
3584         unknown1 = letohl(req->data.onhook.unknown1);
3585         unknown2 = letohl(req->data.onhook.unknown2);
3586
3587         sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
3588
3589         if (!sub) {
3590                 return 0;
3591         }
3592         l = sub->parent;
3593
3594         if (l->hookstate == SKINNY_ONHOOK) {
3595                 /* Something else already put us back on hook */
3596                 return 0;
3597         }
3598         l->hookstate = SKINNY_ONHOOK;
3599
3600         ast_device_state_changed("Skinny/%s@%s", l->name, d->name);
3601
3602         if (sub->onhold) {
3603                 return 0;
3604         }
3605
3606         sub->cxmode = SKINNY_CX_RECVONLY;
3607         transmit_callstate(s, l->instance, l->hookstate, sub->callid);
3608         if (skinnydebug)
3609                 ast_verbose("Skinny %s@%s went on hook\n", l->name, d->name);
3610         if (l->transfer && (sub->owner && sub->next && sub->next->owner) && ((!sub->outgoing) || (sub->next && !sub->next->outgoing))) {
3611                 /* We're allowed to transfer, we have two active calls and
3612                    we made at least one of the calls.  Let's try and transfer */
3613
3614 #if 0
3615                 if ((res = attempt_transfer(p)) < 0) {
3616                         if (sub->next && sub->next->owner) {
3617                                 sub->next->alreadygone = 1;
3618                                 ast_queue_hangup(sub->next->owner,1);
3619                         }
3620                 } else if (res) {
3621                         ast_log(LOG_WARNING, "Transfer attempt failed\n");
3622                         return 0;
3623                 }
3624 #endif
3625         } else {
3626                 /* Hangup the current call */
3627                 /* If there is another active call, skinny_hangup will ring the phone with the other call */
3628                 if (sub->owner) {
3629                         sub->alreadygone = 1;
3630                         ast_queue_hangup(sub->owner);
3631                 } else {
3632                         ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n",
3633                                 l->name, d->name, sub->callid);
3634                 }
3635         }
3636         if ((l->hookstate == SKINNY_ONHOOK) && (sub->next && !sub->next->rtp)) {
3637                 do_housekeeping(s);
3638         }
3639         return 1;
3640 }
3641
3642 static int handle_capabilities_res_message(struct skinny_req *req, struct skinnysession *s)