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