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