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