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