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