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