More places to eliminate the cast to argv but were not giving warnings.
[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_DND,
923         SOFTKEY_GPICKUP,
924         /*SOFTKEY_CONFRN,*/
925 };
926
927 static const uint8_t soft_key_default_connected[] = {
928         SOFTKEY_HOLD,
929         SOFTKEY_ENDCALL,
930         SOFTKEY_TRNSFER,
931         SOFTKEY_PARK,
932         SOFTKEY_CFWDALL,
933         SOFTKEY_CFWDBUSY,
934 };
935
936 static const uint8_t soft_key_default_onhold[] = {
937         SOFTKEY_RESUME,
938         SOFTKEY_NEWCALL,
939         SOFTKEY_ENDCALL,
940         SOFTKEY_TRNSFER,
941 };
942
943 static const uint8_t soft_key_default_ringin[] = {
944         SOFTKEY_ANSWER,
945         SOFTKEY_ENDCALL,
946         SOFTKEY_TRNSFER,
947 };
948
949 static const uint8_t soft_key_default_offhook[] = {
950         SOFTKEY_REDIAL,
951         SOFTKEY_ENDCALL,
952         SOFTKEY_CFWDALL,
953         SOFTKEY_CFWDBUSY,
954         SOFTKEY_GPICKUP,
955 };
956
957 static const uint8_t soft_key_default_connwithtrans[] = {
958         SOFTKEY_HOLD,
959         SOFTKEY_ENDCALL,
960         SOFTKEY_TRNSFER,
961         SOFTKEY_PARK,
962         SOFTKEY_CFWDALL,
963         SOFTKEY_CFWDBUSY,
964 };
965
966 static const uint8_t soft_key_default_dadfd[] = {
967         SOFTKEY_BKSPC,
968         SOFTKEY_ENDCALL,
969         SOFTKEY_FORCEDIAL,
970 };
971
972 static const uint8_t soft_key_default_connwithconf[] = {
973         SOFTKEY_NONE,
974 };
975
976 static const uint8_t soft_key_default_ringout[] = {
977         SOFTKEY_NONE,
978         SOFTKEY_ENDCALL,
979 };
980
981 static const uint8_t soft_key_default_offhookwithfeat[] = {
982         SOFTKEY_REDIAL,
983         SOFTKEY_ENDCALL,
984         SOFTKEY_TRNSFER,
985 };
986
987 static const uint8_t soft_key_default_unknown[] = {
988         SOFTKEY_NONE,
989 };
990
991 static const uint8_t soft_key_default_SLAhold[] = {
992         SOFTKEY_REDIAL,
993         SOFTKEY_NEWCALL,
994         SOFTKEY_RESUME,
995 };
996
997 static const uint8_t soft_key_default_SLAconnectednotactive[] = {
998         SOFTKEY_REDIAL,
999         SOFTKEY_NEWCALL,
1000         SOFTKEY_JOIN,
1001 };
1002
1003 static const struct soft_key_definitions soft_key_default_definitions[] = {
1004         {KEYDEF_ONHOOK, soft_key_default_onhook, sizeof(soft_key_default_onhook) / sizeof(uint8_t)},
1005         {KEYDEF_CONNECTED, soft_key_default_connected, sizeof(soft_key_default_connected) / sizeof(uint8_t)},
1006         {KEYDEF_ONHOLD, soft_key_default_onhold, sizeof(soft_key_default_onhold) / sizeof(uint8_t)},
1007         {KEYDEF_RINGIN, soft_key_default_ringin, sizeof(soft_key_default_ringin) / sizeof(uint8_t)},
1008         {KEYDEF_OFFHOOK, soft_key_default_offhook, sizeof(soft_key_default_offhook) / sizeof(uint8_t)},
1009         {KEYDEF_CONNWITHTRANS, soft_key_default_connwithtrans, sizeof(soft_key_default_connwithtrans) / sizeof(uint8_t)},
1010         {KEYDEF_DADFD, soft_key_default_dadfd, sizeof(soft_key_default_dadfd) / sizeof(uint8_t)},
1011         {KEYDEF_CONNWITHCONF, soft_key_default_connwithconf, sizeof(soft_key_default_connwithconf) / sizeof(uint8_t)},
1012         {KEYDEF_RINGOUT, soft_key_default_ringout, sizeof(soft_key_default_ringout) / sizeof(uint8_t)},
1013         {KEYDEF_OFFHOOKWITHFEAT, soft_key_default_offhookwithfeat, sizeof(soft_key_default_offhookwithfeat) / sizeof(uint8_t)},
1014         {KEYDEF_UNKNOWN, soft_key_default_unknown, sizeof(soft_key_default_unknown) / sizeof(uint8_t)},
1015         {KEYDEF_SLAHOLD, soft_key_default_SLAhold, sizeof(soft_key_default_SLAhold) / sizeof(uint8_t)},
1016         {KEYDEF_SLACONNECTEDNOTACTIVE, soft_key_default_SLAconnectednotactive, sizeof(soft_key_default_SLAconnectednotactive) / sizeof(uint8_t)}
1017 };
1018
1019 struct soft_key_template_res_message {
1020         uint32_t softKeyOffset;
1021         uint32_t softKeyCount;
1022         uint32_t totalSoftKeyCount;
1023         struct soft_key_template_definition softKeyTemplateDefinition[32];
1024 };
1025
1026 #define SOFT_KEY_SET_RES_MESSAGE 0x0109
1027
1028 struct soft_key_set_definition {
1029         uint8_t softKeyTemplateIndex[16];
1030         uint16_t softKeyInfoIndex[16];
1031 };
1032
1033 struct soft_key_set_res_message {
1034         uint32_t softKeySetOffset;
1035         uint32_t softKeySetCount;
1036         uint32_t totalSoftKeySetCount;
1037         struct soft_key_set_definition softKeySetDefinition[16];
1038         uint32_t res;
1039 };
1040
1041 #define SELECT_SOFT_KEYS_MESSAGE 0x0110
1042 struct select_soft_keys_message {
1043         uint32_t instance;
1044         uint32_t reference;
1045         uint32_t softKeySetIndex;
1046         uint32_t validKeyMask;
1047 };
1048
1049 #define CALL_STATE_MESSAGE 0x0111
1050 struct call_state_message {
1051         uint32_t callState;
1052         uint32_t lineInstance;
1053         uint32_t callReference;
1054         uint32_t space[3];
1055 };
1056
1057 #define DISPLAY_PROMPT_STATUS_MESSAGE 0x0112
1058 struct display_prompt_status_message {
1059         uint32_t messageTimeout;
1060         char promptMessage[32];
1061         uint32_t lineInstance;
1062         uint32_t callReference;
1063         uint32_t space[3];
1064 };
1065
1066 #define CLEAR_PROMPT_MESSAGE  0x0113
1067 struct clear_prompt_message {
1068         uint32_t lineInstance;
1069         uint32_t callReference;
1070 };
1071
1072 #define DISPLAY_NOTIFY_MESSAGE 0x0114
1073 struct display_notify_message {
1074         uint32_t displayTimeout;
1075         char displayMessage[100];
1076 };
1077
1078 #define ACTIVATE_CALL_PLANE_MESSAGE 0x0116
1079 struct activate_call_plane_message {
1080         uint32_t lineInstance;
1081 };
1082
1083 #define DIALED_NUMBER_MESSAGE 0x011D
1084 struct dialed_number_message {
1085         char dialedNumber[24];
1086         uint32_t lineInstance;
1087         uint32_t callReference;
1088 };
1089
1090 #define MAX_SERVICEURL 256
1091 #define SERVICEURL_STAT_MESSAGE 0x012F
1092 struct serviceurl_stat_message {
1093         uint32_t instance;
1094         char url[MAX_SERVICEURL];
1095         char displayName[40];
1096 };
1097
1098 #define MAXCALLINFOSTR 256
1099 #define MAXDISPLAYNOTIFYSTR 32
1100
1101 #define DISPLAY_PRINOTIFY_MESSAGE 0x0120
1102 struct display_prinotify_message {
1103         uint32_t timeout;
1104         uint32_t priority;
1105         char text[MAXDISPLAYNOTIFYSTR];
1106 };
1107
1108 #define CLEAR_PRINOTIFY_MESSAGE 0x0121
1109 struct clear_prinotify_message {
1110         uint32_t priority;
1111 };
1112
1113 #define CALL_INFO_MESSAGE_VARIABLE 0x014A
1114 struct call_info_message_variable {
1115         uint32_t instance;
1116         uint32_t callreference;
1117         uint32_t calldirection;
1118         uint32_t unknown1;
1119         uint32_t unknown2;
1120         uint32_t unknown3;
1121         uint32_t unknown4;
1122         uint32_t unknown5;
1123         char calldetails[MAXCALLINFOSTR];
1124 };
1125
1126 #define DISPLAY_PRINOTIFY_MESSAGE_VARIABLE 0x0144
1127 struct display_prinotify_message_variable {
1128         uint32_t timeout;
1129         uint32_t priority;
1130         char text[MAXDISPLAYNOTIFYSTR];
1131 };
1132
1133 #define DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE 0x0145
1134 struct display_prompt_status_message_variable {
1135         uint32_t unknown;
1136         uint32_t lineInstance;
1137         uint32_t callReference;
1138         char promptMessage[MAXCALLINFOSTR];
1139 };
1140
1141 union skinny_data {
1142         struct alarm_message alarm;
1143         struct speed_dial_stat_req_message speeddialreq;
1144         struct register_message reg;
1145         struct register_ack_message regack;
1146         struct register_rej_message regrej;
1147         struct capabilities_res_message caps;
1148         struct version_res_message version;
1149         struct button_template_res_message buttontemplate;
1150         struct displaytext_message displaytext;
1151         struct clear_display_message cleardisplay;
1152         struct display_prompt_status_message displaypromptstatus;
1153         struct clear_prompt_message clearpromptstatus;
1154         struct definetimedate_message definetimedate;
1155         struct start_tone_message starttone;
1156         struct stop_tone_message stoptone;
1157         struct speed_dial_stat_res_message speeddial;
1158         struct line_state_req_message line;
1159         struct line_stat_res_message linestat;
1160         struct soft_key_set_res_message softkeysets;
1161         struct soft_key_template_res_message softkeytemplate;
1162         struct server_res_message serverres;
1163         struct reset_message reset;
1164         struct set_lamp_message setlamp;
1165         struct set_ringer_message setringer;
1166         struct call_state_message callstate;
1167         struct keypad_button_message keypad;
1168         struct select_soft_keys_message selectsoftkey;
1169         struct activate_call_plane_message activatecallplane;
1170         struct stimulus_message stimulus;
1171         struct offhook_message offhook;
1172         struct onhook_message onhook;
1173         struct set_speaker_message setspeaker;
1174         struct set_microphone_message setmicrophone;
1175         struct call_info_message callinfo;
1176         struct start_media_transmission_message_ip4 startmedia_ip4;
1177         struct start_media_transmission_message_ip6 startmedia_ip6;
1178         struct stop_media_transmission_message stopmedia;
1179         struct open_receive_channel_message openreceivechannel;
1180         struct open_receive_channel_ack_message_ip4 openreceivechannelack_ip4;
1181         struct open_receive_channel_ack_message_ip6 openreceivechannelack_ip6;
1182         struct close_receive_channel_message closereceivechannel;
1183         struct display_notify_message displaynotify;
1184         struct dialed_number_message dialednumber;
1185         struct soft_key_event_message softkeyeventmessage;
1186         struct enbloc_call_message enbloccallmessage;
1187         struct forward_stat_message forwardstat;
1188         struct bksp_req_message bkspmessage;
1189         struct call_info_message_variable callinfomessagevariable;
1190         struct display_prompt_status_message_variable displaypromptstatusvar;
1191         struct serviceurl_stat_message serviceurlmessage;
1192         struct clear_prinotify_message clearprinotify;
1193         struct display_prinotify_message displayprinotify;
1194         struct display_prinotify_message_variable displayprinotifyvar;
1195 };
1196
1197 /* packet composition */
1198 struct skinny_req {
1199         int len;
1200         int res;
1201         int e;
1202         union skinny_data data;
1203 };
1204
1205 /* XXX This is the combined size of the variables above.  (len, res, e)
1206    If more are added, this MUST change.
1207    (sizeof(skinny_req) - sizeof(skinny_data)) DOES NOT WORK on all systems (amd64?). */
1208 static int skinny_header_size = 12;
1209
1210 /*****************************
1211  * Asterisk specific globals *
1212  *****************************/
1213
1214 static int skinnyreload = 0;
1215
1216 /* a hostname, portnumber, socket and such is usefull for VoIP protocols */
1217 static struct sockaddr_in bindaddr;
1218 static char ourhost[256];
1219 static int ourport;
1220 static struct in_addr __ourip;
1221 static struct ast_hostent ahp;
1222 static struct hostent *hp;
1223 static int skinnysock = -1;
1224 static pthread_t accept_t;
1225 static int callnums = 1;
1226
1227 #define SKINNY_DEVICE_UNKNOWN -1
1228 #define SKINNY_DEVICE_NONE 0
1229 #define SKINNY_DEVICE_30SPPLUS 1
1230 #define SKINNY_DEVICE_12SPPLUS 2
1231 #define SKINNY_DEVICE_12SP 3
1232 #define SKINNY_DEVICE_12 4
1233 #define SKINNY_DEVICE_30VIP 5
1234 #define SKINNY_DEVICE_7910 6
1235 #define SKINNY_DEVICE_7960 7
1236 #define SKINNY_DEVICE_7940 8
1237 #define SKINNY_DEVICE_7935 9
1238 #define SKINNY_DEVICE_ATA186 12 /* Cisco ATA-186 */
1239 #define SKINNY_DEVICE_7941 115
1240 #define SKINNY_DEVICE_7971 119
1241 #define SKINNY_DEVICE_7914 124 /* Expansion module */
1242 #define SKINNY_DEVICE_7985 302
1243 #define SKINNY_DEVICE_7911 307
1244 #define SKINNY_DEVICE_7961GE 308
1245 #define SKINNY_DEVICE_7941GE 309
1246 #define SKINNY_DEVICE_7931 348
1247 #define SKINNY_DEVICE_7921 365
1248 #define SKINNY_DEVICE_7906 369
1249 #define SKINNY_DEVICE_7962 404 /* Not found */
1250 #define SKINNY_DEVICE_7937 431
1251 #define SKINNY_DEVICE_7942 434
1252 #define SKINNY_DEVICE_7945 435
1253 #define SKINNY_DEVICE_7965 436
1254 #define SKINNY_DEVICE_7975 437
1255 #define SKINNY_DEVICE_7905 20000
1256 #define SKINNY_DEVICE_7920 30002
1257 #define SKINNY_DEVICE_7970 30006
1258 #define SKINNY_DEVICE_7912 30007
1259 #define SKINNY_DEVICE_7902 30008
1260 #define SKINNY_DEVICE_CIPC 30016 /* Cisco IP Communicator */
1261 #define SKINNY_DEVICE_7961 30018
1262 #define SKINNY_DEVICE_7936 30019
1263 #define SKINNY_DEVICE_SCCPGATEWAY_AN 30027 /* Analog gateway */
1264 #define SKINNY_DEVICE_SCCPGATEWAY_BRI 30028 /* BRI gateway */
1265
1266 #define SKINNY_SPEAKERON 1
1267 #define SKINNY_SPEAKEROFF 2
1268
1269 #define SKINNY_MICON 1
1270 #define SKINNY_MICOFF 2
1271
1272 #define SKINNY_OFFHOOK 1
1273 #define SKINNY_ONHOOK 2
1274 #define SKINNY_RINGOUT 3
1275 #define SKINNY_RINGIN 4
1276 #define SKINNY_CONNECTED 5
1277 #define SKINNY_BUSY 6
1278 #define SKINNY_CONGESTION 7
1279 #define SKINNY_HOLD 8
1280 #define SKINNY_CALLWAIT 9
1281 #define SKINNY_TRANSFER 10
1282 #define SKINNY_PARK 11
1283 #define SKINNY_PROGRESS 12
1284 #define SKINNY_CALLREMOTEMULTILINE 13
1285 #define SKINNY_INVALID 14
1286
1287 #define SKINNY_INCOMING 1
1288 #define SKINNY_OUTGOING 2
1289
1290 #define SKINNY_SILENCE 0x00             /* Note sure this is part of the protocol, remove? */
1291 #define SKINNY_DIALTONE 0x21
1292 #define SKINNY_BUSYTONE 0x23
1293 #define SKINNY_ALERT 0x24
1294 #define SKINNY_REORDER 0x25
1295 #define SKINNY_CALLWAITTONE 0x2D
1296 #define SKINNY_ZIPZIP 0x31
1297 #define SKINNY_ZIP 0x32
1298 #define SKINNY_BEEPBONK 0x33
1299 #define SKINNY_BARGIN 0x43
1300 #define SKINNY_NOTONE 0x7F
1301
1302 #define SKINNY_LAMP_OFF 1
1303 #define SKINNY_LAMP_ON 2
1304 #define SKINNY_LAMP_WINK 3
1305 #define SKINNY_LAMP_FLASH 4
1306 #define SKINNY_LAMP_BLINK 5
1307
1308 #define SKINNY_RING_OFF 1
1309 #define SKINNY_RING_INSIDE 2
1310 #define SKINNY_RING_OUTSIDE 3
1311 #define SKINNY_RING_FEATURE 4
1312
1313 #define SKINNY_CFWD_ALL       (1 << 0)
1314 #define SKINNY_CFWD_BUSY      (1 << 1)
1315 #define SKINNY_CFWD_NOANSWER  (1 << 2)
1316
1317 /* Skinny rtp stream modes. Do we really need this? */
1318 #define SKINNY_CX_SENDONLY 0
1319 #define SKINNY_CX_RECVONLY 1
1320 #define SKINNY_CX_SENDRECV 2
1321 #define SKINNY_CX_CONF 3
1322 #define SKINNY_CX_CONFERENCE 3
1323 #define SKINNY_CX_MUTE 4
1324 #define SKINNY_CX_INACTIVE 4
1325
1326 #if 0
1327 static const char * const skinny_cxmodes[] = {
1328         "sendonly",
1329         "recvonly",
1330         "sendrecv",
1331         "confrnce",
1332         "inactive"
1333 };
1334 #endif
1335
1336 /* driver scheduler */
1337 static struct ast_sched_context *sched = NULL;
1338
1339 /* Protect the network socket */
1340 AST_MUTEX_DEFINE_STATIC(netlock);
1341
1342 /* Wait up to 16 seconds for first digit */
1343 static int firstdigittimeout = 16000;
1344
1345 /* How long to wait for following digits */
1346 static int gendigittimeout = 8000;
1347
1348 /* How long to wait for an extra digit, if there is an ambiguous match */
1349 static int matchdigittimeout = 3000;
1350
1351 #define SUBSTATE_UNSET 0
1352 #define SUBSTATE_OFFHOOK 1
1353 #define SUBSTATE_ONHOOK 2
1354 #define SUBSTATE_RINGOUT 3
1355 #define SUBSTATE_RINGIN 4
1356 #define SUBSTATE_CONNECTED 5
1357 #define SUBSTATE_BUSY 6
1358 #define SUBSTATE_CONGESTION 7
1359 #define SUBSTATE_HOLD 8
1360 #define SUBSTATE_CALLWAIT 9
1361 #define SUBSTATE_PROGRESS 12
1362 #define SUBSTATE_DIALING 101
1363
1364 struct skinny_subchannel {
1365         ast_mutex_t lock;
1366         struct ast_channel *owner;
1367         struct ast_rtp_instance *rtp;
1368         struct ast_rtp_instance *vrtp;
1369         unsigned int callid;
1370         char exten[AST_MAX_EXTENSION];
1371         /* time_t lastouttime; */ /* Unused */
1372         int progress;
1373         int ringing;
1374         /* int lastout; */ /* Unused */
1375         int cxmode;
1376         int nat;
1377         int calldirection;
1378         int blindxfer;
1379         int xferor;
1380         int substate;
1381         int aa_sched;
1382         int aa_beep;
1383         int aa_mute;
1384         int dialer_sched;
1385         char *origtonum;
1386         char *origtoname;
1387
1388         AST_LIST_ENTRY(skinny_subchannel) list;
1389         struct skinny_subchannel *related;
1390         struct skinny_line *line;
1391         struct skinny_subline *subline;
1392 };
1393
1394 #define SKINNY_LINE_OPTIONS                             \
1395         char name[80];                                  \
1396         char label[24];                                 \
1397         char accountcode[AST_MAX_ACCOUNT_CODE];         \
1398         char exten[AST_MAX_EXTENSION];                  \
1399         char context[AST_MAX_CONTEXT];                  \
1400         char language[MAX_LANGUAGE];                    \
1401         char cid_num[AST_MAX_EXTENSION];                \
1402         char cid_name[AST_MAX_EXTENSION];               \
1403         char lastcallerid[AST_MAX_EXTENSION];           \
1404         int cfwdtype;                                   \
1405         char call_forward_all[AST_MAX_EXTENSION];       \
1406         char call_forward_busy[AST_MAX_EXTENSION];      \
1407         char call_forward_noanswer[AST_MAX_EXTENSION];  \
1408         char mailbox[AST_MAX_EXTENSION];                \
1409         char vmexten[AST_MAX_EXTENSION];                \
1410         char regexten[AST_MAX_EXTENSION];               \
1411         char regcontext[AST_MAX_CONTEXT];               \
1412         char parkinglot[AST_MAX_CONTEXT];               \
1413         char mohinterpret[MAX_MUSICCLASS];              \
1414         char mohsuggest[MAX_MUSICCLASS];                \
1415         char lastnumberdialed[AST_MAX_EXTENSION];       \
1416         char dialoutexten[AST_MAX_EXTENSION];           \
1417         char dialoutcontext[AST_MAX_CONTEXT];           \
1418         ast_group_t callgroup;                          \
1419         ast_group_t pickupgroup;                        \
1420         struct ast_namedgroups *named_callgroups;       \
1421         struct ast_namedgroups *named_pickupgroups;     \
1422         int callwaiting;                                \
1423         int transfer;                                   \
1424         int threewaycalling;                            \
1425         int mwiblink;                                   \
1426         int cancallforward;                             \
1427         int getforward;                                 \
1428         int dnd;                                        \
1429         int hidecallerid;                               \
1430         int amaflags;                                   \
1431         int instance;                                   \
1432         int group;                                      \
1433         struct ast_codec_pref confprefs;                \
1434         struct ast_codec_pref prefs;                    \
1435         int nonCodecCapability;                         \
1436         int immediate;                                  \
1437         int nat;                                        \
1438         int directmedia;                                \
1439         int prune;
1440
1441 struct skinny_line {
1442         SKINNY_LINE_OPTIONS
1443         ast_mutex_t lock;
1444         struct skinny_container *container;
1445         struct ast_event_sub *mwi_event_sub; /* Event based MWI */
1446         struct skinny_subchannel *activesub;
1447         AST_LIST_HEAD(, skinny_subchannel) sub;
1448         AST_LIST_HEAD(, skinny_subline) sublines;
1449         AST_LIST_ENTRY(skinny_line) list;
1450         AST_LIST_ENTRY(skinny_line) all;
1451         struct skinny_device *device;
1452         struct ast_format_cap *cap;
1453         struct ast_format_cap *confcap;
1454         struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1455         int newmsgs;
1456 };
1457
1458 static struct skinny_line_options{
1459         SKINNY_LINE_OPTIONS
1460 } default_line_struct = {
1461         .callwaiting = 1,
1462         .transfer = 1,
1463         .mwiblink = 0,
1464         .dnd = 0,
1465         .hidecallerid = 0,
1466         .amaflags = 0,
1467         .instance = 0,
1468         .directmedia = 0,
1469         .nat = 0,
1470         .getforward = 0,
1471         .prune = 0,
1472 };
1473 static struct skinny_line_options *default_line = &default_line_struct;
1474
1475 static AST_LIST_HEAD_STATIC(lines, skinny_line);
1476
1477 struct skinny_subline {
1478         struct skinny_container *container;
1479         struct skinny_line *line;
1480         struct skinny_subchannel *sub;
1481         AST_LIST_ENTRY(skinny_subline) list;
1482         char name[80];
1483         char context[AST_MAX_CONTEXT];
1484         char exten[AST_MAX_EXTENSION];
1485         char stname[AST_MAX_EXTENSION];
1486         char lnname[AST_MAX_EXTENSION];
1487         char ourName[40];
1488         char ourNum[24];
1489         char theirName[40];
1490         char theirNum[24];
1491         int calldirection;
1492         int substate;
1493         int extenstate;
1494         unsigned int callid;
1495 };
1496
1497 struct skinny_speeddial {
1498         ast_mutex_t lock;
1499         struct skinny_container *container;
1500         char label[42];
1501         char context[AST_MAX_CONTEXT];
1502         char exten[AST_MAX_EXTENSION];
1503         int instance;
1504         int stateid;
1505         int laststate;
1506         int isHint;
1507
1508         AST_LIST_ENTRY(skinny_speeddial) list;
1509         struct skinny_device *parent;
1510 };
1511
1512 struct skinny_serviceurl {
1513         int instance;
1514         char url[MAX_SERVICEURL];
1515         char displayName[40];
1516         AST_LIST_ENTRY(skinny_serviceurl) list;
1517         struct skinny_device *device;
1518 };
1519
1520 #define SKINNY_DEVICECONTAINER 1
1521 #define SKINNY_LINECONTAINER 2
1522 #define SKINNY_SUBLINECONTAINER 3
1523 #define SKINNY_SDCONTAINER 4
1524
1525 struct skinny_container {
1526         int type;
1527         void *data;
1528 };
1529
1530 struct skinny_addon {
1531         ast_mutex_t lock;
1532         char type[10];
1533         AST_LIST_ENTRY(skinny_addon) list;
1534         struct skinny_device *parent;
1535 };
1536
1537 #define SKINNY_DEVICE_OPTIONS                                   \
1538         char name[80];                                          \
1539         char id[16];                                            \
1540         char version_id[16];                                    \
1541         char vmexten[AST_MAX_EXTENSION];                        \
1542         int type;                                               \
1543         int protocolversion;                            \
1544         int hookstate;                                  \
1545         int lastlineinstance;                                   \
1546         int lastcallreference;                                  \
1547         struct ast_codec_pref confprefs;                        \
1548         int earlyrtp;                                           \
1549         int transfer;                                           \
1550         int callwaiting;                                        \
1551         int mwiblink;                                           \
1552         int dnd;                                                \
1553         int prune;
1554
1555 struct skinny_device {
1556         SKINNY_DEVICE_OPTIONS
1557         struct type *first;
1558         struct type *last;
1559         ast_mutex_t lock;
1560         struct sockaddr_in addr;
1561         struct in_addr ourip;
1562         struct ast_ha *ha;
1563         struct skinnysession *session;
1564         struct skinny_line *activeline;
1565         struct ast_format_cap *cap;
1566         struct ast_format_cap *confcap;
1567         AST_LIST_HEAD(, skinny_line) lines;
1568         AST_LIST_HEAD(, skinny_speeddial) speeddials;
1569         AST_LIST_HEAD(, skinny_serviceurl) serviceurls;
1570         AST_LIST_HEAD(, skinny_addon) addons;
1571         AST_LIST_ENTRY(skinny_device) list;
1572 };
1573
1574 static struct skinny_device_options {
1575         SKINNY_DEVICE_OPTIONS
1576 } default_device_struct = {
1577         .transfer = 1,
1578         .earlyrtp = 1,
1579         .callwaiting = 1,
1580         .mwiblink = 0,
1581         .dnd = 0,
1582         .prune = 0,
1583         .hookstate = SKINNY_ONHOOK,
1584 };
1585 static struct skinny_device_options *default_device = &default_device_struct;
1586
1587 static AST_LIST_HEAD_STATIC(devices, skinny_device);
1588
1589 struct skinnysession {
1590         pthread_t t;
1591         ast_mutex_t lock;
1592         time_t start;
1593         struct sockaddr_in sin;
1594         int fd;
1595         char inbuf[SKINNY_MAX_PACKET];
1596         char outbuf[SKINNY_MAX_PACKET];
1597         struct skinny_device *device;
1598         AST_LIST_ENTRY(skinnysession) list;
1599 };
1600
1601 static struct ast_channel *skinny_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
1602 static AST_LIST_HEAD_STATIC(sessions, skinnysession);
1603
1604 static int skinny_devicestate(const char *data);
1605 static int skinny_call(struct ast_channel *ast, const char *dest, int timeout);
1606 static int skinny_hangup(struct ast_channel *ast);
1607 static int skinny_answer(struct ast_channel *ast);
1608 static struct ast_frame *skinny_read(struct ast_channel *ast);
1609 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1610 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1611 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1612 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1613 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1614 static void mwi_event_cb(const struct ast_event *event, void *userdata);
1615 static int skinny_dialer_cb(const void *data);
1616 static int skinny_reload(void);
1617
1618 static void setsubstate(struct skinny_subchannel *sub, int state);
1619 static void dumpsub(struct skinny_subchannel *sub, int forcehangup);
1620 static void activatesub(struct skinny_subchannel *sub, int state);
1621 static void dialandactivatesub(struct skinny_subchannel *sub, char exten[AST_MAX_EXTENSION]);
1622
1623 static struct ast_channel_tech skinny_tech = {
1624         .type = "Skinny",
1625         .description = tdesc,
1626         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1627         .requester = skinny_request,
1628         .devicestate = skinny_devicestate,
1629         .call = skinny_call,
1630         .hangup = skinny_hangup,
1631         .answer = skinny_answer,
1632         .read = skinny_read,
1633         .write = skinny_write,
1634         .indicate = skinny_indicate,
1635         .fixup = skinny_fixup,
1636         .send_digit_begin = skinny_senddigit_begin,
1637         .send_digit_end = skinny_senddigit_end,
1638         .bridge = ast_rtp_instance_bridge,
1639 };
1640
1641 static int skinny_extensionstate_cb(char *context, char *id, struct ast_state_cb_info *info, void *data);
1642 static int skinny_transfer(struct skinny_subchannel *sub);
1643
1644 static struct skinny_line *skinny_line_alloc(void)
1645 {
1646         struct skinny_line *l;
1647         if (!(l = ast_calloc(1, sizeof(*l)))) {
1648                 return NULL;
1649         }
1650
1651         l->cap = ast_format_cap_alloc_nolock();
1652         l->confcap = ast_format_cap_alloc_nolock();
1653         if (!l->cap || !l->confcap) {
1654                 l->cap = ast_format_cap_destroy(l->cap);
1655                 l->confcap = ast_format_cap_destroy(l->confcap);
1656                 ast_free(l);
1657                 return NULL;
1658         }
1659         return l;
1660 }
1661 static struct skinny_line *skinny_line_destroy(struct skinny_line *l)
1662 {
1663         l->cap = ast_format_cap_destroy(l->cap);
1664         l->confcap = ast_format_cap_destroy(l->confcap);
1665         l->named_callgroups = ast_unref_namedgroups(l->named_callgroups);
1666         l->named_pickupgroups = ast_unref_namedgroups(l->named_pickupgroups);
1667         ast_free(l->container);
1668         ast_free(l);
1669         return NULL;
1670 }
1671 static struct skinny_device *skinny_device_alloc(void)
1672 {
1673         struct skinny_device *d;
1674         if (!(d = ast_calloc(1, sizeof(*d)))) {
1675                 return NULL;
1676         }
1677
1678         d->cap = ast_format_cap_alloc_nolock();
1679         d->confcap = ast_format_cap_alloc_nolock();
1680         if (!d->cap || !d->confcap) {
1681                 d->cap = ast_format_cap_destroy(d->cap);
1682                 d->confcap = ast_format_cap_destroy(d->confcap);
1683                 ast_free(d);
1684                 return NULL;
1685         }
1686         return d;
1687 }
1688 static struct skinny_device *skinny_device_destroy(struct skinny_device *d)
1689 {
1690         d->cap = ast_format_cap_destroy(d->cap);
1691         d->confcap = ast_format_cap_destroy(d->confcap);
1692         ast_free(d);
1693         return NULL;
1694 }
1695
1696 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1697 {
1698         struct skinny_device *d = s->device;
1699         struct skinny_addon *a;
1700         int i;
1701
1702         switch (d->type) {
1703                 case SKINNY_DEVICE_30SPPLUS:
1704                 case SKINNY_DEVICE_30VIP:
1705                         /* 13 rows, 2 columns */
1706                         for (i = 0; i < 4; i++)
1707                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1708                         (btn++)->buttonDefinition = BT_REDIAL;
1709                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1710                         (btn++)->buttonDefinition = BT_CALLPARK;
1711                         (btn++)->buttonDefinition = BT_FORWARDALL;
1712                         (btn++)->buttonDefinition = BT_CONFERENCE;
1713                         for (i = 0; i < 4; i++)
1714                                 (btn++)->buttonDefinition = BT_NONE;
1715                         for (i = 0; i < 13; i++)
1716                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1717
1718                         break;
1719                 case SKINNY_DEVICE_12SPPLUS:
1720                 case SKINNY_DEVICE_12SP:
1721                 case SKINNY_DEVICE_12:
1722                         /* 6 rows, 2 columns */
1723                         for (i = 0; i < 2; i++)
1724                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1725                         for (i = 0; i < 4; i++)
1726                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1727                         (btn++)->buttonDefinition = BT_HOLD;
1728                         (btn++)->buttonDefinition = BT_REDIAL;
1729                         (btn++)->buttonDefinition = BT_TRANSFER;
1730                         (btn++)->buttonDefinition = BT_FORWARDALL;
1731                         (btn++)->buttonDefinition = BT_CALLPARK;
1732                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1733                         break;
1734                 case SKINNY_DEVICE_7910:
1735                         (btn++)->buttonDefinition = BT_LINE;
1736                         (btn++)->buttonDefinition = BT_HOLD;
1737                         (btn++)->buttonDefinition = BT_TRANSFER;
1738                         (btn++)->buttonDefinition = BT_DISPLAY;
1739                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1740                         (btn++)->buttonDefinition = BT_CONFERENCE;
1741                         (btn++)->buttonDefinition = BT_FORWARDALL;
1742                         for (i = 0; i < 2; i++)
1743                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1744                         (btn++)->buttonDefinition = BT_REDIAL;
1745                         break;
1746                 case SKINNY_DEVICE_7960:
1747                 case SKINNY_DEVICE_7961:
1748                 case SKINNY_DEVICE_7961GE:
1749                 case SKINNY_DEVICE_7962:
1750                 case SKINNY_DEVICE_7965:
1751                         for (i = 0; i < 6; i++)
1752                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1753                         break;
1754                 case SKINNY_DEVICE_7940:
1755                 case SKINNY_DEVICE_7941:
1756                 case SKINNY_DEVICE_7941GE:
1757                 case SKINNY_DEVICE_7942:
1758                 case SKINNY_DEVICE_7945:
1759                         for (i = 0; i < 2; i++)
1760                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1761                         break;
1762                 case SKINNY_DEVICE_7935:
1763                 case SKINNY_DEVICE_7936:
1764                         for (i = 0; i < 2; i++)
1765                                 (btn++)->buttonDefinition = BT_LINE;
1766                         break;
1767                 case SKINNY_DEVICE_ATA186:
1768                         (btn++)->buttonDefinition = BT_LINE;
1769                         break;
1770                 case SKINNY_DEVICE_7970:
1771                 case SKINNY_DEVICE_7971:
1772                 case SKINNY_DEVICE_7975:
1773                 case SKINNY_DEVICE_CIPC:
1774                         for (i = 0; i < 8; i++)
1775                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1776                         break;
1777                 case SKINNY_DEVICE_7985:
1778                         /* XXX I have no idea what the buttons look like on these. */
1779                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1780                         break;
1781                 case SKINNY_DEVICE_7912:
1782                 case SKINNY_DEVICE_7911:
1783                 case SKINNY_DEVICE_7905:
1784                         (btn++)->buttonDefinition = BT_LINE;
1785                         (btn++)->buttonDefinition = BT_HOLD;
1786                         break;
1787                 case SKINNY_DEVICE_7920:
1788                         /* XXX I don't know if this is right. */
1789                         for (i = 0; i < 4; i++)
1790                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1791                         break;
1792                 case SKINNY_DEVICE_7921:
1793                         for (i = 0; i < 6; i++)
1794                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1795                         break;
1796                 case SKINNY_DEVICE_7902:
1797                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1798                         break;
1799                 case SKINNY_DEVICE_7906:
1800                         ast_log(LOG_WARNING, "Unsupported device type '%d (7906)' found.\n", d->type);
1801                         break;
1802                 case SKINNY_DEVICE_7931:
1803                         ast_log(LOG_WARNING, "Unsupported device type '%d (7931)' found.\n", d->type);
1804                         break;
1805                 case SKINNY_DEVICE_7937:
1806                         ast_log(LOG_WARNING, "Unsupported device type '%d (7937)' found.\n", d->type);
1807                         break;
1808                 case SKINNY_DEVICE_7914:
1809                         ast_log(LOG_WARNING, "Unsupported device type '%d (7914)' found.  Expansion module registered by itself?\n", d->type);
1810                         break;
1811                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1812                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1813                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1814                         break;
1815                 default:
1816                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1817                         break;
1818         }
1819
1820         AST_LIST_LOCK(&d->addons);
1821         AST_LIST_TRAVERSE(&d->addons, a, list) {
1822                 if (!strcasecmp(a->type, "7914")) {
1823                         for (i = 0; i < 14; i++)
1824                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1825                 } else {
1826                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1827                 }
1828         }
1829         AST_LIST_UNLOCK(&d->addons);
1830
1831         return btn;
1832 }
1833
1834 static struct skinny_req *req_alloc(size_t size, int response_message)
1835 {
1836         struct skinny_req *req;
1837
1838         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1839                 return NULL;
1840
1841         req->len = htolel(size+4);
1842         req->e = htolel(response_message);
1843
1844         return req;
1845 }
1846
1847 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1848 {
1849         struct skinny_line *l;
1850
1851         /*Dialing from on hook or on a 7920 uses instance 0 in requests
1852           but we need to start looking at instance 1 */
1853
1854         if (!instance)
1855                 instance = 1;
1856
1857         AST_LIST_TRAVERSE(&d->lines, l, list){
1858                 if (l->instance == instance)
1859                         break;
1860         }
1861
1862         if (!l) {
1863                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1864         }
1865         return l;
1866 }
1867
1868 static struct skinny_line *find_line_by_name(const char *dest)
1869 {
1870         struct skinny_line *l;
1871         struct skinny_line *tmpl = NULL;
1872         struct skinny_device *d;
1873         char line[256];
1874         char *at;
1875         char *device;
1876         int checkdevice = 0;
1877
1878         ast_copy_string(line, dest, sizeof(line));
1879         at = strchr(line, '@');
1880         if (at)
1881                 *at++ = '\0';
1882         device = at;
1883
1884         if (!ast_strlen_zero(device))
1885                 checkdevice = 1;
1886
1887         AST_LIST_LOCK(&devices);
1888         AST_LIST_TRAVERSE(&devices, d, list){
1889                 if (checkdevice && tmpl)
1890                         break;
1891                 else if (!checkdevice) {
1892                         /* This is a match, since we're checking for line on every device. */
1893                 } else if (!strcasecmp(d->name, device)) {
1894                 } else
1895                         continue;
1896
1897                 /* Found the device (or we don't care which device) */
1898                 AST_LIST_TRAVERSE(&d->lines, l, list){
1899                         /* Search for the right line */
1900                         if (!strcasecmp(l->name, line)) {
1901                                 if (tmpl) {
1902                                         ast_log(LOG_WARNING, "Ambiguous line name: %s\n", line);
1903                                         AST_LIST_UNLOCK(&devices);
1904                                         return NULL;
1905                                 } else
1906                                         tmpl = l;
1907                         }
1908                 }
1909         }
1910         AST_LIST_UNLOCK(&devices);
1911         return tmpl;
1912 }
1913
1914 static struct skinny_subline *find_subline_by_name(const char *dest)
1915 {
1916         struct skinny_line *l;
1917         struct skinny_subline *subline;
1918         struct skinny_subline *tmpsubline = NULL;
1919         struct skinny_device *d;
1920
1921         AST_LIST_LOCK(&devices);
1922         AST_LIST_TRAVERSE(&devices, d, list){
1923                 AST_LIST_TRAVERSE(&d->lines, l, list){
1924                         AST_LIST_TRAVERSE(&l->sublines, subline, list){
1925                                 if (!strcasecmp(subline->name, dest)) {
1926                                         if (tmpsubline) {
1927                                                 ast_verb(2, "Ambiguous subline name: %s\n", dest);
1928                                                 AST_LIST_UNLOCK(&devices);
1929                                                 return NULL;
1930                                         } else
1931                                                 tmpsubline = subline;
1932                                 }
1933                         }
1934                 }
1935         }
1936         AST_LIST_UNLOCK(&devices);
1937         return tmpsubline;
1938 }
1939
1940 static struct skinny_subline *find_subline_by_callid(struct skinny_device *d, int callid)
1941 {
1942         struct skinny_subline *subline;
1943         struct skinny_line *l;
1944
1945         AST_LIST_TRAVERSE(&d->lines, l, list){
1946                 AST_LIST_TRAVERSE(&l->sublines, subline, list){
1947                         if (subline->callid == callid) {
1948                                 return subline;
1949                         }
1950                 }
1951         }
1952         return NULL;
1953 }
1954
1955 /*!
1956  * implement the setvar config line
1957  */
1958 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
1959 {
1960         struct ast_variable *tmpvar = NULL;
1961         char *varname = ast_strdupa(buf), *varval = NULL;
1962
1963         if ((varval = strchr(varname,'='))) {
1964                 *varval++ = '\0';
1965                 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
1966                         tmpvar->next = list;
1967                         list = tmpvar;
1968                 }
1969         }
1970         return list;
1971 }
1972
1973 static int skinny_sched_del(int sched_id, struct skinny_subchannel *sub)
1974 {
1975         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Deleting SCHED %d\n",
1976                 sub->callid, sched_id);
1977         return ast_sched_del(sched, sched_id);
1978 }
1979
1980 static int skinny_sched_add(int when, ast_sched_cb callback, struct skinny_subchannel *sub)
1981 {
1982         int ret;
1983         ret = ast_sched_add(sched, when, callback, sub);
1984         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Added SCHED %d\n",
1985                 sub->callid, ret);
1986         return ret;
1987 }
1988
1989 /* It's quicker/easier to find the subchannel when we know the instance number too */
1990 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
1991 {
1992         struct skinny_line *l = find_line_by_instance(d, instance);
1993         struct skinny_subchannel *sub;
1994
1995         if (!l) {
1996                 return NULL;
1997         }
1998
1999         /* 7920 phones set call reference to 0, so use the first
2000            sub-channel on the list.
2001            This MIGHT need more love to be right */
2002         if (!reference)
2003                 sub = AST_LIST_FIRST(&l->sub);
2004         else {
2005                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
2006                         if (sub->callid == reference)
2007                                 break;
2008                 }
2009         }
2010         if (!sub) {
2011                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
2012         }
2013         return sub;
2014 }
2015
2016 /* Find the subchannel when we only have the callid - this shouldn't happen often */
2017 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
2018 {
2019         struct skinny_line *l;
2020         struct skinny_subchannel *sub = NULL;
2021
2022         AST_LIST_TRAVERSE(&d->lines, l, list){
2023                 AST_LIST_TRAVERSE(&l->sub, sub, list){
2024                         if (sub->callid == reference)
2025                                 break;
2026                 }
2027                 if (sub)
2028                         break;
2029         }
2030
2031         if (!l) {
2032                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
2033         } else {
2034                 if (!sub) {
2035                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
2036                 }
2037         }
2038         return sub;
2039 }
2040
2041 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
2042 {
2043         struct skinny_speeddial *sd;
2044
2045         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2046                 if (sd->isHint == isHint && sd->instance == instance)
2047                         break;
2048         }
2049
2050         if (!sd) {
2051                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
2052         }
2053         return sd;
2054 }
2055
2056 static struct ast_format *codec_skinny2ast(enum skinny_codecs skinnycodec, struct ast_format *result)
2057 {
2058         switch (skinnycodec) {
2059         case SKINNY_CODEC_ALAW:
2060                 return ast_format_set(result, AST_FORMAT_ALAW, 0);
2061         case SKINNY_CODEC_ULAW:
2062                 return ast_format_set(result, AST_FORMAT_ULAW, 0);
2063         case SKINNY_CODEC_G722:
2064                 return ast_format_set(result, AST_FORMAT_G722, 0);
2065         case SKINNY_CODEC_G723_1:
2066                 return ast_format_set(result, AST_FORMAT_G723_1, 0);
2067         case SKINNY_CODEC_G729A:
2068                 return ast_format_set(result, AST_FORMAT_G729A, 0);
2069         case SKINNY_CODEC_G726_32:
2070                 return ast_format_set(result, AST_FORMAT_G726_AAL2, 0); /* XXX Is this right? */
2071         case SKINNY_CODEC_H261:
2072                 return ast_format_set(result, AST_FORMAT_H261, 0);
2073         case SKINNY_CODEC_H263:
2074                 return ast_format_set(result, AST_FORMAT_H263 ,0);
2075         default:
2076                 ast_format_clear(result);
2077                 return result;
2078         }
2079 }
2080
2081 static int codec_ast2skinny(const struct ast_format *astcodec)
2082 {
2083         switch (astcodec->id) {
2084         case AST_FORMAT_ALAW:
2085                 return SKINNY_CODEC_ALAW;
2086         case AST_FORMAT_ULAW:
2087                 return SKINNY_CODEC_ULAW;
2088         case AST_FORMAT_G722:
2089                 return SKINNY_CODEC_G722;
2090         case AST_FORMAT_G723_1:
2091                 return SKINNY_CODEC_G723_1;
2092         case AST_FORMAT_G729A:
2093                 return SKINNY_CODEC_G729A;
2094         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
2095                 return SKINNY_CODEC_G726_32;
2096         case AST_FORMAT_H261:
2097                 return SKINNY_CODEC_H261;
2098         case AST_FORMAT_H263:
2099                 return SKINNY_CODEC_H263;
2100         default:
2101                 return 0;
2102         }
2103 }
2104
2105 static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
2106 {
2107         if (!l)
2108                 return 0;
2109
2110         if (!ast_strlen_zero(cfwd)) {
2111                 if (cfwdtype & SKINNY_CFWD_ALL) {
2112                         l->cfwdtype |= SKINNY_CFWD_ALL;
2113                         ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
2114                 }
2115                 if (cfwdtype & SKINNY_CFWD_BUSY) {
2116                         l->cfwdtype |= SKINNY_CFWD_BUSY;
2117                         ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
2118                 }
2119                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2120                         l->cfwdtype |= SKINNY_CFWD_NOANSWER;
2121                         ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
2122                 }
2123         } else {
2124                 if (cfwdtype & SKINNY_CFWD_ALL) {
2125                         l->cfwdtype &= ~SKINNY_CFWD_ALL;
2126                         memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
2127                 }
2128                 if (cfwdtype & SKINNY_CFWD_BUSY) {
2129                         l->cfwdtype &= ~SKINNY_CFWD_BUSY;
2130                         memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
2131                 }
2132                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2133                         l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
2134                         memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
2135                 }
2136         }
2137         return l->cfwdtype;
2138 }
2139
2140 static void cleanup_stale_contexts(char *new, char *old)
2141 {
2142         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
2143
2144         while ((oldcontext = strsep(&old, "&"))) {
2145                 stalecontext = '\0';
2146                 ast_copy_string(newlist, new, sizeof(newlist));
2147                 stringp = newlist;
2148                 while ((newcontext = strsep(&stringp, "&"))) {
2149                         if (strcmp(newcontext, oldcontext) == 0) {
2150                                 /* This is not the context you're looking for */
2151                                 stalecontext = '\0';
2152                                 break;
2153                         } else if (strcmp(newcontext, oldcontext)) {
2154                                 stalecontext = oldcontext;
2155                         }
2156
2157                 }
2158                 if (stalecontext)
2159                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
2160         }
2161 }
2162
2163 static void register_exten(struct skinny_line *l)
2164 {
2165         char multi[256];
2166         char *stringp, *ext, *context;
2167
2168         if (ast_strlen_zero(regcontext))
2169                 return;
2170
2171         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2172         stringp = multi;
2173         while ((ext = strsep(&stringp, "&"))) {
2174                 if ((context = strchr(ext, '@'))) {
2175                         *context++ = '\0'; /* split ext@context */
2176                         if (!ast_context_find(context)) {
2177                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2178                                 continue;
2179                         }
2180                 } else {
2181                         context = regcontext;
2182                 }
2183                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2184                          ast_strdup(l->name), ast_free_ptr, "Skinny");
2185         }
2186 }
2187
2188 static void unregister_exten(struct skinny_line *l)
2189 {
2190         char multi[256];
2191         char *stringp, *ext, *context;
2192
2193         if (ast_strlen_zero(regcontext))
2194                 return;
2195
2196         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2197         stringp = multi;
2198         while ((ext = strsep(&stringp, "&"))) {
2199                 if ((context = strchr(ext, '@'))) {
2200                         *context++ = '\0'; /* split ext@context */
2201                         if (!ast_context_find(context)) {
2202                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2203                                 continue;
2204                         }
2205                 } else {
2206                         context = regcontext;
2207                 }
2208                 ast_context_remove_extension(context, ext, 1, NULL);
2209         }
2210 }
2211
2212 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
2213 {
2214         struct skinny_device *d;
2215         struct skinny_line *l;
2216         struct skinny_subline *subline;
2217         struct skinny_speeddial *sd;
2218         struct sockaddr_in sin;
2219         socklen_t slen;
2220         int instance;
2221
2222         AST_LIST_LOCK(&devices);
2223         AST_LIST_TRAVERSE(&devices, d, list){
2224                 struct ast_sockaddr addr;
2225                 ast_sockaddr_from_sin(&addr, &s->sin);
2226                 if (!d->session && !strcasecmp(req->data.reg.name, d->id)
2227                                 && ast_apply_ha(d->ha, &addr)) {
2228                         s->device = d;
2229                         d->type = letohl(req->data.reg.type);
2230                         d->protocolversion = letohl(req->data.reg.protocolVersion);
2231                         if (ast_strlen_zero(d->version_id)) {
2232                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
2233                         }
2234                         d->session = s;
2235
2236                         slen = sizeof(sin);
2237                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
2238                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
2239                                 sin.sin_addr = __ourip;
2240                         }
2241                         d->ourip = sin.sin_addr;
2242
2243                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2244                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd->container);
2245                         }
2246                         instance = 0;
2247                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2248                                 instance++;
2249                         }
2250                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2251                                 ast_format_cap_joint_copy(l->confcap, d->cap, l->cap);
2252                                 l->prefs = l->confprefs;
2253                                 if (!l->prefs.order[0]) {
2254                                         l->prefs = d->confprefs;
2255                                 }
2256                                 /* l->capability = d->capability;
2257                                 l->prefs = d->prefs; */
2258                                 l->instance = instance;
2259                                 l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
2260                                 set_callforwards(l, NULL, 0);
2261                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Registered\r\n", l->name, d->name);
2262                                 register_exten(l);
2263                                 /* initialize MWI on line and device */
2264                                 mwi_event_cb(0, l);
2265                                 AST_LIST_TRAVERSE(&l->sublines, subline, list) {
2266                                         ast_extension_state_add(subline->context, subline->exten, skinny_extensionstate_cb, subline->container);
2267                                 }
2268                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
2269                                 --instance;
2270                         }
2271                         break;
2272                 }
2273         }
2274         AST_LIST_UNLOCK(&devices);
2275         if (!d) {
2276                 return 0;
2277         }
2278         return 1;
2279 }
2280
2281 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
2282 {
2283         struct skinny_device *d;
2284         struct skinny_line *l;
2285         struct skinny_speeddial *sd;
2286
2287         d = s->device;
2288
2289         if (d) {
2290                 d->session = NULL;
2291
2292                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2293                         if (sd->stateid > -1)
2294                                 ast_extension_state_del(sd->stateid, NULL);
2295                 }
2296                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2297                         if (l->device == d) {
2298                                 ast_format_cap_remove_all(l->cap);
2299                                 ast_parse_allow_disallow(&l->prefs, l->cap, "all", 0);
2300                                 l->instance = 0;
2301                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Unregistered\r\n", l->name, d->name);
2302                                 unregister_exten(l);
2303                                 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
2304                         }
2305                 }
2306         }
2307
2308         return -1; /* main loop will destroy the session */
2309 }
2310
2311 #ifdef AST_DEVMODE
2312 static char *callstate2str(int ind)
2313 {
2314         char *tmp;
2315
2316         switch (ind) {
2317         case SKINNY_OFFHOOK:
2318                 return "SKINNY_OFFHOOK";
2319         case SKINNY_ONHOOK:
2320                 return "SKINNY_ONHOOK";
2321         case SKINNY_RINGOUT:
2322                 return "SKINNY_RINGOUT";
2323         case SKINNY_RINGIN:
2324                 return "SKINNY_RINGIN";
2325         case SKINNY_CONNECTED:
2326                 return "SKINNY_CONNECTED";
2327         case SKINNY_BUSY:
2328                 return "SKINNY_BUSY";
2329         case SKINNY_CONGESTION:
2330                 return "SKINNY_CONGESTION";
2331         case SKINNY_PROGRESS:
2332                 return "SKINNY_PROGRESS";
2333         case SKINNY_HOLD:
2334                 return "SKINNY_HOLD";
2335         case SKINNY_CALLWAIT:
2336                 return "SKINNY_CALLWAIT";
2337         default:
2338                 if (!(tmp = ast_threadstorage_get(&callstate2str_threadbuf, CALLSTATE2STR_BUFSIZE)))
2339                         return "Unknown";
2340                 snprintf(tmp, CALLSTATE2STR_BUFSIZE, "UNKNOWN-%d", ind);
2341                 return tmp;
2342         }
2343 }
2344
2345 #endif
2346
2347 static int transmit_response_bysession(struct skinnysession *s, struct skinny_req *req)
2348 {
2349         int res = 0;
2350
2351         if (!s) {
2352                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2353                 return -1;
2354         }
2355
2356         ast_mutex_lock(&s->lock);
2357
2358         if ((letohl(req->len) > SKINNY_MAX_PACKET) || (letohl(req->len) < 0)) {
2359                 ast_log(LOG_WARNING, "transmit_response: the length of the request (%d) is out of bounds (%d)\n", letohl(req->len), SKINNY_MAX_PACKET);
2360                 ast_mutex_unlock(&s->lock);
2361                 return -1;
2362         }
2363
2364         memset(s->outbuf, 0, sizeof(s->outbuf));
2365         memcpy(s->outbuf, req, skinny_header_size);
2366         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2367
2368         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2369
2370         if (res != letohl(req->len)+8) {
2371                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2372                 if (res == -1) {
2373                         ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2374                         skinny_unregister(NULL, s);
2375                 }
2376
2377         }
2378
2379         ast_free(req);
2380         ast_mutex_unlock(&s->lock);
2381         return 1;
2382 }
2383
2384 static void transmit_response(struct skinny_device *d, struct skinny_req *req)
2385 {
2386         transmit_response_bysession(d->session, req);
2387 }
2388
2389 static void transmit_registerrej(struct skinnysession *s)
2390 {
2391         struct skinny_req *req;
2392         char name[16];
2393
2394         if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
2395                 return;
2396
2397         memcpy(&name, req->data.reg.name, sizeof(name));
2398         snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2399
2400         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_REJ_MESSAGE to UNKNOWN_DEVICE\n");
2401         transmit_response_bysession(s, req);
2402 }
2403
2404 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2405 {
2406         struct skinny_req *req;
2407
2408         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2409                 return;
2410
2411         req->data.setspeaker.mode = htolel(mode);
2412
2413         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_SPEAKER_MESSAGE to %s, mode %d\n", d->name, mode);
2414         transmit_response(d, req);
2415 }
2416
2417 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2418 {
2419         struct skinny_req *req;
2420
2421         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2422                 return;
2423
2424         req->data.setmicrophone.mode = htolel(mode);
2425
2426         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_MICROPHONE_MESSAGE to %s, mode %d\n", d->name, mode);
2427         transmit_response(d, req);
2428 }
2429
2430 //static void transmit_callinfo(struct skinny_subchannel *sub)
2431 static void transmit_callinfo(struct skinny_device *d, int instance, int callid,
2432         char *fromname, char *fromnum, char *toname, char *tonum, int calldirection, char *origtonum, char *origtoname)
2433 {
2434         struct skinny_req *req;
2435
2436         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2437                 return;
2438
2439         ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2440         ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2441         ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2442         ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2443         if (origtoname) {
2444                 ast_copy_string(req->data.callinfo.originalCalledPartyName, origtoname, sizeof(req->data.callinfo.originalCalledPartyName));
2445         }
2446         if (origtonum) {
2447                 ast_copy_string(req->data.callinfo.originalCalledParty, origtonum, sizeof(req->data.callinfo.originalCalledParty));
2448         }
2449
2450         req->data.callinfo.instance = htolel(instance);
2451         req->data.callinfo.reference = htolel(callid);
2452         req->data.callinfo.type = htolel(calldirection);
2453
2454         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",
2455                 d->name, toname, tonum, fromname, fromnum, origtoname, origtonum, calldirection, d->name, instance);
2456         transmit_response(d, req);
2457 }
2458
2459 static void transmit_callinfo_variable(struct skinny_device *d, int instance, int callreference,
2460         char *fromname, char *fromnum, char *toname, char *tonum, int calldirection, char *origtonum, char *origtoname)
2461 {
2462         struct skinny_req *req;
2463         char *strptr;
2464         char *thestrings[13];
2465         int i;
2466         int callinfostrleft = MAXCALLINFOSTR;
2467
2468         if (!(req = req_alloc(sizeof(struct call_info_message_variable), CALL_INFO_MESSAGE_VARIABLE)))
2469                 return;
2470
2471         req->data.callinfomessagevariable.instance = htolel(instance);
2472         req->data.callinfomessagevariable.callreference = htolel(callreference);
2473         req->data.callinfomessagevariable.calldirection = htolel(calldirection);
2474
2475         req->data.callinfomessagevariable.unknown1 = htolel(0x00);
2476         req->data.callinfomessagevariable.unknown2 = htolel(0x00);
2477         req->data.callinfomessagevariable.unknown3 = htolel(0x00);
2478         req->data.callinfomessagevariable.unknown4 = htolel(0x00);
2479         req->data.callinfomessagevariable.unknown5 = htolel(0x00);
2480
2481         thestrings[0] = fromnum;
2482         thestrings[1] = "";                     /* Appears to be origfrom */
2483         if (calldirection == SKINNY_OUTGOING) {
2484                 thestrings[2] = tonum;
2485                 thestrings[3] = origtonum;
2486         } else {
2487                 thestrings[2] = "";
2488                 thestrings[3] = "";
2489         }
2490         thestrings[4] = "";
2491         thestrings[5] = "";
2492         thestrings[6] = "";
2493         thestrings[7] = "";
2494
2495         thestrings[8] = "";
2496         thestrings[9] = fromname;
2497         thestrings[10] = toname;
2498         thestrings[11] = origtoname;
2499         thestrings[12] = "";
2500
2501         strptr = req->data.callinfomessagevariable.calldetails;
2502
2503         for(i = 0; i < 13; i++) {
2504                 if (thestrings[i]) {
2505                         ast_copy_string(strptr, thestrings[i], callinfostrleft);
2506                         strptr += strlen(thestrings[i]) + 1;
2507                         callinfostrleft -= strlen(thestrings[i]) + 1;
2508                 } else {
2509                         ast_copy_string(strptr, "", callinfostrleft);
2510                         strptr++;
2511                         callinfostrleft--;
2512                 }
2513         }
2514
2515         req->len = req->len - (callinfostrleft & ~0x3);
2516
2517         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",
2518                 d->name, toname, tonum, fromname, fromnum, origtoname, origtonum, calldirection, d->name, instance);
2519         transmit_response(d, req);
2520 }
2521
2522 static void send_callinfo(struct skinny_subchannel *sub)
2523 {
2524         struct ast_channel *ast;
2525         struct skinny_device *d;
2526         struct skinny_line *l;
2527         struct ast_party_id connected_id;
2528         char *fromname;
2529         char *fromnum;
2530         char *toname;
2531         char *tonum;
2532
2533         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2534                 return;
2535         }
2536
2537         ast = sub->owner;
2538         l = sub->line;
2539         d = l->device;
2540         connected_id = ast_channel_connected_effective_id(ast);
2541
2542         if (sub->calldirection == SKINNY_INCOMING) {
2543                 if ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
2544                         fromname = S_COR(connected_id.name.valid, connected_id.name.str, "");
2545                         fromnum = S_COR(connected_id.number.valid, connected_id.number.str, "");
2546                 } else {
2547                         fromname = "";
2548                         fromnum = "";
2549                 }
2550                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2551                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2552         } else if (sub->calldirection == SKINNY_OUTGOING) {
2553                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2554                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2555                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2556                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2557         } else {
2558                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2559                 return;
2560         }
2561
2562         if (d->protocolversion < 17) {
2563                 transmit_callinfo(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
2564         } else {
2565                 transmit_callinfo_variable(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
2566         }
2567 }
2568
2569 static void push_callinfo(struct skinny_subline *subline, struct skinny_subchannel *sub)
2570 {
2571         struct ast_channel *ast;
2572         struct skinny_device *d;
2573         struct skinny_line *l;
2574         struct ast_party_id connected_id;
2575         char *fromname;
2576         char *fromnum;
2577         char *toname;
2578         char *tonum;
2579
2580         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2581                 return;
2582         }
2583
2584         ast = sub->owner;
2585         l = sub->line;
2586         d = l->device;
2587         connected_id = ast_channel_connected_effective_id(ast);
2588
2589         if (sub->calldirection == SKINNY_INCOMING) {
2590                 if((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
2591                         fromname = S_COR(connected_id.name.valid, connected_id.name.str, "");
2592                         fromnum = S_COR(connected_id.number.valid, connected_id.number.str, "");
2593                 } else {
2594                         fromname = "";
2595                         fromnum = "";
2596                 }
2597                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2598                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2599         } else if (sub->calldirection == SKINNY_OUTGOING) {
2600                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2601                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2602                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2603                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2604         } else {
2605                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2606                 return;
2607         }
2608
2609         if (d->protocolversion < 17) {
2610                 transmit_callinfo(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
2611         } else {
2612                 transmit_callinfo_variable(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection, sub->origtonum, sub->origtoname);
2613         }
2614 }
2615
2616 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2617 {
2618         struct skinny_req *req;
2619         struct skinny_line *l = sub->line;
2620         struct ast_format_list fmt;
2621         struct ast_format tmpfmt;
2622
2623         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2624                 return;
2625         ast_best_codec(l->cap, &tmpfmt);
2626         fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
2627
2628         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2629         req->data.openreceivechannel.partyId = htolel(sub->callid);
2630         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2631         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(&fmt.format));
2632         req->data.openreceivechannel.echo = htolel(0);
2633         req->data.openreceivechannel.bitrate = htolel(0);
2634
2635         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",
2636                 d->name, sub->callid, sub->callid, fmt.cur_ms, codec_ast2skinny(&fmt.format), 0, 0);
2637         transmit_response(d, req);
2638 }
2639
2640 static void transmit_start_tone(struct skinny_device *d, int tone, int instance, int reference)
2641 {
2642         struct skinny_req *req;
2643         if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2644                 return;
2645         req->data.starttone.tone = htolel(tone);
2646         req->data.starttone.instance = htolel(instance);
2647         req->data.starttone.reference = htolel(reference);
2648
2649         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting START_TONE_MESSAGE to %s, tone %d, inst %d, ref %d\n",
2650                 d->name, tone, instance, reference);
2651         transmit_response(d, req);
2652 }
2653
2654 static void transmit_stop_tone(struct skinny_device *d, int instance, int reference)
2655 {
2656         struct skinny_req *req;
2657         if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2658                 return;
2659         req->data.stoptone.instance = htolel(instance);
2660         req->data.stoptone.reference = htolel(reference);
2661
2662         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_TONE_MESSAGE to %s, inst %d, ref %d\n",
2663                 d->name, instance, reference);
2664         transmit_response(d, req);
2665 }
2666
2667 static int keyset_translatebitmask(int keyset, int intmask)
2668 {
2669         int extmask = 0;
2670         int x, y;
2671         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
2672
2673         for(x = 0; x < ARRAY_LEN(soft_key_default_definitions); x++) {
2674                 if (softkeymode[x].mode == keyset) {
2675                         const uint8_t *defaults = softkeymode[x].defaults;
2676
2677                         for (y = 0; y < softkeymode[x].count; y++) {
2678                                 if (intmask & (1 << (defaults[y]))) {
2679                                         extmask |= (1 << ((y)));
2680                                 }
2681                         }
2682                         break;
2683                 }
2684         }
2685
2686         return extmask;
2687 }
2688
2689 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey, int mask)
2690 {
2691         struct skinny_req *req;
2692         int newmask;
2693
2694         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2695                 return;
2696
2697         newmask = keyset_translatebitmask(softkey, mask);
2698         req->data.selectsoftkey.instance = htolel(instance);
2699         req->data.selectsoftkey.reference = htolel(callid);
2700         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2701         req->data.selectsoftkey.validKeyMask = htolel(newmask);
2702
2703         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SELECT_SOFT_KEYS_MESSAGE to %s, inst %d, callid %d, softkey %d, mask 0x%08x\n",
2704                 d->name, instance, callid, softkey, newmask);
2705         transmit_response(d, req);
2706 }
2707
2708 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2709 {
2710         struct skinny_req *req;
2711
2712         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2713                 return;
2714
2715         req->data.setlamp.stimulus = htolel(stimulus);
2716         req->data.setlamp.stimulusInstance = htolel(instance);
2717         req->data.setlamp.deviceStimulus = htolel(indication);
2718
2719         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_LAMP_MESSAGE to %s, stim %d, inst %d, ind %d\n",
2720                 d->name, stimulus, instance, indication);
2721         transmit_response(d, req);
2722 }
2723
2724 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2725 {
2726         struct skinny_req *req;
2727
2728         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2729                 return;
2730
2731         req->data.setringer.ringerMode = htolel(mode);
2732         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2733            Note: The phone will always show as ringing on the display.
2734
2735            1: phone will audibly ring over and over
2736            2: phone will audibly ring only once
2737            any other value, will NOT cause the phone to audibly ring
2738         */
2739         req->data.setringer.unknown1 = htolel(1);
2740         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2741            Perhaps a packet capture can shed some light on this. */
2742         req->data.setringer.unknown2 = htolel(1);
2743
2744         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_RINGER_MESSAGE to %s, mode %d, unk1 1, unk2 1\n",
2745                 d->name, mode);
2746         transmit_response(d, req);
2747 }
2748
2749 static void transmit_clear_display_message(struct skinny_device *d, int instance, int reference)
2750 {
2751         struct skinny_req *req;
2752         if (!(req = req_alloc(sizeof(struct clear_display_message), CLEAR_DISPLAY_MESSAGE)))
2753                 return;
2754
2755         //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2756         //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2757         //req->data.clearpromptstatus.lineInstance = instance;
2758         //req->data.clearpromptstatus.callReference = reference;
2759
2760         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_DISPLAY_MESSAGE to %s\n", d->name);
2761         transmit_response(d, req);
2762 }
2763
2764 /* This function is not currently used, but will be (wedhorn)*/
2765 /* static void transmit_display_message(struct skinny_device *d, const char *text, int instance, int reference)
2766 {
2767         struct skinny_req *req;
2768
2769         if (text == 0) {
2770                 ast_verb(1, "Bug, Asked to display empty message\n");
2771                 return;
2772         }
2773
2774         if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2775                 return;
2776
2777         ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2778         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAYTEXT_MESSAGE to %s, text %s\n", d->name, text);
2779         transmit_response(d, req);
2780 } */
2781
2782 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2783 {
2784         struct skinny_req *req;
2785
2786         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2787                 return;
2788
2789         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2790         req->data.displaynotify.displayTimeout = htolel(t);
2791
2792         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_NOTIFY_MESSAGE to %s, text %s\n", d->name, text);
2793         transmit_response(d, req);
2794 }
2795
2796 static void transmit_clearprinotify(struct skinny_device *d, int priority)
2797 {
2798         struct skinny_req *req;
2799
2800         if (!(req = req_alloc(sizeof(struct clear_prinotify_message), CLEAR_PRINOTIFY_MESSAGE)))
2801                 return;
2802
2803         req->data.clearprinotify.priority = htolel(priority);
2804
2805         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_PRINOTIFY_MESSAGE to %s, priority %d\n", d->name, priority);
2806         transmit_response(d, req);
2807 }
2808
2809 static void _transmit_displayprinotify(struct skinny_device *d, const char *text, const char *extratext, int timeout, int priority)
2810 {
2811         struct skinny_req *req;
2812
2813         if (!(req = req_alloc(sizeof(struct display_prinotify_message), DISPLAY_PRINOTIFY_MESSAGE)))
2814                 return;
2815
2816         req->data.displayprinotify.timeout = htolel(timeout);
2817         req->data.displayprinotify.priority = htolel(priority);
2818
2819         if ((char)*text == '\200') {
2820                 int octalstrlen = strlen(text);
2821                 ast_copy_string(req->data.displayprinotify.text, text, sizeof(req->data.displayprinotify.text));
2822                 ast_copy_string(req->data.displayprinotify.text+octalstrlen, extratext, sizeof(req->data.displayprinotify.text)-octalstrlen);
2823                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE to %s, '\\%03o\\%03o', '%s', timeout=%d, priority=%d\n",
2824                         d->name, (uint8_t)*text, (uint8_t)*(text+1), extratext, timeout, priority);
2825         } else {
2826                 ast_copy_string(req->data.displayprinotify.text, text, sizeof(req->data.displayprinotify.text));
2827                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE to %s, '%s', timeout=%d, priority=%d\n",
2828                         d->name, text, timeout, priority);
2829         }
2830
2831         transmit_response(d, req);
2832 }
2833
2834 static void _transmit_displayprinotifyvar(struct skinny_device *d, const char *text, const char *extratext, int timeout, int priority)
2835 {
2836         struct skinny_req *req;
2837         int packetlen;
2838
2839         if (!(req = req_alloc(sizeof(struct display_prinotify_message_variable), DISPLAY_PRINOTIFY_MESSAGE_VARIABLE)))
2840                 return;
2841
2842         req->data.displayprinotifyvar.timeout = htolel(timeout);
2843         req->data.displayprinotifyvar.priority = htolel(priority);
2844
2845         if ((char)*text == '\200') {
2846                 int octalstrlen = strlen(text);
2847                 ast_copy_string(req->data.displayprinotifyvar.text, text, sizeof(req->data.displayprinotifyvar.text));
2848                 ast_copy_string(req->data.displayprinotifyvar.text+octalstrlen, extratext, sizeof(req->data.displayprinotifyvar.text)-octalstrlen);
2849                 packetlen = req->len - MAXDISPLAYNOTIFYSTR + strlen(text) + strlen(extratext);
2850                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE_VARIABLE to %s, '\\%03o\\%03o', '%s', timeout=%d, priority=%d\n",
2851                         d->name, (uint8_t)*text, (uint8_t)*(text+1), extratext, timeout, priority);
2852         } else {
2853                 ast_copy_string(req->data.displayprinotifyvar.text, text, sizeof(req->data.displayprinotifyvar.text));
2854                 packetlen = req->len - MAXDISPLAYNOTIFYSTR + strlen(text);
2855                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PRINOTIFY_MESSAGE_VARIABLE to %s, '%s', timeout=%d, priority=%d\n",
2856                         d->name, text, timeout, priority);
2857         }
2858         
2859         req->len = (packetlen & ~0x3) + 4;
2860
2861         transmit_response(d, req);
2862 }
2863
2864 static void send_displayprinotify(struct skinny_device *d, const char *text, const char *extratext, int timeout, int priority)
2865 {
2866         if (d->protocolversion < 17) {
2867                 _transmit_displayprinotify(d, text, extratext, timeout, priority);
2868         } else {
2869                 _transmit_displayprinotifyvar(d, text, extratext, timeout, priority);
2870         }
2871 }
2872
2873 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, const char *extratext, int t, int instance, int callid)
2874 {
2875         struct skinny_req *req;
2876
2877         if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2878                 return;
2879
2880         req->data.displaypromptstatus.messageTimeout = htolel(t);
2881         req->data.displaypromptstatus.lineInstance = htolel(instance);
2882         req->data.displaypromptstatus.callReference = htolel(callid);
2883
2884         if ((char)*text == '\200') {
2885                 int octalstrlen = strlen(text);
2886                 ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatusvar.promptMessage));
2887                 ast_copy_string(req->data.displaypromptstatus.promptMessage+octalstrlen, extratext, sizeof(req->data.displaypromptstatus.promptMessage)-octalstrlen);
2888                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE to %s, '\\%03o\\%03o', '%s'\n",
2889                         d->name, (uint8_t)*text, (uint8_t)*(text+1), extratext);
2890         } else {
2891                 ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2892                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE to %s, '%s'\n",
2893                         d->name, text);
2894         }
2895         transmit_response(d, req);
2896 }
2897
2898 static void transmit_displaypromptstatusvar(struct skinny_device *d, const char *text, const char *extratext, int t, int instance, int callid)
2899 {
2900         struct skinny_req *req;
2901         int packetlen;
2902
2903         if (!(req = req_alloc(sizeof(struct display_prompt_status_message_variable), DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE)))
2904                 return;
2905
2906         req->data.displaypromptstatusvar.lineInstance = htolel(instance);
2907         req->data.displaypromptstatusvar.callReference = htolel(callid);
2908
2909         if ((char)*text == '\200') {
2910                 int octalstrlen = strlen(text);
2911                 ast_copy_string(req->data.displaypromptstatusvar.promptMessage, text, sizeof(req->data.displaypromptstatusvar.promptMessage));
2912                 ast_copy_string(req->data.displaypromptstatusvar.promptMessage+octalstrlen, extratext, sizeof(req->data.displaypromptstatusvar.promptMessage)-octalstrlen);
2913                 packetlen = req->len - MAXCALLINFOSTR + strlen(text) + strlen(extratext);
2914                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE to %s, '\\%03o\\%03o', '%s'\n",
2915                         d->name, (uint8_t)*text, (uint8_t)*(text+1), extratext);
2916         } else {
2917                 ast_copy_string(req->data.displaypromptstatusvar.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2918                 packetlen = req->len - MAXCALLINFOSTR + strlen(text);
2919                 SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE_VARIABLE to %s, '%s'\n",
2920                         d->name, text);
2921         }
2922         req->len = (packetlen & ~0x3) + 4;
2923
2924         transmit_response(d, req);
2925 }
2926
2927 static void send_displaypromptstatus(struct skinny_device *d, const char *text, const char *extratext, int t, int instance, int callid)
2928 {
2929         if (d->protocolversion < 17) {
2930                 transmit_displaypromptstatus(d, text, extratext, t, instance, callid);
2931         } else {
2932                 transmit_displaypromptstatusvar(d, text, extratext, t, instance, callid);
2933         }
2934 }
2935
2936 static void transmit_clearpromptmessage(struct skinny_device *d, int instance, int callid)
2937 {
2938         struct skinny_req *req;
2939
2940         if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2941                 return;
2942
2943         req->data.clearpromptstatus.lineInstance = htolel(instance);
2944         req->data.clearpromptstatus.callReference = htolel(callid);
2945
2946         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_PROMPT_MESSAGE to %s, inst %d, callid %d\n",
2947                 d->name, instance, callid);
2948         transmit_response(d, req);
2949 }
2950
2951 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2952 {
2953         struct skinny_req *req;
2954
2955         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2956                 return;
2957
2958         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2959         req->data.dialednumber.lineInstance = htolel(instance);
2960         req->data.dialednumber.callReference = htolel(callid);
2961
2962         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DIALED_NUMBER_MESSAGE to %s, num %s, inst %d, callid %d\n",
2963                 d->name, text, instance, callid);
2964         transmit_response(d, req);
2965 }
2966
2967 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2968 {
2969         struct skinny_req *req;
2970
2971         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2972                 return;
2973
2974         req->data.closereceivechannel.conferenceId = htolel(0);
2975         req->data.closereceivechannel.partyId = htolel(sub->callid);
2976
2977         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLOSE_RECEIVE_CHANNEL_MESSAGE to %s, confid %d, callid %d\n",
2978                 d->name, 0, sub->callid);
2979         transmit_response(d, req);
2980 }
2981
2982 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2983 {
2984         struct skinny_req *req;
2985
2986         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2987                 return;
2988
2989         req->data.stopmedia.conferenceId = htolel(0);
2990         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2991
2992         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_MEDIA_TRANSMISSION_MESSAGE to %s, confid %d, passthrupartyid %d\n",
2993                 d->name, 0, sub->callid);
2994         transmit_response(d, req);
2995 }
2996
2997 static void transmit_startmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub, struct sockaddr_in dest, struct ast_format_list fmt)
2998 {
2999         struct skinny_req *req;
3000
3001         if (d->protocolversion < 17) {
3002                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip4), START_MEDIA_TRANSMISSION_MESSAGE)))
3003                         return;
3004                 req->data.startmedia_ip4.conferenceId = htolel(sub->callid);
3005                 req->data.startmedia_ip4.passThruPartyId = htolel(sub->callid);
3006                 req->data.startmedia_ip4.remoteIp = dest.sin_addr.s_addr;
3007                 req->data.startmedia_ip4.remotePort = htolel(ntohs(dest.sin_port));
3008                 req->data.startmedia_ip4.packetSize = htolel(fmt.cur_ms);
3009                 req->data.startmedia_ip4.payloadType = htolel(codec_ast2skinny(&fmt.format));
3010                 req->data.startmedia_ip4.qualifier.precedence = htolel(127);
3011                 req->data.startmedia_ip4.qualifier.vad = htolel(0);
3012                 req->data.startmedia_ip4.qualifier.packets = htolel(0);
3013                 req->data.startmedia_ip4.qualifier.bitRate = htolel(0);
3014         } else {
3015                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip6), START_MEDIA_TRANSMISSION_MESSAGE)))
3016                         return;
3017                 req->data.startmedia_ip6.conferenceId = htolel(sub->callid);
3018                 req->data.startmedia_ip6.passThruPartyId = htolel(sub->callid);
3019                 memcpy(req->data.startmedia_ip6.remoteIp, &dest.sin_addr.s_addr, sizeof(dest.sin_addr.s_addr));
3020                 req->data.startmedia_ip6.remotePort = htolel(ntohs(dest.sin_port));
3021                 req->data.startmedia_ip6.packetSize = htolel(fmt.cur_ms);
3022                 req->data.startmedia_ip6.payloadType = htolel(codec_ast2skinny(&fmt.format));
3023                 req->data.startmedia_ip6.qualifier.precedence = htolel(127);
3024                 req->data.startmedia_ip6.qualifier.vad = htolel(0);
3025                 req->data.startmedia_ip6.qualifier.packets = htolel(0);
3026                 req->data.startmedia_ip6.qualifier.bitRate = htolel(0);
3027         }
3028
3029         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",
3030                 d->name, sub->callid, sub->callid, ast_inet_ntoa(dest.sin_addr), dest.sin_port, fmt.cur_ms, codec_ast2skinny(&fmt.format));
3031         transmit_response(d, req);
3032 }
3033
3034 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
3035 {
3036         struct skinny_req *req;
3037
3038         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
3039                 return;
3040
3041         req->data.activatecallplane.lineInstance = htolel(l->instance);
3042
3043         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting ACTIVATE_CALL_PLANE_MESSAGE to %s, inst %d\n",
3044                 d->name, l->instance);
3045         transmit_response(d, req);
3046 }
3047
3048 static void transmit_callstate(struct skinny_device *d, int buttonInstance, unsigned callid, int state)
3049 {
3050         struct skinny_req *req;
3051
3052         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
3053                 return;
3054
3055         req->data.callstate.callState = htolel(state);
3056         req->data.callstate.lineInstance = htolel(buttonInstance);
3057         req->data.callstate.callReference = htolel(callid);
3058
3059         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_STATE_MESSAGE to %s, state %s, inst %d, callid %d\n",
3060                 d->name, callstate2str(state), buttonInstance, callid);
3061         transmit_response(d, req);
3062 }
3063
3064 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
3065 {
3066         struct skinny_req *req;
3067         int anyon = 0;
3068
3069         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
3070                 return;
3071
3072         if (l->cfwdtype & SKINNY_CFWD_ALL) {
3073                 if (!ast_strlen_zero(l->call_forward_all)) {
3074                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
3075                         req->data.forwardstat.fwdall = htolel(1);
3076                         anyon++;
3077                 } else {
3078                         req->data.forwardstat.fwdall = htolel(0);
3079                 }
3080         }
3081         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
3082                 if (!ast_strlen_zero(l->call_forward_busy)) {
3083                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
3084                         req->data.forwardstat.fwdbusy = htolel(1);
3085                         anyon++;
3086                 } else {
3087                         req->data.forwardstat.fwdbusy = htolel(0);
3088                 }
3089         }
3090         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
3091                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
3092                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
3093                         req->data.forwardstat.fwdnoanswer = htolel(1);
3094                         anyon++;
3095                 } else {
3096                         req->data.forwardstat.fwdnoanswer = htolel(0);
3097                 }
3098         }
3099         req->data.forwardstat.lineNumber = htolel(l->instance);
3100         if (anyon)
3101                 req->data.forwardstat.activeforward = htolel(7);
3102         else
3103                 req->data.forwardstat.activeforward = htolel(0);
3104
3105         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting FORWARD_STAT_MESSAGE to %s, inst %d, all %s, busy %s, noans %s, acitve %d\n",
3106                 d->name, l->instance, l->call_forward_all, l->call_forward_busy, l->call_forward_noanswer, anyon ? 7 : 0);
3107         transmit_response(d, req);
3108 }
3109
3110 static void transmit_speeddialstatres(struct skinny_device *d, struct skinny_speeddial *sd)
3111 {
3112         struct skinny_req *req;
3113
3114         if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
3115                 return;
3116
3117         req->data.speeddialreq.speedDialNumber = htolel(sd->instance);
3118         ast_copy_string(req->data.speeddial.speedDialDirNumber, sd->exten, sizeof(req->data.speeddial.speedDialDirNumber));
3119         ast_copy_string(req->data.speeddial.speedDialDisplayName, sd->label, sizeof(req->data.speeddial.speedDialDisplayName));
3120
3121         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SPEED_DIAL_STAT_RES_MESSAGE to %s, inst %d, dir %s, display %s\n",
3122                 d->name, sd->instance, sd->exten, sd->label);
3123         transmit_response(d, req);
3124 }
3125
3126 //static void transmit_linestatres(struct skinny_device *d, struct skinny_line *l)
3127 static void transmit_linestatres(struct skinny_device *d, int instance)
3128 {
3129         struct skinny_req *req;
3130         struct skinny_line *l;
3131         struct skinny_speeddial *sd;
3132
3133         if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
3134                 return;
3135
3136         if ((l = find_line_by_instance(d, instance))) {
3137                 req->data.linestat.lineNumber = letohl(l->instance);
3138                 memcpy(req->data.linestat.lineDirNumber, l->name, sizeof(req->data.linestat.lineDirNumber));
3139                 memcpy(req->data.linestat.lineDisplayName, l->label, sizeof(req->data.linestat.lineDisplayName));
3140         } else if ((sd = find_speeddial_by_instance(d, instance, 1))) {
3141                 req->data.linestat.lineNumber = letohl(sd->instance);
3142                 memcpy(req->data.linestat.lineDirNumber, sd->label, sizeof(req->data.linestat.lineDirNumber));
3143                 memcpy(req->data.linestat.lineDisplayName, sd->label, sizeof(req->data.linestat.lineDisplayName));
3144         }
3145
3146         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting LINE_STAT_RES_MESSAGE to %s, inst %d, num %s, label %s\n",
3147                 d->name, l->instance, req->data.linestat.lineDirNumber, req->data.linestat.lineDisplayName);
3148         transmit_response(d, req);
3149 }
3150
3151 static void transmit_definetimedate(struct skinny_device *d)
3152 {
3153         struct skinny_req *req;
3154         struct timeval now = ast_tvnow();
3155         struct ast_tm cmtime;
3156
3157         if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
3158                 return;
3159
3160         ast_localtime(&now, &cmtime, NULL);
3161         req->data.definetimedate.year = htolel(cmtime.tm_year+1900);
3162         req->data.definetimedate.month = htolel(cmtime.tm_mon+1);
3163         req->data.definetimedate.dayofweek = htolel(cmtime.tm_wday);
3164         req->data.definetimedate.day = htolel(cmtime.tm_mday);
3165         req->data.definetimedate.hour = htolel(cmtime.tm_hour);
3166         req->data.definetimedate.minute = htolel(cmtime.tm_min);
3167         req->data.definetimedate.seconds = htolel(cmtime.tm_sec);
3168         req->data.definetimedate.milliseconds = htolel(cmtime.tm_usec / 1000);
3169         req->data.definetimedate.timestamp = htolel(now.tv_sec);
3170
3171         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DEFINETIMEDATE_MESSAGE to %s, date %d %d %d dow %d time %d:%d:%d.%d\n",
3172                 d->name, req->data.definetimedate.year, req->data.definetimedate.month, req->data.definetimedate.day, req->data.definetimedate.dayofweek,
3173                 req->data.definetimedate.hour, req->data.definetimedate.minute, req->data.definetimedate.seconds, req->data.definetimedate.milliseconds);
3174         transmit_response(d, req);
3175 }
3176
3177 static void transmit_versionres(struct skinny_device *d)
3178 {
3179         struct skinny_req *req;
3180         if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
3181                 return;
3182
3183         ast_copy_string(req->data.version.version, d->version_id, sizeof(req->data.version.version));
3184
3185         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting VERSION_RES_MESSAGE to %s, version %s\n", d->name, d->version_id);
3186         transmit_response(d, req);
3187 }
3188
3189 static void transmit_serverres(struct skinny_device *d)
3190 {
3191         struct skinny_req *req;
3192         if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
3193                 return;
3194
3195         memcpy(req->data.serverres.server[0].serverName, ourhost,
3196                         sizeof(req->data.serverres.server[0].serverName));
3197         req->data.serverres.serverListenPort[0] = htolel(ourport);
3198         req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
3199
3200         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SERVER_RES_MESSAGE to %s, srvname %s %s:%d\n",
3201                 d->name, ourhost, ast_inet_ntoa(d->ourip), ourport);
3202         transmit_response(d, req);
3203 }
3204
3205 static void transmit_softkeysetres(struct skinny_device *d)
3206 {
3207         struct skinny_req *req;
3208         int i;
3209         int x;
3210         int y;
3211         int keydefcount;
3212         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
3213
3214         if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
3215                 return;
3216
3217         SKINNY_DEBUG(DEBUG_TEMPLATE, 3, "Creating Softkey Template\n");
3218
3219         keydefcount = ARRAY_LEN(soft_key_default_definitions);
3220         req->data.softkeysets.softKeySetOffset = htolel(0);
3221         req->data.softkeysets.softKeySetCount = htolel(keydefcount);
3222         req->data.softkeysets.totalSoftKeySetCount = htolel(keydefcount);
3223         for (x = 0; x < keydefcount; x++) {
3224                 const uint8_t *defaults = softkeymode->defaults;
3225                 /* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
3226                    This will have to do for now. */
3227                 for (y = 0; y < softkeymode->count; y++) {
3228                         for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
3229                                 if (defaults[y] == i+1) {
3230                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = (i+1);
3231                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyInfoIndex[y] = htoles(i+301);
3232                                         SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "softKeySetDefinition : softKeyTemplateIndex: %d softKeyInfoIndex: %d\n",
3233                                                 i+1, i+301);
3234                                 }
3235                         }
3236                 }
3237                 softkeymode++;
3238         }
3239
3240         SKINNY_DEBUG(DEBUG_PACKET | DEBUG_TEMPLATE, 3, "Transmitting SOFT_KEY_SET_RES_MESSAGE to %s, template data\n",
3241                 d->name);
3242         transmit_response(d, req);
3243 }
3244
3245 static void transmit_softkeytemplateres(struct skinny_device *d)
3246 {
3247         struct skinny_req *req;
3248
3249         if (!(req = req_alloc(sizeof(struct soft_key_template_res_message), SOFT_KEY_TEMPLATE_RES_MESSAGE)))
3250                 return;
3251
3252         req->data.softkeytemplate.softKeyOffset = htolel(0);
3253         req->data.softkeytemplate.softKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
3254         req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
3255         memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
3256                 soft_key_template_default,
3257                 sizeof(soft_key_template_default));
3258
3259         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SOFT_KEY_TEMPLATE_RES_MESSAGE to %s, offset 0, keycnt %d, totalkeycnt %d, template data\n",
3260                 d->name, req->data.softkeytemplate.softKeyCount, req->data.softkeytemplate.totalSoftKeyCount);
3261         transmit_response(d, req);
3262 }
3263
3264 static void transmit_reset(struct skinny_device *d, int fullrestart)
3265 {
3266         struct skinny_req *req;
3267
3268         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
3269                 return;
3270
3271         if (fullrestart)
3272                 req->data.reset.resetType = 2;
3273         else
3274                 req->data.reset.resetType = 1;
3275
3276         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting RESET_MESSAGE to %s, type %s\n",
3277                 d->name, (fullrestart) ? "Restarting" : "Resetting");
3278         transmit_response(d, req);
3279 }
3280
3281 static void transmit_keepaliveack(struct skinny_device *d)
3282 {
3283         struct skinny_req *req;
3284
3285         if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))