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