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