Adds variable length callinfo packets to skinny.
[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 static struct soft_key_template_definition soft_key_template_default[] = {
749         { "\200\001", SOFTKEY_REDIAL },
750         { "\200\002", SOFTKEY_NEWCALL },
751         { "\200\003", SOFTKEY_HOLD },
752         { "\200\004", SOFTKEY_TRNSFER },
753         { "\200\005", SOFTKEY_CFWDALL },
754         { "\200\006", SOFTKEY_CFWDBUSY },
755         { "\200\007", SOFTKEY_CFWDNOANSWER },
756         { "\200\010", SOFTKEY_BKSPC },
757         { "\200\011", SOFTKEY_ENDCALL },
758         { "\200\012", SOFTKEY_RESUME },
759         { "\200\013", SOFTKEY_ANSWER },
760         { "\200\014", SOFTKEY_INFO },
761         { "\200\015", SOFTKEY_CONFRN },
762         { "\200\016", SOFTKEY_PARK },
763         { "\200\017", SOFTKEY_JOIN },
764         { "\200\020", SOFTKEY_MEETME },
765         { "\200\021", SOFTKEY_PICKUP },
766         { "\200\022", SOFTKEY_GPICKUP },
767         { "\200\077", SOFTKEY_DND },
768         { "\200\120", SOFTKEY_IDIVERT },
769         { "Dial", SOFTKEY_FORCEDIAL},
770 };
771
772 /* Localized message "codes" (in octal)
773    Below is en_US (taken from a 7970)
774
775    \200\xxx
776        \000: ???
777        \001: Redial
778        \002: New Call
779        \003: Hold
780        \004: Transfer
781        \005: CFwdALL
782        \006: CFwdBusy
783        \007: CFwdNoAnswer
784        \010: <<
785        \011: EndCall
786        \012: Resume
787        \013: Answer
788        \014: Info
789        \015: Confrn
790        \016: Park
791        \017: Join
792        \020: MeetMe
793        \021: PickUp
794        \022: GPickUp
795        \023: Your current options
796        \024: Off Hook
797        \025: On Hook
798        \026: Ring out
799        \027: From
800        \030: Connected
801        \031: Busy
802        \032: Line In Use
803        \033: Call Waiting
804        \034: Call Transfer
805        \035: Call Park
806        \036: Call Proceed
807        \037: In Use Remote
808        \040: Enter number
809        \041: Call park At
810        \042: Primary Only
811        \043: Temp Fail
812        \044: You Have VoiceMail
813        \045: Forwarded to
814        \046: Can Not Complete Conference
815        \047: No Conference Bridge
816        \050: Can Not Hold Primary Control
817        \051: Invalid Conference Participant
818        \052: In Conference Already
819        \053: No Participant Info
820        \054: Exceed Maximum Parties
821        \055: Key Is Not Active
822        \056: Error No License
823        \057: Error DBConfig
824        \060: Error Database
825        \061: Error Pass Limit
826        \062: Error Unknown
827        \063: Error Mismatch
828        \064: Conference
829        \065: Park Number
830        \066: Private
831        \067: Not Enough Bandwidth
832        \070: Unknown Number
833        \071: RmLstC
834        \072: Voicemail
835        \073: ImmDiv
836        \074: Intrcpt
837        \075: SetWtch
838        \076: TrnsfVM
839        \077: DND
840        \100: DivAll
841        \101: CallBack
842        \102: Network congestion,rerouting
843        \103: Barge
844        \104: Failed to setup Barge
845        \105: Another Barge exists
846        \106: Incompatible device type
847        \107: No Park Number Available
848        \110: CallPark Reversion
849        \111: Service is not Active
850        \112: High Traffic Try Again Later
851        \113: QRT
852        \114: MCID
853        \115: DirTrfr
854        \116: Select
855        \117: ConfList
856        \120: iDivert
857        \121: cBarge
858        \122: Can Not Complete Transfer
859        \123: Can Not Join Calls
860        \124: Mcid Successful
861        \125: Number Not Configured
862        \126: Security Error
863        \127: Video Bandwidth Unavailable
864        \130: VidMode
865        \131: Max Call Duration Timeout
866        \132: Max Hold Duration Timeout
867        \133: OPickUp
868        \134: ???
869        \135: ???
870        \136: ???
871        \137: ???
872        \140: ???
873        \141: External Transfer Restricted
874        \142: ???
875        \143: ???
876        \144: ???
877        \145: Mac Address
878        \146: Host Name
879        \147: Domain Name
880        \150: IP Address
881        \151: Subnet Mask
882        \152: TFTP Server 1
883        \153: Default Router 1
884        \154: Default Router 2
885        \155: Default Router 3
886        \156: Default Router 4
887        \157: Default Router 5
888        \160: DNS Server 1
889        \161: DNS Server 2
890        \162: DNS Server 3
891        \163: DNS Server 4
892        \164: DNS Server 5
893        \165: Operational VLAN Id
894        \166: Admin. VLAN Id
895        \167: CallManager 1
896        \170: CallManager 2
897        \171: CallManager 3
898        \172: CallManager 4
899        \173: CallManager 5
900        \174: Information URL
901        \175: Directories URL
902        \176: Messages URL
903        \177: Services URL
904  */
905
906 struct soft_key_definitions {
907         const uint8_t mode;
908         const uint8_t *defaults;
909         const int count;
910 };
911
912 static const uint8_t soft_key_default_onhook[] = {
913         SOFTKEY_REDIAL,
914         SOFTKEY_NEWCALL,
915         SOFTKEY_CFWDALL,
916         SOFTKEY_CFWDBUSY,
917         SOFTKEY_DND,
918         SOFTKEY_GPICKUP,
919         /*SOFTKEY_CONFRN,*/
920 };
921
922 static const uint8_t soft_key_default_connected[] = {
923         SOFTKEY_HOLD,
924         SOFTKEY_ENDCALL,
925         SOFTKEY_TRNSFER,
926         SOFTKEY_PARK,
927         SOFTKEY_CFWDALL,
928         SOFTKEY_CFWDBUSY,
929 };
930
931 static const uint8_t soft_key_default_onhold[] = {
932         SOFTKEY_RESUME,
933         SOFTKEY_NEWCALL,
934         SOFTKEY_ENDCALL,
935         SOFTKEY_TRNSFER,
936 };
937
938 static const uint8_t soft_key_default_ringin[] = {
939         SOFTKEY_ANSWER,
940         SOFTKEY_ENDCALL,
941         SOFTKEY_TRNSFER,
942 };
943
944 static const uint8_t soft_key_default_offhook[] = {
945         SOFTKEY_REDIAL,
946         SOFTKEY_ENDCALL,
947         SOFTKEY_CFWDALL,
948         SOFTKEY_CFWDBUSY,
949         SOFTKEY_GPICKUP,
950 };
951
952 static const uint8_t soft_key_default_connwithtrans[] = {
953         SOFTKEY_HOLD,
954         SOFTKEY_ENDCALL,
955         SOFTKEY_TRNSFER,
956         SOFTKEY_PARK,
957         SOFTKEY_CFWDALL,
958         SOFTKEY_CFWDBUSY,
959 };
960
961 static const uint8_t soft_key_default_dadfd[] = {
962         SOFTKEY_BKSPC,
963         SOFTKEY_ENDCALL,
964         SOFTKEY_FORCEDIAL,
965 };
966
967 static const uint8_t soft_key_default_connwithconf[] = {
968         SOFTKEY_NONE,
969 };
970
971 static const uint8_t soft_key_default_ringout[] = {
972         SOFTKEY_NONE,
973         SOFTKEY_ENDCALL,
974 };
975
976 static const uint8_t soft_key_default_offhookwithfeat[] = {
977         SOFTKEY_REDIAL,
978         SOFTKEY_ENDCALL,
979         SOFTKEY_TRNSFER,
980 };
981
982 static const uint8_t soft_key_default_unknown[] = {
983         SOFTKEY_NONE,
984 };
985
986 static const uint8_t soft_key_default_SLAhold[] = {
987         SOFTKEY_REDIAL,
988         SOFTKEY_NEWCALL,
989         SOFTKEY_RESUME,
990 };
991
992 static const uint8_t soft_key_default_SLAconnectednotactive[] = {
993         SOFTKEY_REDIAL,
994         SOFTKEY_NEWCALL,
995         SOFTKEY_JOIN,
996 };
997
998 static const struct soft_key_definitions soft_key_default_definitions[] = {
999         {KEYDEF_ONHOOK, soft_key_default_onhook, sizeof(soft_key_default_onhook) / sizeof(uint8_t)},
1000         {KEYDEF_CONNECTED, soft_key_default_connected, sizeof(soft_key_default_connected) / sizeof(uint8_t)},
1001         {KEYDEF_ONHOLD, soft_key_default_onhold, sizeof(soft_key_default_onhold) / sizeof(uint8_t)},
1002         {KEYDEF_RINGIN, soft_key_default_ringin, sizeof(soft_key_default_ringin) / sizeof(uint8_t)},
1003         {KEYDEF_OFFHOOK, soft_key_default_offhook, sizeof(soft_key_default_offhook) / sizeof(uint8_t)},
1004         {KEYDEF_CONNWITHTRANS, soft_key_default_connwithtrans, sizeof(soft_key_default_connwithtrans) / sizeof(uint8_t)},
1005         {KEYDEF_DADFD, soft_key_default_dadfd, sizeof(soft_key_default_dadfd) / sizeof(uint8_t)},
1006         {KEYDEF_CONNWITHCONF, soft_key_default_connwithconf, sizeof(soft_key_default_connwithconf) / sizeof(uint8_t)},
1007         {KEYDEF_RINGOUT, soft_key_default_ringout, sizeof(soft_key_default_ringout) / sizeof(uint8_t)},
1008         {KEYDEF_OFFHOOKWITHFEAT, soft_key_default_offhookwithfeat, sizeof(soft_key_default_offhookwithfeat) / sizeof(uint8_t)},
1009         {KEYDEF_UNKNOWN, soft_key_default_unknown, sizeof(soft_key_default_unknown) / sizeof(uint8_t)},
1010         {KEYDEF_SLAHOLD, soft_key_default_SLAhold, sizeof(soft_key_default_SLAhold) / sizeof(uint8_t)},
1011         {KEYDEF_SLACONNECTEDNOTACTIVE, soft_key_default_SLAconnectednotactive, sizeof(soft_key_default_SLAconnectednotactive) / sizeof(uint8_t)}
1012 };
1013
1014 struct soft_key_template_res_message {
1015         uint32_t softKeyOffset;
1016         uint32_t softKeyCount;
1017         uint32_t totalSoftKeyCount;
1018         struct soft_key_template_definition softKeyTemplateDefinition[32];
1019 };
1020
1021 #define SOFT_KEY_SET_RES_MESSAGE 0x0109
1022
1023 struct soft_key_set_definition {
1024         uint8_t softKeyTemplateIndex[16];
1025         uint16_t softKeyInfoIndex[16];
1026 };
1027
1028 struct soft_key_set_res_message {
1029         uint32_t softKeySetOffset;
1030         uint32_t softKeySetCount;
1031         uint32_t totalSoftKeySetCount;
1032         struct soft_key_set_definition softKeySetDefinition[16];
1033         uint32_t res;
1034 };
1035
1036 #define SELECT_SOFT_KEYS_MESSAGE 0x0110
1037 struct select_soft_keys_message {
1038         uint32_t instance;
1039         uint32_t reference;
1040         uint32_t softKeySetIndex;
1041         uint32_t validKeyMask;
1042 };
1043
1044 #define CALL_STATE_MESSAGE 0x0111
1045 struct call_state_message {
1046         uint32_t callState;
1047         uint32_t lineInstance;
1048         uint32_t callReference;
1049         uint32_t space[3];
1050 };
1051
1052 #define DISPLAY_PROMPT_STATUS_MESSAGE 0x0112
1053 struct display_prompt_status_message {
1054         uint32_t messageTimeout;
1055         char promptMessage[32];
1056         uint32_t lineInstance;
1057         uint32_t callReference;
1058         uint32_t space[3];
1059 };
1060
1061 #define CLEAR_PROMPT_MESSAGE  0x0113
1062 struct clear_prompt_message {
1063         uint32_t lineInstance;
1064         uint32_t callReference;
1065 };
1066
1067 #define DISPLAY_NOTIFY_MESSAGE 0x0114
1068 struct display_notify_message {
1069         uint32_t displayTimeout;
1070         char displayMessage[100];
1071 };
1072
1073 #define ACTIVATE_CALL_PLANE_MESSAGE 0x0116
1074 struct activate_call_plane_message {
1075         uint32_t lineInstance;
1076 };
1077
1078 #define DIALED_NUMBER_MESSAGE 0x011D
1079 struct dialed_number_message {
1080         char dialedNumber[24];
1081         uint32_t lineInstance;
1082         uint32_t callReference;
1083 };
1084
1085 #define MAXCALLINFOSTR 256
1086 #define CALL_INFO_MESSAGE_VARIABLE 0x014A
1087 struct call_info_message_variable {
1088         uint32_t instance;
1089         uint32_t callreference;
1090         uint32_t calldirection;
1091         uint32_t unknown1;
1092         uint32_t unknown2;
1093         uint32_t unknown3;
1094         uint32_t unknown4;
1095         uint32_t unknown5;
1096         char calldetails[MAXCALLINFOSTR];
1097 };
1098
1099 union skinny_data {
1100         struct alarm_message alarm;
1101         struct speed_dial_stat_req_message speeddialreq;
1102         struct register_message reg;
1103         struct register_ack_message regack;
1104         struct register_rej_message regrej;
1105         struct capabilities_res_message caps;
1106         struct version_res_message version;
1107         struct button_template_res_message buttontemplate;
1108         struct displaytext_message displaytext;
1109         struct clear_display_message cleardisplay;
1110         struct display_prompt_status_message displaypromptstatus;
1111         struct clear_prompt_message clearpromptstatus;
1112         struct definetimedate_message definetimedate;
1113         struct start_tone_message starttone;
1114         struct stop_tone_message stoptone;
1115         struct speed_dial_stat_res_message speeddial;
1116         struct line_state_req_message line;
1117         struct line_stat_res_message linestat;
1118         struct soft_key_set_res_message softkeysets;
1119         struct soft_key_template_res_message softkeytemplate;
1120         struct server_res_message serverres;
1121         struct reset_message reset;
1122         struct set_lamp_message setlamp;
1123         struct set_ringer_message setringer;
1124         struct call_state_message callstate;
1125         struct keypad_button_message keypad;
1126         struct select_soft_keys_message selectsoftkey;
1127         struct activate_call_plane_message activatecallplane;
1128         struct stimulus_message stimulus;
1129         struct offhook_message offhook;
1130         struct onhook_message onhook;
1131         struct set_speaker_message setspeaker;
1132         struct set_microphone_message setmicrophone;
1133         struct call_info_message callinfo;
1134         struct start_media_transmission_message_ip4 startmedia_ip4;
1135         struct start_media_transmission_message_ip6 startmedia_ip6;
1136         struct stop_media_transmission_message stopmedia;
1137         struct open_receive_channel_message openreceivechannel;
1138         struct open_receive_channel_ack_message_ip4 openreceivechannelack_ip4;
1139         struct open_receive_channel_ack_message_ip6 openreceivechannelack_ip6;
1140         struct close_receive_channel_message closereceivechannel;
1141         struct display_notify_message displaynotify;
1142         struct dialed_number_message dialednumber;
1143         struct soft_key_event_message softkeyeventmessage;
1144         struct enbloc_call_message enbloccallmessage;
1145         struct forward_stat_message forwardstat;
1146         struct bksp_req_message bkspmessage;
1147         struct call_info_message_variable callinfomessagevariable;
1148 };
1149
1150 /* packet composition */
1151 struct skinny_req {
1152         int len;
1153         int res;
1154         int e;
1155         union skinny_data data;
1156 };
1157
1158 /* XXX This is the combined size of the variables above.  (len, res, e)
1159    If more are added, this MUST change.
1160    (sizeof(skinny_req) - sizeof(skinny_data)) DOES NOT WORK on all systems (amd64?). */
1161 static int skinny_header_size = 12;
1162
1163 /*****************************
1164  * Asterisk specific globals *
1165  *****************************/
1166
1167 static int skinnyreload = 0;
1168
1169 /* a hostname, portnumber, socket and such is usefull for VoIP protocols */
1170 static struct sockaddr_in bindaddr;
1171 static char ourhost[256];
1172 static int ourport;
1173 static struct in_addr __ourip;
1174 static struct ast_hostent ahp;
1175 static struct hostent *hp;
1176 static int skinnysock = -1;
1177 static pthread_t accept_t;
1178 static int callnums = 1;
1179
1180 #define SKINNY_DEVICE_UNKNOWN -1
1181 #define SKINNY_DEVICE_NONE 0
1182 #define SKINNY_DEVICE_30SPPLUS 1
1183 #define SKINNY_DEVICE_12SPPLUS 2
1184 #define SKINNY_DEVICE_12SP 3
1185 #define SKINNY_DEVICE_12 4
1186 #define SKINNY_DEVICE_30VIP 5
1187 #define SKINNY_DEVICE_7910 6
1188 #define SKINNY_DEVICE_7960 7
1189 #define SKINNY_DEVICE_7940 8
1190 #define SKINNY_DEVICE_7935 9
1191 #define SKINNY_DEVICE_ATA186 12 /* Cisco ATA-186 */
1192 #define SKINNY_DEVICE_7941 115
1193 #define SKINNY_DEVICE_7971 119
1194 #define SKINNY_DEVICE_7914 124 /* Expansion module */
1195 #define SKINNY_DEVICE_7985 302
1196 #define SKINNY_DEVICE_7911 307
1197 #define SKINNY_DEVICE_7961GE 308
1198 #define SKINNY_DEVICE_7941GE 309
1199 #define SKINNY_DEVICE_7931 348
1200 #define SKINNY_DEVICE_7921 365
1201 #define SKINNY_DEVICE_7906 369
1202 #define SKINNY_DEVICE_7962 404 /* Not found */
1203 #define SKINNY_DEVICE_7937 431
1204 #define SKINNY_DEVICE_7942 434
1205 #define SKINNY_DEVICE_7945 435
1206 #define SKINNY_DEVICE_7965 436
1207 #define SKINNY_DEVICE_7975 437
1208 #define SKINNY_DEVICE_7905 20000
1209 #define SKINNY_DEVICE_7920 30002
1210 #define SKINNY_DEVICE_7970 30006
1211 #define SKINNY_DEVICE_7912 30007
1212 #define SKINNY_DEVICE_7902 30008
1213 #define SKINNY_DEVICE_CIPC 30016 /* Cisco IP Communicator */
1214 #define SKINNY_DEVICE_7961 30018
1215 #define SKINNY_DEVICE_7936 30019
1216 #define SKINNY_DEVICE_SCCPGATEWAY_AN 30027 /* Analog gateway */
1217 #define SKINNY_DEVICE_SCCPGATEWAY_BRI 30028 /* BRI gateway */
1218
1219 #define SKINNY_SPEAKERON 1
1220 #define SKINNY_SPEAKEROFF 2
1221
1222 #define SKINNY_MICON 1
1223 #define SKINNY_MICOFF 2
1224
1225 #define SKINNY_OFFHOOK 1
1226 #define SKINNY_ONHOOK 2
1227 #define SKINNY_RINGOUT 3
1228 #define SKINNY_RINGIN 4
1229 #define SKINNY_CONNECTED 5
1230 #define SKINNY_BUSY 6
1231 #define SKINNY_CONGESTION 7
1232 #define SKINNY_HOLD 8
1233 #define SKINNY_CALLWAIT 9
1234 #define SKINNY_TRANSFER 10
1235 #define SKINNY_PARK 11
1236 #define SKINNY_PROGRESS 12
1237 #define SKINNY_CALLREMOTEMULTILINE 13
1238 #define SKINNY_INVALID 14
1239
1240 #define SKINNY_INCOMING 1
1241 #define SKINNY_OUTGOING 2
1242
1243 #define SKINNY_SILENCE 0x00             /* Note sure this is part of the protocol, remove? */
1244 #define SKINNY_DIALTONE 0x21
1245 #define SKINNY_BUSYTONE 0x23
1246 #define SKINNY_ALERT 0x24
1247 #define SKINNY_REORDER 0x25
1248 #define SKINNY_CALLWAITTONE 0x2D
1249 #define SKINNY_ZIPZIP 0x31
1250 #define SKINNY_ZIP 0x32
1251 #define SKINNY_BEEPBONK 0x33
1252 #define SKINNY_BARGIN 0x43
1253 #define SKINNY_NOTONE 0x7F
1254
1255 #define SKINNY_LAMP_OFF 1
1256 #define SKINNY_LAMP_ON 2
1257 #define SKINNY_LAMP_WINK 3
1258 #define SKINNY_LAMP_FLASH 4
1259 #define SKINNY_LAMP_BLINK 5
1260
1261 #define SKINNY_RING_OFF 1
1262 #define SKINNY_RING_INSIDE 2
1263 #define SKINNY_RING_OUTSIDE 3
1264 #define SKINNY_RING_FEATURE 4
1265
1266 #define SKINNY_CFWD_ALL       (1 << 0)
1267 #define SKINNY_CFWD_BUSY      (1 << 1)
1268 #define SKINNY_CFWD_NOANSWER  (1 << 2)
1269
1270 /* Skinny rtp stream modes. Do we really need this? */
1271 #define SKINNY_CX_SENDONLY 0
1272 #define SKINNY_CX_RECVONLY 1
1273 #define SKINNY_CX_SENDRECV 2
1274 #define SKINNY_CX_CONF 3
1275 #define SKINNY_CX_CONFERENCE 3
1276 #define SKINNY_CX_MUTE 4
1277 #define SKINNY_CX_INACTIVE 4
1278
1279 #if 0
1280 static const char * const skinny_cxmodes[] = {
1281         "sendonly",
1282         "recvonly",
1283         "sendrecv",
1284         "confrnce",
1285         "inactive"
1286 };
1287 #endif
1288
1289 /* driver scheduler */
1290 static struct ast_sched_context *sched = NULL;
1291
1292 /* Protect the network socket */
1293 AST_MUTEX_DEFINE_STATIC(netlock);
1294
1295 /* Wait up to 16 seconds for first digit */
1296 static int firstdigittimeout = 16000;
1297
1298 /* How long to wait for following digits */
1299 static int gendigittimeout = 8000;
1300
1301 /* How long to wait for an extra digit, if there is an ambiguous match */
1302 static int matchdigittimeout = 3000;
1303
1304 #define SUBSTATE_UNSET 0
1305 #define SUBSTATE_OFFHOOK 1
1306 #define SUBSTATE_ONHOOK 2
1307 #define SUBSTATE_RINGOUT 3
1308 #define SUBSTATE_RINGIN 4
1309 #define SUBSTATE_CONNECTED 5
1310 #define SUBSTATE_BUSY 6
1311 #define SUBSTATE_CONGESTION 7
1312 #define SUBSTATE_HOLD 8
1313 #define SUBSTATE_CALLWAIT 9
1314 #define SUBSTATE_PROGRESS 12
1315 #define SUBSTATE_DIALING 101
1316
1317 struct skinny_subchannel {
1318         ast_mutex_t lock;
1319         struct ast_channel *owner;
1320         struct ast_rtp_instance *rtp;
1321         struct ast_rtp_instance *vrtp;
1322         unsigned int callid;
1323         char exten[AST_MAX_EXTENSION];
1324         /* time_t lastouttime; */ /* Unused */
1325         int progress;
1326         int ringing;
1327         /* int lastout; */ /* Unused */
1328         int cxmode;
1329         int nat;
1330         int calldirection;
1331         int blindxfer;
1332         int xferor;
1333         int substate;
1334         int aa_sched;
1335         int aa_beep;
1336         int aa_mute;
1337         int dialer_sched;
1338
1339         AST_LIST_ENTRY(skinny_subchannel) list;
1340         struct skinny_subchannel *related;
1341         struct skinny_line *line;
1342         struct skinny_subline *subline;
1343 };
1344
1345 #define SKINNY_LINE_OPTIONS                             \
1346         char name[80];                                  \
1347         char label[24];                                 \
1348         char accountcode[AST_MAX_ACCOUNT_CODE];         \
1349         char exten[AST_MAX_EXTENSION];                  \
1350         char context[AST_MAX_CONTEXT];                  \
1351         char language[MAX_LANGUAGE];                    \
1352         char cid_num[AST_MAX_EXTENSION];                \
1353         char cid_name[AST_MAX_EXTENSION];               \
1354         char lastcallerid[AST_MAX_EXTENSION];           \
1355         int cfwdtype;                                   \
1356         char call_forward_all[AST_MAX_EXTENSION];       \
1357         char call_forward_busy[AST_MAX_EXTENSION];      \
1358         char call_forward_noanswer[AST_MAX_EXTENSION];  \
1359         char mailbox[AST_MAX_EXTENSION];                \
1360         char vmexten[AST_MAX_EXTENSION];                \
1361         char regexten[AST_MAX_EXTENSION];               \
1362         char regcontext[AST_MAX_CONTEXT];               \
1363         char parkinglot[AST_MAX_CONTEXT];               \
1364         char mohinterpret[MAX_MUSICCLASS];              \
1365         char mohsuggest[MAX_MUSICCLASS];                \
1366         char lastnumberdialed[AST_MAX_EXTENSION];       \
1367         char dialoutexten[AST_MAX_EXTENSION];           \
1368         char dialoutcontext[AST_MAX_CONTEXT];           \
1369         ast_group_t callgroup;                          \
1370         ast_group_t pickupgroup;                        \
1371         struct ast_namedgroups *named_callgroups;       \
1372         struct ast_namedgroups *named_pickupgroups;     \
1373         int callwaiting;                                \
1374         int transfer;                                   \
1375         int threewaycalling;                            \
1376         int mwiblink;                                   \
1377         int cancallforward;                             \
1378         int getforward;                                 \
1379         int dnd;                                        \
1380         int hidecallerid;                               \
1381         int amaflags;                                   \
1382         int instance;                                   \
1383         int group;                                      \
1384         struct ast_codec_pref confprefs;                \
1385         struct ast_codec_pref prefs;                    \
1386         int nonCodecCapability;                         \
1387         int immediate;                                  \
1388         int nat;                                        \
1389         int directmedia;                                \
1390         int prune;
1391
1392 struct skinny_line {
1393         SKINNY_LINE_OPTIONS
1394         ast_mutex_t lock;
1395         struct skinny_container *container;
1396         struct ast_event_sub *mwi_event_sub; /* Event based MWI */
1397         struct skinny_subchannel *activesub;
1398         AST_LIST_HEAD(, skinny_subchannel) sub;
1399         AST_LIST_HEAD(, skinny_subline) sublines;
1400         AST_LIST_ENTRY(skinny_line) list;
1401         AST_LIST_ENTRY(skinny_line) all;
1402         struct skinny_device *device;
1403         struct ast_format_cap *cap;
1404         struct ast_format_cap *confcap;
1405         struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1406         int newmsgs;
1407 };
1408
1409 static struct skinny_line_options{
1410         SKINNY_LINE_OPTIONS
1411 } default_line_struct = {
1412         .callwaiting = 1,
1413         .transfer = 1,
1414         .mwiblink = 0,
1415         .dnd = 0,
1416         .hidecallerid = 0,
1417         .amaflags = 0,
1418         .instance = 0,
1419         .directmedia = 0,
1420         .nat = 0,
1421         .getforward = 0,
1422         .prune = 0,
1423 };
1424 static struct skinny_line_options *default_line = &default_line_struct;
1425
1426 static AST_LIST_HEAD_STATIC(lines, skinny_line);
1427
1428 struct skinny_subline {
1429         struct skinny_container *container;
1430         struct skinny_line *line;
1431         struct skinny_subchannel *sub;
1432         AST_LIST_ENTRY(skinny_subline) list;
1433         char name[80];
1434         char context[AST_MAX_CONTEXT];
1435         char exten[AST_MAX_EXTENSION];
1436         char stname[AST_MAX_EXTENSION];
1437         char lnname[AST_MAX_EXTENSION];
1438         char ourName[40];
1439         char ourNum[24];
1440         char theirName[40];
1441         char theirNum[24];
1442         int calldirection;
1443         int substate;
1444         int extenstate;
1445         unsigned int callid;
1446 };
1447
1448 struct skinny_speeddial {
1449         ast_mutex_t lock;
1450         struct skinny_container *container;
1451         char label[42];
1452         char context[AST_MAX_CONTEXT];
1453         char exten[AST_MAX_EXTENSION];
1454         int instance;
1455         int stateid;
1456         int laststate;
1457         int isHint;
1458
1459         AST_LIST_ENTRY(skinny_speeddial) list;
1460         struct skinny_device *parent;
1461 };
1462
1463 #define SKINNY_DEVICECONTAINER 1
1464 #define SKINNY_LINECONTAINER 2
1465 #define SKINNY_SUBLINECONTAINER 3
1466 #define SKINNY_SDCONTAINER 4
1467
1468 struct skinny_container {
1469         int type;
1470         void *data;
1471 };
1472
1473 struct skinny_addon {
1474         ast_mutex_t lock;
1475         char type[10];
1476         AST_LIST_ENTRY(skinny_addon) list;
1477         struct skinny_device *parent;
1478 };
1479
1480 #define SKINNY_DEVICE_OPTIONS                                   \
1481         char name[80];                                          \
1482         char id[16];                                            \
1483         char version_id[16];                                    \
1484         char vmexten[AST_MAX_EXTENSION];                        \
1485         int type;                                               \
1486         int protocolversion;                            \
1487         int hookstate;                                  \
1488         int lastlineinstance;                                   \
1489         int lastcallreference;                                  \
1490         struct ast_codec_pref confprefs;                        \
1491         int earlyrtp;                                           \
1492         int transfer;                                           \
1493         int callwaiting;                                        \
1494         int mwiblink;                                           \
1495         int dnd;                                                \
1496         int prune;
1497
1498 struct skinny_device {
1499         SKINNY_DEVICE_OPTIONS
1500         struct type *first;
1501         struct type *last;
1502         ast_mutex_t lock;
1503         struct sockaddr_in addr;
1504         struct in_addr ourip;
1505         struct ast_ha *ha;
1506         struct skinnysession *session;
1507         struct skinny_line *activeline;
1508         struct ast_format_cap *cap;
1509         struct ast_format_cap *confcap;
1510         AST_LIST_HEAD(, skinny_line) lines;
1511         AST_LIST_HEAD(, skinny_speeddial) speeddials;
1512         AST_LIST_HEAD(, skinny_addon) addons;
1513         AST_LIST_ENTRY(skinny_device) list;
1514 };
1515
1516 static struct skinny_device_options {
1517         SKINNY_DEVICE_OPTIONS
1518 } default_device_struct = {
1519         .transfer = 1,
1520         .earlyrtp = 1,
1521         .callwaiting = 1,
1522         .mwiblink = 0,
1523         .dnd = 0,
1524         .prune = 0,
1525         .hookstate = SKINNY_ONHOOK,
1526 };
1527 static struct skinny_device_options *default_device = &default_device_struct;
1528
1529 static AST_LIST_HEAD_STATIC(devices, skinny_device);
1530
1531 struct skinnysession {
1532         pthread_t t;
1533         ast_mutex_t lock;
1534         time_t start;
1535         struct sockaddr_in sin;
1536         int fd;
1537         char inbuf[SKINNY_MAX_PACKET];
1538         char outbuf[SKINNY_MAX_PACKET];
1539         struct skinny_device *device;
1540         AST_LIST_ENTRY(skinnysession) list;
1541 };
1542
1543 static struct ast_channel *skinny_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
1544 static AST_LIST_HEAD_STATIC(sessions, skinnysession);
1545
1546 static int skinny_devicestate(const char *data);
1547 static int skinny_call(struct ast_channel *ast, const char *dest, int timeout);
1548 static int skinny_hangup(struct ast_channel *ast);
1549 static int skinny_answer(struct ast_channel *ast);
1550 static struct ast_frame *skinny_read(struct ast_channel *ast);
1551 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1552 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1553 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1554 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1555 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1556 static void mwi_event_cb(const struct ast_event *event, void *userdata);
1557 static int skinny_dialer_cb(const void *data);
1558 static int skinny_reload(void);
1559
1560 static void setsubstate(struct skinny_subchannel *sub, int state);
1561 static void dumpsub(struct skinny_subchannel *sub, int forcehangup);
1562 static void activatesub(struct skinny_subchannel *sub, int state);
1563 static void dialandactivatesub(struct skinny_subchannel *sub, char exten[AST_MAX_EXTENSION]);
1564
1565 static struct ast_channel_tech skinny_tech = {
1566         .type = "Skinny",
1567         .description = tdesc,
1568         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1569         .requester = skinny_request,
1570         .devicestate = skinny_devicestate,
1571         .call = skinny_call,
1572         .hangup = skinny_hangup,
1573         .answer = skinny_answer,
1574         .read = skinny_read,
1575         .write = skinny_write,
1576         .indicate = skinny_indicate,
1577         .fixup = skinny_fixup,
1578         .send_digit_begin = skinny_senddigit_begin,
1579         .send_digit_end = skinny_senddigit_end,
1580         .bridge = ast_rtp_instance_bridge,
1581 };
1582
1583 static int skinny_extensionstate_cb(char *context, char *id, struct ast_state_cb_info *info, void *data);
1584 static int skinny_transfer(struct skinny_subchannel *sub);
1585
1586 static struct skinny_line *skinny_line_alloc(void)
1587 {
1588         struct skinny_line *l;
1589         if (!(l = ast_calloc(1, sizeof(*l)))) {
1590                 return NULL;
1591         }
1592
1593         l->cap = ast_format_cap_alloc_nolock();
1594         l->confcap = ast_format_cap_alloc_nolock();
1595         if (!l->cap || !l->confcap) {
1596                 l->cap = ast_format_cap_destroy(l->cap);
1597                 l->confcap = ast_format_cap_destroy(l->confcap);
1598                 ast_free(l);
1599                 return NULL;
1600         }
1601         return l;
1602 }
1603 static struct skinny_line *skinny_line_destroy(struct skinny_line *l)
1604 {
1605         l->cap = ast_format_cap_destroy(l->cap);
1606         l->confcap = ast_format_cap_destroy(l->confcap);
1607         l->named_callgroups = ast_unref_namedgroups(l->named_callgroups);
1608         l->named_pickupgroups = ast_unref_namedgroups(l->named_pickupgroups);
1609         ast_free(l->container);
1610         ast_free(l);
1611         return NULL;
1612 }
1613 static struct skinny_device *skinny_device_alloc(void)
1614 {
1615         struct skinny_device *d;
1616         if (!(d = ast_calloc(1, sizeof(*d)))) {
1617                 return NULL;
1618         }
1619
1620         d->cap = ast_format_cap_alloc_nolock();
1621         d->confcap = ast_format_cap_alloc_nolock();
1622         if (!d->cap || !d->confcap) {
1623                 d->cap = ast_format_cap_destroy(d->cap);
1624                 d->confcap = ast_format_cap_destroy(d->confcap);
1625                 ast_free(d);
1626                 return NULL;
1627         }
1628         return d;
1629 }
1630 static struct skinny_device *skinny_device_destroy(struct skinny_device *d)
1631 {
1632         d->cap = ast_format_cap_destroy(d->cap);
1633         d->confcap = ast_format_cap_destroy(d->confcap);
1634         ast_free(d);
1635         return NULL;
1636 }
1637
1638 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1639 {
1640         struct skinny_device *d = s->device;
1641         struct skinny_addon *a;
1642         int i;
1643
1644         switch (d->type) {
1645                 case SKINNY_DEVICE_30SPPLUS:
1646                 case SKINNY_DEVICE_30VIP:
1647                         /* 13 rows, 2 columns */
1648                         for (i = 0; i < 4; i++)
1649                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1650                         (btn++)->buttonDefinition = BT_REDIAL;
1651                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1652                         (btn++)->buttonDefinition = BT_CALLPARK;
1653                         (btn++)->buttonDefinition = BT_FORWARDALL;
1654                         (btn++)->buttonDefinition = BT_CONFERENCE;
1655                         for (i = 0; i < 4; i++)
1656                                 (btn++)->buttonDefinition = BT_NONE;
1657                         for (i = 0; i < 13; i++)
1658                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1659
1660                         break;
1661                 case SKINNY_DEVICE_12SPPLUS:
1662                 case SKINNY_DEVICE_12SP:
1663                 case SKINNY_DEVICE_12:
1664                         /* 6 rows, 2 columns */
1665                         for (i = 0; i < 2; i++)
1666                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1667                         for (i = 0; i < 4; i++)
1668                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1669                         (btn++)->buttonDefinition = BT_HOLD;
1670                         (btn++)->buttonDefinition = BT_REDIAL;
1671                         (btn++)->buttonDefinition = BT_TRANSFER;
1672                         (btn++)->buttonDefinition = BT_FORWARDALL;
1673                         (btn++)->buttonDefinition = BT_CALLPARK;
1674                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1675                         break;
1676                 case SKINNY_DEVICE_7910:
1677                         (btn++)->buttonDefinition = BT_LINE;
1678                         (btn++)->buttonDefinition = BT_HOLD;
1679                         (btn++)->buttonDefinition = BT_TRANSFER;
1680                         (btn++)->buttonDefinition = BT_DISPLAY;
1681                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1682                         (btn++)->buttonDefinition = BT_CONFERENCE;
1683                         (btn++)->buttonDefinition = BT_FORWARDALL;
1684                         for (i = 0; i < 2; i++)
1685                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1686                         (btn++)->buttonDefinition = BT_REDIAL;
1687                         break;
1688                 case SKINNY_DEVICE_7960:
1689                 case SKINNY_DEVICE_7961:
1690                 case SKINNY_DEVICE_7961GE:
1691                 case SKINNY_DEVICE_7962:
1692                 case SKINNY_DEVICE_7965:
1693                         for (i = 0; i < 6; i++)
1694                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1695                         break;
1696                 case SKINNY_DEVICE_7940:
1697                 case SKINNY_DEVICE_7941:
1698                 case SKINNY_DEVICE_7941GE:
1699                 case SKINNY_DEVICE_7942:
1700                 case SKINNY_DEVICE_7945:
1701                         for (i = 0; i < 2; i++)
1702                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1703                         break;
1704                 case SKINNY_DEVICE_7935:
1705                 case SKINNY_DEVICE_7936:
1706                         for (i = 0; i < 2; i++)
1707                                 (btn++)->buttonDefinition = BT_LINE;
1708                         break;
1709                 case SKINNY_DEVICE_ATA186:
1710                         (btn++)->buttonDefinition = BT_LINE;
1711                         break;
1712                 case SKINNY_DEVICE_7970:
1713                 case SKINNY_DEVICE_7971:
1714                 case SKINNY_DEVICE_7975:
1715                 case SKINNY_DEVICE_CIPC:
1716                         for (i = 0; i < 8; i++)
1717                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1718                         break;
1719                 case SKINNY_DEVICE_7985:
1720                         /* XXX I have no idea what the buttons look like on these. */
1721                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1722                         break;
1723                 case SKINNY_DEVICE_7912:
1724                 case SKINNY_DEVICE_7911:
1725                 case SKINNY_DEVICE_7905:
1726                         (btn++)->buttonDefinition = BT_LINE;
1727                         (btn++)->buttonDefinition = BT_HOLD;
1728                         break;
1729                 case SKINNY_DEVICE_7920:
1730                         /* XXX I don't know if this is right. */
1731                         for (i = 0; i < 4; i++)
1732                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1733                         break;
1734                 case SKINNY_DEVICE_7921:
1735                         for (i = 0; i < 6; i++)
1736                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1737                         break;
1738                 case SKINNY_DEVICE_7902:
1739                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1740                         break;
1741                 case SKINNY_DEVICE_7906:
1742                         ast_log(LOG_WARNING, "Unsupported device type '%d (7906)' found.\n", d->type);
1743                         break;
1744                 case SKINNY_DEVICE_7931:
1745                         ast_log(LOG_WARNING, "Unsupported device type '%d (7931)' found.\n", d->type);
1746                         break;
1747                 case SKINNY_DEVICE_7937:
1748                         ast_log(LOG_WARNING, "Unsupported device type '%d (7937)' found.\n", d->type);
1749                         break;
1750                 case SKINNY_DEVICE_7914:
1751                         ast_log(LOG_WARNING, "Unsupported device type '%d (7914)' found.  Expansion module registered by itself?\n", d->type);
1752                         break;
1753                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1754                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1755                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1756                         break;
1757                 default:
1758                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1759                         break;
1760         }
1761
1762         AST_LIST_LOCK(&d->addons);
1763         AST_LIST_TRAVERSE(&d->addons, a, list) {
1764                 if (!strcasecmp(a->type, "7914")) {
1765                         for (i = 0; i < 14; i++)
1766                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1767                 } else {
1768                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1769                 }
1770         }
1771         AST_LIST_UNLOCK(&d->addons);
1772
1773         return btn;
1774 }
1775
1776 static struct skinny_req *req_alloc(size_t size, int response_message)
1777 {
1778         struct skinny_req *req;
1779
1780         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1781                 return NULL;
1782
1783         req->len = htolel(size+4);
1784         req->e = htolel(response_message);
1785
1786         return req;
1787 }
1788
1789 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1790 {
1791         struct skinny_line *l;
1792
1793         /*Dialing from on hook or on a 7920 uses instance 0 in requests
1794           but we need to start looking at instance 1 */
1795
1796         if (!instance)
1797                 instance = 1;
1798
1799         AST_LIST_TRAVERSE(&d->lines, l, list){
1800                 if (l->instance == instance)
1801                         break;
1802         }
1803
1804         if (!l) {
1805                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1806         }
1807         return l;
1808 }
1809
1810 static struct skinny_line *find_line_by_name(const char *dest)
1811 {
1812         struct skinny_line *l;
1813         struct skinny_line *tmpl = NULL;
1814         struct skinny_device *d;
1815         char line[256];
1816         char *at;
1817         char *device;
1818         int checkdevice = 0;
1819
1820         ast_copy_string(line, dest, sizeof(line));
1821         at = strchr(line, '@');
1822         if (at)
1823                 *at++ = '\0';
1824         device = at;
1825
1826         if (!ast_strlen_zero(device))
1827                 checkdevice = 1;
1828
1829         AST_LIST_LOCK(&devices);
1830         AST_LIST_TRAVERSE(&devices, d, list){
1831                 if (checkdevice && tmpl)
1832                         break;
1833                 else if (!checkdevice) {
1834                         /* This is a match, since we're checking for line on every device. */
1835                 } else if (!strcasecmp(d->name, device)) {
1836                 } else
1837                         continue;
1838
1839                 /* Found the device (or we don't care which device) */
1840                 AST_LIST_TRAVERSE(&d->lines, l, list){
1841                         /* Search for the right line */
1842                         if (!strcasecmp(l->name, line)) {
1843                                 if (tmpl) {
1844                                         ast_log(LOG_WARNING, "Ambiguous line name: %s\n", line);
1845                                         AST_LIST_UNLOCK(&devices);
1846                                         return NULL;
1847                                 } else
1848                                         tmpl = l;
1849                         }
1850                 }
1851         }
1852         AST_LIST_UNLOCK(&devices);
1853         return tmpl;
1854 }
1855
1856 static struct skinny_subline *find_subline_by_name(const char *dest)
1857 {
1858         struct skinny_line *l;
1859         struct skinny_subline *subline;
1860         struct skinny_subline *tmpsubline = NULL;
1861         struct skinny_device *d;
1862
1863         AST_LIST_LOCK(&devices);
1864         AST_LIST_TRAVERSE(&devices, d, list){
1865                 AST_LIST_TRAVERSE(&d->lines, l, list){
1866                         AST_LIST_TRAVERSE(&l->sublines, subline, list){
1867                                 if (!strcasecmp(subline->name, dest)) {
1868                                         if (tmpsubline) {
1869                                                 ast_verb(2, "Ambiguous subline name: %s\n", dest);
1870                                                 AST_LIST_UNLOCK(&devices);
1871                                                 return NULL;
1872                                         } else
1873                                                 tmpsubline = subline;
1874                                 }
1875                         }
1876                 }
1877         }
1878         AST_LIST_UNLOCK(&devices);
1879         return tmpsubline;
1880 }
1881
1882 static struct skinny_subline *find_subline_by_callid(struct skinny_device *d, int callid)
1883 {
1884         struct skinny_subline *subline;
1885         struct skinny_line *l;
1886
1887         AST_LIST_TRAVERSE(&d->lines, l, list){
1888                 AST_LIST_TRAVERSE(&l->sublines, subline, list){
1889                         if (subline->callid == callid) {
1890                                 return subline;
1891                         }
1892                 }
1893         }
1894         return NULL;
1895 }
1896
1897 /*!
1898  * implement the setvar config line
1899  */
1900 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
1901 {
1902         struct ast_variable *tmpvar = NULL;
1903         char *varname = ast_strdupa(buf), *varval = NULL;
1904
1905         if ((varval = strchr(varname,'='))) {
1906                 *varval++ = '\0';
1907                 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
1908                         tmpvar->next = list;
1909                         list = tmpvar;
1910                 }
1911         }
1912         return list;
1913 }
1914
1915 static int skinny_sched_del(int sched_id, struct skinny_subchannel *sub)
1916 {
1917         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Deleting SCHED %d\n",
1918                 sub->callid, sched_id);
1919         return ast_sched_del(sched, sched_id);
1920 }
1921
1922 static int skinny_sched_add(int when, ast_sched_cb callback, struct skinny_subchannel *sub)
1923 {
1924         int ret;
1925         ret = ast_sched_add(sched, when, callback, sub);
1926         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Added SCHED %d\n",
1927                 sub->callid, ret);
1928         return ret;
1929 }
1930
1931 /* It's quicker/easier to find the subchannel when we know the instance number too */
1932 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
1933 {
1934         struct skinny_line *l = find_line_by_instance(d, instance);
1935         struct skinny_subchannel *sub;
1936
1937         if (!l) {
1938                 return NULL;
1939         }
1940
1941         /* 7920 phones set call reference to 0, so use the first
1942            sub-channel on the list.
1943            This MIGHT need more love to be right */
1944         if (!reference)
1945                 sub = AST_LIST_FIRST(&l->sub);
1946         else {
1947                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
1948                         if (sub->callid == reference)
1949                                 break;
1950                 }
1951         }
1952         if (!sub) {
1953                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
1954         }
1955         return sub;
1956 }
1957
1958 /* Find the subchannel when we only have the callid - this shouldn't happen often */
1959 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
1960 {
1961         struct skinny_line *l;
1962         struct skinny_subchannel *sub = NULL;
1963
1964         AST_LIST_TRAVERSE(&d->lines, l, list){
1965                 AST_LIST_TRAVERSE(&l->sub, sub, list){
1966                         if (sub->callid == reference)
1967                                 break;
1968                 }
1969                 if (sub)
1970                         break;
1971         }
1972
1973         if (!l) {
1974                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
1975         } else {
1976                 if (!sub) {
1977                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
1978                 }
1979         }
1980         return sub;
1981 }
1982
1983 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
1984 {
1985         struct skinny_speeddial *sd;
1986
1987         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1988                 if (sd->isHint == isHint && sd->instance == instance)
1989                         break;
1990         }
1991
1992         if (!sd) {
1993                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
1994         }
1995         return sd;
1996 }
1997
1998 static struct ast_format *codec_skinny2ast(enum skinny_codecs skinnycodec, struct ast_format *result)
1999 {
2000         switch (skinnycodec) {
2001         case SKINNY_CODEC_ALAW:
2002                 return ast_format_set(result, AST_FORMAT_ALAW, 0);
2003         case SKINNY_CODEC_ULAW:
2004                 return ast_format_set(result, AST_FORMAT_ULAW, 0);
2005         case SKINNY_CODEC_G722:
2006                 return ast_format_set(result, AST_FORMAT_G722, 0);
2007         case SKINNY_CODEC_G723_1:
2008                 return ast_format_set(result, AST_FORMAT_G723_1, 0);
2009         case SKINNY_CODEC_G729A:
2010                 return ast_format_set(result, AST_FORMAT_G729A, 0);
2011         case SKINNY_CODEC_G726_32:
2012                 return ast_format_set(result, AST_FORMAT_G726_AAL2, 0); /* XXX Is this right? */
2013         case SKINNY_CODEC_H261:
2014                 return ast_format_set(result, AST_FORMAT_H261, 0);
2015         case SKINNY_CODEC_H263:
2016                 return ast_format_set(result, AST_FORMAT_H263 ,0);
2017         default:
2018                 ast_format_clear(result);
2019                 return result;
2020         }
2021 }
2022
2023 static int codec_ast2skinny(const struct ast_format *astcodec)
2024 {
2025         switch (astcodec->id) {
2026         case AST_FORMAT_ALAW:
2027                 return SKINNY_CODEC_ALAW;
2028         case AST_FORMAT_ULAW:
2029                 return SKINNY_CODEC_ULAW;
2030         case AST_FORMAT_G722:
2031                 return SKINNY_CODEC_G722;
2032         case AST_FORMAT_G723_1:
2033                 return SKINNY_CODEC_G723_1;
2034         case AST_FORMAT_G729A:
2035                 return SKINNY_CODEC_G729A;
2036         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
2037                 return SKINNY_CODEC_G726_32;
2038         case AST_FORMAT_H261:
2039                 return SKINNY_CODEC_H261;
2040         case AST_FORMAT_H263:
2041                 return SKINNY_CODEC_H263;
2042         default:
2043                 return 0;
2044         }
2045 }
2046
2047 static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
2048 {
2049         if (!l)
2050                 return 0;
2051
2052         if (!ast_strlen_zero(cfwd)) {
2053                 if (cfwdtype & SKINNY_CFWD_ALL) {
2054                         l->cfwdtype |= SKINNY_CFWD_ALL;
2055                         ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
2056                 }
2057                 if (cfwdtype & SKINNY_CFWD_BUSY) {
2058                         l->cfwdtype |= SKINNY_CFWD_BUSY;
2059                         ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
2060                 }
2061                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2062                         l->cfwdtype |= SKINNY_CFWD_NOANSWER;
2063                         ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
2064                 }
2065         } else {
2066                 if (cfwdtype & SKINNY_CFWD_ALL) {
2067                         l->cfwdtype &= ~SKINNY_CFWD_ALL;
2068                         memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
2069                 }
2070                 if (cfwdtype & SKINNY_CFWD_BUSY) {
2071                         l->cfwdtype &= ~SKINNY_CFWD_BUSY;
2072                         memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
2073                 }
2074                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2075                         l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
2076                         memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
2077                 }
2078         }
2079         return l->cfwdtype;
2080 }
2081
2082 static void cleanup_stale_contexts(char *new, char *old)
2083 {
2084         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
2085
2086         while ((oldcontext = strsep(&old, "&"))) {
2087                 stalecontext = '\0';
2088                 ast_copy_string(newlist, new, sizeof(newlist));
2089                 stringp = newlist;
2090                 while ((newcontext = strsep(&stringp, "&"))) {
2091                         if (strcmp(newcontext, oldcontext) == 0) {
2092                                 /* This is not the context you're looking for */
2093                                 stalecontext = '\0';
2094                                 break;
2095                         } else if (strcmp(newcontext, oldcontext)) {
2096                                 stalecontext = oldcontext;
2097                         }
2098
2099                 }
2100                 if (stalecontext)
2101                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
2102         }
2103 }
2104
2105 static void register_exten(struct skinny_line *l)
2106 {
2107         char multi[256];
2108         char *stringp, *ext, *context;
2109
2110         if (ast_strlen_zero(regcontext))
2111                 return;
2112
2113         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2114         stringp = multi;
2115         while ((ext = strsep(&stringp, "&"))) {
2116                 if ((context = strchr(ext, '@'))) {
2117                         *context++ = '\0'; /* split ext@context */
2118                         if (!ast_context_find(context)) {
2119                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2120                                 continue;
2121                         }
2122                 } else {
2123                         context = regcontext;
2124                 }
2125                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2126                          ast_strdup(l->name), ast_free_ptr, "Skinny");
2127         }
2128 }
2129
2130 static void unregister_exten(struct skinny_line *l)
2131 {
2132         char multi[256];
2133         char *stringp, *ext, *context;
2134
2135         if (ast_strlen_zero(regcontext))
2136                 return;
2137
2138         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2139         stringp = multi;
2140         while ((ext = strsep(&stringp, "&"))) {
2141                 if ((context = strchr(ext, '@'))) {
2142                         *context++ = '\0'; /* split ext@context */
2143                         if (!ast_context_find(context)) {
2144                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2145                                 continue;
2146                         }
2147                 } else {
2148                         context = regcontext;
2149                 }
2150                 ast_context_remove_extension(context, ext, 1, NULL);
2151         }
2152 }
2153
2154 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
2155 {
2156         struct skinny_device *d;
2157         struct skinny_line *l;
2158         struct skinny_subline *subline;
2159         struct skinny_speeddial *sd;
2160         struct sockaddr_in sin;
2161         socklen_t slen;
2162         int instance;
2163
2164         AST_LIST_LOCK(&devices);
2165         AST_LIST_TRAVERSE(&devices, d, list){
2166                 struct ast_sockaddr addr;
2167                 ast_sockaddr_from_sin(&addr, &s->sin);
2168                 if (!d->session && !strcasecmp(req->data.reg.name, d->id)
2169                                 && ast_apply_ha(d->ha, &addr)) {
2170                         s->device = d;
2171                         d->type = letohl(req->data.reg.type);
2172                         d->protocolversion = letohl(req->data.reg.protocolVersion);
2173                         if (ast_strlen_zero(d->version_id)) {
2174                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
2175                         }
2176                         d->session = s;
2177
2178                         slen = sizeof(sin);
2179                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
2180                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
2181                                 sin.sin_addr = __ourip;
2182                         }
2183                         d->ourip = sin.sin_addr;
2184
2185                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2186                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd->container);
2187                         }
2188                         instance = 0;
2189                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2190                                 instance++;
2191                         }
2192                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2193                                 ast_format_cap_joint_copy(l->confcap, d->cap, l->cap);
2194                                 l->prefs = l->confprefs;
2195                                 if (!l->prefs.order[0]) {
2196                                         l->prefs = d->confprefs;
2197                                 }
2198                                 /* l->capability = d->capability;
2199                                 l->prefs = d->prefs; */
2200                                 l->instance = instance;
2201                                 l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
2202                                 set_callforwards(l, NULL, 0);
2203                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Registered\r\n", l->name, d->name);
2204                                 register_exten(l);
2205                                 /* initialize MWI on line and device */
2206                                 mwi_event_cb(0, l);
2207                                 AST_LIST_TRAVERSE(&l->sublines, subline, list) {
2208                                         ast_extension_state_add(subline->context, subline->exten, skinny_extensionstate_cb, subline->container);
2209                                 }
2210                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
2211                                 --instance;
2212                         }
2213                         break;
2214                 }
2215         }
2216         AST_LIST_UNLOCK(&devices);
2217         if (!d) {
2218                 return 0;
2219         }
2220         return 1;
2221 }
2222
2223 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
2224 {
2225         struct skinny_device *d;
2226         struct skinny_line *l;
2227         struct skinny_speeddial *sd;
2228
2229         d = s->device;
2230
2231         if (d) {
2232                 d->session = NULL;
2233
2234                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2235                         if (sd->stateid > -1)
2236                                 ast_extension_state_del(sd->stateid, NULL);
2237                 }
2238                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2239                         if (l->device == d) {
2240                                 ast_format_cap_remove_all(l->cap);
2241                                 ast_parse_allow_disallow(&l->prefs, l->cap, "all", 0);
2242                                 l->instance = 0;
2243                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Unregistered\r\n", l->name, d->name);
2244                                 unregister_exten(l);
2245                                 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
2246                         }
2247                 }
2248         }
2249
2250         return -1; /* main loop will destroy the session */
2251 }
2252
2253 #ifdef AST_DEVMODE
2254 static char *callstate2str(int ind)
2255 {
2256         char *tmp;
2257
2258         switch (ind) {
2259         case SKINNY_OFFHOOK:
2260                 return "SKINNY_OFFHOOK";
2261         case SKINNY_ONHOOK:
2262                 return "SKINNY_ONHOOK";
2263         case SKINNY_RINGOUT:
2264                 return "SKINNY_RINGOUT";
2265         case SKINNY_RINGIN:
2266                 return "SKINNY_RINGIN";
2267         case SKINNY_CONNECTED:
2268                 return "SKINNY_CONNECTED";
2269         case SKINNY_BUSY:
2270                 return "SKINNY_BUSY";
2271         case SKINNY_CONGESTION:
2272                 return "SKINNY_CONGESTION";
2273         case SKINNY_PROGRESS:
2274                 return "SKINNY_PROGRESS";
2275         case SKINNY_HOLD:
2276                 return "SKINNY_HOLD";
2277         case SKINNY_CALLWAIT:
2278                 return "SKINNY_CALLWAIT";
2279         default:
2280                 if (!(tmp = ast_threadstorage_get(&callstate2str_threadbuf, CALLSTATE2STR_BUFSIZE)))
2281                         return "Unknown";
2282                 snprintf(tmp, CALLSTATE2STR_BUFSIZE, "UNKNOWN-%d", ind);
2283                 return tmp;
2284         }
2285 }
2286
2287 #endif
2288
2289 static int transmit_response_bysession(struct skinnysession *s, struct skinny_req *req)
2290 {
2291         int res = 0;
2292
2293         if (!s) {
2294                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2295                 return -1;
2296         }
2297
2298         ast_mutex_lock(&s->lock);
2299
2300         if ((letohl(req->len) > SKINNY_MAX_PACKET) || (letohl(req->len) < 0)) {
2301                 ast_log(LOG_WARNING, "transmit_response: the length of the request (%d) is out of bounds (%d)\n", letohl(req->len), SKINNY_MAX_PACKET);
2302                 ast_mutex_unlock(&s->lock);
2303                 return -1;
2304         }
2305
2306         memset(s->outbuf, 0, sizeof(s->outbuf));
2307         memcpy(s->outbuf, req, skinny_header_size);
2308         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2309
2310         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2311
2312         if (res != letohl(req->len)+8) {
2313                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2314                 if (res == -1) {
2315                         ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2316                         skinny_unregister(NULL, s);
2317                 }
2318
2319         }
2320
2321         ast_free(req);
2322         ast_mutex_unlock(&s->lock);
2323         return 1;
2324 }
2325
2326 static void transmit_response(struct skinny_device *d, struct skinny_req *req)
2327 {
2328         transmit_response_bysession(d->session, req);
2329 }
2330
2331 static void transmit_registerrej(struct skinnysession *s)
2332 {
2333         struct skinny_req *req;
2334         char name[16];
2335
2336         if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
2337                 return;
2338
2339         memcpy(&name, req->data.reg.name, sizeof(name));
2340         snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2341
2342         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_REJ_MESSAGE to UNKNOWN_DEVICE\n");
2343         transmit_response_bysession(s, req);
2344 }
2345
2346 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2347 {
2348         struct skinny_req *req;
2349
2350         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2351                 return;
2352
2353         req->data.setspeaker.mode = htolel(mode);
2354
2355         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_SPEAKER_MESSAGE to %s, mode %d\n", d->name, mode);
2356         transmit_response(d, req);
2357 }
2358
2359 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2360 {
2361         struct skinny_req *req;
2362
2363         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2364                 return;
2365
2366         req->data.setmicrophone.mode = htolel(mode);
2367
2368         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_MICROPHONE_MESSAGE to %s, mode %d\n", d->name, mode);
2369         transmit_response(d, req);
2370 }
2371
2372 //static void transmit_callinfo(struct skinny_subchannel *sub)
2373 static void transmit_callinfo(struct skinny_device *d, int instance, int callid, char *fromname, char *fromnum, char *toname, char *tonum, int calldirection)
2374 {
2375         struct skinny_req *req;
2376
2377         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2378                 return;
2379
2380         ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2381         ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2382         ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2383         ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2384         req->data.callinfo.instance = htolel(instance);
2385         req->data.callinfo.reference = htolel(callid);
2386         req->data.callinfo.type = htolel(calldirection);
2387
2388         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_INFO_MESSAGE to %s, to %s(%s) from %s(%s) (dir=%d) on %s(%d)\n",
2389                 d->name, toname, tonum, fromname, fromnum, calldirection, d->name, instance);
2390         transmit_response(d, req);
2391 }
2392
2393 static void transmit_callinfo_variable(struct skinny_device *d, int instance, int callreference,
2394         char *fromname, char *fromnum, char *toname, char *tonum, int calldirection)
2395 {
2396         struct skinny_req *req;
2397         char *strptr;
2398         char *thestrings[12];
2399         int i;
2400         int callinfostrleft = MAXCALLINFOSTR;
2401
2402         if (!(req = req_alloc(sizeof(struct call_info_message_variable), CALL_INFO_MESSAGE_VARIABLE)))
2403                 return;
2404
2405         req->data.callinfomessagevariable.instance = htolel(instance);
2406         req->data.callinfomessagevariable.callreference = htolel(callreference);
2407         req->data.callinfomessagevariable.calldirection = htolel(calldirection);
2408
2409         req->data.callinfomessagevariable.unknown1 = htolel(0x00);
2410         req->data.callinfomessagevariable.unknown2 = htolel(0x00);
2411         req->data.callinfomessagevariable.unknown3 = htolel(0x00);
2412         req->data.callinfomessagevariable.unknown4 = htolel(0x00);
2413         req->data.callinfomessagevariable.unknown5 = htolel(0x00);
2414
2415         thestrings[0] = fromnum;
2416         thestrings[1] = "";                     /* Appears to be origfrom */
2417         thestrings[2] = tonum;
2418         thestrings[3] = "";
2419         thestrings[4] = "";
2420         thestrings[5] = "";
2421         thestrings[6] = "";
2422         thestrings[7] = "";
2423
2424         thestrings[8] = "";
2425         thestrings[9] = fromname;
2426         thestrings[10] = toname;
2427         thestrings[11] = "";
2428
2429         strptr = req->data.callinfomessagevariable.calldetails;
2430
2431         for(i = 0; i < 12; i++) {
2432                 ast_copy_string(strptr, thestrings[i], callinfostrleft);
2433                 strptr += strlen(thestrings[i]) + 1;
2434                 callinfostrleft -= strlen(thestrings[i]) + 1;
2435         }
2436
2437         req->len = req->len - (callinfostrleft & ~0x3);
2438
2439         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_INFO_MESSAGE_VARIABLE to %s, to %s(%s) from %s(%s) (dir=%d) on %s(%d)\n",
2440                 d->name, toname, tonum, fromname, fromnum, calldirection, d->name, instance);
2441         transmit_response(d, req);
2442 }
2443
2444 static void send_callinfo(struct skinny_subchannel *sub)
2445 {
2446         struct ast_channel *ast;
2447         struct skinny_device *d;
2448         struct skinny_line *l;
2449         char *fromname;
2450         char *fromnum;
2451         char *toname;
2452         char *tonum;
2453
2454         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2455                 return;
2456         }
2457
2458         ast = sub->owner;
2459         l = sub->line;
2460         d = l->device;
2461
2462         if (sub->calldirection == SKINNY_INCOMING) {
2463                 fromname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2464                 fromnum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, "");
2465                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2466                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2467         } else if (sub->calldirection == SKINNY_OUTGOING) {
2468                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2469                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2470                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, l->lastnumberdialed);
2471                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2472         } else {
2473                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2474                 return;
2475         }
2476
2477         if (d->protocolversion < 17) {
2478                 transmit_callinfo(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection);
2479         } else {
2480                 transmit_callinfo_variable(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection);
2481         }
2482 }
2483
2484 static void push_callinfo(struct skinny_subline *subline, struct skinny_subchannel *sub)
2485 {
2486         struct ast_channel *ast;
2487         struct skinny_device *d;
2488         struct skinny_line *l;
2489         char *fromname;
2490         char *fromnum;
2491         char *toname;
2492         char *tonum;
2493
2494         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2495                 return;
2496         }
2497
2498         ast = sub->owner;
2499         l = sub->line;
2500         d = l->device;
2501
2502         if (sub->calldirection == SKINNY_INCOMING) {
2503                 fromname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2504                 fromnum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, "");
2505                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2506                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2507         } else if (sub->calldirection == SKINNY_OUTGOING) {
2508                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2509                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2510                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, l->lastnumberdialed);
2511                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2512         } else {
2513                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2514                 return;
2515         }
2516
2517         if (d->protocolversion < 17) {
2518                 transmit_callinfo(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection);
2519         } else {
2520                 transmit_callinfo_variable(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection);
2521         }
2522 }
2523
2524 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2525 {
2526         struct skinny_req *req;
2527         struct skinny_line *l = sub->line;
2528         struct ast_format_list fmt;
2529         struct ast_format tmpfmt;
2530
2531         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2532                 return;
2533         ast_best_codec(l->cap, &tmpfmt);
2534         fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
2535
2536         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2537         req->data.openreceivechannel.partyId = htolel(sub->callid);
2538         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2539         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(&fmt.format));
2540         req->data.openreceivechannel.echo = htolel(0);
2541         req->data.openreceivechannel.bitrate = htolel(0);
2542
2543         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",
2544                 d->name, sub->callid, sub->callid, fmt.cur_ms, codec_ast2skinny(&fmt.format), 0, 0);
2545         transmit_response(d, req);
2546 }
2547
2548 static void transmit_start_tone(struct skinny_device *d, int tone, int instance, int reference)
2549 {
2550         struct skinny_req *req;
2551         if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2552                 return;
2553         req->data.starttone.tone = htolel(tone);
2554         req->data.starttone.instance = htolel(instance);
2555         req->data.starttone.reference = htolel(reference);
2556
2557         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting START_TONE_MESSAGE to %s, tone %d, inst %d, ref %d\n",
2558                 d->name, tone, instance, reference);
2559         transmit_response(d, req);
2560 }
2561
2562 static void transmit_stop_tone(struct skinny_device *d, int instance, int reference)
2563 {
2564         struct skinny_req *req;
2565         if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2566                 return;
2567         req->data.stoptone.instance = htolel(instance);
2568         req->data.stoptone.reference = htolel(reference);
2569
2570         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_TONE_MESSAGE to %s, inst %d, ref %d\n",
2571                 d->name, instance, reference);
2572         transmit_response(d, req);
2573 }
2574
2575 static int keyset_translatebitmask(int keyset, int intmask)
2576 {
2577         int extmask = 0;
2578         int x, y;
2579         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
2580
2581         for(x = 0; x < ARRAY_LEN(soft_key_default_definitions); x++) {
2582                 if (softkeymode[x].mode == keyset) {
2583                         const uint8_t *defaults = softkeymode[x].defaults;
2584
2585                         for (y = 0; y < softkeymode[x].count; y++) {
2586                                 if (intmask & (1 << (defaults[y]))) {
2587                                         extmask |= (1 << ((y)));
2588                                 }
2589                         }
2590                         break;
2591                 }
2592         }
2593
2594         return extmask;
2595 }
2596
2597 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey, int mask)
2598 {
2599         struct skinny_req *req;
2600         int newmask;
2601
2602         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2603                 return;
2604
2605         newmask = keyset_translatebitmask(softkey, mask);
2606         req->data.selectsoftkey.instance = htolel(instance);
2607         req->data.selectsoftkey.reference = htolel(callid);
2608         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2609         req->data.selectsoftkey.validKeyMask = htolel(newmask);
2610
2611         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SELECT_SOFT_KEYS_MESSAGE to %s, inst %d, callid %d, softkey %d, mask 0x%08x\n",
2612                 d->name, instance, callid, softkey, newmask);
2613         transmit_response(d, req);
2614 }
2615
2616 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2617 {
2618         struct skinny_req *req;
2619
2620         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2621                 return;
2622
2623         req->data.setlamp.stimulus = htolel(stimulus);
2624         req->data.setlamp.stimulusInstance = htolel(instance);
2625         req->data.setlamp.deviceStimulus = htolel(indication);
2626
2627         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_LAMP_MESSAGE to %s, stim %d, inst %d, ind %d\n",
2628                 d->name, stimulus, instance, indication);
2629         transmit_response(d, req);
2630 }
2631
2632 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2633 {
2634         struct skinny_req *req;
2635
2636         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2637                 return;
2638
2639         req->data.setringer.ringerMode = htolel(mode);
2640         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2641            Note: The phone will always show as ringing on the display.
2642
2643            1: phone will audibly ring over and over
2644            2: phone will audibly ring only once
2645            any other value, will NOT cause the phone to audibly ring
2646         */
2647         req->data.setringer.unknown1 = htolel(1);
2648         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2649            Perhaps a packet capture can shed some light on this. */
2650         req->data.setringer.unknown2 = htolel(1);
2651
2652         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_RINGER_MESSAGE to %s, mode %d, unk1 1, unk2 1\n",
2653                 d->name, mode);
2654         transmit_response(d, req);
2655 }
2656
2657 static void transmit_clear_display_message(struct skinny_device *d, int instance, int reference)
2658 {
2659         struct skinny_req *req;
2660         if (!(req = req_alloc(sizeof(struct clear_display_message), CLEAR_DISPLAY_MESSAGE)))
2661                 return;
2662
2663         //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2664         //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2665         //req->data.clearpromptstatus.lineInstance = instance;
2666         //req->data.clearpromptstatus.callReference = reference;
2667
2668         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_DISPLAY_MESSAGE to %s\n", d->name);
2669         transmit_response(d, req);
2670 }
2671
2672 /* This function is not currently used, but will be (wedhorn)*/
2673 /* static void transmit_display_message(struct skinny_device *d, const char *text, int instance, int reference)
2674 {
2675         struct skinny_req *req;
2676
2677         if (text == 0) {
2678                 ast_verb(1, "Bug, Asked to display empty message\n");
2679                 return;
2680         }
2681
2682         if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2683                 return;
2684
2685         ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2686         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAYTEXT_MESSAGE to %s, text %s\n", d->name, text);
2687         transmit_response(d, req);
2688 } */
2689
2690 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2691 {
2692         struct skinny_req *req;
2693
2694         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2695                 return;
2696
2697         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2698         req->data.displaynotify.displayTimeout = htolel(t);
2699
2700         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_NOTIFY_MESSAGE to %s, text %s\n", d->name, text);
2701         transmit_response(d, req);
2702 }
2703
2704 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
2705 {
2706         struct skinny_req *req;
2707
2708         if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2709                 return;
2710
2711         ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2712         req->data.displaypromptstatus.messageTimeout = htolel(t);
2713         req->data.displaypromptstatus.lineInstance = htolel(instance);
2714         req->data.displaypromptstatus.callReference = htolel(callid);
2715
2716         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE to %s, text %s\n", d->name, text);
2717         transmit_response(d, req);
2718 }
2719
2720 static void transmit_clearpromptmessage(struct skinny_device *d, int instance, int callid)
2721 {
2722         struct skinny_req *req;
2723
2724         if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2725                 return;
2726
2727         req->data.clearpromptstatus.lineInstance = htolel(instance);
2728         req->data.clearpromptstatus.callReference = htolel(callid);
2729
2730         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_PROMPT_MESSAGE to %s, inst %d, callid %d\n",
2731                 d->name, instance, callid);
2732         transmit_response(d, req);
2733 }
2734
2735 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2736 {
2737         struct skinny_req *req;
2738
2739         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2740                 return;
2741
2742         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2743         req->data.dialednumber.lineInstance = htolel(instance);
2744         req->data.dialednumber.callReference = htolel(callid);
2745
2746         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DIALED_NUMBER_MESSAGE to %s, num %s, inst %d, callid %d\n",
2747                 d->name, text, instance, callid);
2748         transmit_response(d, req);
2749 }
2750
2751 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2752 {
2753         struct skinny_req *req;
2754
2755         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2756                 return;
2757
2758         req->data.closereceivechannel.conferenceId = htolel(0);
2759         req->data.closereceivechannel.partyId = htolel(sub->callid);
2760
2761         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLOSE_RECEIVE_CHANNEL_MESSAGE to %s, confid %d, callid %d\n",
2762                 d->name, 0, sub->callid);
2763         transmit_response(d, req);
2764 }
2765
2766 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2767 {
2768         struct skinny_req *req;
2769
2770         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2771                 return;
2772
2773         req->data.stopmedia.conferenceId = htolel(0);
2774         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2775
2776         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_MEDIA_TRANSMISSION_MESSAGE to %s, confid %d, passthrupartyid %d\n",
2777                 d->name, 0, sub->callid);
2778         transmit_response(d, req);
2779 }
2780
2781 static void transmit_startmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub, struct sockaddr_in dest, struct ast_format_list fmt)
2782 {
2783         struct skinny_req *req;
2784
2785         if (d->protocolversion < 17) {
2786                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip4), START_MEDIA_TRANSMISSION_MESSAGE)))
2787                         return;
2788                 req->data.startmedia_ip4.conferenceId = htolel(sub->callid);
2789                 req->data.startmedia_ip4.passThruPartyId = htolel(sub->callid);
2790                 req->data.startmedia_ip4.remoteIp = dest.sin_addr.s_addr;
2791                 req->data.startmedia_ip4.remotePort = htolel(ntohs(dest.sin_port));
2792                 req->data.startmedia_ip4.packetSize = htolel(fmt.cur_ms);
2793                 req->data.startmedia_ip4.payloadType = htolel(codec_ast2skinny(&fmt.format));
2794                 req->data.startmedia_ip4.qualifier.precedence = htolel(127);
2795                 req->data.startmedia_ip4.qualifier.vad = htolel(0);
2796                 req->data.startmedia_ip4.qualifier.packets = htolel(0);
2797                 req->data.startmedia_ip4.qualifier.bitRate = htolel(0);
2798         } else {
2799                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip6), START_MEDIA_TRANSMISSION_MESSAGE)))
2800                         return;
2801                 req->data.startmedia_ip6.conferenceId = htolel(sub->callid);
2802                 req->data.startmedia_ip6.passThruPartyId = htolel(sub->callid);
2803                 memcpy(req->data.startmedia_ip6.remoteIp, &dest.sin_addr.s_addr, sizeof(dest.sin_addr.s_addr));
2804                 req->data.startmedia_ip6.remotePort = htolel(ntohs(dest.sin_port));
2805                 req->data.startmedia_ip6.packetSize = htolel(fmt.cur_ms);
2806                 req->data.startmedia_ip6.payloadType = htolel(codec_ast2skinny(&fmt.format));
2807                 req->data.startmedia_ip6.qualifier.precedence = htolel(127);
2808                 req->data.startmedia_ip6.qualifier.vad = htolel(0);
2809                 req->data.startmedia_ip6.qualifier.packets = htolel(0);
2810                 req->data.startmedia_ip6.qualifier.bitRate = htolel(0);
2811         }
2812
2813         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",
2814                 d->name, sub->callid, sub->callid, ast_inet_ntoa(dest.sin_addr), dest.sin_port, fmt.cur_ms, codec_ast2skinny(&fmt.format));
2815         transmit_response(d, req);
2816 }
2817
2818 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
2819 {
2820         struct skinny_req *req;
2821
2822         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2823                 return;
2824
2825         req->data.activatecallplane.lineInstance = htolel(l->instance);
2826
2827         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting ACTIVATE_CALL_PLANE_MESSAGE to %s, inst %d\n",
2828                 d->name, l->instance);
2829         transmit_response(d, req);
2830 }
2831
2832 static void transmit_callstate(struct skinny_device *d, int buttonInstance, unsigned callid, int state)
2833 {
2834         struct skinny_req *req;
2835
2836         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2837                 return;
2838
2839         req->data.callstate.callState = htolel(state);
2840         req->data.callstate.lineInstance = htolel(buttonInstance);
2841         req->data.callstate.callReference = htolel(callid);
2842
2843         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_STATE_MESSAGE to %s, state %s, inst %d, callid %d\n",
2844                 d->name, callstate2str(state), buttonInstance, callid);
2845         transmit_response(d, req);
2846 }
2847
2848 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
2849 {
2850         struct skinny_req *req;
2851         int anyon = 0;
2852
2853         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
2854                 return;
2855
2856         if (l->cfwdtype & SKINNY_CFWD_ALL) {
2857                 if (!ast_strlen_zero(l->call_forward_all)) {
2858                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
2859                         req->data.forwardstat.fwdall = htolel(1);
2860                         anyon++;
2861                 } else {
2862                         req->data.forwardstat.fwdall = htolel(0);
2863                 }
2864         }
2865         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
2866                 if (!ast_strlen_zero(l->call_forward_busy)) {
2867                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
2868                         req->data.forwardstat.fwdbusy = htolel(1);
2869                         anyon++;
2870                 } else {
2871                         req->data.forwardstat.fwdbusy = htolel(0);
2872                 }
2873         }
2874         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
2875                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
2876                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
2877                         req->data.forwardstat.fwdnoanswer = htolel(1);
2878                         anyon++;
2879                 } else {
2880                         req->data.forwardstat.fwdnoanswer = htolel(0);
2881                 }
2882         }
2883         req->data.forwardstat.lineNumber = htolel(l->instance);
2884         if (anyon)
2885                 req->data.forwardstat.activeforward = htolel(7);
2886         else
2887                 req->data.forwardstat.activeforward = htolel(0);
2888
2889         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting FORWARD_STAT_MESSAGE to %s, inst %d, all %s, busy %s, noans %s, acitve %d\n",
2890                 d->name, l->instance, l->call_forward_all, l->call_forward_busy, l->call_forward_noanswer, anyon ? 7 : 0);
2891         transmit_response(d, req);
2892 }
2893
2894 static void transmit_speeddialstatres(struct skinny_device *d, struct skinny_speeddial *sd)
2895 {
2896         struct skinny_req *req;
2897
2898         if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
2899                 return;
2900
2901         req->data.speeddialreq.speedDialNumber = htolel(sd->instance);
2902         ast_copy_string(req->data.speeddial.speedDialDirNumber, sd->exten, sizeof(req->data.speeddial.speedDialDirNumber));
2903         ast_copy_string(req->data.speeddial.speedDialDisplayName, sd->label, sizeof(req->data.speeddial.speedDialDisplayName));
2904
2905         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SPEED_DIAL_STAT_RES_MESSAGE to %s, inst %d, dir %s, display %s\n",
2906                 d->name, sd->instance, sd->exten, sd->label);
2907         transmit_response(d, req);
2908 }
2909
2910 //static void transmit_linestatres(struct skinny_device *d, struct skinny_line *l)
2911 static void transmit_linestatres(struct skinny_device *d, int instance)
2912 {
2913         struct skinny_req *req;
2914         struct skinny_line *l;
2915         struct skinny_speeddial *sd;
2916
2917         if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
2918                 return;
2919
2920         if ((l = find_line_by_instance(d, instance))) {
2921                 req->data.linestat.lineNumber = letohl(l->instance);
2922                 memcpy(req->data.linestat.lineDirNumber, l->name, sizeof(req->data.linestat.lineDirNumber));
2923                 memcpy(req->data.linestat.lineDisplayName, l->label, sizeof(req->data.linestat.lineDisplayName));
2924         } else if ((sd = find_speeddial_by_instance(d, instance, 1))) {
2925                 req->data.linestat.lineNumber = letohl(sd->instance);
2926                 memcpy(req->data.linestat.lineDirNumber, sd->label, sizeof(req->data.linestat.lineDirNumber));
2927                 memcpy(req->data.linestat.lineDisplayName, sd->label, sizeof(req->data.linestat.lineDisplayName));
2928         }
2929
2930         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting LINE_STAT_RES_MESSAGE to %s, inst %d, num %s, label %s\n",
2931                 d->name, l->instance, req->data.linestat.lineDirNumber, req->data.linestat.lineDisplayName);
2932         transmit_response(d, req);
2933 }
2934
2935 static void transmit_definetimedate(struct skinny_device *d)
2936 {
2937         struct skinny_req *req;
2938         struct timeval now = ast_tvnow();
2939         struct ast_tm cmtime;
2940
2941         if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
2942                 return;
2943
2944         ast_localtime(&now, &cmtime, NULL);
2945         req->data.definetimedate.year = htolel(cmtime.tm_year+1900);
2946         req->data.definetimedate.month = htolel(cmtime.tm_mon+1);
2947         req->data.definetimedate.dayofweek = htolel(cmtime.tm_wday);
2948         req->data.definetimedate.day = htolel(cmtime.tm_mday);
2949         req->data.definetimedate.hour = htolel(cmtime.tm_hour);
2950         req->data.definetimedate.minute = htolel(cmtime.tm_min);
2951         req->data.definetimedate.seconds = htolel(cmtime.tm_sec);
2952         req->data.definetimedate.milliseconds = htolel(cmtime.tm_usec / 1000);
2953         req->data.definetimedate.timestamp = htolel(now.tv_sec);
2954
2955         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DEFINETIMEDATE_MESSAGE to %s, date %d %d %d dow %d time %d:%d:%d.%d\n",
2956                 d->name, req->data.definetimedate.year, req->data.definetimedate.month, req->data.definetimedate.day, req->data.definetimedate.dayofweek,
2957                 req->data.definetimedate.hour, req->data.definetimedate.minute, req->data.definetimedate.seconds, req->data.definetimedate.milliseconds);
2958         transmit_response(d, req);
2959 }
2960
2961 static void transmit_versionres(struct skinny_device *d)
2962 {
2963         struct skinny_req *req;
2964         if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
2965                 return;
2966
2967         ast_copy_string(req->data.version.version, d->version_id, sizeof(req->data.version.version));
2968
2969         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting VERSION_RES_MESSAGE to %s, version %s\n", d->name, d->version_id);
2970         transmit_response(d, req);
2971 }
2972
2973 static void transmit_serverres(struct skinny_device *d)
2974 {
2975         struct skinny_req *req;
2976         if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
2977                 return;
2978
2979         memcpy(req->data.serverres.server[0].serverName, ourhost,
2980                         sizeof(req->data.serverres.server[0].serverName));
2981         req->data.serverres.serverListenPort[0] = htolel(ourport);
2982         req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
2983
2984         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SERVER_RES_MESSAGE to %s, srvname %s %s:%d\n",
2985                 d->name, ourhost, ast_inet_ntoa(d->ourip), ourport);
2986         transmit_response(d, req);
2987 }
2988
2989 static void transmit_softkeysetres(struct skinny_device *d)
2990 {
2991         struct skinny_req *req;
2992         int i;
2993         int x;
2994         int y;
2995         int keydefcount;
2996         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
2997
2998         if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
2999                 return;
3000
3001         SKINNY_DEBUG(DEBUG_TEMPLATE, 3, "Creating Softkey Template\n");
3002
3003         keydefcount = ARRAY_LEN(soft_key_default_definitions);
3004         req->data.softkeysets.softKeySetOffset = htolel(0);
3005         req->data.softkeysets.softKeySetCount = htolel(keydefcount);
3006         req->data.softkeysets.totalSoftKeySetCount = htolel(keydefcount);
3007         for (x = 0; x < keydefcount; x++) {
3008                 const uint8_t *defaults = softkeymode->defaults;
3009                 /* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
3010                    This will have to do for now. */
3011                 for (y = 0; y < softkeymode->count; y++) {
3012                         for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
3013                                 if (defaults[y] == i+1) {
3014                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = (i+1);
3015                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyInfoIndex[y] = htoles(i+301);
3016                                         SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "softKeySetDefinition : softKeyTemplateIndex: %d softKeyInfoIndex: %d\n",
3017                                                 i+1, i+301);
3018                                 }
3019                         }
3020                 }
3021                 softkeymode++;
3022         }
3023
3024         SKINNY_DEBUG(DEBUG_PACKET | DEBUG_TEMPLATE, 3, "Transmitting SOFT_KEY_SET_RES_MESSAGE to %s, template data\n",
3025                 d->name);
3026         transmit_response(d, req);
3027 }
3028
3029 static void transmit_softkeytemplateres(struct skinny_device *d)
3030 {
3031         struct skinny_req *req;
3032
3033         if (!(req = req_alloc(sizeof(struct soft_key_template_res_message), SOFT_KEY_TEMPLATE_RES_MESSAGE)))
3034                 return;
3035
3036         req->data.softkeytemplate.softKeyOffset = htolel(0);
3037         req->data.softkeytemplate.softKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
3038         req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
3039         memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
3040                 soft_key_template_default,
3041                 sizeof(soft_key_template_default));
3042
3043         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SOFT_KEY_TEMPLATE_RES_MESSAGE to %s, offset 0, keycnt %d, totalkeycnt %d, template data\n",
3044                 d->name, req->data.softkeytemplate.softKeyCount, req->data.softkeytemplate.totalSoftKeyCount);
3045         transmit_response(d, req);
3046 }
3047
3048 static void transmit_reset(struct skinny_device *d, int fullrestart)
3049 {
3050         struct skinny_req *req;
3051
3052         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
3053                 return;
3054
3055         if (fullrestart)
3056                 req->data.reset.resetType = 2;
3057         else
3058                 req->data.reset.resetType = 1;
3059
3060         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting RESET_MESSAGE to %s, type %s\n",
3061                 d->name, (fullrestart) ? "Restarting" : "Resetting");
3062         transmit_response(d, req);
3063 }
3064
3065 static void transmit_keepaliveack(struct skinny_device *d)
3066 {
3067         struct skinny_req *req;
3068
3069         if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
3070                 return;
3071
3072         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting KEEP_ALIVE_ACK_MESSAGE to %s\n", d->name);
3073         transmit_response(d, req);
3074 }
3075
3076 static void transmit_registerack(struct skinny_device *d)
3077 {
3078         struct skinny_req *req;
3079
3080         if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
3081                 return;
3082
3083         req->data.regack.res[0] = '0';
3084         req->data.regack.res[1] = '\0';
3085         req->data.regack.keepAlive = htolel(keep_alive);
3086         memcpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate));
3087         req->data.regack.res2[0] = '0';
3088         req->data.regack.res2[1] = '\0';
3089         req->data.regack.secondaryKeepAlive = htolel(keep_alive);
3090
3091 #ifdef AST_DEVMODE
3092         {
3093         short res = req->data.regack.res[0] << 8 | req->data.regack.res[1];
3094         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];
3095         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_ACK_MESSAGE to %s, keepalive %d, datetemplate %s, seckeepalive %d, res 0x%04x, res2 0x%08x\n",
3096                 d->name, keep_alive, date_format, keep_alive, res, res2);
3097         }
3098 #endif
3099
3100         transmit_response(d, req);
3101 }
3102
3103 static void transmit_capabilitiesreq(struct skinny_device *d)
3104 {
3105         struct skinny_req *req;
3106
3107         if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
3108                 return;
3109
3110         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CAPABILITIES_REQ_MESSAGE to %s\n", d->name);
3111         transmit_response(d, req);
3112 }
3113
3114 static void transmit_backspace(struct skinny_device *d, int instance, unsigned callid)
3115 {
3116         struct skinny_req *req;
3117
3118         if (!(req = req_alloc(sizeof(struct bksp_req_message), BKSP_REQ_MESSAGE)))
3119                 return;
3120
3121         req->data.bkspmessage.instance = htolel(instance);
3122         req->data.bkspmessage.callreference = htolel(callid);
3123
3124         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting BKSP_REQ_MESSAGE to %s, inst %d, callid %d \n",
3125                 d->name, instance, callid);
3126         transmit_response(d, req);
3127 }
3128
3129 static int skinny_extensionstate_cb(char *context, char *exten, struct ast_state_cb_info *info, void *data)
3130 {
3131         struct skinny_container *container = data;
3132         struct skinny_device *d = NULL;
3133         char hint[AST_MAX_EXTENSION];
3134         int state = info->exten_state;
3135
3136         /* only interested in device state here */
3137         if (info->reason != AST_HINT_UPDATE_DEVICE) {
3138                 return 0;
3139         }
3140
3141         if (container->type == SKINNY_SDCONTAINER) {
3142                 struct skinny_speeddial *sd = container->data;
3143                 d = sd->parent;
3144
3145                 SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on speeddial %s\n", ast_extension_state2str(state), sd->label);
3146
3147                 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
3148                         /* If they are not registered, we will override notification and show no availability */
3149                         if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
3150                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_FLASH);
3151                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3152                                 return 0;
3153                         }
3154                         switch (state) {
3155                         case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
3156                         case AST_EXTENSION_REMOVED:     /* Extension is gone */
3157                                 SKINNY_DEBUG(DEBUG_HINT, 3, "Extension state: Watcher for hint %s %s. Notify Device %s\n",
3158                                         exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
3159                                 sd->stateid = -1;
3160                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
3161                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3162                                 break;
3163                         case AST_EXTENSION_RINGING:
3164                         case AST_EXTENSION_UNAVAILABLE:
3165                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_BLINK);
3166                                 transmit_callstate(d, sd->instance, 0, SKINNY_RINGIN);
3167                                 break;
3168                         case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
3169                         case AST_EXTENSION_INUSE:
3170                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_ON);
3171                                 transmit_callstate(d, sd->instance, 0, SKINNY_CALLREMOTEMULTILINE);
3172                                 break;
3173                         case AST_EXTENSION_ONHOLD:
3174                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_WINK);
3175                                 transmit_callstate(d, sd->instance, 0, SKINNY_HOLD);
3176                                 break;
3177                         case AST_EXTENSION_NOT_INUSE:
3178                         default:
3179                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
3180                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3181                                 break;
3182                         }
3183                 }
3184                 sd->laststate = state;
3185         } else if (container->type == SKINNY_SUBLINECONTAINER) {
3186                 struct skinny_subline *subline = container->data;
3187                 struct skinny_line *l = subline->line;
3188                 d = l->device;
3189
3190                 SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on subline %s (%s@%s)\n", ast_extension_state2str(state), subline->name, exten, context);
3191
3192                 subline->extenstate = state;
3193
3194                 if (subline->callid == 0) {
3195                         return 0;
3196                 }
3197
3198                 switch (state) {
3199                 case AST_EXTENSION_RINGING: /* Handled by normal ringin */
3200                         break;
3201                 case AST_EXTENSION_INUSE:
3202                         if (subline->sub && (subline->sub->substate == SKINNY_CONNECTED)) { /* Device has a real call */
3203                                 transmit_callstate(d, l->instance, subline->callid, SKINNY_CONNECTED);
3204                                 transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_CONNECTED, KEYMASK_ALL);
3205                                 transmit_displaypromptstatus(d, "Connected", 0, l->instance, subline->callid);
3206                         } else { /* Some other device has active call */
3207                                 transmit_callstate(d, l->instance, subline->callid, SKINNY_CALLREMOTEMULTILINE);
3208                                 transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLACONNECTEDNOTACTIVE, KEYMASK_ALL);
3209                                 transmit_displaypromptstatus(d, "In Use", 0, l->instance, subline->callid);
3210                         }
3211                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3212                         transmit_ringer_mode(d, SKINNY_RING_OFF);
3213                         transmit_activatecallplane(d, l);
3214                         break;
3215                 case AST_EXTENSION_ONHOLD:
3216                         transmit_callstate(d, l->instance, subline->callid, SKINNY_HOLD);
3217                         transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLAHOLD, KEYMASK_ALL);
3218                         transmit_displaypromptstatus(d, "Hold", 0, l->instance, subline->callid);
3219                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3220                         transmit_activatecallplane(d, l);
3221                         break;
3222                 case AST_EXTENSION_NOT_INUSE:
3223                         transmit_callstate(d, l->instance, subline->callid, SKINNY_ONHOOK);
3224                         transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_ONHOOK, KEYMASK_ALL);
3225                         transmit_clearpromptmessage(d, l->instance, subline->callid);
3226                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
3227                         transmit_activatecallplane(d, l);
3228                         subline->callid = 0;
3229                         break;
3230                 default:
3231                         ast_log(LOG_WARNING, "AST_EXTENSION_STATE %s not configured\n", ast_extension_state2str(state));
3232                 }
3233         } else {
3234                 ast_log(LOG_WARNING, "Invalid data supplied to skinny_extensionstate_cb\n");
3235         }
3236
3237         return 0;
3238 }
3239
3240 static void update_connectedline(struct skinny_subchannel *sub, const void *data, size_t datalen)
3241 {
3242         struct ast_channel *c = sub->owner;
3243         struct skinny_line *l = sub->line;
3244         struct skinny_device *d = l->device;
3245
3246         if (!d->session) {
3247                 return;
3248         }
3249
3250         if (!ast_channel_caller(c)->id.number.valid
3251                 || ast_strlen_zero(ast_channel_caller(c)->id.number.str)
3252                 || !ast_channel_connected(c)->id.number.valid
3253                 || ast_strlen_zero(ast_channel_connected(c)->id.number.str))
3254                 return;
3255
3256         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Updating\n", sub->callid);
3257
3258         send_callinfo(sub);
3259 }
3260
3261 static void mwi_event_cb(const struct ast_event *event, void *userdata)
3262 {
3263         struct skinny_line *l = userdata;
3264         struct skinny_device *d = l->device;
3265         struct skinny_line *l2;
3266         int dev_msgs = 0;
3267
3268         if (!d || !d->session) {
3269                 return;
3270         }
3271
3272         if (event) {
3273                 l->newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
3274         }
3275
3276         if (l->newmsgs) {
3277                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
3278         } else {
3279                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
3280         }
3281
3282         /* find out wether the device lamp should be on or off */
3283         AST_LIST_TRAVERSE(&d->lines, l2, list) {
3284                 if (l2->newmsgs) {
3285                         dev_msgs++;
3286                 }
3287         }
3288
3289         if (dev_msgs) {
3290                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
3291         } else {
3292                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
3293         }
3294         ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", l->newmsgs);
3295 }
3296
3297 /* I do not believe skinny can deal with video.
3298    Anyone know differently? */
3299 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
3300 static enum ast_rtp_glue_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
3301 {
3302         struct skinny_subchannel *sub = NULL;
3303
3304         if (!(sub = ast_channel_tech_pvt(c)) || !(sub->vrtp))
3305                 return AST_RTP_GLUE_RESULT_FORBID;
3306