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