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