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