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