f5b7dfff3e9269f1fbf0b88c1e80a7c8e1973148
[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 /*! \li \ref chan_skinny.c uses the configuration file \ref skinny.conf
29  * \addtogroup configuration_file
30  */
31
32 /*! \page skinny.conf skinny.conf
33  * \verbinclude skinny.conf.sample
34  */
35
36 /*** MODULEINFO
37         <support_level>extended</support_level>
38  ***/
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <netinet/tcp.h>
47 #include <sys/ioctl.h>
48 #include <net/if.h>
49 #include <fcntl.h>
50 #include <netdb.h>
51 #include <arpa/inet.h>
52 #include <sys/signal.h>
53 #include <signal.h>
54 #include <ctype.h>
55
56 #include "asterisk/lock.h"
57 #include "asterisk/channel.h"
58 #include "asterisk/config.h"
59 #include "asterisk/module.h"
60 #include "asterisk/pbx.h"
61 #include "asterisk/sched.h"
62 #include "asterisk/io.h"
63 #include "asterisk/rtp_engine.h"
64 #include "asterisk/netsock2.h"
65 #include "asterisk/acl.h"
66 #include "asterisk/callerid.h"
67 #include "asterisk/cli.h"
68 #include "asterisk/manager.h"
69 #include "asterisk/say.h"
70 #include "asterisk/cdr.h"
71 #include "asterisk/astdb.h"
72 #include "asterisk/features.h"
73 #include "asterisk/app.h"
74 #include "asterisk/musiconhold.h"
75 #include "asterisk/utils.h"
76 #include "asterisk/dsp.h"
77 #include "asterisk/stringfields.h"
78 #include "asterisk/abstract_jb.h"
79 #include "asterisk/threadstorage.h"
80 #include "asterisk/devicestate.h"
81 #include "asterisk/event.h"
82 #include "asterisk/indications.h"
83 #include "asterisk/linkedlists.h"
84
85 /*** DOCUMENTATION
86         <manager name="SKINNYdevices" language="en_US">
87                 <synopsis>
88                         List SKINNY devices (text format).
89                 </synopsis>
90                 <syntax>
91                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
92                 </syntax>
93                 <description>
94                         <para>Lists Skinny devices in text format with details on current status.
95                         Devicelist will follow as separate events, followed by a final event called
96                         DevicelistComplete.</para>
97                 </description>
98         </manager>
99         <manager name="SKINNYshowdevice" language="en_US">
100                 <synopsis>
101                         Show SKINNY device (text format).
102                 </synopsis>
103                 <syntax>
104                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
105                         <parameter name="Device" required="true">
106                                 <para>The device name you want to check.</para>
107                         </parameter>
108                 </syntax>
109                 <description>
110                         <para>Show one SKINNY device with details on current status.</para>
111                 </description>
112         </manager>
113         <manager name="SKINNYlines" language="en_US">
114                 <synopsis>
115                         List SKINNY lines (text format).
116                 </synopsis>
117                 <syntax>
118                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
119                 </syntax>
120                 <description>
121                         <para>Lists Skinny lines in text format with details on current status.
122                         Linelist will follow as separate events, followed by a final event called
123                         LinelistComplete.</para>
124                 </description>
125         </manager>
126         <manager name="SKINNYshowline" language="en_US">
127                 <synopsis>
128                         Show SKINNY line (text format).
129                 </synopsis>
130                 <syntax>
131                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
132                         <parameter name="Line" required="true">
133                                 <para>The line name you want to check.</para>
134                         </parameter>
135                 </syntax>
136                 <description>
137                         <para>Show one SKINNY line with details on current status.</para>
138                 </description>
139         </manager>
140  ***/
141
142 /* Skinny debugging only available if asterisk configured with --enable-dev-mode */
143 #ifdef AST_DEVMODE
144 static int skinnydebug = 0;
145 char dbgcli_buf[256];
146 char dbgreg_buf[256];
147 char dbgsub_buf[256];
148 #define DEBUG_GENERAL   (1 << 1)
149 #define DEBUG_SUB       (1 << 2)
150 #define DEBUG_PACKET    (1 << 3)
151 #define DEBUG_AUDIO     (1 << 4)
152 #define DEBUG_LOCK      (1 << 5)
153 #define DEBUG_TEMPLATE  (1 << 6)
154 #define DEBUG_THREAD    (1 << 7)
155 #define DEBUG_HINT      (1 << 8)
156 #define SKINNY_DEBUG(type, verb_level, text, ...)                                               \
157         do{                                                                                     \
158                 if (skinnydebug & (type)) {                                                     \
159                         ast_verb(verb_level, "[%d] " text, ast_get_tid(), ##__VA_ARGS__);       \
160                 }                                                                               \
161         }while(0)
162 #else
163 #define SKINNY_DEBUG(type, verb_level, text, ...)
164 #endif
165
166 /*************************************
167  * Skinny/Asterisk Protocol Settings *
168  *************************************/
169 static const char tdesc[] = "Skinny Client Control Protocol (Skinny)";
170 static const char config[] = "skinny.conf";
171
172 static struct ast_format_cap *default_cap;
173 static struct ast_codec_pref default_prefs;
174
175 enum skinny_codecs {
176         SKINNY_CODEC_ALAW = 2,
177         SKINNY_CODEC_ULAW = 4,
178         SKINNY_CODEC_G722 = 6,
179         SKINNY_CODEC_G723_1 = 9,
180         SKINNY_CODEC_G729A = 12,
181         SKINNY_CODEC_G726_32 = 82, /* XXX Which packing order does this translate to? */
182         SKINNY_CODEC_H261 = 100,
183         SKINNY_CODEC_H263 = 101
184 };
185
186 #define DEFAULT_SKINNY_PORT 2000
187 #define DEFAULT_SKINNY_BACKLOG 2
188 #define SKINNY_MAX_PACKET 2000
189 #define DEFAULT_AUTH_TIMEOUT 30
190 #define DEFAULT_AUTH_LIMIT 50
191
192 static struct {
193         unsigned int tos;
194         unsigned int tos_audio;
195         unsigned int tos_video;
196         unsigned int cos;
197         unsigned int cos_audio;
198         unsigned int cos_video;
199 } qos = { 0, 0, 0, 0, 0, 0 };
200
201 static int keep_alive = 120;
202 static int auth_timeout = DEFAULT_AUTH_TIMEOUT;
203 static int auth_limit = DEFAULT_AUTH_LIMIT;
204 static int unauth_sessions = 0;
205 static char immed_dialchar;
206 static char vmexten[AST_MAX_EXTENSION];      /* Voicemail pilot number */
207 static char used_context[AST_MAX_EXTENSION]; /* placeholder to check if context are already used in regcontext */
208 static char regcontext[AST_MAX_CONTEXT];     /* Context for auto-extension */
209 static char date_format[6] = "D-M-Y";
210 static char version_id[16] = "P002F202";
211
212 #if __BYTE_ORDER == __LITTLE_ENDIAN
213 #define letohl(x) (x)
214 #define letohs(x) (x)
215 #define htolel(x) (x)
216 #define htoles(x) (x)
217 #else
218 #if defined(HAVE_BYTESWAP_H)
219 #include <byteswap.h>
220 #define letohl(x) bswap_32(x)
221 #define letohs(x) bswap_16(x)
222 #define htolel(x) bswap_32(x)
223 #define htoles(x) bswap_16(x)
224 #elif defined(HAVE_SYS_ENDIAN_SWAP16)
225 #include <sys/endian.h>
226 #define letohl(x) __swap32(x)
227 #define letohs(x) __swap16(x)
228 #define htolel(x) __swap32(x)
229 #define htoles(x) __swap16(x)
230 #elif defined(HAVE_SYS_ENDIAN_BSWAP16)
231 #include <sys/endian.h>
232 #define letohl(x) bswap32(x)
233 #define letohs(x) bswap16(x)
234 #define htolel(x) bswap32(x)
235 #define htoles(x) bswap16(x)
236 #else
237 #define __bswap_16(x) \
238         ((((x) & 0xff00) >> 8) | \
239          (((x) & 0x00ff) << 8))
240 #define __bswap_32(x) \
241         ((((x) & 0xff000000) >> 24) | \
242          (((x) & 0x00ff0000) >>  8) | \
243          (((x) & 0x0000ff00) <<  8) | \
244          (((x) & 0x000000ff) << 24))
245 #define letohl(x) __bswap_32(x)
246 #define letohs(x) __bswap_16(x)
247 #define htolel(x) __bswap_32(x)
248 #define htoles(x) __bswap_16(x)
249 #endif
250 #endif
251
252 /*! Global jitterbuffer configuration - by default, jb is disabled
253  *  \note Values shown here match the defaults shown in skinny.conf.sample */
254 static struct ast_jb_conf default_jbconf =
255 {
256         .flags = 0,
257         .max_size = 200,
258         .resync_threshold = 1000,
259         .impl = "fixed",
260         .target_extra = 40,
261 };
262 static struct ast_jb_conf global_jbconf;
263
264 #ifdef AST_DEVMODE
265 AST_THREADSTORAGE(message2str_threadbuf);
266 #define MESSAGE2STR_BUFSIZE   35
267 #endif
268
269 AST_THREADSTORAGE(device2str_threadbuf);
270 #define DEVICE2STR_BUFSIZE   15
271
272 AST_THREADSTORAGE(control2str_threadbuf);
273 #define CONTROL2STR_BUFSIZE   100
274
275 AST_THREADSTORAGE(substate2str_threadbuf);
276 #define SUBSTATE2STR_BUFSIZE   15
277
278 AST_THREADSTORAGE(callstate2str_threadbuf);
279 #define CALLSTATE2STR_BUFSIZE   15
280
281 /*********************
282  * Protocol Messages *
283  *********************/
284 /* message types */
285 #define KEEP_ALIVE_MESSAGE 0x0000
286 /* no additional struct */
287
288 #define REGISTER_MESSAGE 0x0001
289 struct register_message {
290         char name[16];
291         uint32_t userId;
292         uint32_t instance;
293         uint32_t ip;
294         uint32_t type;
295         uint32_t maxStreams;
296         uint32_t space;
297         uint8_t protocolVersion;
298         /*! \brief space2 is used for newer version of skinny */
299         char space2[3];
300 };
301
302 #define IP_PORT_MESSAGE 0x0002
303
304 #define KEYPAD_BUTTON_MESSAGE 0x0003
305 struct keypad_button_message {
306         uint32_t button;
307         uint32_t lineInstance;
308         uint32_t callReference;
309 };
310
311
312 #define ENBLOC_CALL_MESSAGE 0x0004
313 struct enbloc_call_message {
314         char calledParty[24];
315 };
316
317 #define STIMULUS_MESSAGE 0x0005
318 struct stimulus_message {
319         uint32_t stimulus;
320         uint32_t stimulusInstance;
321         uint32_t callreference;
322 };
323
324 #define OFFHOOK_MESSAGE 0x0006
325 struct offhook_message {
326         uint32_t instance;
327         uint32_t reference;
328 };
329
330 #define ONHOOK_MESSAGE 0x0007
331 struct onhook_message {
332         uint32_t instance;
333         uint32_t reference;
334 };
335
336 #define CAPABILITIES_RES_MESSAGE 0x0010
337 struct station_capabilities {
338         uint32_t codec; /* skinny codec, not ast codec */
339         uint32_t frames;
340         union {
341                 char res[8];
342                 uint32_t rate;
343         } payloads;
344 };
345
346 #define SKINNY_MAX_CAPABILITIES 18
347
348 struct capabilities_res_message {
349         uint32_t count;
350         struct station_capabilities caps[SKINNY_MAX_CAPABILITIES];
351 };
352
353 #define SPEED_DIAL_STAT_REQ_MESSAGE 0x000A
354 struct speed_dial_stat_req_message {
355         uint32_t speedDialNumber;
356 };
357
358 #define LINE_STATE_REQ_MESSAGE 0x000B
359 struct line_state_req_message {
360         uint32_t lineNumber;
361 };
362
363 #define TIME_DATE_REQ_MESSAGE 0x000D
364 #define BUTTON_TEMPLATE_REQ_MESSAGE 0x000E
365 #define VERSION_REQ_MESSAGE 0x000F
366 #define SERVER_REQUEST_MESSAGE 0x0012
367
368 #define ALARM_MESSAGE 0x0020
369 struct alarm_message {
370         uint32_t alarmSeverity;
371         char displayMessage[80];
372         uint32_t alarmParam1;
373         uint32_t alarmParam2;
374 };
375
376 #define OPEN_RECEIVE_CHANNEL_ACK_MESSAGE 0x0022
377 struct open_receive_channel_ack_message_ip4 {
378         uint32_t status;
379         uint32_t ipAddr;
380         uint32_t port;
381         uint32_t callReference;
382 };
383 struct open_receive_channel_ack_message_ip6 {
384         uint32_t status;
385         uint32_t space;
386         char ipAddr[16];
387         uint32_t port;
388         uint32_t callReference;
389 };
390
391 #define SOFT_KEY_SET_REQ_MESSAGE 0x0025
392
393 #define SOFT_KEY_EVENT_MESSAGE 0x0026
394 struct soft_key_event_message {
395         uint32_t softKeyEvent;
396         uint32_t instance;
397         uint32_t callreference;
398 };
399
400 #define UNREGISTER_MESSAGE 0x0027
401 #define SOFT_KEY_TEMPLATE_REQ_MESSAGE 0x0028
402 #define HEADSET_STATUS_MESSAGE 0x002B
403 #define REGISTER_AVAILABLE_LINES_MESSAGE 0x002D
404
405 #define SERVICEURL_STATREQ_MESSAGE 0x0033
406 struct serviceurl_statreq_message {
407         uint32_t instance;
408 };
409
410 #define REGISTER_ACK_MESSAGE 0x0081
411 struct register_ack_message {
412         uint32_t keepAlive;
413         char dateTemplate[6];
414         char res[2];
415         uint32_t secondaryKeepAlive;
416         char res2[4];
417 };
418
419 #define START_TONE_MESSAGE 0x0082
420 struct start_tone_message {
421         uint32_t tone;
422         uint32_t space;
423         uint32_t instance;
424         uint32_t reference;
425 };
426
427 #define STOP_TONE_MESSAGE 0x0083
428 struct stop_tone_message {
429         uint32_t instance;
430         uint32_t reference;
431         uint32_t space;
432 };
433
434 #define SET_RINGER_MESSAGE 0x0085
435 struct set_ringer_message {
436         uint32_t ringerMode;
437         uint32_t unknown1; /* See notes in transmit_ringer_mode */
438         uint32_t unknown2;
439         uint32_t space[2];
440 };
441
442 #define SET_LAMP_MESSAGE 0x0086
443 struct set_lamp_message {
444         uint32_t stimulus;
445         uint32_t stimulusInstance;
446         uint32_t deviceStimulus;
447 };
448
449 #define SET_SPEAKER_MESSAGE 0x0088
450 struct set_speaker_message {
451         uint32_t mode;
452 };
453
454 /* XXX When do we need to use this? */
455 #define SET_MICROPHONE_MESSAGE 0x0089
456 struct set_microphone_message {
457         uint32_t mode;
458 };
459
460 #define START_MEDIA_TRANSMISSION_MESSAGE 0x008A
461 struct media_qualifier {
462         uint32_t precedence;
463         uint32_t vad;
464         uint32_t packets;
465         uint32_t bitRate;
466 };
467
468 struct start_media_transmission_message_ip4 {
469         uint32_t conferenceId;
470         uint32_t passThruPartyId;
471         uint32_t remoteIp;
472         uint32_t remotePort;
473         uint32_t packetSize;
474         uint32_t payloadType;
475         struct media_qualifier qualifier;
476         uint32_t space[19];
477 };
478
479 struct start_media_transmission_message_ip6 {
480         uint32_t conferenceId;
481         uint32_t passThruPartyId;
482         uint32_t space;
483         char remoteIp[16];
484         uint32_t remotePort;
485         uint32_t packetSize;
486         uint32_t payloadType;
487         struct media_qualifier qualifier;
488         /*! \brief space2 is used for newer version of skinny */
489         uint32_t space2[19];
490 };
491
492 #define STOP_MEDIA_TRANSMISSION_MESSAGE 0x008B
493 struct stop_media_transmission_message {
494         uint32_t conferenceId;
495         uint32_t passThruPartyId;
496         uint32_t space[3];
497 };
498
499 #define CALL_INFO_MESSAGE 0x008F
500 struct call_info_message {
501         char callingPartyName[40];
502         char callingParty[24];
503         char calledPartyName[40];
504         char calledParty[24];
505         uint32_t instance;
506         uint32_t reference;
507         uint32_t type;
508         char originalCalledPartyName[40];
509         char originalCalledParty[24];
510         char lastRedirectingPartyName[40];
511         char lastRedirectingParty[24];
512         uint32_t originalCalledPartyRedirectReason;
513         uint32_t lastRedirectingReason;
514         char callingPartyVoiceMailbox[24];
515         char calledPartyVoiceMailbox[24];
516         char originalCalledPartyVoiceMailbox[24];
517         char lastRedirectingVoiceMailbox[24];
518         uint32_t space[3];
519 };
520
521 #define FORWARD_STAT_MESSAGE 0x0090
522 struct forward_stat_message {
523         uint32_t activeforward;
524         uint32_t lineNumber;
525         uint32_t fwdall;
526         char fwdallnum[24];
527         uint32_t fwdbusy;
528         char fwdbusynum[24];
529         uint32_t fwdnoanswer;
530         char fwdnoanswernum[24];
531 };
532
533 #define SPEED_DIAL_STAT_RES_MESSAGE 0x0091
534 struct speed_dial_stat_res_message {
535         uint32_t speedDialNumber;
536         char speedDialDirNumber[24];
537         char speedDialDisplayName[40];
538 };
539
540 #define LINE_STAT_RES_MESSAGE 0x0092
541 struct line_stat_res_message {
542         uint32_t lineNumber;
543         char lineDirNumber[24];
544         char lineDisplayName[24];
545         uint32_t space[15];
546 };
547
548 #define DEFINETIMEDATE_MESSAGE 0x0094
549 struct definetimedate_message {
550         uint32_t year; /* since 1900 */
551         uint32_t month;
552         uint32_t dayofweek; /* monday = 1 */
553         uint32_t day;
554         uint32_t hour;
555         uint32_t minute;
556         uint32_t seconds;
557         uint32_t milliseconds;
558         uint32_t timestamp;
559 };
560
561 #define BUTTON_TEMPLATE_RES_MESSAGE 0x0097
562 struct button_definition {
563         uint8_t instanceNumber;
564         uint8_t buttonDefinition;
565 };
566
567 struct button_definition_template {
568         uint8_t buttonDefinition;
569         /* for now, anything between 0xB0 and 0xCF is custom */
570         /*int custom;*/
571 };
572
573 #define STIMULUS_REDIAL 0x01
574 #define STIMULUS_SPEEDDIAL 0x02
575 #define STIMULUS_HOLD 0x03
576 #define STIMULUS_TRANSFER 0x04
577 #define STIMULUS_FORWARDALL 0x05
578 #define STIMULUS_FORWARDBUSY 0x06
579 #define STIMULUS_FORWARDNOANSWER 0x07
580 #define STIMULUS_DISPLAY 0x08
581 #define STIMULUS_LINE 0x09
582 #define STIMULUS_VOICEMAIL 0x0F
583 #define STIMULUS_AUTOANSWER 0x11
584 #define STIMULUS_SERVICEURL 0x14
585 #define STIMULUS_DND 0x3F
586 #define STIMULUS_CONFERENCE 0x7D
587 #define STIMULUS_CALLPARK 0x7E
588 #define STIMULUS_CALLPICKUP 0x7F
589 #define STIMULUS_NONE 0xFF
590
591 /* Button types */
592 #define BT_REDIAL STIMULUS_REDIAL
593 #define BT_SPEEDDIAL STIMULUS_SPEEDDIAL
594 #define BT_HOLD STIMULUS_HOLD
595 #define BT_TRANSFER STIMULUS_TRANSFER
596 #define BT_FORWARDALL STIMULUS_FORWARDALL
597 #define BT_FORWARDBUSY STIMULUS_FORWARDBUSY
598 #define BT_FORWARDNOANSWER STIMULUS_FORWARDNOANSWER
599 #define BT_DISPLAY STIMULUS_DISPLAY
600 #define BT_LINE STIMULUS_LINE
601 #define BT_VOICEMAIL STIMULUS_VOICEMAIL
602 #define BT_AUTOANSWER STIMULUS_AUTOANSWER
603 #define BT_SERVICEURL STIMULUS_SERVICEURL
604 #define BT_DND STIMULUS_DND
605 #define BT_CONFERENCE STIMULUS_CONFERENCE
606 #define BT_CALLPARK STIMULUS_CALLPARK
607 #define BT_CALLPICKUP STIMULUS_CALLPICKUP
608 #define BT_NONE 0x00
609
610 /* Custom button types - add our own between 0xB0 and 0xCF.
611    This may need to be revised in the future,
612    if stimuluses are ever added in this range. */
613 #define BT_CUST_LINESPEEDDIAL 0xB0 /* line or speeddial with/without hint */
614 #define BT_CUST_LINE 0xB1          /* line or speeddial with hint only */
615
616 struct button_template_res_message {
617         uint32_t buttonOffset;
618         uint32_t buttonCount;
619         uint32_t totalButtonCount;
620         struct button_definition definition[42];
621 };
622
623 #define VERSION_RES_MESSAGE 0x0098
624 struct version_res_message {
625         char version[16];
626 };
627
628 #define DISPLAYTEXT_MESSAGE 0x0099
629 struct displaytext_message {
630         char text[40];
631 };
632
633 #define CLEAR_NOTIFY_MESSAGE  0x0115
634 #define CLEAR_DISPLAY_MESSAGE 0x009A
635 struct clear_display_message {
636         uint32_t space;
637 };
638
639 #define CAPABILITIES_REQ_MESSAGE 0x009B
640
641 #define REGISTER_REJ_MESSAGE 0x009D
642 struct register_rej_message {
643         char errMsg[33];
644 };
645
646 #define SERVER_RES_MESSAGE 0x009E
647 struct server_identifier {
648         char serverName[48];
649 };
650
651 struct server_res_message {
652         struct server_identifier server[5];
653         uint32_t serverListenPort[5];
654         uint32_t serverIpAddr[5];
655 };
656
657 #define RESET_MESSAGE 0x009F
658 struct reset_message {
659         uint32_t resetType;
660 };
661
662 #define KEEP_ALIVE_ACK_MESSAGE 0x0100
663
664 #define OPEN_RECEIVE_CHANNEL_MESSAGE 0x0105
665 struct open_receive_channel_message {
666         uint32_t conferenceId;
667         uint32_t partyId;
668         uint32_t packets;
669         uint32_t capability;
670         uint32_t echo;
671         uint32_t bitrate;
672         uint32_t space[36];
673 };
674
675 #define CLOSE_RECEIVE_CHANNEL_MESSAGE 0x0106
676 struct close_receive_channel_message {
677         uint32_t conferenceId;
678         uint32_t partyId;
679         uint32_t space[2];
680 };
681
682 #define SOFT_KEY_TEMPLATE_RES_MESSAGE 0x0108
683 struct soft_key_template_definition {
684         char softKeyLabel[16];
685         uint32_t softKeyEvent;
686 };
687
688 #define BKSP_REQ_MESSAGE 0x0119
689 struct bksp_req_message {
690         uint32_t instance;
691         uint32_t callreference;
692 };
693
694 #define KEYDEF_ONHOOK 0
695 #define KEYDEF_CONNECTED 1
696 #define KEYDEF_ONHOLD 2
697 #define KEYDEF_RINGIN 3
698 #define KEYDEF_OFFHOOK 4
699 #define KEYDEF_CONNWITHTRANS 5
700 #define KEYDEF_DADFD 6 /* Digits After Dialing First Digit */
701 #define KEYDEF_CONNWITHCONF 7
702 #define KEYDEF_RINGOUT 8
703 #define KEYDEF_OFFHOOKWITHFEAT 9
704 #define KEYDEF_UNKNOWN 10
705 #define KEYDEF_SLAHOLD 11
706 #define KEYDEF_SLACONNECTEDNOTACTIVE 12
707
708 #define SOFTKEY_NONE 0x00
709 #define SOFTKEY_REDIAL 0x01
710 #define SOFTKEY_NEWCALL 0x02
711 #define SOFTKEY_HOLD 0x03
712 #define SOFTKEY_TRNSFER 0x04
713 #define SOFTKEY_CFWDALL 0x05
714 #define SOFTKEY_CFWDBUSY 0x06
715 #define SOFTKEY_CFWDNOANSWER 0x07
716 #define SOFTKEY_BKSPC 0x08
717 #define SOFTKEY_ENDCALL 0x09
718 #define SOFTKEY_RESUME 0x0A
719 #define SOFTKEY_ANSWER 0x0B
720 #define SOFTKEY_INFO 0x0C
721 #define SOFTKEY_CONFRN 0x0D
722 #define SOFTKEY_PARK 0x0E
723 #define SOFTKEY_JOIN 0x0F
724 #define SOFTKEY_MEETME 0x10
725 #define SOFTKEY_PICKUP 0x11
726 #define SOFTKEY_GPICKUP 0x12
727 #define SOFTKEY_DND 0x13
728 #define SOFTKEY_IDIVERT 0x14
729 #define SOFTKEY_FORCEDIAL 0x15
730
731 #define KEYMASK_ALL            0xFFFFFFFF
732 #define KEYMASK_NONE           (1 << 0)
733 #define KEYMASK_REDIAL         (1 << 1)
734 #define KEYMASK_NEWCALL        (1 << 2)
735 #define KEYMASK_HOLD           (1 << 3)
736 #define KEYMASK_TRNSFER        (1 << 4)
737 #define KEYMASK_CFWDALL        (1 << 5)
738 #define KEYMASK_CFWDBUSY       (1 << 6)
739 #define KEYMASK_CFWDNOANSWER   (1 << 7)
740 #define KEYMASK_BKSPC          (1 << 8)
741 #define KEYMASK_ENDCALL        (1 << 9)
742 #define KEYMASK_RESUME         (1 << 10)
743 #define KEYMASK_ANSWER         (1 << 11)
744 #define KEYMASK_INFO           (1 << 12)
745 #define KEYMASK_CONFRN         (1 << 13)
746 #define KEYMASK_PARK           (1 << 14)
747 #define KEYMASK_JOIN           (1 << 15)
748 #define KEYMASK_MEETME         (1 << 16)
749 #define KEYMASK_PICKUP         (1 << 17)
750 #define KEYMASK_GPICKUP        (1 << 18)
751 #define KEYMASK_DND            (1 << 29)
752 #define KEYMASK_IDIVERT        (1 << 20)
753 #define KEYMASK_FORCEDIAL      (1 << 21)
754
755 /* Localized message "codes" (in octal)
756    Below is en_US (taken from a 7970) */
757
758 /*                            "\200\000"        ??? */
759 #define OCTAL_REDIAL          "\200\001"     /* Redial */
760 #define OCTAL_NEWCALL         "\200\002"     /* New Call */
761 #define OCTAL_HOLD            "\200\003"     /* Hold */
762 #define OCTAL_TRANSFER        "\200\004"     /* Transfer */
763 #define OCTAL_CFWDALL         "\200\005"     /* CFwdALL */
764 #define OCTAL_CFWDBUSY        "\200\006"     /* CFwdBusy */
765 #define OCTAL_CFWDNOAN        "\200\007"     /* CFwdNoAnswer */
766 #define OCTAL_BKSPC           "\200\010"     /* << */
767 #define OCTAL_ENDCALL         "\200\011"     /* EndCall */
768 #define OCTAL_RESUME          "\200\012"     /* Resume */
769 #define OCTAL_ANSWER          "\200\013"     /* Answer */
770 #define OCTAL_INFO            "\200\014"     /* Info */
771 #define OCTAL_CONFRN          "\200\015"     /* Confrn */
772 #define OCTAL_PARK            "\200\016"     /* Park */
773 #define OCTAL_JOIN            "\200\017"     /* Join */
774 #define OCTAL_MEETME          "\200\020"     /* MeetMe */
775 #define OCTAL_PICKUP          "\200\021"     /* PickUp */
776 #define OCTAL_GPICKUP         "\200\022"     /* GPickUp */
777 #define OCTAL_CUROPTS         "\200\023"     /* Your current options */
778 #define OCTAL_OFFHOOK         "\200\024"     /* Off Hook */
779 #define OCTAL_ONHOOK          "\200\025"     /* On Hook */
780 #define OCTAL_RINGOUT         "\200\026"     /* Ring out */
781 #define OCTAL_FROM            "\200\027"     /* From */
782 #define OCTAL_CONNECTED       "\200\030"     /* Connected */
783 #define OCTAL_BUSY            "\200\031"     /* Busy */
784 #define OCTAL_LINEINUSE       "\200\032"     /* Line In Use */
785 #define OCTAL_CALLWAITING     "\200\033"     /* Call Waiting */
786 #define OCTAL_CALLXFER        "\200\034"     /* Call Transfer */
787 #define OCTAL_CALLPARK        "\200\035"     /* Call Park */
788 #define OCTAL_CALLPROCEED     "\200\036"     /* Call Proceed */
789 #define OCTAL_INUSEREMOTE     "\200\037"     /* In Use Remote */
790 #define OCTAL_ENTRNUM         "\200\040"     /* Enter number */
791 #define OCTAL_PARKAT          "\200\041"     /* Call park At */
792 #define OCTAL_PRIMONLY        "\200\042"     /* Primary Only */
793 #define OCTAL_TMPFAIL         "\200\043"     /* Temp Fail */
794 #define OCTAL_HAVEVMAIL       "\200\044"     /* You Have VoiceMail */
795 #define OCTAL_FWDEDTO         "\200\045"     /* Forwarded to */
796 #define OCTAL_CANTCOMPCNF     "\200\046"     /* Can Not Complete Conference */
797 #define OCTAL_NOCONFBRDG      "\200\047"     /* No Conference Bridge */
798 #define OCTAL_NOPRIMARYCTL    "\200\050"     /* Can Not Hold Primary Control */
799 #define OCTAL_INVALCONFPART   "\200\051"     /* Invalid Conference Participant */
800 #define OCTAL_INCONFALREADY   "\200\052"     /* In Conference Already */
801 #define OCTAL_NOPARTINFO      "\200\053"     /* No Participant Info */
802 #define OCTAL_MAXPARTEXCEED   "\200\054"     /* Exceed Maximum Parties */
803 #define OCTAL_KEYNOTACTIVE    "\200\055"     /* Key Is Not Active */
804 #define OCTAL_ERRNOLIC        "\200\056"     /* Error No License */
805 #define OCTAL_ERRDBCFG        "\200\057"     /* Error DBConfig */
806 #define OCTAL_ERRDB           "\200\060"     /* Error Database */
807 #define OCTAL_ERRPASSLMT      "\200\061"     /* Error Pass Limit */
808 #define OCTAL_ERRUNK          "\200\062"     /* Error Unknown */
809 #define OCTAL_ERRMISMATCH     "\200\063"     /* Error Mismatch */
810 #define OCTAL_CONFERENCE      "\200\064"     /* Conference */
811 #define OCTAL_PARKNO          "\200\065"     /* Park Number */
812 #define OCTAL_PRIVATE         "\200\066"     /* Private */
813 #define OCTAL_INSUFBANDW      "\200\067"     /* Not Enough Bandwidth */
814 #define OCTAL_UNKNUM          "\200\070"     /* Unknown Number */
815 #define OCTAL_RMLSTC          "\200\071"     /* RmLstC */
816 #define OCTAL_VOICEMAIL       "\200\072"     /* Voicemail */
817 #define OCTAL_IMMDIV          "\200\073"     /* ImmDiv */
818 #define OCTAL_INTRCPT         "\200\074"     /* Intrcpt */
819 #define OCTAL_SETWTCH         "\200\075"     /* SetWtch */
820 #define OCTAL_TRNSFVM         "\200\076"     /* TrnsfVM */
821 #define OCTAL_DND             "\200\077"     /* DND */
822 #define OCTAL_DIVALL          "\200\100"     /* DivAll */
823 #define OCTAL_CALLBACK        "\200\101"     /* CallBack */
824 #define OCTAL_NETCNGREROUT    "\200\102"     /* Network congestion,rerouting */
825 #define OCTAL_BARGE           "\200\103"     /* Barge */
826 #define OCTAL_BARGEFAIL       "\200\104"     /* Failed to setup Barge */
827 #define OCTAL_BARGEEXIST      "\200\105"     /* Another Barge exists */
828 #define OCTAL_INCOMPATDEV     "\200\106"     /* Incompatible device type */
829 #define OCTAL_PARKNONUM       "\200\107"     /* No Park Number Available */
830 #define OCTAL_PARKREVERSION   "\200\110"     /* CallPark Reversion */
831 #define OCTAL_SRVNOTACTIVE    "\200\111"     /* Service is not Active */
832 #define OCTAL_HITRAFFIC       "\200\112"     /* High Traffic Try Again Later */
833 #define OCTAL_QRT             "\200\113"     /* QRT */
834 #define OCTAL_MCID            "\200\114"     /* MCID */
835 #define OCTAL_DIRTRFR         "\200\115"     /* DirTrfr */
836 #define OCTAL_SELECT          "\200\116"     /* Select */
837 #define OCTAL_CONFLIST        "\200\117"     /* ConfList */
838 #define OCTAL_IDIVERT         "\200\120"     /* iDivert */
839 #define OCTAL_CBARGE          "\200\121"     /* cBarge */
840 #define OCTAL_CANTCOMPLXFER   "\200\122"     /* Can Not Complete Transfer */
841 #define OCTAL_CANTJOINCALLS   "\200\123"     /* Can Not Join Calls */
842 #define OCTAL_MCIDSUCCESS     "\200\124"     /* Mcid Successful */
843 #define OCTAL_NUMNOTCFG       "\200\125"     /* Number Not Configured */
844 #define OCTAL_SECERROR        "\200\126"     /* Security Error */
845 #define OCTAL_VIDBANDWNA      "\200\127"     /* Video Bandwidth Unavailable */
846 #define OCTAL_VIDMODE         "\200\130"     /* VidMode */
847 #define OCTAL_CALLDURTIMEOUT  "\200\131"     /* Max Call Duration Timeout */
848 #define OCTAL_HOLDDURTIMEOUT  "\200\132"     /* Max Hold Duration Timeout */
849 #define OCTAL_OPICKUP         "\200\133"     /* OPickUp */
850 /*                            "\200\134"        ??? */
851 /*                            "\200\135"        ??? */
852 /*                            "\200\136"        ??? */
853 /*                            "\200\137"        ??? */
854 /*                            "\200\140"        ??? */
855 #define OCTAL_EXTXFERRESTRICT "\200\141"     /* External Transfer Restricted */
856 /*                            "\200\142"        ??? */
857 /*                            "\200\143"        ??? */
858 /*                            "\200\144"        ??? */
859 #define OCTAL_MACADD          "\200\145"     /* Mac Address */
860 #define OCTAL_HOST            "\200\146"     /* Host Name */
861 #define OCTAL_DOMAIN          "\200\147"     /* Domain Name */
862 #define OCTAL_IPADD           "\200\150"     /* IP Address */
863 #define OCTAL_SUBMASK         "\200\151"     /* Subnet Mask */
864 #define OCTAL_TFTP1           "\200\152"     /* TFTP Server 1 */
865 #define OCTAL_ROUTER1         "\200\153"     /* Default Router 1 */
866 #define OCTAL_ROUTER2         "\200\154"     /* Default Router 2 */
867 #define OCTAL_ROUTER3         "\200\155"     /* Default Router 3 */
868 #define OCTAL_ROUTER4         "\200\156"     /* Default Router 4 */
869 #define OCTAL_ROUTER5         "\200\157"     /* Default Router 5 */
870 #define OCTAL_DNS1            "\200\160"     /* DNS Server 1 */
871 #define OCTAL_DNS2            "\200\161"     /* DNS Server 2 */
872 #define OCTAL_DNS3            "\200\162"     /* DNS Server 3 */
873 #define OCTAL_DNS4            "\200\163"     /* DNS Server 4 */
874 #define OCTAL_DNS5            "\200\164"     /* DNS Server 5 */
875 #define OCTAL_VLANOPID        "\200\165"     /* Operational VLAN Id */
876 #define OCTAL_VLANADID        "\200\166"     /* Admin. VLAN Id */
877 #define OCTAL_CM1             "\200\167"     /* CallManager 1 */
878 #define OCTAL_CM2             "\200\170"     /* CallManager 2 */
879 #define OCTAL_CM3             "\200\171"     /* CallManager 3 */
880 #define OCTAL_CM4             "\200\172"     /* CallManager 4 */
881 #define OCTAL_CM5             "\200\173"     /* CallManager 5 */
882 #define OCTAL_URLINFO         "\200\174"     /* Information URL */
883 #define OCTAL_URLDIRS         "\200\175"     /* Directories URL */
884 #define OCTAL_URLMSGS         "\200\176"     /* Messages URL */
885 #define OCTAL_URLSRVS         "\200\177"     /* Services URL */
886
887 static struct soft_key_template_definition soft_key_template_default[] = {
888         { OCTAL_REDIAL, SOFTKEY_REDIAL },
889         { OCTAL_NEWCALL, SOFTKEY_NEWCALL },
890         { OCTAL_HOLD, SOFTKEY_HOLD },
891         { OCTAL_TRANSFER, SOFTKEY_TRNSFER },
892         { OCTAL_CFWDALL, SOFTKEY_CFWDALL },
893         { OCTAL_CFWDBUSY, SOFTKEY_CFWDBUSY },
894         { OCTAL_CFWDNOAN, SOFTKEY_CFWDNOANSWER },
895         { OCTAL_BKSPC, SOFTKEY_BKSPC },
896         { OCTAL_ENDCALL, SOFTKEY_ENDCALL },
897         { OCTAL_RESUME, SOFTKEY_RESUME },
898         { OCTAL_ANSWER, SOFTKEY_ANSWER },
899         { OCTAL_INFO, SOFTKEY_INFO },
900         { OCTAL_CONFRN, SOFTKEY_CONFRN },
901         { OCTAL_PARK, SOFTKEY_PARK },
902         { OCTAL_JOIN, SOFTKEY_JOIN },
903         { OCTAL_MEETME, SOFTKEY_MEETME },
904         { OCTAL_PICKUP, SOFTKEY_PICKUP },
905         { OCTAL_GPICKUP, SOFTKEY_GPICKUP },
906         { OCTAL_DND, SOFTKEY_DND },
907         { OCTAL_IDIVERT, SOFTKEY_IDIVERT },
908         { "Dial", SOFTKEY_FORCEDIAL},
909 };
910
911 struct soft_key_definitions {
912         const uint8_t mode;
913         const uint8_t *defaults;
914         const int count;
915 };
916
917 static const uint8_t soft_key_default_onhook[] = {
918         SOFTKEY_REDIAL,
919         SOFTKEY_NEWCALL,
920         SOFTKEY_CFWDALL,
921         SOFTKEY_CFWDBUSY,
922         SOFTKEY_CFWDNOANSWER,
923         SOFTKEY_DND,
924         SOFTKEY_GPICKUP,
925         /*SOFTKEY_CONFRN,*/
926 };
927
928 static const uint8_t soft_key_default_connected[] = {
929         SOFTKEY_HOLD,
930         SOFTKEY_ENDCALL,
931         SOFTKEY_TRNSFER,
932         SOFTKEY_PARK,
933         SOFTKEY_CFWDALL,
934         SOFTKEY_CFWDBUSY,
935         SOFTKEY_CFWDNOANSWER,
936 };
937
938 static const uint8_t soft_key_default_onhold[] = {
939         SOFTKEY_RESUME,
940         SOFTKEY_NEWCALL,
941         SOFTKEY_ENDCALL,
942         SOFTKEY_TRNSFER,
943 };
944
945 static const uint8_t soft_key_default_ringin[] = {
946         SOFTKEY_ANSWER,
947         SOFTKEY_ENDCALL,
948         SOFTKEY_TRNSFER,
949 };
950
951 static const uint8_t soft_key_default_offhook[] = {
952         SOFTKEY_REDIAL,
953         SOFTKEY_ENDCALL,
954         SOFTKEY_CFWDALL,
955         SOFTKEY_CFWDBUSY,
956         SOFTKEY_CFWDNOANSWER,
957         SOFTKEY_GPICKUP,
958 };
959
960 static const uint8_t soft_key_default_connwithtrans[] = {
961         SOFTKEY_HOLD,
962         SOFTKEY_ENDCALL,
963         SOFTKEY_TRNSFER,
964         SOFTKEY_PARK,
965         SOFTKEY_CFWDALL,
966         SOFTKEY_CFWDBUSY,
967         SOFTKEY_CFWDNOANSWER,
968 };
969
970 static const uint8_t soft_key_default_dadfd[] = {
971         SOFTKEY_BKSPC,
972         SOFTKEY_ENDCALL,
973         SOFTKEY_FORCEDIAL,
974 };
975
976 static const uint8_t soft_key_default_connwithconf[] = {
977         SOFTKEY_NONE,
978 };
979
980 static const uint8_t soft_key_default_ringout[] = {
981         SOFTKEY_NONE,
982         SOFTKEY_ENDCALL,
983 };
984
985 static const uint8_t soft_key_default_offhookwithfeat[] = {
986         SOFTKEY_REDIAL,
987         SOFTKEY_ENDCALL,
988         SOFTKEY_TRNSFER,
989 };
990
991 static const uint8_t soft_key_default_unknown[] = {
992         SOFTKEY_NONE,
993 };
994
995 static const uint8_t soft_key_default_SLAhold[] = {
996         SOFTKEY_REDIAL,
997         SOFTKEY_NEWCALL,
998         SOFTKEY_RESUME,
999 };
1000
1001 static const uint8_t soft_key_default_SLAconnectednotactive[] = {
1002         SOFTKEY_REDIAL,
1003         SOFTKEY_NEWCALL,
1004         SOFTKEY_JOIN,
1005 };
1006
1007 static const struct soft_key_definitions soft_key_default_definitions[] = {
1008         {KEYDEF_ONHOOK, soft_key_default_onhook, sizeof(soft_key_default_onhook) / sizeof(uint8_t)},
1009         {KEYDEF_CONNECTED, soft_key_default_connected, sizeof(soft_key_default_connected) / sizeof(uint8_t)},
1010         {KEYDEF_ONHOLD, soft_key_default_onhold, sizeof(soft_key_default_onhold) / sizeof(uint8_t)},
1011         {KEYDEF_RINGIN, soft_key_default_ringin, sizeof(soft_key_default_ringin) / sizeof(uint8_t)},
1012         {KEYDEF_OFFHOOK, soft_key_default_offhook, sizeof(soft_key_default_offhook) / sizeof(uint8_t)},
1013         {KEYDEF_CONNWITHTRANS, soft_key_default_connwithtrans, sizeof(soft_key_default_connwithtrans) / sizeof(uint8_t)},
1014         {KEYDEF_DADFD, soft_key_default_dadfd, sizeof(soft_key_default_dadfd) / sizeof(uint8_t)},
1015         {KEYDEF_CONNWITHCONF, soft_key_default_connwithconf, sizeof(soft_key_default_connwithconf) / sizeof(uint8_t)},
1016         {KEYDEF_RINGOUT, soft_key_default_ringout, sizeof(soft_key_default_ringout) / sizeof(uint8_t)},
1017         {KEYDEF_OFFHOOKWITHFEAT, soft_key_default_offhookwithfeat, sizeof(soft_key_default_offhookwithfeat) / sizeof(uint8_t)},
1018         {KEYDEF_UNKNOWN, soft_key_default_unknown, sizeof(soft_key_default_unknown) / sizeof(uint8_t)},
1019         {KEYDEF_SLAHOLD, soft_key_default_SLAhold, sizeof(soft_key_default_SLAhold) / sizeof(uint8_t)},
1020         {KEYDEF_SLACONNECTEDNOTACTIVE, soft_key_default_SLAconnectednotactive, sizeof(soft_key_default_SLAconnectednotactive) / sizeof(uint8_t)}
1021 };
1022
1023 struct soft_key_template_res_message {
1024         uint32_t softKeyOffset;
1025         uint32_t softKeyCount;
1026         uint32_t totalSoftKeyCount;
1027         struct soft_key_template_definition softKeyTemplateDefinition[32];
1028 };
1029
1030 #define SOFT_KEY_SET_RES_MESSAGE 0x0109
1031
1032 struct soft_key_set_definition {
1033         uint8_t softKeyTemplateIndex[16];
1034         uint16_t softKeyInfoIndex[16];
1035 };
1036
1037 struct soft_key_set_res_message {
1038         uint32_t softKeySetOffset;
1039         uint32_t softKeySetCount;
1040         uint32_t totalSoftKeySetCount;
1041         struct soft_key_set_definition softKeySetDefinition[16];
1042         uint32_t res;
1043 };
1044
1045 #define SELECT_SOFT_KEYS_MESSAGE 0x0110
1046 struct select_soft_keys_message {
1047         uint32_t instance;
1048         uint32_t reference;
1049         uint32_t softKeySetIndex;
1050         uint32_t validKeyMask;
1051 };
1052
1053 #define CALL_STATE_MESSAGE 0x0111
1054 struct call_state_message {
1055         uint32_t callState;
1056         uint32_t lineInstance;
1057         uint32_t callReference;
1058         uint32_t space[3];
1059 };
1060
1061 #define DISPLAY_PROMPT_STATUS_MESSAGE 0x0112
1062 struct display_prompt_status_message {
1063         uint32_t messageTimeout;
1064         char promptMessage[32];
1065         uint32_t lineInstance;
1066         uint32_t callReference;
1067         uint32_t space[3];
1068 };
1069
1070 #define CLEAR_PROMPT_MESSAGE  0x0113
1071 struct clear_prompt_message {
1072         uint32_t lineInstance;
1073         uint32_t callReference;
1074 };
1075
1076 #define DISPLAY_NOTIFY_MESSAGE 0x0114
1077 struct display_notify_message {
1078         uint32_t displayTimeout;
1079         char displayMessage[100];
1080 };
1081
1082 #define ACTIVATE_CALL_PLANE_MESSAGE 0x0116
1083 struct activate_call_plane_message {
1084         uint32_t lineInstance;
1085 };
1086
1087 #define DIALED_NUMBER_MESSAGE 0x011D
1088 struct dialed_number_message {
1089         char dialedNumber[24];
1090         uint32_t lineInstance;
1091         uint32_t callReference;
1092 };
1093
1094 #define MAX_SERVICEURL 256
1095 #define SERVICEURL_STAT_MESSAGE 0x012F
1096 struct serviceurl_stat_message {
1097         uint32_t instance;
1098         char url[MAX_SERVICEURL];
1099         char displayName[40];
1100 };
1101
1102 #define MAXCALLINFOSTR 256
1103 #define MAXDISPLAYNOTIFYSTR 32
1104
1105 #define DISPLAY_PRINOTIFY_MESSAGE 0x0120
1106 struct display_prinotify_message {
1107         uint32_t timeout;
1108         uint32_t priority;
1109         char text[MAXDISPLAYNOTIFYSTR];
1110 };
1111
1112 #define CLEAR_PRINOTIFY_MESSAGE 0x0121
1113 struct clear_prinotify_message {
1114         uint32_t priority;
1115 };
1116
1117 #define CALL_INFO_MESSAGE_VARIABLE 0x014A
1118 struct call_info_message_variable {
1119         uint32_t instance;
1120         uint32_t callreference;
1121         uint32_t calldirection;
1122         uint32_t unknown1;
1123         uint32_t unknown2;
1124         uint32_t unknown3;
1125         uint32_t unknown4;
1126         uint32_t unknown5;
1127         char calldetails[MAXCALLINFOSTR];
1128 };
1129
1130 #define DISPLAY_PRINOTIFY_MESSAGE_VARIABLE 0x0144
1131 struct display_prinotify_message_variable {
1132         uint32_t timeout;
1133         uint32_t priority;
1134         char text[MAXDISPLAYNOTIFYSTR];
1135 };
1136
1137 #define DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE 0x0145
1138 struct display_prompt_status_message_variable {
1139         uint32_t unknown;
1140         uint32_t lineInstance;
1141         uint32_t callReference;
1142         char promptMessage[MAXCALLINFOSTR];
1143 };
1144
1145 union skinny_data {
1146         struct alarm_message alarm;
1147         struct speed_dial_stat_req_message speeddialreq;
1148         struct register_message reg;
1149         struct register_ack_message regack;
1150         struct register_rej_message regrej;
1151         struct capabilities_res_message caps;
1152         struct version_res_message version;
1153         struct button_template_res_message buttontemplate;
1154         struct displaytext_message displaytext;
1155         struct clear_display_message cleardisplay;
1156         struct display_prompt_status_message displaypromptstatus;
1157         struct clear_prompt_message clearpromptstatus;
1158         struct definetimedate_message definetimedate;
1159         struct start_tone_message starttone;
1160         struct stop_tone_message stoptone;
1161         struct speed_dial_stat_res_message speeddial;
1162         struct line_state_req_message line;
1163         struct line_stat_res_message linestat;
1164         struct soft_key_set_res_message softkeysets;
1165         struct soft_key_template_res_message softkeytemplate;
1166         struct server_res_message serverres;
1167         struct reset_message reset;
1168         struct set_lamp_message setlamp;
1169         struct set_ringer_message setringer;
1170         struct call_state_message callstate;
1171         struct keypad_button_message keypad;
1172         struct select_soft_keys_message selectsoftkey;
1173         struct activate_call_plane_message activatecallplane;
1174         struct stimulus_message stimulus;
1175         struct offhook_message offhook;
1176         struct onhook_message onhook;
1177         struct set_speaker_message setspeaker;
1178         struct set_microphone_message setmicrophone;
1179         struct call_info_message callinfo;
1180         struct start_media_transmission_message_ip4 startmedia_ip4;
1181         struct start_media_transmission_message_ip6 startmedia_ip6;
1182         struct stop_media_transmission_message stopmedia;
1183         struct open_receive_channel_message openreceivechannel;
1184         struct open_receive_channel_ack_message_ip4 openreceivechannelack_ip4;
1185         struct open_receive_channel_ack_message_ip6 openreceivechannelack_ip6;
1186         struct close_receive_channel_message closereceivechannel;
1187         struct display_notify_message displaynotify;
1188         struct dialed_number_message dialednumber;
1189         struct soft_key_event_message softkeyeventmessage;
1190         struct enbloc_call_message enbloccallmessage;
1191         struct forward_stat_message forwardstat;
1192         struct bksp_req_message bkspmessage;
1193         struct call_info_message_variable callinfomessagevariable;
1194         struct display_prompt_status_message_variable displaypromptstatusvar;
1195         struct serviceurl_stat_message serviceurlmessage;
1196         struct clear_prinotify_message clearprinotify;
1197         struct display_prinotify_message displayprinotify;
1198         struct display_prinotify_message_variable displayprinotifyvar;
1199 };
1200
1201 /* packet composition */
1202 struct skinny_req {
1203         int len;
1204         int res;
1205         int e;
1206         union skinny_data data;
1207 };
1208
1209 /* XXX This is the combined size of the variables above.  (len, res, e)
1210    If more are added, this MUST change.
1211    (sizeof(skinny_req) - sizeof(skinny_data)) DOES NOT WORK on all systems (amd64?). */
1212 static int skinny_header_size = 12;
1213
1214 /*****************************
1215  * Asterisk specific globals *
1216  *****************************/
1217
1218 static int skinnyreload = 0;
1219
1220 /* a hostname, portnumber, socket and such is usefull for VoIP protocols */
1221 static struct sockaddr_in bindaddr;
1222 static char ourhost[256];
1223 static int ourport;
1224 static struct in_addr __ourip;
1225 static struct ast_hostent ahp;
1226 static struct hostent *hp;
1227 static int skinnysock = -1;
1228 static pthread_t accept_t;
1229 static int callnums = 1;
1230
1231 #define SKINNY_DEVICE_UNKNOWN -1
1232 #define SKINNY_DEVICE_NONE 0
1233 #define SKINNY_DEVICE_30SPPLUS 1
1234 #define SKINNY_DEVICE_12SPPLUS 2
1235 #define SKINNY_DEVICE_12SP 3
1236 #define SKINNY_DEVICE_12 4
1237 #define SKINNY_DEVICE_30VIP 5
1238 #define SKINNY_DEVICE_7910 6
1239 #define SKINNY_DEVICE_7960 7
1240 #define SKINNY_DEVICE_7940 8
1241 #define SKINNY_DEVICE_7935 9
1242 #define SKINNY_DEVICE_ATA186 12 /* Cisco ATA-186 */
1243 #define SKINNY_DEVICE_7941 115
1244 #define SKINNY_DEVICE_7971 119
1245 #define SKINNY_DEVICE_7914 124 /* Expansion module */
1246 #define SKINNY_DEVICE_7985 302
1247 #define SKINNY_DEVICE_7911 307
1248 #define SKINNY_DEVICE_7961GE 308
1249 #define SKINNY_DEVICE_7941GE 309
1250 #define SKINNY_DEVICE_7931 348
1251 #define SKINNY_DEVICE_7921 365
1252 #define SKINNY_DEVICE_7906 369
1253 #define SKINNY_DEVICE_7962 404 /* Not found */
1254 #define SKINNY_DEVICE_7937 431
1255 #define SKINNY_DEVICE_7942 434
1256 #define SKINNY_DEVICE_7945 435
1257 #define SKINNY_DEVICE_7965 436
1258 #define SKINNY_DEVICE_7975 437
1259 #define SKINNY_DEVICE_7905 20000
1260 #define SKINNY_DEVICE_7920 30002
1261 #define SKINNY_DEVICE_7970 30006
1262 #define SKINNY_DEVICE_7912 30007
1263 #define SKINNY_DEVICE_7902 30008
1264 #define SKINNY_DEVICE_CIPC 30016 /* Cisco IP Communicator */
1265 #define SKINNY_DEVICE_7961 30018
1266 #define SKINNY_DEVICE_7936 30019
1267 #define SKINNY_DEVICE_SCCPGATEWAY_AN 30027 /* Analog gateway */
1268 #define SKINNY_DEVICE_SCCPGATEWAY_BRI 30028 /* BRI gateway */
1269
1270 #define SKINNY_SPEAKERON 1
1271 #define SKINNY_SPEAKEROFF 2
1272
1273 #define SKINNY_MICON 1
1274 #define SKINNY_MICOFF 2
1275
1276 #define SKINNY_OFFHOOK 1
1277 #define SKINNY_ONHOOK 2
1278 #define SKINNY_RINGOUT 3
1279 #define SKINNY_RINGIN 4
1280 #define SKINNY_CONNECTED 5
1281 #define SKINNY_BUSY 6
1282 #define SKINNY_CONGESTION 7
1283 #define SKINNY_HOLD 8
1284 #define SKINNY_CALLWAIT 9
1285 #define SKINNY_TRANSFER 10
1286 #define SKINNY_PARK 11
1287 #define SKINNY_PROGRESS 12
1288 #define SKINNY_CALLREMOTEMULTILINE 13
1289 #define SKINNY_INVALID 14
1290
1291 #define SKINNY_INCOMING 1
1292 #define SKINNY_OUTGOING 2
1293
1294 #define SKINNY_SILENCE 0x00             /* Note sure this is part of the protocol, remove? */
1295 #define SKINNY_DIALTONE 0x21
1296 #define SKINNY_BUSYTONE 0x23
1297 #define SKINNY_ALERT 0x24
1298 #define SKINNY_REORDER 0x25
1299 #define SKINNY_CALLWAITTONE 0x2D
1300 #define SKINNY_ZIPZIP 0x31
1301 #define SKINNY_ZIP 0x32
1302 #define SKINNY_BEEPBONK 0x33
1303 #define SKINNY_BARGIN 0x43
1304 #define SKINNY_NOTONE 0x7F
1305
1306 #define SKINNY_LAMP_OFF 1
1307 #define SKINNY_LAMP_ON 2
1308 #define SKINNY_LAMP_WINK 3
1309 #define SKINNY_LAMP_FLASH 4
1310 #define SKINNY_LAMP_BLINK 5
1311
1312 #define SKINNY_RING_OFF 1
1313 #define SKINNY_RING_INSIDE 2
1314 #define SKINNY_RING_OUTSIDE 3
1315 #define SKINNY_RING_FEATURE 4
1316
1317 #define SKINNY_CFWD_ALL       (1 << 0)
1318 #define SKINNY_CFWD_BUSY      (1 << 1)
1319 #define SKINNY_CFWD_NOANSWER  (1 << 2)
1320
1321 /* Skinny rtp stream modes. Do we really need this? */
1322 #define SKINNY_CX_SENDONLY 0
1323 #define SKINNY_CX_RECVONLY 1
1324 #define SKINNY_CX_SENDRECV 2
1325 #define SKINNY_CX_CONF 3
1326 #define SKINNY_CX_CONFERENCE 3
1327 #define SKINNY_CX_MUTE 4
1328 #define SKINNY_CX_INACTIVE 4
1329
1330 #if 0
1331 static const char * const skinny_cxmodes[] = {
1332         "sendonly",
1333         "recvonly",
1334         "sendrecv",
1335         "confrnce",
1336         "inactive"
1337 };
1338 #endif
1339
1340 /* driver scheduler */
1341 static struct ast_sched_context *sched = NULL;
1342
1343 /* Protect the network socket */
1344 AST_MUTEX_DEFINE_STATIC(netlock);
1345
1346 /* Wait up to 16 seconds for first digit */
1347 static int firstdigittimeout = 16000;
1348
1349 /* How long to wait for following digits */
1350 static int gendigittimeout = 8000;
1351
1352 /* How long to wait for an extra digit, if there is an ambiguous match */
1353 static int matchdigittimeout = 3000;
1354
1355 #define SUBSTATE_UNSET 0
1356 #define SUBSTATE_OFFHOOK 1
1357 #define SUBSTATE_ONHOOK 2
1358 #define SUBSTATE_RINGOUT 3
1359 #define SUBSTATE_RINGIN 4
1360 #define SUBSTATE_CONNECTED 5
1361 #define SUBSTATE_BUSY 6
1362 #define SUBSTATE_CONGESTION 7
1363 #define SUBSTATE_HOLD 8
1364 #define SUBSTATE_CALLWAIT 9
1365 #define SUBSTATE_PROGRESS 12
1366 #define SUBSTATE_DIALING 101
1367
1368 #define DIALTYPE_NORMAL      1<<0
1369 #define DIALTYPE_CFWD        1<<1
1370
1371 struct skinny_subchannel {
1372         ast_mutex_t lock;
1373         struct ast_channel *owner;
1374         struct ast_rtp_instance *rtp;
1375         struct ast_rtp_instance *vrtp;
1376         unsigned int callid;
1377         char exten[AST_MAX_EXTENSION];
1378         /* time_t lastouttime; */ /* Unused */
1379         int progress;
1380         int ringing;
1381         /* int lastout; */ /* Unused */
1382         int cxmode;
1383         int nat;
1384         int calldirection;
1385         int blindxfer;
1386         int xferor;
1387         int substate;
1388         int aa_sched;
1389         int aa_beep;
1390         int aa_mute;
1391         int dialer_sched;
1392         int cfwd_sched;
1393         int dialType;
1394         int getforward;
1395         char *origtonum;
1396         char *origtoname;
1397
1398         AST_LIST_ENTRY(skinny_subchannel) list;
1399         struct skinny_subchannel *related;
1400         struct skinny_line *line;
1401         struct skinny_subline *subline;
1402 };
1403
1404 #define SKINNY_LINE_OPTIONS                             \
1405         char name[80];                                  \
1406         char label[24];                                 \
1407         char accountcode[AST_MAX_ACCOUNT_CODE];         \
1408         char exten[AST_MAX_EXTENSION];                  \
1409         char context[AST_MAX_CONTEXT];                  \
1410         char language[MAX_LANGUAGE];                    \
1411         char cid_num[AST_MAX_EXTENSION];                \
1412         char cid_name[AST_MAX_EXTENSION];               \
1413         char lastcallerid[AST_MAX_EXTENSION];           \
1414         int cfwdtype;                                   \
1415         char call_forward_all[AST_MAX_EXTENSION];       \
1416         char call_forward_busy[AST_MAX_EXTENSION];      \
1417         char call_forward_noanswer[AST_MAX_EXTENSION];  \
1418         char mailbox[AST_MAX_EXTENSION];                \
1419         char vmexten[AST_MAX_EXTENSION];                \
1420         char regexten[AST_MAX_EXTENSION];               \
1421         char regcontext[AST_MAX_CONTEXT];               \
1422         char parkinglot[AST_MAX_CONTEXT];               \
1423         char mohinterpret[MAX_MUSICCLASS];              \
1424         char mohsuggest[MAX_MUSICCLASS];                \
1425         char lastnumberdialed[AST_MAX_EXTENSION];       \
1426         char dialoutexten[AST_MAX_EXTENSION];           \
1427         char dialoutcontext[AST_MAX_CONTEXT];           \
1428         ast_group_t callgroup;                          \
1429         ast_group_t pickupgroup;                        \
1430         struct ast_namedgroups *named_callgroups;       \
1431         struct ast_namedgroups *named_pickupgroups;     \
1432         int callwaiting;                                \
1433         int transfer;                                   \
1434         int threewaycalling;                            \
1435         int mwiblink;                                   \
1436         int cancallforward;                             \
1437         int callfwdtimeout;                             \
1438         int dnd;                                        \
1439         int hidecallerid;                               \
1440         int amaflags;                                   \
1441         int instance;                                   \
1442         int group;                                      \
1443         struct ast_codec_pref confprefs;                \
1444         struct ast_codec_pref prefs;                    \
1445         int nonCodecCapability;                         \
1446         int immediate;                                  \
1447         int nat;                                        \
1448         int directmedia;                                \
1449         int prune;
1450
1451 struct skinny_line {
1452         SKINNY_LINE_OPTIONS
1453         ast_mutex_t lock;
1454         struct skinny_container *container;
1455         struct stasis_subscription *mwi_event_sub; /* Event based MWI */
1456         struct skinny_subchannel *activesub;
1457         AST_LIST_HEAD(, skinny_subchannel) sub;
1458         AST_LIST_HEAD(, skinny_subline) sublines;
1459         AST_LIST_ENTRY(skinny_line) list;
1460         AST_LIST_ENTRY(skinny_line) all;
1461         struct skinny_device *device;
1462         struct ast_format_cap *cap;
1463         struct ast_format_cap *confcap;
1464         struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1465         int newmsgs;
1466 };
1467
1468 static struct skinny_line_options{
1469         SKINNY_LINE_OPTIONS
1470 } default_line_struct = {
1471         .callwaiting = 1,
1472         .transfer = 1,
1473         .mwiblink = 0,
1474         .dnd = 0,
1475         .hidecallerid = 0,
1476         .amaflags = 0,
1477         .instance = 0,
1478         .directmedia = 0,
1479         .nat = 0,
1480         .callfwdtimeout = 20000,
1481         .prune = 0,
1482 };
1483 static struct skinny_line_options *default_line = &default_line_struct;
1484
1485 static AST_LIST_HEAD_STATIC(lines, skinny_line);
1486
1487 struct skinny_subline {
1488         struct skinny_container *container;
1489         struct skinny_line *line;
1490         struct skinny_subchannel *sub;
1491         AST_LIST_ENTRY(skinny_subline) list;
1492         char name[80];
1493         char context[AST_MAX_CONTEXT];
1494         char exten[AST_MAX_EXTENSION];
1495         char stname[AST_MAX_EXTENSION];
1496         char lnname[AST_MAX_EXTENSION];
1497         char ourName[40];
1498         char ourNum[24];
1499         char theirName[40];
1500         char theirNum[24];
1501         int calldirection;
1502         int substate;
1503         int extenstate;
1504         unsigned int callid;
1505 };
1506
1507 struct skinny_speeddial {
1508         ast_mutex_t lock;
1509         struct skinny_container *container;
1510         char label[42];
1511         char context[AST_MAX_CONTEXT];
1512         char exten[AST_MAX_EXTENSION];
1513         int instance;
1514         int stateid;
1515         int laststate;
1516         int isHint;
1517
1518         AST_LIST_ENTRY(skinny_speeddial) list;
1519         struct skinny_device *parent;
1520 };
1521
1522 struct skinny_serviceurl {
1523         int instance;
1524         char url[MAX_SERVICEURL];
1525         char displayName[40];
1526         AST_LIST_ENTRY(skinny_serviceurl) list;
1527         struct skinny_device *device;
1528 };
1529
1530 #define SKINNY_DEVICECONTAINER 1
1531 #define SKINNY_LINECONTAINER 2
1532 #define SKINNY_SUBLINECONTAINER 3
1533 #define SKINNY_SDCONTAINER 4
1534
1535 struct skinny_container {
1536         int type;
1537         void *data;
1538 };
1539
1540 struct skinny_addon {
1541         ast_mutex_t lock;
1542         char type[10];
1543         AST_LIST_ENTRY(skinny_addon) list;
1544         struct skinny_device *parent;
1545 };
1546
1547 #define SKINNY_DEVICE_OPTIONS                                   \
1548         char name[80];                                          \
1549         char id[16];                                            \
1550         char version_id[16];                                    \
1551         char vmexten[AST_MAX_EXTENSION];                        \
1552         int type;                                               \
1553         int protocolversion;                            \
1554         int hookstate;                                  \
1555         int lastlineinstance;                                   \
1556         int lastcallreference;                                  \
1557         struct ast_codec_pref confprefs;                        \
1558         int earlyrtp;                                           \
1559         int transfer;                                           \
1560         int callwaiting;                                        \
1561         int mwiblink;                                           \
1562         int dnd;                                                \
1563         int prune;
1564
1565 struct skinny_device {
1566         SKINNY_DEVICE_OPTIONS
1567         struct type *first;
1568         struct type *last;
1569         ast_mutex_t lock;
1570         struct sockaddr_in addr;
1571         struct in_addr ourip;
1572         struct ast_ha *ha;
1573         struct skinnysession *session;
1574         struct skinny_line *activeline;
1575         struct ast_format_cap *cap;
1576         struct ast_format_cap *confcap;
1577         AST_LIST_HEAD(, skinny_line) lines;
1578         AST_LIST_HEAD(, skinny_speeddial) speeddials;
1579         AST_LIST_HEAD(, skinny_serviceurl) serviceurls;
1580         AST_LIST_HEAD(, skinny_addon) addons;
1581         AST_LIST_ENTRY(skinny_device) list;
1582 };
1583
1584 static struct skinny_device_options {
1585         SKINNY_DEVICE_OPTIONS
1586 } default_device_struct = {
1587         .transfer = 1,
1588         .earlyrtp = 1,
1589         .callwaiting = 1,
1590         .mwiblink = 0,
1591         .dnd = 0,
1592         .prune = 0,
1593         .hookstate = SKINNY_ONHOOK,
1594 };
1595 static struct skinny_device_options *default_device = &default_device_struct;
1596
1597 static AST_LIST_HEAD_STATIC(devices, skinny_device);
1598
1599 struct skinnysession {
1600         pthread_t t;
1601         ast_mutex_t lock;
1602         time_t start;
1603         struct sockaddr_in sin;
1604         int fd;
1605         char inbuf[SKINNY_MAX_PACKET];
1606         char outbuf[SKINNY_MAX_PACKET];
1607         struct skinny_device *device;
1608         AST_LIST_ENTRY(skinnysession) list;
1609 };
1610
1611 static struct ast_channel *skinny_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
1612 static AST_LIST_HEAD_STATIC(sessions, skinnysession);
1613
1614 static int skinny_devicestate(const char *data);
1615 static int skinny_call(struct ast_channel *ast, const char *dest, int timeout);
1616 static int skinny_hangup(struct ast_channel *ast);
1617 static int skinny_answer(struct ast_channel *ast);
1618 static struct ast_frame *skinny_read(struct ast_channel *ast);
1619 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1620 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1621 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1622 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1623 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1624 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *msg);
1625 static int skinny_dialer_cb(const void *data);
1626 static int skinny_reload(void);
1627
1628 static void setsubstate(struct skinny_subchannel *sub, int state);
1629 static void dumpsub(struct skinny_subchannel *sub, int forcehangup);
1630 static void activatesub(struct skinny_subchannel *sub, int state);
1631 static void dialandactivatesub(struct skinny_subchannel *sub, char exten[AST_MAX_EXTENSION]);
1632
1633 static struct ast_channel_tech skinny_tech = {
1634         .type = "Skinny",
1635         .description = tdesc,
1636         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1637         .requester = skinny_request,
1638         .devicestate = skinny_devicestate,
1639         .call = skinny_call,
1640         .hangup = skinny_hangup,
1641         .answer = skinny_answer,
1642         .read = skinny_read,
1643         .write = skinny_write,
1644         .indicate = skinny_indicate,
1645         .fixup = skinny_fixup,
1646         .send_digit_begin = skinny_senddigit_begin,
1647         .send_digit_end = skinny_senddigit_end,
1648         .bridge = ast_rtp_instance_bridge,
1649 };
1650
1651 static int skinny_extensionstate_cb(char *context, char *id, struct ast_state_cb_info *info, void *data);
1652 static int skinny_transfer(struct skinny_subchannel *sub);
1653
1654 static struct skinny_line *skinny_line_alloc(void)
1655 {
1656         struct skinny_line *l;
1657         if (!(l = ast_calloc(1, sizeof(*l)))) {
1658                 return NULL;
1659         }
1660
1661         l->cap = ast_format_cap_alloc_nolock();
1662         l->confcap = ast_format_cap_alloc_nolock();
1663         if (!l->cap || !l->confcap) {
1664                 l->cap = ast_format_cap_destroy(l->cap);
1665                 l->confcap = ast_format_cap_destroy(l->confcap);
1666                 ast_free(l);
1667                 return NULL;
1668         }
1669         return l;
1670 }
1671 static struct skinny_line *skinny_line_destroy(struct skinny_line *l)
1672 {
1673         l->cap = ast_format_cap_destroy(l->cap);
1674         l->confcap = ast_format_cap_destroy(l->confcap);
1675         l->named_callgroups = ast_unref_namedgroups(l->named_callgroups);
1676         l->named_pickupgroups = ast_unref_namedgroups(l->named_pickupgroups);
1677         ast_free(l->container);
1678         ast_free(l);
1679         return NULL;
1680 }
1681 static struct skinny_device *skinny_device_alloc(void)
1682 {
1683         struct skinny_device *d;
1684         if (!(d = ast_calloc(1, sizeof(*d)))) {
1685                 return NULL;
1686         }
1687
1688         d->cap = ast_format_cap_alloc_nolock();
1689         d->confcap = ast_format_cap_alloc_nolock();
1690         if (!d->cap || !d->confcap) {
1691                 d->cap = ast_format_cap_destroy(d->cap);
1692                 d->confcap = ast_format_cap_destroy(d->confcap);
1693                 ast_free(d);
1694                 return NULL;
1695         }
1696         return d;
1697 }
1698 static struct skinny_device *skinny_device_destroy(struct skinny_device *d)
1699 {
1700         d->cap = ast_format_cap_destroy(d->cap);
1701         d->confcap = ast_format_cap_destroy(d->confcap);
1702         ast_free(d);
1703         return NULL;
1704 }
1705
1706 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1707 {
1708         struct skinny_device *d = s->device;
1709         struct skinny_addon *a;
1710         int i;
1711
1712         switch (d->type) {
1713                 case SKINNY_DEVICE_30SPPLUS:
1714                 case SKINNY_DEVICE_30VIP:
1715                         /* 13 rows, 2 columns */
1716                         for (i = 0; i < 4; i++)
1717                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1718                         (btn++)->buttonDefinition = BT_REDIAL;
1719                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1720                         (btn++)->buttonDefinition = BT_CALLPARK;
1721                         (btn++)->buttonDefinition = BT_FORWARDALL;
1722                         (btn++)->buttonDefinition = BT_CONFERENCE;
1723                         for (i = 0; i < 4; i++)
1724                                 (btn++)->buttonDefinition = BT_NONE;
1725                         for (i = 0; i < 13; i++)
1726                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1727
1728                         break;
1729                 case SKINNY_DEVICE_12SPPLUS:
1730                 case SKINNY_DEVICE_12SP:
1731                 case SKINNY_DEVICE_12:
1732                         /* 6 rows, 2 columns */
1733                         for (i = 0; i < 2; i++)
1734                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1735                         for (i = 0; i < 4; i++)
1736                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1737                         (btn++)->buttonDefinition = BT_HOLD;
1738                         (btn++)->buttonDefinition = BT_REDIAL;
1739                         (btn++)->buttonDefinition = BT_TRANSFER;
1740                         (btn++)->buttonDefinition = BT_FORWARDALL;
1741                         (btn++)->buttonDefinition = BT_CALLPARK;
1742                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1743                         break;
1744                 case SKINNY_DEVICE_7910:
1745                         (btn++)->buttonDefinition = BT_LINE;
1746                         (btn++)->buttonDefinition = BT_HOLD;
1747                         (btn++)->buttonDefinition = BT_TRANSFER;
1748                         (btn++)->buttonDefinition = BT_DISPLAY;
1749                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1750                         (btn++)->buttonDefinition = BT_CONFERENCE;
1751                         (btn++)->buttonDefinition = BT_FORWARDALL;
1752                         for (i = 0; i < 2; i++)
1753                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1754                         (btn++)->buttonDefinition = BT_REDIAL;
1755                         break;
1756                 case SKINNY_DEVICE_7960:
1757                 case SKINNY_DEVICE_7961:
1758                 case SKINNY_DEVICE_7961GE:
1759                 case SKINNY_DEVICE_7962:
1760                 case SKINNY_DEVICE_7965:
1761                         for (i = 0; i < 6; i++)
1762                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1763                         break;
1764                 case SKINNY_DEVICE_7940:
1765                 case SKINNY_DEVICE_7941:
1766                 case SKINNY_DEVICE_7941GE:
1767                 case SKINNY_DEVICE_7942:
1768                 case SKINNY_DEVICE_7945:
1769                         for (i = 0; i < 2; i++)
1770                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1771                         break;
1772                 case SKINNY_DEVICE_7935:
1773                 case SKINNY_DEVICE_7936:
1774                         for (i = 0; i < 2; i++)
1775                                 (btn++)->buttonDefinition = BT_LINE;
1776                         break;
1777                 case SKINNY_DEVICE_ATA186:
1778                         (btn++)->buttonDefinition = BT_LINE;
1779                         break;
1780                 case SKINNY_DEVICE_7970:
1781                 case SKINNY_DEVICE_7971:
1782                 case SKINNY_DEVICE_7975:
1783                 case SKINNY_DEVICE_CIPC:
1784                         for (i = 0; i < 8; i++)
1785                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1786                         break;
1787                 case SKINNY_DEVICE_7985:
1788                         /* XXX I have no idea what the buttons look like on these. */
1789                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1790                         break;
1791                 case SKINNY_DEVICE_7912:
1792                 case SKINNY_DEVICE_7911:
1793                 case SKINNY_DEVICE_7905:
1794                         (btn++)->buttonDefinition = BT_LINE;
1795                         (btn++)->buttonDefinition = BT_HOLD;
1796                         break;
1797                 case SKINNY_DEVICE_7920:
1798                         /* XXX I don't know if this is right. */
1799                         for (i = 0; i < 4; i++)
1800                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1801                         break;
1802                 case SKINNY_DEVICE_7921:
1803                         for (i = 0; i < 6; i++)
1804                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1805                         break;
1806                 case SKINNY_DEVICE_7902:
1807                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1808                         break;
1809                 case SKINNY_DEVICE_7906:
1810                         ast_log(LOG_WARNING, "Unsupported device type '%d (7906)' found.\n", d->type);
1811                         break;
1812                 case SKINNY_DEVICE_7931:
1813                         ast_log(LOG_WARNING, "Unsupported device type '%d (7931)' found.\n", d->type);
1814                         break;
1815                 case SKINNY_DEVICE_7937:
1816                         ast_log(LOG_WARNING, "Unsupported device type '%d (7937)' found.\n", d->type);
1817                         break;
1818                 case SKINNY_DEVICE_7914:
1819                         ast_log(LOG_WARNING, "Unsupported device type '%d (7914)' found.  Expansion module registered by itself?\n", d->type);
1820                         break;
1821                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1822                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1823                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1824                         break;
1825                 default:
1826                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1827                         break;
1828         }
1829
1830         AST_LIST_LOCK(&d->addons);
1831         AST_LIST_TRAVERSE(&d->addons, a, list) {
1832                 if (!strcasecmp(a->type, "7914")) {
1833                         for (i = 0; i < 14; i++)
1834                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1835                 } else {
1836                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1837                 }
1838         }
1839         AST_LIST_UNLOCK(&d->addons);
1840
1841         return btn;
1842 }
1843
1844 static struct skinny_req *req_alloc(size_t size, int response_message)
1845 {
1846         struct skinny_req *req;
1847
1848         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1849                 return NULL;
1850
1851         req->len = htolel(size+4);
1852         req->e = htolel(response_message);
1853
1854         return req;
1855 }
1856
1857 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1858 {
1859         struct skinny_line *l;
1860
1861         /*Dialing from on hook or on a 7920 uses instance 0 in requests
1862           but we need to start looking at instance 1 */
1863
1864         if (!instance)
1865                 instance = 1;
1866
1867         AST_LIST_TRAVERSE(&d->lines, l, list){
1868                 if (l->instance == instance)
1869                         break;
1870         }
1871
1872         if (!l) {
1873                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1874         }
1875         return l;
1876 }
1877
1878 static struct skinny_line *find_line_by_name(const char *dest)
1879 {
1880         struct skinny_line *l;
1881         struct skinny_line *tmpl = NULL;
1882         struct skinny_device *d;
1883         char line[256];
1884         char *at;
1885         char *device;
1886         int checkdevice = 0;
1887
1888         ast_copy_string(line, dest, sizeof(line));
1889         at = strchr(line, '@');
1890         if (at)
1891                 *at++ = '\0';
1892         device = at;
1893
1894         if (!ast_strlen_zero(device))
1895                 checkdevice = 1;
1896
1897         AST_LIST_LOCK(&devices);
1898         AST_LIST_TRAVERSE(&devices, d, list){
1899                 if (checkdevice && tmpl)
1900                         break;
1901                 else if (!checkdevice) {
1902                         /* This is a match, since we're checking for line on every device. */
1903                 } else if (!strcasecmp(d->name, device)) {
1904                 } else
1905                         continue;
1906
1907                 /* Found the device (or we don't care which device) */
1908                 AST_LIST_TRAVERSE(&d->lines, l, list){
1909                         /* Search for the right line */
1910                         if (!strcasecmp(l->name, line)) {
1911                                 if (tmpl) {
1912                                         ast_log(LOG_WARNING, "Ambiguous line name: %s\n", line);
1913                                         AST_LIST_UNLOCK(&devices);
1914                                         return NULL;
1915                                 } else
1916                                         tmpl = l;
1917                         }
1918                 }
1919         }
1920         AST_LIST_UNLOCK(&devices);
1921         return tmpl;
1922 }
1923
1924 static struct skinny_subline *find_subline_by_name(const char *dest)
1925 {
1926         struct skinny_line *l;
1927         struct skinny_subline *subline;
1928         struct skinny_subline *tmpsubline = NULL;
1929         struct skinny_device *d;
1930
1931         AST_LIST_LOCK(&devices);
1932         AST_LIST_TRAVERSE(&devices, d, list){
1933                 AST_LIST_TRAVERSE(&d->lines, l, list){
1934                         AST_LIST_TRAVERSE(&l->sublines, subline, list){
1935                                 if (!strcasecmp(subline->name, dest)) {
1936                                         if (tmpsubline) {
1937                                                 ast_verb(2, "Ambiguous subline name: %s\n", dest);
1938                                                 AST_LIST_UNLOCK(&devices);
1939                                                 return NULL;
1940                                         } else
1941                                                 tmpsubline = subline;
1942                                 }
1943                         }
1944                 }
1945         }
1946         AST_LIST_UNLOCK(&devices);
1947         return tmpsubline;
1948 }
1949
1950 static struct skinny_subline *find_subline_by_callid(struct skinny_device *d, int callid)
1951 {
1952         struct skinny_subline *subline;
1953         struct skinny_line *l;
1954
1955         AST_LIST_TRAVERSE(&d->lines, l, list){
1956                 AST_LIST_TRAVERSE(&l->sublines, subline, list){
1957                         if (subline->callid == callid) {
1958                                 return subline;
1959                         }
1960                 }
1961         }
1962         return NULL;
1963 }
1964
1965 /*!
1966  * implement the setvar config line
1967  */
1968 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
1969 {
1970         struct ast_variable *tmpvar = NULL;
1971         char *varname = ast_strdupa(buf), *varval = NULL;
1972
1973         if ((varval = strchr(varname,'='))) {
1974                 *varval++ = '\0';
1975                 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
1976                         tmpvar->next = list;
1977                         list = tmpvar;
1978                 }
1979         }
1980         return list;
1981 }
1982
1983 static int skinny_sched_del(int sched_id, struct skinny_subchannel *sub)
1984 {
1985         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Deleting SCHED %d\n",
1986                 sub->callid, sched_id);
1987         return ast_sched_del(sched, sched_id);
1988 }
1989
1990 static int skinny_sched_add(int when, ast_sched_cb callback, struct skinny_subchannel *sub)
1991 {
1992         int ret;
1993         ret = ast_sched_add(sched, when, callback, sub);
1994         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Added SCHED %d\n",
1995                 sub->callid, ret);
1996         return ret;
1997 }
1998
1999 /* It's quicker/easier to find the subchannel when we know the instance number too */
2000 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
2001 {
2002         struct skinny_line *l = find_line_by_instance(d, instance);
2003         struct skinny_subchannel *sub;
2004
2005         if (!l) {
2006                 return NULL;
2007         }
2008
2009         /* 7920 phones set call reference to 0, so use the first
2010            sub-channel on the list.
2011            This MIGHT need more love to be right */
2012         if (!reference)
2013                 sub = AST_LIST_FIRST(&l->sub);
2014         else {
2015                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
2016                         if (sub->callid == reference)
2017                                 break;
2018                 }
2019         }
2020         if (!sub) {
2021                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
2022         }
2023         return sub;
2024 }
2025
2026 /* Find the subchannel when we only have the callid - this shouldn't happen often */
2027 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
2028 {
2029         struct skinny_line *l;
2030         struct skinny_subchannel *sub = NULL;
2031
2032         AST_LIST_TRAVERSE(&d->lines, l, list){
2033                 AST_LIST_TRAVERSE(&l->sub, sub, list){
2034                         if (sub->callid == reference)
2035                                 break;
2036                 }
2037                 if (sub)
2038                         break;
2039         }
2040
2041         if (!l) {
2042                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
2043         } else {
2044                 if (!sub) {
2045                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
2046                 }
2047         }
2048         return sub;
2049 }
2050
2051 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
2052 {
2053         struct skinny_speeddial *sd;
2054
2055         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2056                 if (sd->isHint == isHint && sd->instance == instance)
2057                         break;
2058         }
2059
2060         if (!sd) {
2061                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
2062         }
2063         return sd;
2064 }
2065
2066 static struct ast_format *codec_skinny2ast(enum skinny_codecs skinnycodec, struct ast_format *result)
2067 {
2068         switch (skinnycodec) {
2069         case SKINNY_CODEC_ALAW:
2070                 return ast_format_set(result, AST_FORMAT_ALAW, 0);
2071         case SKINNY_CODEC_ULAW:
2072                 return ast_format_set(result, AST_FORMAT_ULAW, 0);
2073         case SKINNY_CODEC_G722:
2074                 return ast_format_set(result, AST_FORMAT_G722, 0);
2075         case SKINNY_CODEC_G723_1:
2076                 return ast_format_set(result, AST_FORMAT_G723_1, 0);
2077         case SKINNY_CODEC_G729A:
2078                 return ast_format_set(result, AST_FORMAT_G729A, 0);
2079         case SKINNY_CODEC_G726_32:
2080                 return ast_format_set(result, AST_FORMAT_G726_AAL2, 0); /* XXX Is this right? */
2081         case SKINNY_CODEC_H261:
2082                 return ast_format_set(result, AST_FORMAT_H261, 0);
2083         case SKINNY_CODEC_H263:
2084                 return ast_format_set(result, AST_FORMAT_H263 ,0);
2085         default:
2086                 ast_format_clear(result);
2087                 return result;
2088         }
2089 }
2090
2091 static int codec_ast2skinny(const struct ast_format *astcodec)
2092 {
2093         switch (astcodec->id) {
2094         case AST_FORMAT_ALAW:
2095                 return SKINNY_CODEC_ALAW;
2096         case AST_FORMAT_ULAW:
2097                 return SKINNY_CODEC_ULAW;
2098         case AST_FORMAT_G722:
2099                 return SKINNY_CODEC_G722;
2100         case AST_FORMAT_G723_1:
2101                 return SKINNY_CODEC_G723_1;
2102         case AST_FORMAT_G729A:
2103                 return SKINNY_CODEC_G729A;
2104         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
2105                 return SKINNY_CODEC_G726_32;
2106         case AST_FORMAT_H261:
2107                 return SKINNY_CODEC_H261;
2108         case AST_FORMAT_H263:
2109                 return SKINNY_CODEC_H263;
2110         default:
2111                 return 0;
2112         }
2113 }
2114
2115 static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
2116 {
2117         if (!l)
2118                 return 0;
2119
2120         if (!ast_strlen_zero(cfwd)) {
2121                 if (cfwdtype & SKINNY_CFWD_ALL) {
2122                         l->cfwdtype |= SKINNY_CFWD_ALL;
2123                         ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
2124                 }
2125                 if (cfwdtype & SKINNY_CFWD_BUSY) {
2126                         l->cfwdtype |= SKINNY_CFWD_BUSY;
2127                         ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
2128                 }
2129                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2130                         l->cfwdtype |= SKINNY_CFWD_NOANSWER;
2131                         ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
2132                 }
2133         } else {
2134                 if (cfwdtype & SKINNY_CFWD_ALL) {
2135                         l->cfwdtype &= ~SKINNY_CFWD_ALL;
2136                         memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
2137                 }
2138                 if (cfwdtype & SKINNY_CFWD_BUSY) {
2139                         l->cfwdtype &= ~SKINNY_CFWD_BUSY;
2140                         memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
2141                 }
2142                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2143                         l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
2144                         memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
2145                 }
2146         }
2147         return l->cfwdtype;
2148 }
2149
2150 static void cleanup_stale_contexts(char *new, char *old)
2151 {
2152         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
2153
2154         while ((oldcontext = strsep(&old, "&"))) {
2155                 stalecontext = '\0';
2156                 ast_copy_string(newlist, new, sizeof(newlist));
2157                 stringp = newlist;
2158                 while ((newcontext = strsep(&stringp, "&"))) {
2159                         if (strcmp(newcontext, oldcontext) == 0) {
2160                                 /* This is not the context you're looking for */
2161                                 stalecontext = '\0';
2162                                 break;
2163                         } else if (strcmp(newcontext, oldcontext)) {
2164                                 stalecontext = oldcontext;
2165                         }
2166
2167                 }
2168                 if (stalecontext)
2169                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
2170         }
2171 }
2172
2173 static void register_exten(struct skinny_line *l)
2174 {
2175         char multi[256];
2176         char *stringp, *ext, *context;
2177
2178         if (ast_strlen_zero(regcontext))
2179                 return;
2180
2181         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2182         stringp = multi;
2183         while ((ext = strsep(&stringp, "&"))) {
2184                 if ((context = strchr(ext, '@'))) {
2185                         *context++ = '\0'; /* split ext@context */
2186                         if (!ast_context_find(context)) {
2187                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2188                                 continue;
2189                         }
2190                 } else {
2191                         context = regcontext;
2192                 }
2193                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2194                          ast_strdup(l->name), ast_free_ptr, "Skinny");
2195         }
2196 }
2197
2198 static void unregister_exten(struct skinny_line *l)
2199 {
2200         char multi[256];
2201         char *stringp, *ext, *context;
2202
2203         if (ast_strlen_zero(regcontext))
2204                 return;
2205
2206         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2207         stringp = multi;
2208         while ((ext = strsep(&stringp, "&"))) {
2209                 if ((context = strchr(ext, '@'))) {
2210                         *context++ = '\0'; /* split ext@context */
2211                         if (!ast_context_find(context)) {
2212                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2213                                 continue;
2214                         }
2215                 } else {
2216                         context = regcontext;
2217                 }
2218                 ast_context_remove_extension(context, ext, 1, NULL);
2219         }
2220 }
2221
2222 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
2223 {
2224         struct skinny_device *d;
2225         struct skinny_line *l;
2226         struct skinny_subline *subline;
2227         struct skinny_speeddial *sd;
2228         struct sockaddr_in sin;
2229         socklen_t slen;
2230         int instance;
2231
2232         AST_LIST_LOCK(&devices);
2233         AST_LIST_TRAVERSE(&devices, d, list){
2234                 struct ast_sockaddr addr;
2235                 ast_sockaddr_from_sin(&addr, &s->sin);
2236                 if (!d->session && !strcasecmp(req->data.reg.name, d->id)
2237                                 && ast_apply_ha(d->ha, &addr)) {
2238                         s->device = d;
2239                         d->type = letohl(req->data.reg.type);
2240                         d->protocolversion = letohl(req->data.reg.protocolVersion);
2241                         if (ast_strlen_zero(d->version_id)) {
2242                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
2243                         }
2244                         d->session = s;
2245
2246                         slen = sizeof(sin);
2247                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
2248                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
2249                                 sin.sin_addr = __ourip;
2250                         }
2251                         d->ourip = sin.sin_addr;
2252
2253                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2254                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd->container);
2255                         }
2256                         instance = 0;
2257                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2258                                 instance++;
2259                         }
2260                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2261                                 ast_format_cap_joint_copy(l->confcap, d->cap, l->cap);
2262                                 l->prefs = l->confprefs;
2263                                 if (!l->prefs.order[0]) {
2264                                         l->prefs = d->confprefs;
2265                                 }
2266                                 /* l->capability = d->capability;
2267                                 l->prefs = d->prefs; */
2268                                 l->instance = instance;
2269                                 l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
2270                                 set_callforwards(l, NULL, SKINNY_CFWD_ALL|SKINNY_CFWD_BUSY|SKINNY_CFWD_NOANSWER);
2271                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Registered\r\n", l->name, d->name);
2272                                 register_exten(l);
2273                                 /* initialize MWI on line and device */
2274                                 mwi_event_cb(l, NULL, NULL, NULL);
2275                                 AST_LIST_TRAVERSE(&l->sublines, subline, list) {
2276                                         ast_extension_state_add(subline->context, subline->exten, skinny_extensionstate_cb, subline->container);
2277                                 }
2278                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
2279                                 --instance;
2280                         }
2281                         break;
2282                 }
2283         }
2284         AST_LIST_UNLOCK(&devices);
2285         if (!d) {
2286                 return 0;
2287         }
2288         return 1;
2289 }
2290
2291 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
2292 {
2293         struct skinny_device *d;
2294         struct skinny_line *l;
2295         struct skinny_speeddial *sd;
2296
2297         d = s->device;
2298
2299         if (d) {
2300                 d->session = NULL;
2301
2302                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2303                         if (sd->stateid > -1)
2304                                 ast_extension_state_del(sd->stateid, NULL);
2305                 }
2306                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2307                         if (l->device == d) {
2308                                 ast_format_cap_remove_all(l->cap);
2309                                 ast_parse_allow_disallow(&l->prefs, l->cap, "all", 0);
2310                                 l->instance = 0;
2311                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Unregistered\r\n", l->name, d->name);
2312                                 unregister_exten(l);
2313                                 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
2314                         }
2315                 }
2316         }
2317
2318         return -1; /* main loop will destroy the session */
2319 }
2320
2321 #ifdef AST_DEVMODE
2322 static char *callstate2str(int ind)
2323 {
2324         char *tmp;
2325
2326         switch (ind) {
2327         case SKINNY_OFFHOOK:
2328                 return "SKINNY_OFFHOOK";
2329         case SKINNY_ONHOOK:
2330                 return "SKINNY_ONHOOK";
2331         case SKINNY_RINGOUT:
2332                 return "SKINNY_RINGOUT";
2333         case SKINNY_RINGIN:
2334                 return "SKINNY_RINGIN";
2335         case SKINNY_CONNECTED:
2336                 return "SKINNY_CONNECTED";
2337         case SKINNY_BUSY:
2338                 return "SKINNY_BUSY";
2339         case SKINNY_CONGESTION:
2340                 return "SKINNY_CONGESTION";
2341         case SKINNY_PROGRESS:
2342                 return "SKINNY_PROGRESS";
2343         case SKINNY_HOLD:
2344                 return "SKINNY_HOLD";
2345         case SKINNY_CALLWAIT:
2346                 return "SKINNY_CALLWAIT";
2347         default:
2348                 if (!(tmp = ast_threadstorage_get(&callstate2str_threadbuf, CALLSTATE2STR_BUFSIZE)))
2349                         return "Unknown";
2350                 snprintf(tmp, CALLSTATE2STR_BUFSIZE, "UNKNOWN-%d", ind);
2351                 return tmp;
2352         }
2353 }
2354
2355 #endif
2356
2357 static int transmit_response_bysession(struct skinnysession *s, struct skinny_req *req)
2358 {
2359         int res = 0;
2360
2361         if (!s) {
2362                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2363                 return -1;
2364         }
2365
2366         ast_mutex_lock(&s->lock);
2367
2368         if ((letohl(req->len) > SKINNY_MAX_PACKET) || (letohl(req->len) < 0)) {
2369                 ast_log(LOG_WARNING, "transmit_response: the length of the request (%d) is out of bounds (%d)\n", letohl(req->len), SKINNY_MAX_PACKET);
2370                 ast_mutex_unlock(&s->lock);
2371                 return -1;
2372         }
2373
2374         memset(s->outbuf, 0, sizeof(s->outbuf));
2375         memcpy(s->outbuf, req, skinny_header_size);
2376         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2377
2378         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2379
2380         if (res != letohl(req->len)+8) {
2381                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2382                 if (res == -1) {
2383                         ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2384                         skinny_unregister(NULL, s);
2385                 }
2386
2387         }
2388
2389         ast_free(req);
2390         ast_mutex_unlock(&s->lock);
2391         return 1;
2392 }
2393
2394 static void transmit_response(struct skinny_device *d, struct skinny_req *req)
2395 {
2396         transmit_response_bysession(d->session, req);
2397 }
2398
2399 static void transmit_registerrej(struct skinnysession *s)
2400 {
2401         struct skinny_req *req;
2402         char name[16];
2403
2404         if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
2405                 return;
2406
2407         memcpy(&name, req->data.reg.name, sizeof(name));
2408         snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2409
2410         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_REJ_MESSAGE to UNKNOWN_DEVICE\n");
2411         transmit_response_bysession(s, req);
2412 }
2413
2414 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2415 {
2416         struct skinny_req *req;
2417
2418         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2419                 return;
2420
2421         req->data.setspeaker.mode = htolel(mode);
2422
2423         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_SPEAKER_MESSAGE to %s, mode %d\n", d->name, mode);
2424         transmit_response(d, req);
2425 }
2426
2427 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2428 {
2429         struct skinny_req *req;
2430
2431         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2432                 return;
2433
2434         req->data.setmicrophone.mode = htolel(mode);
2435
2436         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_MICROPHONE_MESSAGE to %s, mode %d\n", d->name, mode);
2437         transmit_response(d, req);
2438 }
2439
2440 //static void transmit_callinfo(struct skinny_subchannel *sub)
2441 static void transmit_callinfo(struct skinny_device *d, int instance, int callid,
2442         char *fromname, char *fromnum, char *toname, char *tonum, int calldirection, char *origtonum, char *origtoname)
2443 {
2444         struct skinny_req *req;
2445
2446         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2447                 return;
2448
2449         ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2450         ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2451         ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2452         ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2453         if (origtoname) {
2454                 ast_copy_string(req->data.callinfo.originalCalledPartyName, origtoname, sizeof(req->data.callinfo.originalCalledPartyName));
2455         }
2456         if (origtonum) {
2457                 ast_copy_string(req->data.callinfo.originalCalledParty, origtonum, sizeof(req->data.callinfo.originalCalledParty));
2458         }
2459
2460         req->data.callinfo.instance = htolel(instance);
2461         req->data.callinfo.reference = htolel(callid);
2462         req->data.callinfo.type = htolel(calldirection);
2463
2464         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_INFO_MESSAGE to %s, to %s(%s) from %s(%s), origto %s(%s) (dir=%d) on %s(%d)\n",
2465                 d->name, toname, tonum, fromname, fromnum, origtoname, origtonum, calldirection, d->name, instance);
2466         transmit_response(d, req);
2467 }
2468
2469 static void transmit_callinfo_variable(struct skinny_device *d, int instance, int callreference,
2470         char *fromname, char *fromnum, char *toname, char *tonum, int calldirection, char *origtonum, char *origtoname)
2471 {
2472         struct skinny_req *req;
2473         char *strptr;
2474         char *thestrings[13];
2475         int i;
2476         int callinfostrleft = MAXCALLINFOSTR;
2477
2478         if (!(req = req_alloc(sizeof(struct call_info_message_variable), CALL_INFO_MESSAGE_VARIABLE)))
2479                 return;
2480
2481         req->data.callinfomessagevariable.instance = htolel(instance);
2482         req->data.callinfomessagevariable.callreference = htolel(callreference);
2483         req->data.callinfomessagevariable.calldirection = htolel(calldirection);
2484
2485         req->data.callinfomessagevariable.unknown1 = htolel(0x00);
2486         req->data.callinfomessagevariable.unknown2 = htolel(0x00);
2487         req->data.callinfomessagevariable.unknown3 = htolel(0x00);
2488         req->data.callinfomessagevariable.unknown4 = htolel(0x00);
2489         req->data.callinfomessagevariable.unknown5 = htolel(0x00);
2490
2491         thestrings[0] = fromnum;
2492         thestrings[1] = "";                     /* Appears to be origfrom */
2493         if (calldirection == SKINNY_OUTGOING) {
2494                 thestrings[2] = tonum;
2495                 thestrings[3] = origtonum;
2496         } else {
2497                 thestrings[2] = "";
2498                 thestrings[3] = "";
2499         }
2500         thestrings[4] = "";
2501         thestrings[5] = "";
2502         thestrings[6] = "";
2503         thestrings[7] = "";
2504
2505         thestrings[8] = "";
2506         thestrings[9] = fromname;
2507         thestrings[10] = toname;
2508         thestrings[11] = origtoname;
2509         thestrings[12] = "";
2510
2511         strptr = req->data.callinfomessagevariable.calldetails;
2512
2513         for(i = 0; i < 13; i++) {
2514                 if (thestrings[i]) {
2515                         ast_copy_string(strptr, thestrings[i], callinfostrleft);
2516                         strptr += strlen(thestrings[i]) + 1;
2517                         callinfostrleft -= strlen(thestrings[i]) + 1;
2518                 } else {
2519                         ast_copy_string(strptr, "", callinfostrleft);
2520                         strptr++;
2521                         callinfostrleft--;
2522                 }
2523         }
2524
2525         req->len = req->len - (callinfostrleft & ~0x3);
2526
2527         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_INFO_MESSAGE_VARIABLE to %s, to %s(%s) from %s(%s), origto %s(%s) (dir=%d) on %s(%d)\n",
2528                 d->name, toname, tonum, fromname, fromnum, origtoname, origtonum, calldirection, d->name, instance);
2529         transmit_response(d, req);
2530 }
2531
2532 static void send_callinfo(struct skinny_subchannel *sub)
2533 {
2534         struct ast_channel *ast;
2535         struct skinny_device *d;
2536         struct skinny_line *l;
2537         struct ast_party_id connected_id;
2538         char *fromname;
2539         char *fromnum;
2540         char *toname;
2541         char *tonum;
2542
2543         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2544                 return;
2545         }
2546
2547         ast = sub->owner;
2548         l = sub->line;
2549         d = l->device;
2550         connected_id = ast_channel_connected_effective_id(ast);
2551
2552         if (sub->calldirection == SKINNY_INCOMING) {
2553                 if ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
2554                         fromname = S_COR(connected_id.name.valid, connected_id.name.str, "");
2555                         fromnum = S_COR(connected_id.number.valid, connected_id.number.str, "");
2556                 } else {
2557                         fromname = "";
2558                         fromnum = "";
2559                 }
2560                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2561                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2562         } else if (sub->calldirection == SKINNY_OUTGOING) {
2563                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2564                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2565                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2566                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2567         } else {
2568                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2569                 return;
2570         }
2571
2572         if (d->protocolversion < 17) {
2573                 transmit_callinfo(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
2574         } else {
2575                 transmit_callinfo_variable(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
2576         }
2577 }
2578
2579 static void push_callinfo(struct skinny_subline *subline, struct skinny_subchannel *sub)
2580 {
2581         struct ast_channel *ast;
2582         struct skinny_device *d;
2583         struct skinny_line *l;
2584         struct ast_party_id connected_id;
2585         char *fromname;
2586         char *fromnum;
2587         char *toname;
2588         char *tonum;
2589
2590         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2591                 return;
2592         }
2593
2594         ast = sub->owner;
2595         l = sub->line;
2596         d = l->device;
2597         connected_id = ast_channel_connected_effective_id(ast);
2598
2599         if (sub->calldirection == SKINNY_INCOMING) {
2600                 if((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
2601                         fromname = S_COR(connected_id.name.valid, connected_id.name.str, "");
2602                         fromnum = S_COR(connected_id.number.valid, connected_id.number.str, "");
2603                 } else {
2604                         fromname = "";
2605                         fromnum = "";
2606                 }
2607                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2608                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2609         } else if (sub->calldirection == SKINNY_OUTGOING) {
2610                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2611                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2612                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2613                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2614         } else {
2615                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2616                 return;
2617         }
2618
2619         if (d->protocolversion < 17) {
2620                 transmit_callinfo(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
2621         } else {
2622                 transmit_callinfo_variable(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
2623         }
2624 }
2625
2626 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2627 {
2628         struct skinny_req *req;
2629         struct skinny_line *l = sub->line;
2630         struct ast_format_list fmt;
2631         struct ast_format tmpfmt;
2632
2633         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2634                 return;
2635         ast_best_codec(l->cap, &tmpfmt);
2636         fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
2637
2638         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2639         req->data.openreceivechannel.partyId = htolel(sub->callid);
2640         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2641         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(&fmt.format));
2642         req->data.openreceivechannel.echo = htolel(0);
2643         req->data.openreceivechannel.bitrate = htolel(0);
2644
2645         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting OPEN_RECEIVE_CHANNEL_MESSAGE to %s, confid %d, partyid %d, ms %d, fmt %d, echo %d, brate %d\n",
2646                 d->name, sub->callid, sub->callid, fmt.cur_ms, codec_ast2skinny(&fmt.format), 0, 0);
2647         transmit_response(d, req);
2648 }
2649
2650 static void transmit_start_tone(struct skinny_device *d, int tone, int instance, int reference)
2651 {
2652         struct skinny_req *req;
2653         if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2654                 return;
2655         req->data.starttone.tone = htolel(tone);
2656         req->data.starttone.instance = htolel(instance);
2657         req->data.starttone.reference = htolel(reference);
2658
2659         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting START_TONE_MESSAGE to %s, tone %d, inst %d, ref %d\n",
2660                 d->name, tone, instance, reference);
2661         transmit_response(d, req);
2662 }
2663
2664 static void transmit_stop_tone(struct skinny_device *d, int instance, int reference)
2665 {
2666         struct skinny_req *req;
2667         if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2668                 return;
2669         req->data.stoptone.instance = htolel(instance);
2670         req->data.stoptone.reference = htolel(reference);
2671
2672         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_TONE_MESSAGE to %s, inst %d, ref %d\n",
2673                 d->name, instance, reference);
2674         transmit_response(d, req);
2675 }
2676
2677 static int keyset_translatebitmask(int keyset, int intmask)
2678 {
2679         int extmask = 0;
2680         int x, y;
2681         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
2682
2683         for(x = 0; x < ARRAY_LEN(soft_key_default_definitions); x++) {
2684                 if (softkeymode[x].mode == keyset) {
2685                         const uint8_t *defaults = softkeymode[x].defaults;
2686
2687                         for (y = 0; y < softkeymode[x].count; y++) {
2688                                 if (intmask & (1 << (defaults[y]))) {
2689                                         extmask |= (1 << ((y)));
2690                                 }
2691                         }
2692                         break;
2693                 }
2694         }
2695
2696         return extmask;
2697 }
2698
2699 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey, int mask)
2700 {
2701         struct skinny_req *req;
2702         int newmask;
2703
2704         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2705                 return;
2706
2707         newmask = keyset_translatebitmask(softkey, mask);
2708         req->data.selectsoftkey.instance = htolel(instance);
2709         req->data.selectsoftkey.reference = htolel(callid);
2710         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2711         req->data.selectsoftkey.validKeyMask = htolel(newmask);
2712
2713         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SELECT_SOFT_KEYS_MESSAGE to %s, inst %d, callid %d, softkey %d, mask 0x%08x\n",
2714                 d->name, instance, callid, softkey, newmask);
2715         transmit_response(d, req);
2716 }
2717
2718 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2719 {
2720         struct skinny_req *req;
2721
2722         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2723                 return;
2724
2725         req->data.setlamp.stimulus = htolel(stimulus);
2726         req->data.setlamp.stimulusInstance = htolel(instance);
2727         req->data.setlamp.deviceStimulus = htolel(indication);
2728
2729         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_LAMP_MESSAGE to %s, stim %d, inst %d, ind %d\n",
2730                 d->name, stimulus, instance, indication);
2731         transmit_response(d, req);
2732 }
2733
2734 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2735 {
2736         struct skinny_req *req;
2737
2738         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2739                 return;
2740
2741         req->data.setringer.ringerMode = htolel(mode);
2742         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2743            Note: The phone will always show as ringing on the display.
2744
2745            1: phone will audibly ring over and over
2746            2: phone will audibly ring only once
2747            any other value, will NOT cause the phone to audibly ring
2748         */
2749         req->data.setringer.unknown1 = htolel(1);
2750         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2751            Perhaps a packet capture can shed some light on this. */
2752         req->data.setringer.unknown2 = htolel(1);
2753
2754         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_RINGER_MESSAGE to %s, mode %d, unk1 1, unk2 1\n",
2755                 d->name, mode);
2756         transmit_response(d, req);
2757 }
2758
2759 static void transmit_clear_display_message(struct skinny_device *d, int instance, int reference)
2760 {
2761         struct skinny_req *req;
2762         if (!(req = req_alloc(sizeof(struct clear_display_message), CLEAR_DISPLAY_MESSAGE)))
2763                 return;
2764
2765         //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2766         //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2767         //req->data.clearpromptstatus.lineInstance = instance;
2768         //req->data.clearpromptstatus.callReference = reference;
2769
2770         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_DISPLAY_MESSAGE to %s\n", d->name);
2771         transmit_response(d, req);
2772 }
2773
2774 /* This function is not currently used, but will be (wedhorn)*/
2775 /* static void transmit_display_message(struct skinny_device *d, const char *text, int instance, int reference)
2776 {
2777         struct skinny_req *req;
2778
2779         if (text == 0) {
2780                 ast_verb(1, "Bug, Asked to display empty message\n");
2781                 return;
2782         }
2783
2784         if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2785                 return;
2786
2787         ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2788         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAYTEXT_MESSAGE to %s, text %s\n", d->name, text);
2789         transmit_response(d, req);
2790 } */
2791
2792 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2793 {
2794         struct skinny_req *req;
2795
2796         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2797                 return;
2798
2799         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2800         req->data.displaynotify.displayTimeout = htolel(t);
2801
2802         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_NOTIFY_MESSAGE to %s, text %s\n", d->name, text);
2803         transmit_response(d, req);
2804 }
2805
2806 static void transmit_clearprinotify(struct skinny_device *d, int priority)
2807 {
2808         struct skinny_req *req;
2809
2810         if (!(req = req_alloc(sizeof(struct clear_prinotify_message), CLEAR_PRINOTIFY_MESSAGE)))
2811                 return;
2812
2813         req->data.clearprinotify.priority = htolel(priority);
2814
2815         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_PRINOTIFY_MESSAGE to %s, priority %d\n", d->name, priority);
2816         transmit_response(d, req);
2817 }
2818
2819 static void _transmit_displayprinotify(struct skinny_device *d, const char *text, const char *extratext, int timeout, int priority)
2820 {
2821         struct skinny_req *req;
2822
2823         if (!(req = req_alloc(sizeof(struct display_prinotify_message), DISPLAY_PRINOTIFY_MESSAGE)))
2824                 return;
2825
2826         req->data.displayprinotify.timeout = htolel(timeout);
2827         req->data.displayprinotify.priority = htolel(priority);
2828
2829         if ((char)*text == '\200') {
2830                 int octalstrlen = strlen(text);
2831                 ast_copy_string(req->data.displayprinotify.text, text, sizeof(req->data.displayprinotify.text));
2832                 ast_copy_string(req->data.displayprinotify.text+octalstrlen, extratext, sizeof(req->data.displayprinotify.text)-octalstrlen);
2833                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE to %s, '\\%03o\\%03o', '%s', timeout=%d, priority=%d\n",
2834                         d->name, (uint8_t)*text, (uint8_t)*(text+1), extratext, timeout, priority);
2835         } else {
2836                 ast_copy_string(req->data.displayprinotify.text, text, sizeof(req->data.displayprinotify.text));
2837                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE to %s, '%s', timeout=%d, priority=%d\n",
2838                         d->name, text, timeout, priority);
2839         }
2840
2841         transmit_response(d, req);
2842 }
2843
2844 static void _transmit_displayprinotifyvar(struct skinny_device *d, const char *text, const char *extratext, int timeout, int priority)
2845 {
2846         struct skinny_req *req;
2847         int packetlen;
2848
2849         if (!(req = req_alloc(sizeof(struct display_prinotify_message_variable), DISPLAY_PRINOTIFY_MESSAGE_VARIABLE)))
2850                 return;
2851
2852         req->data.displayprinotifyvar.timeout = htolel(timeout);
2853         req->data.displayprinotifyvar.priority = htolel(priority);
2854
2855         if ((char)*text == '\200') {
2856                 int octalstrlen = strlen(text);
2857                 ast_copy_string(req->data.displayprinotifyvar.text, text, sizeof(req->data.displayprinotifyvar.text));
2858                 ast_copy_string(req->data.displayprinotifyvar.text+octalstrlen, extratext, sizeof(req->data.displayprinotifyvar.text)-octalstrlen);
2859                 packetlen = req->len - MAXDISPLAYNOTIFYSTR + strlen(text) + strlen(extratext);
2860                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE_VARIABLE to %s, '\\%03o\\%03o', '%s', timeout=%d, priority=%d\n",
2861                         d->name, (uint8_t)*text, (uint8_t)*(text+1), extratext, timeout, priority);
2862         } else {
2863                 ast_copy_string(req->data.displayprinotifyvar.text, text, sizeof(req->data.displayprinotifyvar.text));
2864                 packetlen = req->len - MAXDISPLAYNOTIFYSTR + strlen(text);
2865                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE_VARIABLE to %s, '%s', timeout=%d, priority=%d\n",
2866                         d->name, text, timeout, priority);
2867         }
2868         
2869         req->len = (packetlen & ~0x3) + 4;
2870
2871         transmit_response(d, req);
2872 }
2873
2874 static void send_displayprinotify(struct skinny_device *d, const char *text, const char *extratext, int timeout, int priority)
2875 {
2876         if (d->protocolversion < 17) {
2877                 _transmit_displayprinotify(d, text, extratext, timeout, priority);
2878         } else {
2879                 _transmit_displayprinotifyvar(d, text, extratext, timeout, priority);
2880         }
2881 }
2882
2883 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, const char *extratext, int t, int instance, int callid)
2884 {
2885         struct skinny_req *req;
2886
2887         if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2888                 return;
2889
2890         req->data.displaypromptstatus.messageTimeout = htolel(t);
2891         req->data.displaypromptstatus.lineInstance = htolel(instance);
2892         req->data.displaypromptstatus.callReference = htolel(callid);
2893
2894         if ((char)*text == '\200') {
2895                 int octalstrlen = strlen(text);
2896                 ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatusvar.promptMessage));
2897                 ast_copy_string(req->data.displaypromptstatus.promptMessage+octalstrlen, extratext, sizeof(req->data.displaypromptstatus.promptMessage)-octalstrlen);
2898                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE to %s, '\\%03o\\%03o', '%s'\n",
2899                         d->name, (uint8_t)*text, (uint8_t)*(text+1), extratext);
2900         } else {
2901                 ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2902                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE to %s, '%s'\n",
2903                         d->name, text);
2904         }
2905         transmit_response(d, req);
2906 }
2907
2908 static void transmit_displaypromptstatusvar(struct skinny_device *d, const char *text, const char *extratext, int t, int instance, int callid)
2909 {
2910         struct skinny_req *req;
2911         int packetlen;
2912
2913         if (!(req = req_alloc(sizeof(struct display_prompt_status_message_variable), DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE)))
2914                 return;
2915
2916         req->data.displaypromptstatusvar.lineInstance = htolel(instance);
2917         req->data.displaypromptstatusvar.callReference = htolel(callid);
2918
2919         if ((char)*text == '\200') {
2920                 int octalstrlen = strlen(text);
2921                 ast_copy_string(req->data.displaypromptstatusvar.promptMessage, text, sizeof(req->data.displaypromptstatusvar.promptMessage));
2922                 ast_copy_string(req->data.displaypromptstatusvar.promptMessage+octalstrlen, extratext, sizeof(req->data.displaypromptstatusvar.promptMessage)-octalstrlen);
2923                 packetlen = req->len - MAXCALLINFOSTR + strlen(text) + strlen(extratext);
2924                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE to %s, '\\%03o\\%03o', '%s'\n",
2925                         d->name, (uint8_t)*text, (uint8_t)*(text+1), extratext);
2926         } else {
2927                 ast_copy_string(req->data.displaypromptstatusvar.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2928                 packetlen = req->len - MAXCALLINFOSTR + strlen(text);
2929                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE to %s, '%s'\n",
2930                         d->name, text);
2931         }
2932         req->len = (packetlen & ~0x3) + 4;
2933
2934         transmit_response(d, req);
2935 }
2936
2937 static void send_displaypromptstatus(struct skinny_device *d, const char *text, const char *extratext, int t, int instance, int callid)
2938 {
2939         if (d->protocolversion < 17) {
2940                 transmit_displaypromptstatus(d, text, extratext, t, instance, callid);
2941         } else {
2942                 transmit_displaypromptstatusvar(d, text, extratext, t, instance, callid);
2943         }
2944 }
2945
2946 static void transmit_clearpromptmessage(struct skinny_device *d, int instance, int callid)
2947 {
2948         struct skinny_req *req;
2949
2950         if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2951                 return;
2952
2953         req->data.clearpromptstatus.lineInstance = htolel(instance);
2954         req->data.clearpromptstatus.callReference = htolel(callid);
2955
2956         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_PROMPT_MESSAGE to %s, inst %d, callid %d\n",
2957                 d->name, instance, callid);
2958         transmit_response(d, req);
2959 }
2960
2961 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2962 {
2963         struct skinny_req *req;
2964
2965         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2966                 return;
2967
2968         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2969         req->data.dialednumber.lineInstance = htolel(instance);
2970         req->data.dialednumber.callReference = htolel(callid);
2971
2972         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DIALED_NUMBER_MESSAGE to %s, num %s, inst %d, callid %d\n",
2973                 d->name, text, instance, callid);
2974         transmit_response(d, req);
2975 }
2976
2977 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2978 {
2979         struct skinny_req *req;
2980
2981         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2982                 return;
2983
2984         req->data.closereceivechannel.conferenceId = htolel(0);
2985         req->data.closereceivechannel.partyId = htolel(sub->callid);
2986
2987         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLOSE_RECEIVE_CHANNEL_MESSAGE to %s, confid %d, callid %d\n",
2988                 d->name, 0, sub->callid);
2989         transmit_response(d, req);
2990 }
2991
2992 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2993 {
2994         struct skinny_req *req;
2995
2996         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2997                 return;
2998
2999         req->data.stopmedia.conferenceId = htolel(0);
3000         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
3001
3002         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_MEDIA_TRANSMISSION_MESSAGE to %s, confid %d, passthrupartyid %d\n",
3003                 d->name, 0, sub->callid);
3004         transmit_response(d, req);
3005 }
3006
3007 static void transmit_startmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub, struct sockaddr_in dest, struct ast_format_list fmt)
3008 {
3009         struct skinny_req *req;
3010
3011         if (d->protocolversion < 17) {
3012                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip4), START_MEDIA_TRANSMISSION_MESSAGE)))
3013                         return;
3014                 req->data.startmedia_ip4.conferenceId = htolel(sub->callid);
3015                 req->data.startmedia_ip4.passThruPartyId = htolel(sub->callid);
3016                 req->data.startmedia_ip4.remoteIp = dest.sin_addr.s_addr;
3017                 req->data.startmedia_ip4.remotePort = htolel(ntohs(dest.sin_port));
3018                 req->data.startmedia_ip4.packetSize = htolel(fmt.cur_ms);
3019                 req->data.startmedia_ip4.payloadType = htolel(codec_ast2skinny(&fmt.format));
3020                 req->data.startmedia_ip4.qualifier.precedence = htolel(127);
3021                 req->data.startmedia_ip4.qualifier.vad = htolel(0);
3022                 req->data.startmedia_ip4.qualifier.packets = htolel(0);
3023                 req->data.startmedia_ip4.qualifier.bitRate = htolel(0);
3024         } else {
3025                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip6), START_MEDIA_TRANSMISSION_MESSAGE)))
3026                         return;
3027                 req->data.startmedia_ip6.conferenceId = htolel(sub->callid);
3028                 req->data.startmedia_ip6.passThruPartyId = htolel(sub->callid);
3029                 memcpy(req->data.startmedia_ip6.remoteIp, &dest.sin_addr.s_addr, sizeof(dest.sin_addr.s_addr));
3030                 req->data.startmedia_ip6.remotePort = htolel(ntohs(dest.sin_port));
3031                 req->data.startmedia_ip6.packetSize = htolel(fmt.cur_ms);
3032                 req->data.startmedia_ip6.payloadType = htolel(codec_ast2skinny(&fmt.format));
3033                 req->data.startmedia_ip6.qualifier.precedence = htolel(127);
3034                 req->data.startmedia_ip6.qualifier.vad = htolel(0);
3035                 req->data.startmedia_ip6.qualifier.packets = htolel(0);
3036                 req->data.startmedia_ip6.qualifier.bitRate = htolel(0);
3037         }
3038
3039         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting START_MEDIA_TRANSMISSION_MESSAGE to %s, callid %d, passthrupartyid %d, ip %s:%d, ms %d, fmt %d, prec 127\n",
3040                 d->name, sub->callid, sub->callid, ast_inet_ntoa(dest.sin_addr), dest.sin_port, fmt.cur_ms, codec_ast2skinny(&fmt.format));
3041         transmit_response(d, req);
3042 }
3043
3044 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
3045 {
3046         struct skinny_req *req;
3047
3048         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
3049                 return;
3050
3051         req->data.activatecallplane.lineInstance = htolel(l->instance);
3052
3053         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting ACTIVATE_CALL_PLANE_MESSAGE to %s, inst %d\n",
3054                 d->name, l->instance);
3055         transmit_response(d, req);
3056 }
3057
3058 static void transmit_callstate(struct skinny_device *d, int buttonInstance, unsigned callid, int state)
3059 {
3060         struct skinny_req *req;
3061
3062         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
3063                 return;
3064
3065         req->data.callstate.callState = htolel(state);
3066         req->data.callstate.lineInstance = htolel(buttonInstance);
3067         req->data.callstate.callReference = htolel(callid);
3068
3069         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_STATE_MESSAGE to %s, state %s, inst %d, callid %d\n",
3070                 d->name, callstate2str(state), buttonInstance, callid);
3071         transmit_response(d, req);
3072 }
3073
3074 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
3075 {
3076         struct skinny_req *req;
3077         int anyon = 0;
3078
3079         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
3080                 return;
3081
3082         if (l->cfwdtype & SKINNY_CFWD_ALL) {
3083                 if (!ast_strlen_zero(l->call_forward_all)) {
3084                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
3085                         req->data.forwardstat.fwdall = htolel(1);
3086                         anyon++;
3087                 } else {
3088                         req->data.forwardstat.fwdall = htolel(0);
3089                 }
3090         }
3091         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
3092                 if (!ast_strlen_zero(l->call_forward_busy)) {
3093                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
3094                         req->data.forwardstat.fwdbusy = htolel(1);
3095                         anyon++;
3096                 } else {
3097                         req->data.forwardstat.fwdbusy = htolel(0);
3098                 }
3099         }
3100         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
3101                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
3102                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
3103                         req->data.forwardstat.fwdnoanswer = htolel(1);
3104                         anyon++;
3105                 } else {
3106                         req->data.forwardstat.fwdnoanswer = htolel(0);
3107                 }
3108         }
3109         req->data.forwardstat.lineNumber = htolel(l->instance);
3110         if (anyon)
3111                 req->data.forwardstat.activeforward = htolel(7);
3112         else
3113                 req->data.forwardstat.activeforward = htolel(0);
3114
3115         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting FORWARD_STAT_MESSAGE to %s, inst %d, all %s, busy %s, noans %s, acitve %d\n",
3116                 d->name, l->instance, l->call_forward_all, l->call_forward_busy, l->call_forward_noanswer, anyon ? 7 : 0);
3117         transmit_response(d, req);
3118 }
3119
3120 static void transmit_speeddialstatres(struct skinny_device *d, struct skinny_speeddial *sd)
3121 {
3122         struct skinny_req *req;
3123
3124         if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
3125                 return;
3126
3127         req->data.speeddialreq.speedDialNumber = htolel(sd->instance);
3128         ast_copy_string(req->data.speeddial.speedDialDirNumber, sd->exten, sizeof(req->data.speeddial.speedDialDirNumber));
3129         ast_copy_string(req->data.speeddial.speedDialDisplayName, sd->label, sizeof(req->data.speeddial.speedDialDisplayName));
3130
3131         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SPEED_DIAL_STAT_RES_MESSAGE to %s, inst %d, dir %s, display %s\n",
3132                 d->name, sd->instance, sd->exten, sd->label);
3133         transmit_response(d, req);
3134 }
3135
3136 //static void transmit_linestatres(struct skinny_device *d, struct skinny_line *l)
3137 static void transmit_linestatres(struct skinny_device *d, int instance)
3138 {
3139         struct skinny_req *req;
3140         struct skinny_line *l;
3141         struct skinny_speeddial *sd;
3142
3143         if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
3144                 return;
3145
3146         if ((l = find_line_by_instance(d, instance))) {
3147                 req->data.linestat.lineNumber = letohl(l->instance);
3148                 memcpy(req->data.linestat.lineDirNumber, l->name, sizeof(req->data.linestat.lineDirNumber));
3149                 memcpy(req->data.linestat.lineDisplayName, l->label, sizeof(req->data.linestat.lineDisplayName));
3150         } else if ((sd = find_speeddial_by_instance(d, instance, 1))) {
3151                 req->data.linestat.lineNumber = letohl(sd->instance);
3152                 memcpy(req->data.linestat.lineDirNumber, sd->label, sizeof(req->data.linestat.lineDirNumber));
3153                 memcpy(req->data.linestat.lineDisplayName, sd->label, sizeof(req->data.linestat.lineDisplayName));
3154         }
3155
3156         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting LINE_STAT_RES_MESSAGE to %s, inst %d, num %s, label %s\n",
3157                 d->name, l->instance, req->data.linestat.lineDirNumber, req->data.linestat.lineDisplayName);
3158         transmit_response(d, req);
3159 }
3160
3161 static void transmit_definetimedate(struct skinny_device *d)
3162 {
3163         struct skinny_req *req;
3164         struct timeval now = ast_tvnow();
3165         struct ast_tm cmtime;
3166
3167         if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
3168                 return;
3169
3170         ast_localtime(&now, &cmtime, NULL);
3171         req->data.definetimedate.year = htolel(cmtime.tm_year+1900);
3172         req->data.definetimedate.month = htolel(cmtime.tm_mon+1);
3173         req->data.definetimedate.dayofweek = htolel(cmtime.tm_wday);
3174         req->data.definetimedate.day = htolel(cmtime.tm_mday);
3175         req->data.definetimedate.hour = htolel(cmtime.tm_hour);
3176         req->data.definetimedate.minute = htolel(cmtime.tm_min);
3177         req->data.definetimedate.seconds = htolel(cmtime.tm_sec);
3178         req->data.definetimedate.milliseconds = htolel(cmtime.tm_usec / 1000);
3179         req->data.definetimedate.timestamp = htolel(now.tv_sec);
3180
3181         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DEFINETIMEDATE_MESSAGE to %s, date %d %d %d dow %d time %d:%d:%d.%d\n",
3182                 d->name, req->data.definetimedate.year, req->data.definetimedate.month, req->data.definetimedate.day, req->data.definetimedate.dayofweek,
3183                 req->data.definetimedate.hour, req->data.definetimedate.minute, req->data.definetimedate.seconds, req->data.definetimedate.milliseconds);
3184         transmit_response(d, req);
3185 }
3186
3187 static void transmit_versionres(struct skinny_device *d)
3188 {
3189         struct skinny_req *req;
3190         if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
3191                 return;
3192
3193         ast_copy_string(req->data.version.version, d->version_id, sizeof(req->data.version.version));
3194
3195         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting VERSION_RES_MESSAGE to %s, version %s\n", d->name, d->version_id);
3196         transmit_response(d, req);
3197 }
3198
3199 static void transmit_serverres(struct skinny_device *d)
3200 {
3201         struct skinny_req *req;
3202         if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
3203                 return;
3204
3205         memcpy(req->data.serverres.server[0].serverName, ourhost,
3206                         sizeof(req->data.serverres.server[0].serverName));
3207         req->data.serverres.serverListenPort[0] = htolel(ourport);
3208         req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
3209
3210         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SERVER_RES_MESSAGE to %s, srvname %s %s:%d\n",
3211                 d->name, ourhost, ast_inet_ntoa(d->ourip), ourport);
3212         transmit_response(d, req);
3213 }
3214
3215 static void transmit_softkeysetres(struct skinny_device *d)
3216 {
3217         struct skinny_req *req;
3218         int i;
3219         int x;
3220         int y;
3221         int keydefcount;
3222         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
3223
3224         if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
3225                 return;
3226
3227         SKINNY_DEBUG(DEBUG_TEMPLATE, 3, "Creating Softkey Template\n");
3228
3229         keydefcount = ARRAY_LEN(soft_key_default_definitions);
3230         req->data.softkeysets.softKeySetOffset = htolel(0);
3231         req->data.softkeysets.softKeySetCount = htolel(keydefcount);
3232         req->data.softkeysets.totalSoftKeySetCount = htolel(keydefcount);
3233         for (x = 0; x < keydefcount; x++) {
3234                 const uint8_t *defaults = softkeymode->defaults;
3235                 /* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
3236                    This will have to do for now. */
3237                 for (y = 0; y < softkeymode->count; y++) {
3238                         for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
3239                                 if (defaults[y] == i+1) {
3240                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = (i+1);
3241                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyInfoIndex[y] = htoles(i+301);
3242                                         SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "softKeySetDefinition : softKeyTemplateIndex: %d softKeyInfoIndex: %d\n",
3243                                                 i+1, i+301);
3244                                 }
3245                         }
3246                 }
3247                 softkeymode++;
3248         }
3249
3250         SKINNY_DEBUG(DEBUG_PACKET | DEBUG_TEMPLATE, 3, "Transmitting SOFT_KEY_SET_RES_MESSAGE to %s, template data\n",
3251                 d->name);
3252         transmit_response(d, req);
3253 }
3254
3255 static void transmit_softkeytemplateres(struct skinny_device *d)
3256 {
3257         struct skinny_req *req;
3258
3259         if (!(req = req_alloc(sizeof(struct soft_key_template_res_message), SOFT_KEY_TEMPLATE_RES_MESSAGE)))
3260                 return;
3261
3262         req->data.softkeytemplate.softKeyOffset = htolel(0);
3263         req->data.softkeytemplate.softKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
3264         req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
3265         memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
3266                 soft_key_template_default,
3267                 sizeof(soft_key_template_default));
3268
3269         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SOFT_KEY_TEMPLATE_RES_MESSAGE to %s, offset 0, keycnt %d, totalkeycnt %d, template data\n",
3270                 d->name, req->data.softkeytemplate.softKeyCount, req->data.softkeytemplate.totalSoftKeyCount);
3271         transmit_response(d, req);
3272 }
3273
3274 static void transmit_reset(struct skinny_device *d, int fullrestart)
3275 {
3276         struct skinny_req *req;
3277
3278         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
3279                 return;
3280
3281         if (fullrestart)
3282                 req->data.reset.resetType = 2;
3283         else
3284                 req->data.reset.resetType = 1;
3285
3286         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting RESET_MESSAGE to %s, type %s\n",
3287                 d->name, (fullrestart) ? "Restarting" : "Resetting");
3288         transmit_response(d, req);
3289 }
3290
3291 static void transmit_keepaliveack(struct skinny_device *d)
3292 {
3293         struct skinny_req *req;
3294
3295         if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
3296                 return;
3297
3298         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting KEEP_ALIVE_ACK_MESSAGE to %s\n", d->name);
3299         transmit_response(d, req);
3300 }
3301
3302 static void transmit_registerack(struct skinny_device *d)
3303 {
3304         struct skinny_req *req;
3305
3306         if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
3307                 return;
3308
3309         req->data.regack.res[0] = '0';
3310         req->data.regack.res[1] = '\0';
3311         req->data.regack.keepAlive = htolel(keep_alive);
3312         memcpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate));
3313         req->data.regack.res2[0] = '0';
3314         req->data.regack.res2[1] = '\0';
3315         req->data.regack.secondaryKeepAlive = htolel(keep_alive);
3316
3317 #ifdef AST_DEVMODE
3318         {
3319         short res = req->data.regack.res[0] << 8 | req->data.regack.res[1];
3320         int res2 = req->data.regack.res2[0] << 24 | req->data.regack.res2[1] << 16 | req->data.regack.res2[2] << 8 | req->data.regack.res2[3];
3321         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_ACK_MESSAGE to %s, keepalive %d, datetemplate %s, seckeepalive %d, res 0x%04x, res2 0x%08x\n",
3322                 d->name, keep_alive, date_format, keep_alive, res, res2);
3323         }
3324 #endif
3325
3326         transmit_response(d, req);
3327 }
3328
3329 static void transmit_capabilitiesreq(struct skinny_device *d)
3330 {
3331         struct skinny_req *req;
3332
3333         if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
3334                 return;
3335
3336         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CAPABILITIES_REQ_MESSAGE to %s\n", d->name);
3337         transmit_response(d, req);
3338 }
3339
3340 static void transmit_backspace(struct skinny_device *d, int instance, unsigned callid)
3341 {
3342         struct skinny_req *req;
3343
3344         if (!(req = req_alloc(sizeof(struct bksp_req_message), BKSP_REQ_MESSAGE)))
3345                 return;
3346
3347         req->data.bkspmessage.instance = htolel(instance);
3348         req->data.bkspmessage.callreference = htolel(callid);
3349
3350         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting BKSP_REQ_MESSAGE to %s, inst %d, callid %d \n",
3351                 d->name, instance, callid);
3352         transmit_response(d, req);
3353 }
3354
3355 static void transmit_serviceurlstat(struct skinny_device *d, int instance)
3356 {
3357         struct skinny_req *req;
3358         struct skinny_serviceurl *surl;
3359
3360         if (!(req = req_alloc(sizeof(struct serviceurl_stat_message), SERVICEURL_STAT_MESSAGE)))
3361                 return;
3362
3363         AST_LIST_TRAVERSE(&d->serviceurls, surl, list) {
3364                 if (surl->instance == instance) {
3365                         break;
3366                 }
3367         }
3368
3369         if (surl) {
3370                 memcpy(req->data.serviceurlmessage.displayName, surl->displayName, sizeof(req->data.serviceurlmessage.displayName));
3371                 memcpy(req->data.serviceurlmessage.url, surl->url, sizeof(req->data.serviceurlmessage.url));
3372         }
3373         req->data.serviceurlmessage.instance = htolel(instance);
3374
3375         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SERVICEURL_STAT_MESSAGE to %s, inst %d\n",
3376                 d->name, instance);
3377         transmit_response(d, req);
3378 }
3379
3380 static int skinny_extensionstate_cb(char *context, char *exten, struct ast_state_cb_info *info, void *data)
3381 {
3382         struct skinny_container *container = data;
3383         struct skinny_device *d = NULL;
3384         char hint[AST_MAX_EXTENSION];
3385         int state = info->exten_state;
3386
3387         /* only interested in device state here */
3388         if (info->reason != AST_HINT_UPDATE_DEVICE) {
3389                 return 0;
3390         }
3391
3392         if (container->type == SKINNY_SDCONTAINER) {
3393                 struct skinny_speeddial *sd = container->data;
3394                 d = sd->parent;
3395
3396                 SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on speeddial %s\n", ast_extension_state2str(state), sd->label);
3397
3398                 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
3399                         /* If they are not registered, we will override notification and show no availability */
3400                         if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
3401                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_FLASH);
3402                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3403                                 return 0;
3404                         }
3405                         switch (state) {
3406                         case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
3407                         case AST_EXTENSION_REMOVED:     /* Extension is gone */
3408                                 SKINNY_DEBUG(DEBUG_HINT, 3, "Extension state: Watcher for hint %s %s. Notify Device %s\n",
3409                                         exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
3410                                 sd->stateid = -1;
3411                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
3412                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3413                                 break;
3414                         case AST_EXTENSION_RINGING:
3415                         case AST_EXTENSION_UNAVAILABLE:
3416                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_BLINK);
3417                                 transmit_callstate(d, sd->instance, 0, SKINNY_RINGIN);
3418                                 break;
3419                         case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
3420                         case AST_EXTENSION_INUSE:
3421                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_ON);
3422                                 transmit_callstate(d, sd->instance, 0, SKINNY_CALLREMOTEMULTILINE);
3423                                 break;
3424                         case AST_EXTENSION_ONHOLD:
3425                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_WINK);
3426                                 transmit_callstate(d, sd->instance, 0, SKINNY_HOLD);
3427                                 break;
3428                         case AST_EXTENSION_NOT_INUSE:
3429                         default:
3430                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
3431                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3432                                 break;
3433                         }
3434                 }
3435                 sd->laststate = state;
3436         } else if (container->type == SKINNY_SUBLINECONTAINER) {
3437                 struct skinny_subline *subline = container->data;
3438                 struct skinny_line *l = subline->line;
3439                 d = l->device;
3440
3441                 SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on subline %s (%s@%s)\n", ast_extension_state2str(state), subline->name, exten, context);
3442
3443                 subline->extenstate = state;
3444
3445                 if (subline->callid == 0) {
3446                         return 0;
3447                 }
3448
3449                 switch (state) {
3450                 case AST_EXTENSION_RINGING: /* Handled by normal ringin */
3451                         break;
3452                 case AST_EXTENSION_INUSE:
3453                         if (subline->sub && (subline->sub->substate == SKINNY_CONNECTED)) { /* Device has a real call */
3454                                 transmit_callstate(d, l->instance, subline->callid, SKINNY_CONNECTED);
3455                                 transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_CONNECTED, KEYMASK_ALL);
3456                                 send_displaypromptstatus(d, OCTAL_CONNECTED, "", 0, l->instance, subline->callid);
3457                         } else { /* Some other device has active call */
3458                                 transmit_callstate(d, l->instance, subline->callid, SKINNY_CALLREMOTEMULTILINE);
3459                                 transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLACONNECTEDNOTACTIVE, KEYMASK_ALL);
3460                                 send_displaypromptstatus(d, "In Use", "", 0, l->instance, subline->callid);
3461                         }
3462                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3463                         transmit_ringer_mode(d, SKINNY_RING_OFF);
3464                         transmit_activatecallplane(d, l);
3465                         break;
3466                 case AST_EXTENSION_ONHOLD:
3467                         transmit_callstate(d, l->instance, subline->callid, SKINNY_HOLD);
3468                         transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLAHOLD, KEYMASK_ALL);
3469                         send_displaypromptstatus(d, "Hold", "", 0, l->instance, subline->callid);
3470                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3471                         transmit_activatecallplane(d, l);
3472                         break;
3473                 case AST_EXTENSION_NOT_INUSE:
3474                         transmit_callstate(d, l->instance, subline->callid, SKINNY_ONHOOK);
3475                         transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_ONHOOK, KEYMASK_ALL);
3476                         transmit_clearpromptmessage(d, l->instance, subline->callid);
3477                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
3478                         transmit_activatecallplane(d, l);
3479                         subline->callid = 0;
3480                         break;
3481                 default:
3482                         ast_log(LOG_WARNING, "AST_EXTENSION_STATE %s not configured\n", ast_extension_state2str(state));
3483                 }
3484         } else {
3485                 ast_log(LOG_WARNING, "Invalid data supplied to skinny_extensionstate_cb\n");
3486         }
3487
3488         return 0;
3489 }
3490
3491 static void update_connectedline(struct skinny_subchannel *sub, const void *data, size_t datalen)
3492 {
3493         struct ast_channel *c = sub->owner;
3494         struct skinny_line *l = sub->line;
3495         struct skinny_device *d = l->device;
3496
3497         if (!d->session) {
3498                 return;
3499         }
3500
3501         if (sub->calldirection == SKINNY_OUTGOING && !sub->origtonum) {
3502                 /* Do not set origtonum before here or origtoname won't be set */
3503                 sub->origtonum = ast_strdup(sub->exten);
3504                 if (ast_channel_connected(c)->id.name.valid) {
3505                         sub->origtoname = ast_strdup(ast_channel_connected(c)->id.name.str);
3506                 }
3507         }
3508
3509         if (!ast_channel_caller(c)->id.number.valid
3510                 || ast_strlen_zero(ast_channel_caller(c)->id.number.str)
3511                 || !ast_channel_connected(c)->id.number.valid
3512                 || ast_strlen_zero(ast_channel_connected(c)->id.number.str))
3513                 return;
3514
3515         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Updating\n", sub->callid);
3516
3517         send_callinfo(sub);
3518 }
3519
3520 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *msg)
3521 {
3522         struct skinny_line *l = userdata;
3523         struct skinny_device *d = l->device;
3524         struct skinny_line *l2;
3525         int dev_msgs = 0;
3526
3527         if (!d || !d->session) {
3528                 return;
3529         }
3530
3531         if (msg && stasis_mwi_state_type() == stasis_message_type(msg)) {
3532                 struct stasis_mwi_state *mwi_state = stasis_message_data(msg);
3533                 l->newmsgs = mwi_state->new_msgs;
3534         }
3535
3536         if (l->newmsgs) {
3537                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
3538         } else {
3539                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
3540         }
3541
3542         /* find out wether the device lamp should be on or off */
3543         AST_LIST_TRAVERSE(&d->lines, l2, list) {
3544                 if (l2->newmsgs) {
3545                         dev_msgs++;
3546                 }
3547         }
3548
3549         if (dev_msgs) {
3550                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
3551         } else {
3552                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
3553         }
3554         ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", l->newmsgs);
3555 }
3556
3557 /* I do not believe skinny can deal with video.
3558    Anyone know differently? */
3559 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
3560 static enum ast_rtp_glue_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
3561 {
3562         struct skinny_subchannel *sub = NULL;
3563
3564         if (!(sub = ast_channel_tech_pvt(c)) || !(sub->vrtp))
3565                 return AST_RTP_GLUE_RESULT_FORBID;
3566
3567         ao2_ref(sub->vrtp, +1);
3568         *instance = sub->vrtp;
3569
3570         return AST_RTP_GLUE_RESULT_REMOTE;
3571 }
3572
3573 static enum ast_rtp_glue_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
3574 {
3575         struct skinny_subchannel *sub = NULL;
3576         struct skinny_line *l;
3577         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE;
3578
3579         SKINNY_DEBUG(DEBUG_AUDIO, 4, "skinny_get_rtp_peer() Channel = %s\n", ast_channel_name(c));
3580
3581         if (!(sub = ast_channel_tech_pvt(c)))
3582                 return AST_RTP_GLUE_RESULT_FORBID;
3583
3584         ast_mutex_lock(&sub->lock);
3585
3586         if (!(sub->rtp)){
3587                 ast_mutex_unlock(&sub->lock);
3588                 return AST_RTP_GLUE_RESULT_FORBID;
3589         }
3590
3591         ao2_ref(sub->rtp, +1);
3592         *instance = sub->rtp;
3593
3594         l = sub->line;
3595
3596         if (!l->directmedia || l->nat){
3597                 res = AST_RTP_GLUE_RESULT_LOCAL;
3598                 SKINNY_DEBUG(DEBUG_AUDIO, 4, "skinny_get_rtp_peer() Using AST_RTP_GLUE_RESULT_LOCAL \n");
3599         }
3600
3601         ast_mutex_unlock(&sub->lock);
3602
3603         return res;
3604
3605 }
3606
3607 static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *trtp, const struct ast_format_cap *codecs, int nat_active)
3608 {
3609         struct skinny_subchannel *sub;
3610         struct skinny_line *l;
3611         struct skinny_device *d;
3612         struct ast_format_list fmt;
3613         struct sockaddr_in us = { 0, };
3614         struct sockaddr_in them = { 0, };
3615         struct ast_sockaddr them_tmp;
3616         struct ast_sockaddr us_tmp;
3617
3618         sub = ast_channel_tech_pvt(c);
3619
3620         if (ast_channel_state(c) != AST_STATE_UP)
3621                 return 0;
3622
3623         if (!sub) {
3624                 return -1;
3625         }
3626
3627         l = sub->line;
3628         d = l->device;
3629
3630         if (rtp){
3631                 struct ast_format tmpfmt;
3632                 ast_rtp_instance_get_remote_address(rtp, &them_tmp);
3633                 ast_sockaddr_to_sin(&them_tmp, &them);
3634
3635                 /* Shutdown any early-media or previous media on re-invite */
3636                 transmit_stopmediatransmission(d, sub);
3637
3638                 SKINNY_DEBUG(DEBUG_AUDIO, 4, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
3639
3640                 ast_best_codec(l->cap, &tmpfmt);
3641                 fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
3642
3643                 SKINNY_DEBUG(DEBUG_AUDIO, 4, "Setting payloadType to '%s' (%d ms)\n", ast_getformatname(&fmt.format), fmt.cur_ms);
3644
3645                 if (!(l->directmedia) || (l->nat)){
3646                         ast_rtp_instance_get_local_address(rtp, &us_tmp);
3647                         ast_sockaddr_to_sin(&us_tmp, &us);
3648                         us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->ourip.s_addr;
3649                         transmit_startmediatransmission(d, sub, us, fmt);
3650                 } else {
3651                         transmit_startmediatransmission(d, sub, them, fmt);
3652                 }
3653
3654                 return 0;
3655         }
3656         /* Need a return here to break the bridge */
3657         return 0;
3658 }
3659
3660 static struct ast_rtp_glue skinny_rtp_glue = {
3661         .type = "Skinny",
3662         .get_rtp_info = skinny_get_rtp_peer,
3663         .get_vrtp_info = skinny_get_vrtp_peer,
3664         .update_peer = skinny_set_rtp_peer,
3665 };
3666
3667 #ifdef AST_DEVMODE
3668 static char *skinny_debugs(void)
3669 {
3670         char *ptr;
3671         int posn = 0;
3672
3673         ptr = dbgcli_buf;
3674         strncpy(ptr, "\0", 1);
3675         if (skinnydebug & DEBUG_GENERAL) {
3676                 strncpy(ptr, "general ", 8);
3677                 posn += 8;
3678                 ptr += 8;
3679         }
3680         if (skinnydebug & DEBUG_SUB) {
3681                 strncpy(ptr, "sub ", 4);
3682                 posn += 4;
3683                 ptr += 4;
3684         }
3685         if (skinnydebug & DEBUG_AUDIO) {
3686                 strncpy(ptr, "audio ", 6);
3687                 posn += 6;
3688                 ptr += 6;
3689         }
3690         if (skinnydebug & DEBUG_PACKET) {
3691                 strncpy(ptr, "packet ", 7);
3692                 posn += 7;
3693                 ptr += 7;
3694         }
3695         if (skinnydebug & DEBUG_LOCK) {
3696                 strncpy(ptr, "lock ", 5);
3697                 posn += 5;
3698                 ptr += 5;
3699         }
3700         if (skinnydebug & DEBUG_TEMPLATE) {
3701                 strncpy(ptr, "template ", 9);
3702                 posn += 9;
3703                 ptr += 9;
3704         }
3705         if (skinnydebug & DEBUG_THREAD) {
3706                 strncpy(ptr, "thread ", 7);
3707                 posn += 7;
3708                 ptr += 7;
3709         }
3710         if (skinnydebug & DEBUG_HINT) {
3711                 strncpy(ptr, "hint ", 5);
3712                 posn += 5;
3713                 ptr += 5;
3714         }
3715         if (posn > 0) {
3716                 strncpy(--ptr, "\0", 1);
3717         }
3718         return dbgcli_buf;
3719 }
3720
3721 static char *complete_skinny_debug(const char *line, const char *word, int pos, int state)
3722 {
3723         const char *debugOpts[]={ "all","audio","hint","lock","off","packet","show","sub","template","thread",NULL };
3724         char *wordptr = (char *)word;
3725         char buf[32];
3726         char *bufptr = buf;
3727         int buflen = sizeof(buf);
3728         int wordlen;
3729         int which = 0;
3730         int i = 0;
3731
3732         if (*word == '+' || *word == '-' || *word == '!') {
3733                 *bufptr = *word;
3734                 wordptr++;
3735                 bufptr++;
3736                 buflen--;
3737         }
3738         wordlen = strlen(wordptr);
3739
3740         while (debugOpts[i]) {
3741                 if (!strncasecmp(wordptr, debugOpts[i], wordlen) && ++which > state) {
3742                         ast_copy_string(bufptr, debugOpts[i], buflen);
3743                         return ast_strdup(buf);
3744                 }
3745                 i++;
3746         }
3747
3748         return NULL;
3749 }
3750
3751 static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3752 {
3753         int i;
3754         int result = 0;
3755         const char *arg;
3756         int bitmask;
3757         int negate;
3758
3759         switch (cmd) {
3760         case CLI_INIT:
3761                 e->command = "skinny debug";
3762                 e->usage =
3763                         "Usage: skinny debug {audio|hint|lock|off|packet|show|sub|template|thread}\n"
3764                         "       Enables/Disables various Skinny debugging messages\n";
3765                 return NULL;
3766         case CLI_GENERATE:
3767                 return complete_skinny_debug(a->line, a->word, a->pos, a->n);
3768
3769         }
3770
3771         if (a->argc < 3)
3772                 return CLI_SHOWUSAGE;
3773
3774         if (a->argc == 3 && !strncasecmp(a->argv[e->args-1], "show", 4)) {
3775                 ast_cli(a->fd, "Skinny Debugging - %s\n", skinny_debugs());
3776                 return CLI_SUCCESS;
3777         }
3778
3779         for(i = e->args; i < a->argc; i++) {
3780                 result++;
3781                 arg = a->argv[i];
3782
3783                 if (!strncasecmp(arg, "off", 3)) {
3784                         skinnydebug = 0;
3785                         continue;
3786                 }
3787
3788                 if (!strncasecmp(arg, "all", 3)) {
3789                         skinnydebug = DEBUG_GENERAL|DEBUG_SUB|DEBUG_PACKET|DEBUG_AUDIO|DEBUG_LOCK|DEBUG_TEMPLATE|DEBUG_THREAD|DEBUG_HINT;
3790