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