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