Add g722 codec support to skinny
[asterisk/asterisk.git] / channels / chan_skinny.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * chan_skinny was developed by Jeremy McNamara & Florian Overkamp
7  * chan_skinny was heavily modified/fixed by North Antara
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \brief Implementation of the Skinny protocol
23  *
24  * \author Jeremy McNamara & Florian Overkamp & North Antara
25  * \ingroup channel_drivers
26  */
27
28 /*! \li \ref chan_skinny.c uses the configuration file \ref skinny.conf
29  * \addtogroup configuration_file
30  */
31
32 /*! \page skinny.conf skinny.conf
33  * \verbinclude skinny.conf.sample
34  */
35
36 /*** MODULEINFO
37         <support_level>extended</support_level>
38  ***/
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <netinet/tcp.h>
47 #include <sys/ioctl.h>
48 #include <net/if.h>
49 #include <fcntl.h>
50 #include <netdb.h>
51 #include <arpa/inet.h>
52 #include <sys/signal.h>
53 #include <signal.h>
54 #include <ctype.h>
55
56 #include "asterisk/lock.h"
57 #include "asterisk/channel.h"
58 #include "asterisk/config.h"
59 #include "asterisk/module.h"
60 #include "asterisk/pbx.h"
61 #include "asterisk/sched.h"
62 #include "asterisk/io.h"
63 #include "asterisk/rtp_engine.h"
64 #include "asterisk/netsock2.h"
65 #include "asterisk/acl.h"
66 #include "asterisk/callerid.h"
67 #include "asterisk/cli.h"
68 #include "asterisk/manager.h"
69 #include "asterisk/say.h"
70 #include "asterisk/cdr.h"
71 #include "asterisk/astdb.h"
72 #include "asterisk/features.h"
73 #include "asterisk/app.h"
74 #include "asterisk/musiconhold.h"
75 #include "asterisk/utils.h"
76 #include "asterisk/dsp.h"
77 #include "asterisk/stringfields.h"
78 #include "asterisk/abstract_jb.h"
79 #include "asterisk/threadstorage.h"
80 #include "asterisk/devicestate.h"
81 #include "asterisk/event.h"
82 #include "asterisk/indications.h"
83 #include "asterisk/linkedlists.h"
84
85 /*** DOCUMENTATION
86         <manager name="SKINNYdevices" language="en_US">
87                 <synopsis>
88                         List SKINNY devices (text format).
89                 </synopsis>
90                 <syntax>
91                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
92                 </syntax>
93                 <description>
94                         <para>Lists Skinny devices in text format with details on current status.
95                         Devicelist will follow as separate events, followed by a final event called
96                         DevicelistComplete.</para>
97                 </description>
98         </manager>
99         <manager name="SKINNYshowdevice" language="en_US">
100                 <synopsis>
101                         Show SKINNY device (text format).
102                 </synopsis>
103                 <syntax>
104                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
105                         <parameter name="Device" required="true">
106                                 <para>The device name you want to check.</para>
107                         </parameter>
108                 </syntax>
109                 <description>
110                         <para>Show one SKINNY device with details on current status.</para>
111                 </description>
112         </manager>
113         <manager name="SKINNYlines" language="en_US">
114                 <synopsis>
115                         List SKINNY lines (text format).
116                 </synopsis>
117                 <syntax>
118                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
119                 </syntax>
120                 <description>
121                         <para>Lists Skinny lines in text format with details on current status.
122                         Linelist will follow as separate events, followed by a final event called
123                         LinelistComplete.</para>
124                 </description>
125         </manager>
126         <manager name="SKINNYshowline" language="en_US">
127                 <synopsis>
128                         Show SKINNY line (text format).
129                 </synopsis>
130                 <syntax>
131                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
132                         <parameter name="Line" required="true">
133                                 <para>The line name you want to check.</para>
134                         </parameter>
135                 </syntax>
136                 <description>
137                         <para>Show one SKINNY line with details on current status.</para>
138                 </description>
139         </manager>
140  ***/
141
142 /* Skinny debugging only available if asterisk configured with --enable-dev-mode */
143 #ifdef AST_DEVMODE
144 static int skinnydebug = 0;
145 char dbgcli_buf[256];
146 char dbgreg_buf[256];
147 char dbgsub_buf[256];
148 #define DEBUG_GENERAL   (1 << 1)
149 #define DEBUG_SUB       (1 << 2)
150 #define DEBUG_PACKET    (1 << 3)
151 #define DEBUG_AUDIO     (1 << 4)
152 #define DEBUG_LOCK      (1 << 5)
153 #define DEBUG_TEMPLATE  (1 << 6)
154 #define DEBUG_THREAD    (1 << 7)
155 #define DEBUG_HINT      (1 << 8)
156 #define SKINNY_DEBUG(type, verb_level, text, ...)                                               \
157         do{                                                                                     \
158                 if (skinnydebug & (type)) {                                                     \
159                         ast_verb(verb_level, "[%d] " text, ast_get_tid(), ##__VA_ARGS__);       \
160                 }                                                                               \
161         }while(0)
162 #else
163 #define SKINNY_DEBUG(type, verb_level, text, ...)
164 #endif
165
166 /*************************************
167  * Skinny/Asterisk Protocol Settings *
168  *************************************/
169 static const char tdesc[] = "Skinny Client Control Protocol (Skinny)";
170 static const char config[] = "skinny.conf";
171
172 static struct ast_format_cap *default_cap;
173 static struct ast_codec_pref default_prefs;
174
175 enum skinny_codecs {
176         SKINNY_CODEC_ALAW = 2,
177         SKINNY_CODEC_ULAW = 4,
178         SKINNY_CODEC_G722 = 6,
179         SKINNY_CODEC_G723_1 = 9,
180         SKINNY_CODEC_G729A = 12,
181         SKINNY_CODEC_G726_32 = 82, /* XXX Which packing order does this translate to? */
182         SKINNY_CODEC_H261 = 100,
183         SKINNY_CODEC_H263 = 101
184 };
185
186 #define DEFAULT_SKINNY_PORT 2000
187 #define DEFAULT_SKINNY_BACKLOG 2
188 #define SKINNY_MAX_PACKET 2000
189 #define DEFAULT_AUTH_TIMEOUT 30
190 #define DEFAULT_AUTH_LIMIT 50
191
192 static struct {
193         unsigned int tos;
194         unsigned int tos_audio;
195         unsigned int tos_video;
196         unsigned int cos;
197         unsigned int cos_audio;
198         unsigned int cos_video;
199 } qos = { 0, 0, 0, 0, 0, 0 };
200
201 static int keep_alive = 120;
202 static int auth_timeout = DEFAULT_AUTH_TIMEOUT;
203 static int auth_limit = DEFAULT_AUTH_LIMIT;
204 static int unauth_sessions = 0;
205 static char global_vmexten[AST_MAX_EXTENSION];      /* Voicemail pilot number */
206 static char used_context[AST_MAX_EXTENSION]; /* placeholder to check if context are already used in regcontext */
207 static char regcontext[AST_MAX_CONTEXT];     /* Context for auto-extension */
208 static char date_format[6] = "D-M-Y";
209 static char version_id[16] = "P002F202";
210
211 #if __BYTE_ORDER == __LITTLE_ENDIAN
212 #define letohl(x) (x)
213 #define letohs(x) (x)
214 #define htolel(x) (x)
215 #define htoles(x) (x)
216 #else
217 #if defined(HAVE_BYTESWAP_H)
218 #include <byteswap.h>
219 #define letohl(x) bswap_32(x)
220 #define letohs(x) bswap_16(x)
221 #define htolel(x) bswap_32(x)
222 #define htoles(x) bswap_16(x)
223 #elif defined(HAVE_SYS_ENDIAN_SWAP16)
224 #include <sys/endian.h>
225 #define letohl(x) __swap32(x)
226 #define letohs(x) __swap16(x)
227 #define htolel(x) __swap32(x)
228 #define htoles(x) __swap16(x)
229 #elif defined(HAVE_SYS_ENDIAN_BSWAP16)
230 #include <sys/endian.h>
231 #define letohl(x) bswap32(x)
232 #define letohs(x) bswap16(x)
233 #define htolel(x) bswap32(x)
234 #define htoles(x) bswap16(x)
235 #else
236 #define __bswap_16(x) \
237         ((((x) & 0xff00) >> 8) | \
238          (((x) & 0x00ff) << 8))
239 #define __bswap_32(x) \
240         ((((x) & 0xff000000) >> 24) | \
241          (((x) & 0x00ff0000) >>  8) | \
242          (((x) & 0x0000ff00) <<  8) | \
243          (((x) & 0x000000ff) << 24))
244 #define letohl(x) __bswap_32(x)
245 #define letohs(x) __bswap_16(x)
246 #define htolel(x) __bswap_32(x)
247 #define htoles(x) __bswap_16(x)
248 #endif
249 #endif
250
251 /*! Global jitterbuffer configuration - by default, jb is disabled
252  *  \note Values shown here match the defaults shown in skinny.conf.sample */
253 static struct ast_jb_conf default_jbconf =
254 {
255         .flags = 0,
256         .max_size = 200,
257         .resync_threshold = 1000,
258         .impl = "fixed",
259         .target_extra = 40,
260 };
261 static struct ast_jb_conf global_jbconf;
262
263 #ifdef AST_DEVMODE
264 AST_THREADSTORAGE(message2str_threadbuf);
265 #define MESSAGE2STR_BUFSIZE   35
266 #endif
267
268 AST_THREADSTORAGE(device2str_threadbuf);
269 #define DEVICE2STR_BUFSIZE   15
270
271 AST_THREADSTORAGE(control2str_threadbuf);
272 #define CONTROL2STR_BUFSIZE   100
273
274 AST_THREADSTORAGE(substate2str_threadbuf);
275 #define SUBSTATE2STR_BUFSIZE   15
276
277 AST_THREADSTORAGE(callstate2str_threadbuf);
278 #define CALLSTATE2STR_BUFSIZE   15
279
280 /*********************
281  * Protocol Messages *
282  *********************/
283 /* message types */
284 #define KEEP_ALIVE_MESSAGE 0x0000
285 /* no additional struct */
286
287 #define REGISTER_MESSAGE 0x0001
288 struct register_message {
289         char name[16];
290         uint32_t userId;
291         uint32_t instance;
292         uint32_t ip;
293         uint32_t type;
294         uint32_t maxStreams;
295         uint32_t space;
296         uint8_t protocolVersion;
297         /*! \brief space2 is used for newer version of skinny */
298         char space2[3];
299 };
300
301 #define IP_PORT_MESSAGE 0x0002
302
303 #define KEYPAD_BUTTON_MESSAGE 0x0003
304 struct keypad_button_message {
305         uint32_t button;
306         uint32_t lineInstance;
307         uint32_t callReference;
308 };
309
310
311 #define ENBLOC_CALL_MESSAGE 0x0004
312 struct enbloc_call_message {
313         char calledParty[24];
314 };
315
316 #define STIMULUS_MESSAGE 0x0005
317 struct stimulus_message {
318         uint32_t stimulus;
319         uint32_t stimulusInstance;
320         uint32_t callreference;
321 };
322
323 #define OFFHOOK_MESSAGE 0x0006
324 struct offhook_message {
325         uint32_t instance;
326         uint32_t reference;
327 };
328
329 #define ONHOOK_MESSAGE 0x0007
330 struct onhook_message {
331         uint32_t instance;
332         uint32_t reference;
333 };
334
335 #define CAPABILITIES_RES_MESSAGE 0x0010
336 struct station_capabilities {
337         uint32_t codec; /* skinny codec, not ast codec */
338         uint32_t frames;
339         union {
340                 char res[8];
341                 uint32_t rate;
342         } payloads;
343 };
344
345 #define SKINNY_MAX_CAPABILITIES 18
346
347 struct capabilities_res_message {
348         uint32_t count;
349         struct station_capabilities caps[SKINNY_MAX_CAPABILITIES];
350 };
351
352 #define SPEED_DIAL_STAT_REQ_MESSAGE 0x000A
353 struct speed_dial_stat_req_message {
354         uint32_t speedDialNumber;
355 };
356
357 #define LINE_STATE_REQ_MESSAGE 0x000B
358 struct line_state_req_message {
359         uint32_t lineNumber;
360 };
361
362 #define TIME_DATE_REQ_MESSAGE 0x000D
363 #define BUTTON_TEMPLATE_REQ_MESSAGE 0x000E
364 #define VERSION_REQ_MESSAGE 0x000F
365 #define SERVER_REQUEST_MESSAGE 0x0012
366
367 #define ALARM_MESSAGE 0x0020
368 struct alarm_message {
369         uint32_t alarmSeverity;
370         char displayMessage[80];
371         uint32_t alarmParam1;
372         uint32_t alarmParam2;
373 };
374
375 #define OPEN_RECEIVE_CHANNEL_ACK_MESSAGE 0x0022
376 struct open_receive_channel_ack_message_ip4 {
377         uint32_t status;
378         uint32_t ipAddr;
379         uint32_t port;
380         uint32_t callReference;
381 };
382 struct open_receive_channel_ack_message_ip6 {
383         uint32_t status;
384         uint32_t space;
385         char ipAddr[16];
386         uint32_t port;
387         uint32_t callReference;
388 };
389
390 #define SOFT_KEY_SET_REQ_MESSAGE 0x0025
391
392 #define SOFT_KEY_EVENT_MESSAGE 0x0026
393 struct soft_key_event_message {
394         uint32_t softKeyEvent;
395         uint32_t instance;
396         uint32_t callreference;
397 };
398
399 #define UNREGISTER_MESSAGE 0x0027
400 #define SOFT_KEY_TEMPLATE_REQ_MESSAGE 0x0028
401 #define HEADSET_STATUS_MESSAGE 0x002B
402 #define REGISTER_AVAILABLE_LINES_MESSAGE 0x002D
403
404 #define REGISTER_ACK_MESSAGE 0x0081
405 struct register_ack_message {
406         uint32_t keepAlive;
407         char dateTemplate[6];
408         char res[2];
409         uint32_t secondaryKeepAlive;
410         char res2[4];
411 };
412
413 #define START_TONE_MESSAGE 0x0082
414 struct start_tone_message {
415         uint32_t tone;
416         uint32_t space;
417         uint32_t instance;
418         uint32_t reference;
419 };
420
421 #define STOP_TONE_MESSAGE 0x0083
422 struct stop_tone_message {
423         uint32_t instance;
424         uint32_t reference;
425         uint32_t space;
426 };
427
428 #define SET_RINGER_MESSAGE 0x0085
429 struct set_ringer_message {
430         uint32_t ringerMode;
431         uint32_t unknown1; /* See notes in transmit_ringer_mode */
432         uint32_t unknown2;
433         uint32_t space[2];
434 };
435
436 #define SET_LAMP_MESSAGE 0x0086
437 struct set_lamp_message {
438         uint32_t stimulus;
439         uint32_t stimulusInstance;
440         uint32_t deviceStimulus;
441 };
442
443 #define SET_SPEAKER_MESSAGE 0x0088
444 struct set_speaker_message {
445         uint32_t mode;
446 };
447
448 /* XXX When do we need to use this? */
449 #define SET_MICROPHONE_MESSAGE 0x0089
450 struct set_microphone_message {
451         uint32_t mode;
452 };
453
454 #define START_MEDIA_TRANSMISSION_MESSAGE 0x008A
455 struct media_qualifier {
456         uint32_t precedence;
457         uint32_t vad;
458         uint32_t packets;
459         uint32_t bitRate;
460 };
461
462 struct start_media_transmission_message_ip4 {
463         uint32_t conferenceId;
464         uint32_t passThruPartyId;
465         uint32_t remoteIp;
466         uint32_t remotePort;
467         uint32_t packetSize;
468         uint32_t payloadType;
469         struct media_qualifier qualifier;
470         uint32_t space[19];
471 };
472
473 struct start_media_transmission_message_ip6 {
474         uint32_t conferenceId;
475         uint32_t passThruPartyId;
476         uint32_t space;
477         char remoteIp[16];
478         uint32_t remotePort;
479         uint32_t packetSize;
480         uint32_t payloadType;
481         struct media_qualifier qualifier;
482         /*! \brief space2 is used for newer version of skinny */
483         uint32_t space2[19];
484 };
485
486 #define STOP_MEDIA_TRANSMISSION_MESSAGE 0x008B
487 struct stop_media_transmission_message {
488         uint32_t conferenceId;
489         uint32_t passThruPartyId;
490         uint32_t space[3];
491 };
492
493 #define CALL_INFO_MESSAGE 0x008F
494 struct call_info_message {
495         char callingPartyName[40];
496         char callingParty[24];
497         char calledPartyName[40];
498         char calledParty[24];
499         uint32_t instance;
500         uint32_t reference;
501         uint32_t type;
502         char originalCalledPartyName[40];
503         char originalCalledParty[24];
504         char lastRedirectingPartyName[40];
505         char lastRedirectingParty[24];
506         uint32_t originalCalledPartyRedirectReason;
507         uint32_t lastRedirectingReason;
508         char callingPartyVoiceMailbox[24];
509         char calledPartyVoiceMailbox[24];
510         char originalCalledPartyVoiceMailbox[24];
511         char lastRedirectingVoiceMailbox[24];
512         uint32_t space[3];
513 };
514
515 #define FORWARD_STAT_MESSAGE 0x0090
516 struct forward_stat_message {
517         uint32_t activeforward;
518         uint32_t lineNumber;
519         uint32_t fwdall;
520         char fwdallnum[24];
521         uint32_t fwdbusy;
522         char fwdbusynum[24];
523         uint32_t fwdnoanswer;
524         char fwdnoanswernum[24];
525 };
526
527 #define SPEED_DIAL_STAT_RES_MESSAGE 0x0091
528 struct speed_dial_stat_res_message {
529         uint32_t speedDialNumber;
530         char speedDialDirNumber[24];
531         char speedDialDisplayName[40];
532 };
533
534 #define LINE_STAT_RES_MESSAGE 0x0092
535 struct line_stat_res_message {
536         uint32_t lineNumber;
537         char lineDirNumber[24];
538         char lineDisplayName[24];
539         uint32_t space[15];
540 };
541
542 #define DEFINETIMEDATE_MESSAGE 0x0094
543 struct definetimedate_message {
544         uint32_t year; /* since 1900 */
545         uint32_t month;
546         uint32_t dayofweek; /* monday = 1 */
547         uint32_t day;
548         uint32_t hour;
549         uint32_t minute;
550         uint32_t seconds;
551         uint32_t milliseconds;
552         uint32_t timestamp;
553 };
554
555 #define BUTTON_TEMPLATE_RES_MESSAGE 0x0097
556 struct button_definition {
557         uint8_t instanceNumber;
558         uint8_t buttonDefinition;
559 };
560
561 struct button_definition_template {
562         uint8_t buttonDefinition;
563         /* for now, anything between 0xB0 and 0xCF is custom */
564         /*int custom;*/
565 };
566
567 #define STIMULUS_REDIAL 0x01
568 #define STIMULUS_SPEEDDIAL 0x02
569 #define STIMULUS_HOLD 0x03
570 #define STIMULUS_TRANSFER 0x04
571 #define STIMULUS_FORWARDALL 0x05
572 #define STIMULUS_FORWARDBUSY 0x06
573 #define STIMULUS_FORWARDNOANSWER 0x07
574 #define STIMULUS_DISPLAY 0x08
575 #define STIMULUS_LINE 0x09
576 #define STIMULUS_VOICEMAIL 0x0F
577 #define STIMULUS_AUTOANSWER 0x11
578 #define STIMULUS_DND 0x3F
579 #define STIMULUS_CONFERENCE 0x7D
580 #define STIMULUS_CALLPARK 0x7E
581 #define STIMULUS_CALLPICKUP 0x7F
582 #define STIMULUS_NONE 0xFF
583
584 /* Button types */
585 #define BT_REDIAL STIMULUS_REDIAL
586 #define BT_SPEEDDIAL STIMULUS_SPEEDDIAL
587 #define BT_HOLD STIMULUS_HOLD
588 #define BT_TRANSFER STIMULUS_TRANSFER
589 #define BT_FORWARDALL STIMULUS_FORWARDALL
590 #define BT_FORWARDBUSY STIMULUS_FORWARDBUSY
591 #define BT_FORWARDNOANSWER STIMULUS_FORWARDNOANSWER
592 #define BT_DISPLAY STIMULUS_DISPLAY
593 #define BT_LINE STIMULUS_LINE
594 #define BT_VOICEMAIL STIMULUS_VOICEMAIL
595 #define BT_AUTOANSWER STIMULUS_AUTOANSWER
596 #define BT_DND STIMULUS_DND
597 #define BT_CONFERENCE STIMULUS_CONFERENCE
598 #define BT_CALLPARK STIMULUS_CALLPARK
599 #define BT_CALLPICKUP STIMULUS_CALLPICKUP
600 #define BT_NONE 0x00
601
602 /* Custom button types - add our own between 0xB0 and 0xCF.
603    This may need to be revised in the future,
604    if stimuluses are ever added in this range. */
605 #define BT_CUST_LINESPEEDDIAL 0xB0 /* line or speeddial with/without hint */
606 #define BT_CUST_LINE 0xB1          /* line or speeddial with hint only */
607
608 struct button_template_res_message {
609         uint32_t buttonOffset;
610         uint32_t buttonCount;
611         uint32_t totalButtonCount;
612         struct button_definition definition[42];
613 };
614
615 #define VERSION_RES_MESSAGE 0x0098
616 struct version_res_message {
617         char version[16];
618 };
619
620 #define DISPLAYTEXT_MESSAGE 0x0099
621 struct displaytext_message {
622         char text[40];
623 };
624
625 #define CLEAR_NOTIFY_MESSAGE  0x0115
626 #define CLEAR_DISPLAY_MESSAGE 0x009A
627 struct clear_display_message {
628         uint32_t space;
629 };
630
631 #define CAPABILITIES_REQ_MESSAGE 0x009B
632
633 #define REGISTER_REJ_MESSAGE 0x009D
634 struct register_rej_message {
635         char errMsg[33];
636 };
637
638 #define SERVER_RES_MESSAGE 0x009E
639 struct server_identifier {
640         char serverName[48];
641 };
642
643 struct server_res_message {
644         struct server_identifier server[5];
645         uint32_t serverListenPort[5];
646         uint32_t serverIpAddr[5];
647 };
648
649 #define RESET_MESSAGE 0x009F
650 struct reset_message {
651         uint32_t resetType;
652 };
653
654 #define KEEP_ALIVE_ACK_MESSAGE 0x0100
655
656 #define OPEN_RECEIVE_CHANNEL_MESSAGE 0x0105
657 struct open_receive_channel_message {
658         uint32_t conferenceId;
659         uint32_t partyId;
660         uint32_t packets;
661         uint32_t capability;
662         uint32_t echo;
663         uint32_t bitrate;
664         uint32_t space[36];
665 };
666
667 #define CLOSE_RECEIVE_CHANNEL_MESSAGE 0x0106
668 struct close_receive_channel_message {
669         uint32_t conferenceId;
670         uint32_t partyId;
671         uint32_t space[2];
672 };
673
674 #define SOFT_KEY_TEMPLATE_RES_MESSAGE 0x0108
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_G722:
1944                 return ast_format_set(result, AST_FORMAT_G722, 0);
1945         case SKINNY_CODEC_G723_1:
1946                 return ast_format_set(result, AST_FORMAT_G723_1, 0);
1947         case SKINNY_CODEC_G729A:
1948                 return ast_format_set(result, AST_FORMAT_G729A, 0);
1949         case SKINNY_CODEC_G726_32:
1950                 return ast_format_set(result, AST_FORMAT_G726_AAL2, 0); /* XXX Is this right? */
1951         case SKINNY_CODEC_H261:
1952                 return ast_format_set(result, AST_FORMAT_H261, 0);
1953         case SKINNY_CODEC_H263:
1954                 return ast_format_set(result, AST_FORMAT_H263 ,0);
1955         default:
1956                 ast_format_clear(result);
1957                 return result;
1958         }
1959 }
1960
1961 static int codec_ast2skinny(const struct ast_format *astcodec)
1962 {
1963         switch (astcodec->id) {
1964         case AST_FORMAT_ALAW:
1965                 return SKINNY_CODEC_ALAW;
1966         case AST_FORMAT_ULAW:
1967                 return SKINNY_CODEC_ULAW;
1968         case AST_FORMAT_G722:
1969                 return SKINNY_CODEC_G722;
1970         case AST_FORMAT_G723_1:
1971                 return SKINNY_CODEC_G723_1;
1972         case AST_FORMAT_G729A:
1973                 return SKINNY_CODEC_G729A;
1974         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
1975                 return SKINNY_CODEC_G726_32;
1976         case AST_FORMAT_H261:
1977                 return SKINNY_CODEC_H261;
1978         case AST_FORMAT_H263:
1979                 return SKINNY_CODEC_H263;
1980         default:
1981                 return 0;
1982         }
1983 }
1984
1985 static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
1986 {
1987         if (!l)
1988                 return 0;
1989
1990         if (!ast_strlen_zero(cfwd)) {
1991                 if (cfwdtype & SKINNY_CFWD_ALL) {
1992                         l->cfwdtype |= SKINNY_CFWD_ALL;
1993                         ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
1994                 }
1995                 if (cfwdtype & SKINNY_CFWD_BUSY) {
1996                         l->cfwdtype |= SKINNY_CFWD_BUSY;
1997                         ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
1998                 }
1999                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2000                         l->cfwdtype |= SKINNY_CFWD_NOANSWER;
2001                         ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
2002                 }
2003         } else {
2004                 if (cfwdtype & SKINNY_CFWD_ALL) {
2005                         l->cfwdtype &= ~SKINNY_CFWD_ALL;
2006                         memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
2007                 }
2008                 if (cfwdtype & SKINNY_CFWD_BUSY) {
2009                         l->cfwdtype &= ~SKINNY_CFWD_BUSY;
2010                         memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
2011                 }
2012                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2013                         l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
2014                         memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
2015                 }
2016         }
2017         return l->cfwdtype;
2018 }
2019
2020 static void cleanup_stale_contexts(char *new, char *old)
2021 {
2022         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
2023
2024         while ((oldcontext = strsep(&old, "&"))) {
2025                 stalecontext = '\0';
2026                 ast_copy_string(newlist, new, sizeof(newlist));
2027                 stringp = newlist;
2028                 while ((newcontext = strsep(&stringp, "&"))) {
2029                         if (strcmp(newcontext, oldcontext) == 0) {
2030                                 /* This is not the context you're looking for */
2031                                 stalecontext = '\0';
2032                                 break;
2033                         } else if (strcmp(newcontext, oldcontext)) {
2034                                 stalecontext = oldcontext;
2035                         }
2036                         
2037                 }
2038                 if (stalecontext)
2039                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
2040         }
2041 }
2042
2043 static void register_exten(struct skinny_line *l)
2044 {
2045         char multi[256];
2046         char *stringp, *ext, *context;
2047
2048         if (ast_strlen_zero(regcontext))
2049                 return;
2050
2051         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2052         stringp = multi;
2053         while ((ext = strsep(&stringp, "&"))) {
2054                 if ((context = strchr(ext, '@'))) {
2055                         *context++ = '\0'; /* split ext@context */
2056                         if (!ast_context_find(context)) {
2057                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2058                                 continue;
2059                         }
2060                 } else {
2061                         context = regcontext;
2062                 }
2063                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2064                          ast_strdup(l->name), ast_free_ptr, "Skinny");
2065         }
2066 }
2067
2068 static void unregister_exten(struct skinny_line *l)
2069 {
2070         char multi[256];
2071         char *stringp, *ext, *context;
2072
2073         if (ast_strlen_zero(regcontext))
2074                 return;
2075
2076         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2077         stringp = multi;
2078         while ((ext = strsep(&stringp, "&"))) {
2079                 if ((context = strchr(ext, '@'))) {
2080                         *context++ = '\0'; /* split ext@context */
2081                         if (!ast_context_find(context)) {
2082                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2083                                 continue;
2084                         }
2085                 } else {
2086                         context = regcontext;
2087                 }
2088                 ast_context_remove_extension(context, ext, 1, NULL);
2089         }
2090 }
2091
2092 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
2093 {
2094         struct skinny_device *d;
2095         struct skinny_line *l;
2096         struct skinny_subline *subline;
2097         struct skinny_speeddial *sd;
2098         struct sockaddr_in sin;
2099         socklen_t slen;
2100         int instance;
2101
2102         AST_LIST_LOCK(&devices);
2103         AST_LIST_TRAVERSE(&devices, d, list){
2104                 struct ast_sockaddr addr;
2105                 ast_sockaddr_from_sin(&addr, &s->sin);
2106                 if (!d->session && !strcasecmp(req->data.reg.name, d->id)
2107                                 && ast_apply_ha(d->ha, &addr)) {
2108                         s->device = d;
2109                         d->type = letohl(req->data.reg.type);
2110                         d->protocolversion = letohl(req->data.reg.protocolVersion);
2111                         if (ast_strlen_zero(d->version_id)) {
2112                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
2113                         }
2114                         d->session = s;
2115
2116                         slen = sizeof(sin);
2117                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
2118                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
2119                                 sin.sin_addr = __ourip;
2120                         }
2121                         d->ourip = sin.sin_addr;
2122
2123                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2124                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd->container);
2125                         }
2126                         instance = 0;
2127                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2128                                 instance++;
2129                         }
2130                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2131                                 ast_format_cap_joint_copy(l->confcap, d->cap, l->cap);
2132                                 l->prefs = l->confprefs;
2133                                 if (!l->prefs.order[0]) {
2134                                         l->prefs = d->confprefs;
2135                                 }
2136                                 /* l->capability = d->capability;
2137                                 l->prefs = d->prefs; */
2138                                 l->instance = instance;
2139                                 l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
2140                                 set_callforwards(l, NULL, 0);
2141                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Registered\r\n", l->name, d->name);
2142                                 register_exten(l);
2143                                 /* initialize MWI on line and device */
2144                                 mwi_event_cb(0, l);
2145                                 AST_LIST_TRAVERSE(&l->sublines, subline, list) {
2146                                         ast_extension_state_add(subline->context, subline->exten, skinny_extensionstate_cb, subline->container);
2147                                 }
2148                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s", l->name);
2149                                 --instance;
2150                         }
2151                         break;
2152                 }
2153         }
2154         AST_LIST_UNLOCK(&devices);
2155         if (!d) {
2156                 return 0;
2157         }
2158         return 1;
2159 }
2160
2161 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
2162 {
2163         struct skinny_device *d;
2164         struct skinny_line *l;
2165         struct skinny_speeddial *sd;
2166
2167         d = s->device;
2168
2169         if (d) {
2170                 d->session = NULL;
2171
2172                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2173                         if (sd->stateid > -1)
2174                                 ast_extension_state_del(sd->stateid, NULL);
2175                 }
2176                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2177                         if (l->device == d) {
2178                                 ast_format_cap_remove_all(l->cap);
2179                                 ast_parse_allow_disallow(&l->prefs, l->cap, "all", 0);
2180                                 l->instance = 0;
2181                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Unregistered\r\n", l->name, d->name);
2182                                 unregister_exten(l);
2183                                 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "Skinny/%s", l->name);
2184                         }
2185                 }
2186         }
2187
2188         return -1; /* main loop will destroy the session */
2189 }
2190
2191 #ifdef AST_DEVMODE
2192 static char *callstate2str(int ind)
2193 {
2194         char *tmp;
2195
2196         switch (ind) {
2197         case SKINNY_OFFHOOK:
2198                 return "SKINNY_OFFHOOK";
2199         case SKINNY_ONHOOK:
2200                 return "SKINNY_ONHOOK";
2201         case SKINNY_RINGOUT:
2202                 return "SKINNY_RINGOUT";
2203         case SKINNY_RINGIN:
2204                 return "SKINNY_RINGIN";
2205         case SKINNY_CONNECTED:
2206                 return "SKINNY_CONNECTED";
2207         case SKINNY_BUSY:
2208                 return "SKINNY_BUSY";
2209         case SKINNY_CONGESTION:
2210                 return "SKINNY_CONGESTION";
2211         case SKINNY_PROGRESS:
2212                 return "SKINNY_PROGRESS";
2213         case SKINNY_HOLD:
2214                 return "SKINNY_HOLD";
2215         case SKINNY_CALLWAIT:
2216                 return "SKINNY_CALLWAIT";
2217         default:
2218                 if (!(tmp = ast_threadstorage_get(&callstate2str_threadbuf, CALLSTATE2STR_BUFSIZE)))
2219                         return "Unknown";
2220                 snprintf(tmp, CALLSTATE2STR_BUFSIZE, "UNKNOWN-%d", ind);
2221                 return tmp;
2222         }
2223 }
2224
2225 #endif
2226
2227 static int transmit_response_bysession(struct skinnysession *s, struct skinny_req *req)
2228 {
2229         int res = 0;
2230
2231         if (!s) {
2232                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2233                 return -1;
2234         }
2235
2236         ast_mutex_lock(&s->lock);
2237
2238         if ((letohl(req->len) > SKINNY_MAX_PACKET) || (letohl(req->len) < 0)) {
2239                 ast_log(LOG_WARNING, "transmit_response: the length of the request (%d) is out of bounds (%d)\n", letohl(req->len), SKINNY_MAX_PACKET);
2240                 ast_mutex_unlock(&s->lock);
2241                 return -1;
2242         }
2243
2244         memset(s->outbuf, 0, sizeof(s->outbuf));
2245         memcpy(s->outbuf, req, skinny_header_size);
2246         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2247
2248         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2249
2250         if (res != letohl(req->len)+8) {
2251                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2252                 if (res == -1) {
2253                         ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2254                         skinny_unregister(NULL, s);
2255                 }
2256
2257         }
2258
2259         ast_free(req);
2260         ast_mutex_unlock(&s->lock);
2261         return 1;
2262 }
2263
2264 static void transmit_response(struct skinny_device *d, struct skinny_req *req)
2265 {
2266         transmit_response_bysession(d->session, req);
2267 }
2268
2269 static void transmit_registerrej(struct skinnysession *s)
2270 {
2271         struct skinny_req *req;
2272         char name[16];
2273
2274         if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
2275                 return;
2276
2277         memcpy(&name, req->data.reg.name, sizeof(name));
2278         snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2279
2280         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_REJ_MESSAGE to UNKNOWN_DEVICE\n");
2281         transmit_response_bysession(s, req);
2282 }
2283
2284 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2285 {
2286         struct skinny_req *req;
2287
2288         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2289                 return;
2290
2291         req->data.setspeaker.mode = htolel(mode);
2292
2293         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_SPEAKER_MESSAGE to %s, mode %d\n", d->name, mode);
2294         transmit_response(d, req);
2295 }
2296
2297 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2298 {
2299         struct skinny_req *req;
2300
2301         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2302                 return;
2303
2304         req->data.setmicrophone.mode = htolel(mode);
2305
2306         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_MICROPHONE_MESSAGE to %s, mode %d\n", d->name, mode);
2307         transmit_response(d, req);
2308 }
2309
2310 //static void transmit_callinfo(struct skinny_subchannel *sub)
2311 static void transmit_callinfo(struct skinny_device *d, int instance, int callid, char *fromname, char *fromnum, char *toname, char *tonum, int calldirection)
2312 {
2313         struct skinny_req *req;
2314
2315         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2316                 return;
2317
2318         ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2319         ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2320         ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2321         ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2322         req->data.callinfo.instance = htolel(instance);
2323         req->data.callinfo.reference = htolel(callid);
2324         req->data.callinfo.type = htolel(calldirection);
2325
2326         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_INFO_MESSAGE to %s, to %s(%s) from %s(%s) (dir=%d) on %s(%d)\n",
2327                 d->name, toname, tonum, fromname, fromnum, calldirection, d->name, instance);
2328         transmit_response(d, req);
2329 }
2330
2331 static void send_callinfo(struct skinny_subchannel *sub)
2332 {
2333         struct ast_channel *ast;
2334         struct skinny_device *d;
2335         struct skinny_line *l;
2336         char *fromname;
2337         char *fromnum;
2338         char *toname;
2339         char *tonum;
2340
2341         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2342                 return;
2343         }
2344         
2345         ast = sub->owner;
2346         l = sub->line;
2347         d = l->device;
2348         
2349         if (sub->calldirection == SKINNY_INCOMING) {
2350                 fromname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2351                 fromnum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, "");
2352                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2353                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2354         } else if (sub->calldirection == SKINNY_OUTGOING) {
2355                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2356                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2357                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, l->lastnumberdialed);
2358                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2359         } else {
2360                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2361                 return;
2362         }
2363         transmit_callinfo(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection);
2364 }
2365
2366 static void push_callinfo(struct skinny_subline *subline, struct skinny_subchannel *sub)
2367 {
2368         struct ast_channel *ast;
2369         struct skinny_device *d;
2370         struct skinny_line *l;
2371         char *fromname;
2372         char *fromnum;
2373         char *toname;
2374         char *tonum;
2375
2376         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2377                 return;
2378         }
2379         
2380         ast = sub->owner;
2381         l = sub->line;
2382         d = l->device;
2383         
2384         if (sub->calldirection == SKINNY_INCOMING) {
2385                 fromname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2386                 fromnum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, "");
2387                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2388                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2389         } else if (sub->calldirection == SKINNY_OUTGOING) {
2390                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2391                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2392                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, l->lastnumberdialed);
2393                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2394         } else {
2395                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2396                 return;
2397         }
2398         transmit_callinfo(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection);
2399 }
2400
2401 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2402 {
2403         struct skinny_req *req;
2404         struct skinny_line *l = sub->line;
2405         struct ast_format_list fmt;
2406         struct ast_format tmpfmt;
2407
2408         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2409                 return;
2410         ast_best_codec(l->cap, &tmpfmt);
2411         fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
2412
2413         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2414         req->data.openreceivechannel.partyId = htolel(sub->callid);
2415         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2416         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(&fmt.format));
2417         req->data.openreceivechannel.echo = htolel(0);
2418         req->data.openreceivechannel.bitrate = htolel(0);
2419
2420         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",
2421                 d->name, sub->callid, sub->callid, fmt.cur_ms, codec_ast2skinny(&fmt.format), 0, 0);
2422         transmit_response(d, req);
2423 }
2424
2425 static void transmit_start_tone(struct skinny_device *d, int tone, int instance, int reference)
2426 {
2427         struct skinny_req *req;
2428         if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2429                 return;
2430         req->data.starttone.tone = htolel(tone);
2431         req->data.starttone.instance = htolel(instance);
2432         req->data.starttone.reference = htolel(reference);
2433
2434         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting START_TONE_MESSAGE to %s, tone %d, inst %d, ref %d\n",
2435                 d->name, tone, instance, reference);
2436         transmit_response(d, req);
2437 }
2438
2439 static void transmit_stop_tone(struct skinny_device *d, int instance, int reference)
2440 {
2441         struct skinny_req *req;
2442         if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2443                 return;
2444         req->data.stoptone.instance = htolel(instance);
2445         req->data.stoptone.reference = htolel(reference);
2446
2447         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_TONE_MESSAGE to %s, inst %d, ref %d\n",
2448                 d->name, instance, reference);
2449         transmit_response(d, req);
2450 }
2451
2452 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey)
2453 {
2454         struct skinny_req *req;
2455
2456         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2457                 return;
2458
2459         req->data.selectsoftkey.instance = htolel(instance);
2460         req->data.selectsoftkey.reference = htolel(callid);
2461         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2462         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
2463
2464         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SELECT_SOFT_KEYS_MESSAGE to %s, inst %d, callid %d, softkey %d, mask 0xFFFFFFFF\n",
2465                 d->name, instance, callid, softkey);
2466         transmit_response(d, req);
2467 }
2468
2469 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2470 {
2471         struct skinny_req *req;
2472
2473         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2474                 return;
2475
2476         req->data.setlamp.stimulus = htolel(stimulus);
2477         req->data.setlamp.stimulusInstance = htolel(instance);
2478         req->data.setlamp.deviceStimulus = htolel(indication);
2479
2480         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_LAMP_MESSAGE to %s, stim %d, inst %d, ind %d\n",
2481                 d->name, stimulus, instance, indication);
2482         transmit_response(d, req);
2483 }
2484
2485 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2486 {
2487         struct skinny_req *req;
2488
2489         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2490                 return;
2491
2492         req->data.setringer.ringerMode = htolel(mode);
2493         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2494            Note: The phone will always show as ringing on the display.
2495
2496            1: phone will audibly ring over and over
2497            2: phone will audibly ring only once
2498            any other value, will NOT cause the phone to audibly ring
2499         */
2500         req->data.setringer.unknown1 = htolel(1);
2501         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2502            Perhaps a packet capture can shed some light on this. */
2503         req->data.setringer.unknown2 = htolel(1);
2504
2505         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_RINGER_MESSAGE to %s, mode %d, unk1 1, unk2 1\n",
2506                 d->name, mode);
2507         transmit_response(d, req);
2508 }
2509
2510 static void transmit_clear_display_message(struct skinny_device *d, int instance, int reference)
2511 {
2512         struct skinny_req *req;
2513         if (!(req = req_alloc(sizeof(struct clear_display_message), CLEAR_DISPLAY_MESSAGE)))
2514                 return;
2515
2516         //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2517         //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2518         //req->data.clearpromptstatus.lineInstance = instance;
2519         //req->data.clearpromptstatus.callReference = reference;
2520
2521         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_DISPLAY_MESSAGE to %s\n", d->name);
2522         transmit_response(d, req);
2523 }
2524
2525 /* This function is not currently used, but will be (wedhorn)*/
2526 /* static void transmit_display_message(struct skinny_device *d, const char *text, int instance, int reference)
2527 {
2528         struct skinny_req *req;
2529
2530         if (text == 0) {
2531                 ast_verb(1, "Bug, Asked to display empty message\n");
2532                 return;
2533         }
2534
2535         if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2536                 return;
2537
2538         ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2539         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAYTEXT_MESSAGE to %s, text %s\n", d->name, text);
2540         transmit_response(d, req);
2541 } */
2542
2543 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2544 {
2545         struct skinny_req *req;
2546
2547         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2548                 return;
2549
2550         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2551         req->data.displaynotify.displayTimeout = htolel(t);
2552
2553         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_NOTIFY_MESSAGE to %s, text %s\n", d->name, text);
2554         transmit_response(d, req);
2555 }
2556
2557 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
2558 {
2559         struct skinny_req *req;
2560
2561         if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2562                 return;
2563
2564         ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2565         req->data.displaypromptstatus.messageTimeout = htolel(t);
2566         req->data.displaypromptstatus.lineInstance = htolel(instance);
2567         req->data.displaypromptstatus.callReference = htolel(callid);
2568
2569         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE to %s, text %s\n", d->name, text);
2570         transmit_response(d, req);
2571 }
2572
2573 static void transmit_clearpromptmessage(struct skinny_device *d, int instance, int callid)
2574 {
2575         struct skinny_req *req;
2576
2577         if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2578                 return;
2579
2580         req->data.clearpromptstatus.lineInstance = htolel(instance);
2581         req->data.clearpromptstatus.callReference = htolel(callid);
2582
2583         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_PROMPT_MESSAGE to %s, inst %d, callid %d\n",
2584                 d->name, instance, callid);
2585         transmit_response(d, req);
2586 }
2587
2588 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2589 {
2590         struct skinny_req *req;
2591
2592         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2593                 return;
2594
2595         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2596         req->data.dialednumber.lineInstance = htolel(instance);
2597         req->data.dialednumber.callReference = htolel(callid);
2598
2599         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DIALED_NUMBER_MESSAGE to %s, num %s, inst %d, callid %d\n",
2600                 d->name, text, instance, callid);
2601         transmit_response(d, req);
2602 }
2603
2604 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2605 {
2606         struct skinny_req *req;
2607
2608         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2609                 return;
2610
2611         req->data.closereceivechannel.conferenceId = htolel(0);
2612         req->data.closereceivechannel.partyId = htolel(sub->callid);
2613
2614         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLOSE_RECEIVE_CHANNEL_MESSAGE to %s, confid %d, callid %d\n",
2615                 d->name, 0, sub->callid);
2616         transmit_response(d, req);
2617 }
2618
2619 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2620 {
2621         struct skinny_req *req;
2622
2623         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2624                 return;
2625
2626         req->data.stopmedia.conferenceId = htolel(0);
2627         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2628
2629         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_MEDIA_TRANSMISSION_MESSAGE to %s, confid %d, passthrupartyid %d\n",
2630                 d->name, 0, sub->callid);
2631         transmit_response(d, req);
2632 }
2633
2634 static void transmit_startmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub, struct sockaddr_in dest, struct ast_format_list fmt)
2635 {
2636         struct skinny_req *req;
2637
2638         if (d->protocolversion < 17) {
2639                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip4), START_MEDIA_TRANSMISSION_MESSAGE)))
2640                         return;
2641                 req->data.startmedia_ip4.conferenceId = htolel(sub->callid);
2642                 req->data.startmedia_ip4.passThruPartyId = htolel(sub->callid);
2643                 req->data.startmedia_ip4.remoteIp = dest.sin_addr.s_addr;
2644                 req->data.startmedia_ip4.remotePort = htolel(ntohs(dest.sin_port));
2645                 req->data.startmedia_ip4.packetSize = htolel(fmt.cur_ms);
2646                 req->data.startmedia_ip4.payloadType = htolel(codec_ast2skinny(&fmt.format));
2647                 req->data.startmedia_ip4.qualifier.precedence = htolel(127);
2648                 req->data.startmedia_ip4.qualifier.vad = htolel(0);
2649                 req->data.startmedia_ip4.qualifier.packets = htolel(0);
2650                 req->data.startmedia_ip4.qualifier.bitRate = htolel(0);
2651         } else {
2652                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip6), START_MEDIA_TRANSMISSION_MESSAGE)))
2653                         return;
2654                 req->data.startmedia_ip6.conferenceId = htolel(sub->callid);
2655                 req->data.startmedia_ip6.passThruPartyId = htolel(sub->callid);
2656                 memcpy(req->data.startmedia_ip6.remoteIp, &dest.sin_addr.s_addr, sizeof(dest.sin_addr.s_addr));
2657                 req->data.startmedia_ip6.remotePort = htolel(ntohs(dest.sin_port));
2658                 req->data.startmedia_ip6.packetSize = htolel(fmt.cur_ms);
2659                 req->data.startmedia_ip6.payloadType = htolel(codec_ast2skinny(&fmt.format));
2660                 req->data.startmedia_ip6.qualifier.precedence = htolel(127);
2661                 req->data.startmedia_ip6.qualifier.vad = htolel(0);
2662                 req->data.startmedia_ip6.qualifier.packets = htolel(0);
2663                 req->data.startmedia_ip6.qualifier.bitRate = htolel(0);
2664         }
2665
2666         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",
2667                 d->name, sub->callid, sub->callid, ast_inet_ntoa(dest.sin_addr), dest.sin_port, fmt.cur_ms, codec_ast2skinny(&fmt.format));
2668         transmit_response(d, req);
2669 }
2670
2671 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
2672 {
2673         struct skinny_req *req;
2674
2675         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2676                 return;
2677
2678         req->data.activatecallplane.lineInstance = htolel(l->instance);
2679
2680         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting ACTIVATE_CALL_PLANE_MESSAGE to %s, inst %d\n",
2681                 d->name, l->instance);
2682         transmit_response(d, req);
2683 }
2684
2685 static void transmit_callstate(struct skinny_device *d, int buttonInstance, unsigned callid, int state)
2686 {
2687         struct skinny_req *req;
2688
2689         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2690                 return;
2691
2692         req->data.callstate.callState = htolel(state);
2693         req->data.callstate.lineInstance = htolel(buttonInstance);
2694         req->data.callstate.callReference = htolel(callid);
2695
2696         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_STATE_MESSAGE to %s, state %s, inst %d, callid %d\n",
2697                 d->name, callstate2str(state), buttonInstance, callid);
2698         transmit_response(d, req);
2699 }
2700
2701 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
2702 {
2703         struct skinny_req *req;
2704         int anyon = 0;
2705
2706         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
2707                 return;
2708
2709         if (l->cfwdtype & SKINNY_CFWD_ALL) {
2710                 if (!ast_strlen_zero(l->call_forward_all)) {
2711                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
2712                         req->data.forwardstat.fwdall = htolel(1);
2713                         anyon++;
2714                 } else {
2715                         req->data.forwardstat.fwdall = htolel(0);
2716                 }
2717         }
2718         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
2719                 if (!ast_strlen_zero(l->call_forward_busy)) {
2720                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
2721                         req->data.forwardstat.fwdbusy = htolel(1);
2722                         anyon++;
2723                 } else {
2724                         req->data.forwardstat.fwdbusy = htolel(0);
2725                 }
2726         }
2727         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
2728                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
2729                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
2730                         req->data.forwardstat.fwdnoanswer = htolel(1);
2731                         anyon++;
2732                 } else {
2733                         req->data.forwardstat.fwdnoanswer = htolel(0);
2734                 }
2735         }
2736         req->data.forwardstat.lineNumber = htolel(l->instance);
2737         if (anyon)
2738                 req->data.forwardstat.activeforward = htolel(7);
2739         else
2740                 req->data.forwardstat.activeforward = htolel(0);
2741
2742         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting FORWARD_STAT_MESSAGE to %s, inst %d, all %s, busy %s, noans %s, acitve %d\n",
2743                 d->name, l->instance, l->call_forward_all, l->call_forward_busy, l->call_forward_noanswer, anyon ? 7 : 0);
2744         transmit_response(d, req);
2745 }
2746
2747 static void transmit_speeddialstatres(struct skinny_device *d, struct skinny_speeddial *sd)
2748 {
2749         struct skinny_req *req;
2750
2751         if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
2752                 return;
2753
2754         req->data.speeddialreq.speedDialNumber = htolel(sd->instance);
2755         ast_copy_string(req->data.speeddial.speedDialDirNumber, sd->exten, sizeof(req->data.speeddial.speedDialDirNumber));
2756         ast_copy_string(req->data.speeddial.speedDialDisplayName, sd->label, sizeof(req->data.speeddial.speedDialDisplayName));
2757
2758         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SPEED_DIAL_STAT_RES_MESSAGE to %s, inst %d, dir %s, display %s\n",
2759                 d->name, sd->instance, sd->exten, sd->label);
2760         transmit_response(d, req);
2761 }
2762
2763 //static void transmit_linestatres(struct skinny_device *d, struct skinny_line *l)
2764 static void transmit_linestatres(struct skinny_device *d, int instance)
2765 {
2766         struct skinny_req *req;
2767         struct skinny_line *l;
2768         struct skinny_speeddial *sd;
2769
2770         if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
2771                 return;
2772
2773         if ((l = find_line_by_instance(d, instance))) {
2774                 req->data.linestat.lineNumber = letohl(l->instance);
2775                 memcpy(req->data.linestat.lineDirNumber, l->name, sizeof(req->data.linestat.lineDirNumber));
2776                 memcpy(req->data.linestat.lineDisplayName, l->label, sizeof(req->data.linestat.lineDisplayName));
2777         } else if ((sd = find_speeddial_by_instance(d, instance, 1))) {
2778                 req->data.linestat.lineNumber = letohl(sd->instance);
2779                 memcpy(req->data.linestat.lineDirNumber, sd->label, sizeof(req->data.linestat.lineDirNumber));
2780                 memcpy(req->data.linestat.lineDisplayName, sd->label, sizeof(req->data.linestat.lineDisplayName));
2781         }
2782
2783         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting LINE_STAT_RES_MESSAGE to %s, inst %d, num %s, label %s\n",
2784                 d->name, l->instance, req->data.linestat.lineDirNumber, req->data.linestat.lineDisplayName);
2785         transmit_response(d, req);
2786 }
2787
2788 static void transmit_definetimedate(struct skinny_device *d)
2789 {
2790         struct skinny_req *req;
2791         struct timeval now = ast_tvnow();
2792         struct ast_tm cmtime;
2793
2794         if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
2795                 return;
2796
2797         ast_localtime(&now, &cmtime, NULL);
2798         req->data.definetimedate.year = htolel(cmtime.tm_year+1900);
2799         req->data.definetimedate.month = htolel(cmtime.tm_mon+1);
2800         req->data.definetimedate.dayofweek = htolel(cmtime.tm_wday);
2801         req->data.definetimedate.day = htolel(cmtime.tm_mday);
2802         req->data.definetimedate.hour = htolel(cmtime.tm_hour);
2803         req->data.definetimedate.minute = htolel(cmtime.tm_min);
2804         req->data.definetimedate.seconds = htolel(cmtime.tm_sec);
2805         req->data.definetimedate.milliseconds = htolel(cmtime.tm_usec / 1000);
2806         req->data.definetimedate.timestamp = htolel(now.tv_sec);
2807
2808         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DEFINETIMEDATE_MESSAGE to %s, date %d %d %d dow %d time %d:%d:%d.%d\n",
2809                 d->name, req->data.definetimedate.year, req->data.definetimedate.month, req->data.definetimedate.day, req->data.definetimedate.dayofweek,
2810                 req->data.definetimedate.hour, req->data.definetimedate.minute, req->data.definetimedate.seconds, req->data.definetimedate.milliseconds);
2811         transmit_response(d, req);
2812 }
2813
2814 static void transmit_versionres(struct skinny_device *d)
2815 {
2816         struct skinny_req *req;
2817         if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
2818                 return;
2819
2820         ast_copy_string(req->data.version.version, d->version_id, sizeof(req->data.version.version));
2821
2822         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting VERSION_RES_MESSAGE to %s, version %s\n", d->name, d->version_id);
2823         transmit_response(d, req);
2824 }
2825
2826 static void transmit_serverres(struct skinny_device *d)
2827 {
2828         struct skinny_req *req;
2829         if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
2830                 return;
2831
2832         memcpy(req->data.serverres.server[0].serverName, ourhost,
2833                         sizeof(req->data.serverres.server[0].serverName));
2834         req->data.serverres.serverListenPort[0] = htolel(ourport);
2835         req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
2836
2837         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SERVER_RES_MESSAGE to %s, srvname %s %s:%d\n",
2838                 d->name, ourhost, ast_inet_ntoa(d->ourip), ourport);
2839         transmit_response(d, req);
2840 }
2841
2842 static void transmit_softkeysetres(struct skinny_device *d)
2843 {
2844         struct skinny_req *req;
2845         int i;
2846         int x;
2847         int y;
2848         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
2849
2850         if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
2851                 return;
2852
2853         SKINNY_DEBUG(DEBUG_TEMPLATE, 3, "Creating Softkey Template\n");
2854
2855         req->data.softkeysets.softKeySetOffset = htolel(0);
2856         req->data.softkeysets.softKeySetCount = htolel(13);
2857         req->data.softkeysets.totalSoftKeySetCount = htolel(13);
2858         for (x = 0; x < sizeof(soft_key_default_definitions) / sizeof(struct soft_key_definitions); x++) {
2859                 const uint8_t *defaults = softkeymode->defaults;
2860                 /* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
2861                    This will have to do for now. */
2862                 for (y = 0; y < softkeymode->count; y++) {
2863                         for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
2864                                 if (defaults[y] == i+1) {
2865                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = (i+1);
2866                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyInfoIndex[y] = htoles(i+301);
2867                                         SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "softKeySetDefinition : softKeyTemplateIndex: %d softKeyInfoIndex: %d\n",
2868                                                 i+1, i+301);
2869                                 }
2870                         }
2871                 }
2872                 softkeymode++;
2873         }
2874
2875         SKINNY_DEBUG(DEBUG_PACKET | DEBUG_TEMPLATE, 3, "Transmitting SOFT_KEY_SET_RES_MESSAGE to %s, template data\n",
2876                 d->name);
2877         transmit_response(d, req);
2878 }
2879
2880 static void transmit_softkeytemplateres(struct skinny_device *d)
2881 {
2882         struct skinny_req *req;
2883         if (!(req = req_alloc(sizeof(struct soft_key_template_res_message), SOFT_KEY_TEMPLATE_RES_MESSAGE)))
2884                 return;
2885
2886         req->data.softkeytemplate.softKeyOffset = htolel(0);
2887         req->data.softkeytemplate.softKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
2888         req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
2889         memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
2890                 soft_key_template_default,
2891                 sizeof(soft_key_template_default));
2892
2893         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SOFT_KEY_TEMPLATE_RES_MESSAGE to %s, offset 0, keycnt %d, totalkeycnt %d, template data\n",
2894                 d->name, req->data.softkeytemplate.softKeyCount, req->data.softkeytemplate.totalSoftKeyCount);
2895         transmit_response(d, req);
2896 }
2897
2898 static void transmit_reset(struct skinny_device *d, int fullrestart)
2899 {
2900         struct skinny_req *req;
2901   
2902         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
2903                 return;
2904   
2905         if (fullrestart)
2906                 req->data.reset.resetType = 2;
2907         else
2908                 req->data.reset.resetType = 1;
2909
2910         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting RESET_MESSAGE to %s, type %s\n",
2911                 d->name, (fullrestart) ? "Restarting" : "Resetting");
2912         transmit_response(d, req);
2913 }
2914
2915 static void transmit_keepaliveack(struct skinny_device *d)
2916 {
2917         struct skinny_req *req;
2918
2919         if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
2920                 return;
2921
2922         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting KEEP_ALIVE_ACK_MESSAGE to %s\n", d->name);
2923         transmit_response(d, req);
2924 }
2925
2926 static void transmit_registerack(struct skinny_device *d)
2927 {
2928         struct skinny_req *req;
2929
2930         if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
2931                 return;
2932
2933         req->data.regack.res[0] = '0';
2934         req->data.regack.res[1] = '\0';
2935         req->data.regack.keepAlive = htolel(keep_alive);
2936         memcpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate));
2937         req->data.regack.res2[0] = '0';
2938         req->data.regack.res2[1] = '\0';
2939         req->data.regack.secondaryKeepAlive = htolel(keep_alive);
2940
2941 #ifdef AST_DEVMODE
2942         {
2943         short res = req->data.regack.res[0] << 8 | req->data.regack.res[1];
2944         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];
2945         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_ACK_MESSAGE to %s, keepalive %d, datetemplate %s, seckeepalive %d, res 0x%04x, res2 0x%08x\n",
2946                 d->name, keep_alive, date_format, keep_alive, res, res2);
2947         }
2948 #endif
2949
2950         transmit_response(d, req);
2951 }
2952
2953 static void transmit_capabilitiesreq(struct skinny_device *d)
2954 {
2955         struct skinny_req *req;
2956
2957         if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
2958                 return;
2959
2960         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CAPABILITIES_REQ_MESSAGE to %s\n", d->name);
2961         transmit_response(d, req);
2962 }
2963
2964 static int skinny_extensionstate_cb(char *context, char *exten, struct ast_state_cb_info *info, void *data)
2965 {
2966         struct skinny_container *container = data;
2967         struct skinny_device *d = NULL;
2968         char hint[AST_MAX_EXTENSION];
2969         int state = info->exten_state;
2970
2971         /* only interested in device state here */
2972         if (info->reason != AST_HINT_UPDATE_DEVICE) {
2973                 return 0;
2974         }
2975
2976         if (container->type == SKINNY_SDCONTAINER) {
2977                 struct skinny_speeddial *sd = container->data;
2978                 d = sd->parent;
2979
2980                 SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on speeddial %s\n", ast_extension_state2str(state), sd->label);
2981
2982                 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
2983                         /* If they are not registered, we will override notification and show no availability */
2984                         if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
2985                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_FLASH);
2986                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
2987                                 return 0;
2988                         }
2989                         switch (state) {
2990                         case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
2991                         case AST_EXTENSION_REMOVED:     /* Extension is gone */
2992                                 SKINNY_DEBUG(DEBUG_HINT, 3, "Extension state: Watcher for hint %s %s. Notify Device %s\n",
2993                                         exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
2994                                 sd->stateid = -1;
2995                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
2996                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
2997                                 break;
2998                         case AST_EXTENSION_RINGING:
2999                         case AST_EXTENSION_UNAVAILABLE:
3000                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_BLINK);
3001                                 transmit_callstate(d, sd->instance, 0, SKINNY_RINGIN);
3002                                 break;
3003                         case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
3004                         case AST_EXTENSION_INUSE:
3005                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_ON);
3006                                 transmit_callstate(d, sd->instance, 0, SKINNY_CALLREMOTEMULTILINE);
3007                                 break;
3008                         case AST_EXTENSION_ONHOLD:
3009                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_WINK);
3010                                 transmit_callstate(d, sd->instance, 0, SKINNY_HOLD);
3011                                 break;
3012                         case AST_EXTENSION_NOT_INUSE:
3013                         default:
3014                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
3015                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3016                                 break;
3017                         }
3018                 }
3019                 sd->laststate = state;
3020         } else if (container->type == SKINNY_SUBLINECONTAINER) {
3021                 struct skinny_subline *subline = container->data;
3022                 struct skinny_line *l = subline->line;
3023                 d = l->device;
3024
3025                 SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on subline %s (%s@%s)\n", ast_extension_state2str(state), subline->name, exten, context);
3026
3027                 subline->extenstate = state;
3028
3029                 if (subline->callid == 0) {
3030                         return 0;
3031                 }
3032
3033                 switch (state) {
3034                 case AST_EXTENSION_RINGING: /* Handled by normal ringin */
3035                         break;
3036                 case AST_EXTENSION_INUSE:
3037                         if (subline->sub && (subline->sub->substate == SKINNY_CONNECTED)) { /* Device has a real call */
3038                                 transmit_callstate(d, l->instance, subline->callid, SKINNY_CONNECTED);
3039                                 transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_CONNECTED);
3040                                 transmit_displaypromptstatus(d, "Connected", 0, l->instance, subline->callid);
3041                         } else { /* Some other device has active call */
3042                                 transmit_callstate(d, l->instance, subline->callid, SKINNY_CALLREMOTEMULTILINE);
3043                                 transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLACONNECTEDNOTACTIVE);
3044                                 transmit_displaypromptstatus(d, "In Use", 0, l->instance, subline->callid);
3045                         }
3046                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3047                         transmit_ringer_mode(d, SKINNY_RING_OFF);
3048                         transmit_activatecallplane(d, l);
3049                         break;
3050                 case AST_EXTENSION_ONHOLD:
3051                         transmit_callstate(d, l->instance, subline->callid, SKINNY_HOLD);
3052                         transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLAHOLD);
3053                         transmit_displaypromptstatus(d, "Hold", 0, l->instance, subline->callid);
3054                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3055                         transmit_activatecallplane(d, l);
3056                         break;
3057                 case AST_EXTENSION_NOT_INUSE:
3058                         transmit_callstate(d, l->instance, subline->callid, SKINNY_ONHOOK);
3059                         transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_ONHOOK);
3060                         transmit_clearpromptmessage(d, l->instance, subline->callid);
3061                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
3062                         transmit_activatecallplane(d, l);
3063                         subline->callid = 0;
3064                         break;
3065                 default:
3066                         ast_log(LOG_WARNING, "AST_EXTENSION_STATE %s not configured\n", ast_extension_state2str(state));
3067                 }
3068         } else {
3069                 ast_log(LOG_WARNING, "Invalid data supplied to skinny_extensionstate_cb\n");
3070         }
3071
3072         return 0;
3073 }
3074
3075 static void update_connectedline(struct skinny_subchannel *sub, const void *data, size_t datalen)
3076 {
3077         struct ast_channel *c = sub->owner;
3078         struct skinny_line *l = sub->line;
3079         struct skinny_device *d = l->device;
3080
3081         if (!d->session) {
3082                 return;
3083         }
3084
3085         if (!ast_channel_caller(c)->id.number.valid
3086                 || ast_strlen_zero(ast_channel_caller(c)->id.number.str)
3087                 || !ast_channel_connected(c)->id.number.valid
3088                 || ast_strlen_zero(ast_channel_connected(c)->id.number.str))
3089                 return;
3090
3091         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Updating\n", sub->callid);
3092
3093         send_callinfo(sub);
3094         if (ast_channel_state(sub->owner) == AST_STATE_UP) {
3095                 transmit_callstate(d, l->instance, sub->callid, SKINNY_CONNECTED);
3096                 transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
3097         } else {
3098                 if (sub->calldirection == SKINNY_INCOMING) {
3099                         transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGIN);
3100                         transmit_displaypromptstatus(d, "Ring-In", 0, l->instance, sub->callid);
3101                 } else {
3102                         if (!sub->ringing) {
3103                                 transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGOUT);
3104                                 transmit_displaypromptstatus(d, "Ring-Out", 0, l->instance, sub->callid);
3105                                 sub->ringing = 1;
3106                         } else {
3107                                 transmit_callstate(d, l->instance, sub->callid, SKINNY_PROGRESS);
3108                                 transmit_displaypromptstatus(d, "Call Progress", 0, l->instance, sub->callid);
3109                                 sub->progress = 1;
3110                         }
3111                 }
3112         }
3113 }
3114
3115 static void mwi_event_cb(const struct ast_event *event, void *userdata)
3116 {
3117         struct skinny_line *l = userdata;
3118         struct skinny_device *d = l->device;
3119         struct skinny_line *l2;
3120         int dev_msgs = 0;
3121         
3122         if (!d || !d->session) {
3123                 return;
3124         }
3125
3126         if (event) {
3127                 l->newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
3128         }
3129
3130         if (l->newmsgs) {
3131                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
3132         } else {
3133                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
3134         }
3135
3136         /* find out wether the device lamp should be on or off */
3137         AST_LIST_TRAVERSE(&d->lines, l2, list) {
3138                 if (l2->newmsgs) {
3139                         dev_msgs++;
3140                 }
3141         }
3142
3143         if (dev_msgs) {
3144                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
3145         } else {
3146                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
3147         }
3148         ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", l->newmsgs);
3149 }
3150
3151 /* I do not believe skinny can deal with video.
3152    Anyone know differently? */
3153 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
3154 static enum ast_rtp_glue_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
3155 {
3156         struct skinny_subchannel *sub = NULL;
3157
3158         if (!(sub = ast_channel_tech_pvt(c)) || !(sub->vrtp))
3159                 return AST_RTP_GLUE_RESULT_FORBID;
3160
3161         ao2_ref(sub->vrtp, +1);
3162         *instance = sub->vrtp;
3163
3164         return AST_RTP_GLUE_RESULT_REMOTE;
3165 }
3166
3167 static enum ast_rtp_glue_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
3168 {
3169         struct skinny_subchannel *sub = NULL;
3170         struct skinny_line *l;
3171         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE;
3172
3173         SKINNY_DEBUG(DEBUG_AUDIO, 4, "skinny_get_rtp_peer() Channel = %s\n", ast_channel_name(c));
3174
3175         if (!(sub = ast_channel_tech_pvt(c)))
3176                 return AST_RTP_GLUE_RESULT_FORBID;
3177
3178         ast_mutex_lock(&sub->lock);
3179
3180         if (!(sub->rtp)){
3181                 ast_mutex_unlock(&sub->lock);
3182                 return AST_RTP_GLUE_RESULT_FORBID;
3183         }
3184
3185         ao2_ref(sub->rtp, +1);
3186         *instance = sub->rtp;
3187
3188         l = sub->line;
3189
3190         if (!l->directmedia || l->nat){
3191                 res = AST_RTP_GLUE_RESULT_LOCAL;
3192                 SKINNY_DEBUG(DEBUG_AUDIO, 4, "skinny_get_rtp_peer() Using AST_RTP_GLUE_RESULT_LOCAL \n");
3193         }
3194
3195         ast_mutex_unlock(&sub->lock);
3196
3197         return res;
3198
3199 }
3200
3201 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)
3202 {
3203         struct skinny_subchannel *sub;
3204         struct skinny_line *l;
3205         struct skinny_device *d;
3206         struct ast_format_list fmt;
3207         struct sockaddr_in us = { 0, };
3208         struct sockaddr_in them = { 0, };
3209         struct ast_sockaddr them_tmp;
3210         struct ast_sockaddr us_tmp;
3211         
3212         sub = ast_channel_tech_pvt(c);
3213
3214         if (ast_channel_state(c) != AST_STATE_UP)
3215                 return 0;
3216
3217         if (!sub) {
3218                 return -1;
3219         }
3220
3221         l = sub->line;
3222         d = l->device;
3223
3224         if (rtp){
3225                 struct ast_format tmpfmt;
3226                 ast_rtp_instance_get_remote_address(rtp, &them_tmp);
3227                 ast_sockaddr_to_sin(&them_tmp, &them);
3228
3229                 /* Shutdown any early-media or previous media on re-invite */
3230                 transmit_stopmediatransmission(d, sub);
3231
3232                 SKINNY_DEBUG(DEBUG_AUDIO, 4, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
3233
3234                 ast_best_codec(l->cap, &tmpfmt);
3235                 fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
3236
3237                 SKINNY_DEBUG(DEBUG_AUDIO, 4, "Setting payloadType to '%s' (%d ms)\n", ast_getformatname(&fmt.format), fmt.cur_ms);
3238
3239                 if (!(l->directmedia) || (l->nat)){
3240                         ast_rtp_instance_get_local_address(rtp, &us_tmp);
3241                         ast_sockaddr_to_sin(&us_tmp, &us);
3242                         us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->ourip.s_addr;
3243                         transmit_startmediatransmission(d, sub, us, fmt);
3244                 } else {
3245                         transmit_startmediatransmission(d, sub, them, fmt);
3246                 }
3247
3248                 return 0;
3249         }
3250         /* Need a return here to break the bridge */
3251         return 0;
3252 }
3253
3254 static struct ast_rtp_glue skinny_rtp_glue = {
3255         .type = "Skinny",
3256         .get_rtp_info = skinny_get_rtp_peer,
3257         .get_vrtp_info = skinny_get_vrtp_peer,
3258         .update_peer = skinny_set_rtp_peer,
3259 };
3260
3261 #ifdef AST_DEVMODE
3262 static char *skinny_debugs(void)
3263 {
3264         char *ptr;
3265         int posn = 0;
3266
3267         ptr = dbgcli_buf;
3268         strncpy(ptr, "\0", 1);
3269         if (skinnydebug & DEBUG_GENERAL) {
3270                 strncpy(ptr, "general ", 8);
3271                 posn += 8;
3272                 ptr += 8;
3273         }
3274         if (skinnydebug & DEBUG_SUB) {
3275                 strncpy(ptr, "sub ", 4);
3276                 posn += 4;
3277                 ptr += 4;
3278         }
3279         if (skinnydebug & DEBUG_AUDIO) {
3280                 strncpy(ptr, "audio ", 6);
3281                 posn += 6;
3282                 ptr += 6;
3283         }
3284         if (skinnydebug & DEBUG_PACKET) {
3285                 strncpy(ptr, "packet ", 7);
3286                 posn += 7;
3287                 ptr += 7;
3288         }
3289         if (skinnydebug & DEBUG_LOCK) {
3290                 strncpy(ptr, "lock ", 5);
3291                 posn += 5;
3292                 ptr += 5;
3293         }
3294         if (skinnydebug & DEBUG_TEMPLATE) {
3295                 strncpy(ptr, "template ", 9);
3296                 posn += 9;
3297                 ptr += 9;
3298         }
3299         if (skinnydebug & DEBUG_THREAD) {
3300                 strncpy(ptr, "thread ", 7);
3301