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