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