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