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