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