Skinny blob cleanup
[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         struct ast_namedgroups *named_callgroups;       \
1329         struct ast_namedgroups *named_pickupgroups;     \
1330         int callwaiting;                                \
1331         int transfer;                                   \
1332         int threewaycalling;                            \
1333         int mwiblink;                                   \
1334         int cancallforward;                             \
1335         int getforward;                                 \
1336         int dnd;                                        \
1337         int hidecallerid;                               \
1338         int amaflags;                                   \
1339         int instance;                                   \
1340         int group;                                      \
1341         struct ast_codec_pref confprefs;                \
1342         struct ast_codec_pref prefs;                    \
1343         int nonCodecCapability;                         \
1344         int immediate;                                  \
1345         int nat;                                        \
1346         int directmedia;                                \
1347         int prune;
1348
1349 struct skinny_line {
1350         SKINNY_LINE_OPTIONS
1351         ast_mutex_t lock;
1352         struct skinny_container *container;
1353         struct ast_event_sub *mwi_event_sub; /* Event based MWI */
1354         struct skinny_subchannel *activesub;
1355         AST_LIST_HEAD(, skinny_subchannel) sub;
1356         AST_LIST_HEAD(, skinny_subline) sublines;
1357         AST_LIST_ENTRY(skinny_line) list;
1358         AST_LIST_ENTRY(skinny_line) all;
1359         struct skinny_device *device;
1360         struct ast_format_cap *cap;
1361         struct ast_format_cap *confcap;
1362         struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1363         int newmsgs;
1364 };
1365
1366 static struct skinny_line_options{
1367         SKINNY_LINE_OPTIONS
1368 } default_line_struct = {
1369         .callwaiting = 1,
1370         .transfer = 1,
1371         .mwiblink = 0,
1372         .dnd = 0,
1373         .hidecallerid = 0,
1374         .amaflags = 0,
1375         .instance = 0,
1376         .directmedia = 0,
1377         .nat = 0,
1378         .getforward = 0,
1379         .prune = 0,
1380 };
1381 static struct skinny_line_options *default_line = &default_line_struct;
1382
1383 static AST_LIST_HEAD_STATIC(lines, skinny_line);
1384
1385 struct skinny_subline {
1386         struct skinny_container *container;
1387         struct skinny_line *line;
1388         struct skinny_subchannel *sub;
1389         AST_LIST_ENTRY(skinny_subline) list;
1390         char name[80];
1391         char context[AST_MAX_CONTEXT];
1392         char exten[AST_MAX_EXTENSION];
1393         char stname[AST_MAX_EXTENSION];
1394         char lnname[AST_MAX_EXTENSION];
1395         char ourName[40];
1396         char ourNum[24];
1397         char theirName[40];
1398         char theirNum[24];
1399         int calldirection;
1400         int substate;
1401         int extenstate;
1402         unsigned int callid;
1403 };
1404
1405 struct skinny_speeddial {
1406         ast_mutex_t lock;
1407         struct skinny_container *container;
1408         char label[42];
1409         char context[AST_MAX_CONTEXT];
1410         char exten[AST_MAX_EXTENSION];
1411         int instance;
1412         int stateid;
1413         int laststate;
1414         int isHint;
1415
1416         AST_LIST_ENTRY(skinny_speeddial) list;
1417         struct skinny_device *parent;
1418 };
1419
1420 #define SKINNY_DEVICECONTAINER 1
1421 #define SKINNY_LINECONTAINER 2
1422 #define SKINNY_SUBLINECONTAINER 3
1423 #define SKINNY_SDCONTAINER 4
1424
1425 struct skinny_container {
1426         int type;
1427         void *data;
1428 };
1429
1430 struct skinny_addon {
1431         ast_mutex_t lock;
1432         char type[10];
1433         AST_LIST_ENTRY(skinny_addon) list;
1434         struct skinny_device *parent;
1435 };
1436
1437 #define SKINNY_DEVICE_OPTIONS                                   \
1438         char name[80];                                          \
1439         char id[16];                                            \
1440         char version_id[16];                                    \
1441         char vmexten[AST_MAX_EXTENSION];                        \
1442         int type;                                               \
1443         int protocolversion;                            \
1444         int hookstate;                                  \
1445         int lastlineinstance;                                   \
1446         int lastcallreference;                                  \
1447         struct ast_codec_pref confprefs;                        \
1448         int earlyrtp;                                           \
1449         int transfer;                                           \
1450         int callwaiting;                                        \
1451         int mwiblink;                                           \
1452         int dnd;                                                \
1453         int prune;
1454
1455 struct skinny_device {
1456         SKINNY_DEVICE_OPTIONS
1457         struct type *first;
1458         struct type *last;
1459         ast_mutex_t lock;
1460         struct sockaddr_in addr;
1461         struct in_addr ourip;
1462         struct ast_ha *ha;
1463         struct skinnysession *session;
1464         struct skinny_line *activeline;
1465         struct ast_format_cap *cap;
1466         struct ast_format_cap *confcap;
1467         AST_LIST_HEAD(, skinny_line) lines;
1468         AST_LIST_HEAD(, skinny_speeddial) speeddials;
1469         AST_LIST_HEAD(, skinny_addon) addons;
1470         AST_LIST_ENTRY(skinny_device) list;
1471 };
1472
1473 static struct skinny_device_options {
1474         SKINNY_DEVICE_OPTIONS
1475 } default_device_struct = {
1476         .transfer = 1,
1477         .earlyrtp = 1,
1478         .callwaiting = 1,
1479         .mwiblink = 0,
1480         .dnd = 0,
1481         .prune = 0,
1482         .hookstate = SKINNY_ONHOOK,
1483 };
1484 static struct skinny_device_options *default_device = &default_device_struct;
1485
1486 static AST_LIST_HEAD_STATIC(devices, skinny_device);
1487
1488 struct skinnysession {
1489         pthread_t t;
1490         ast_mutex_t lock;
1491         time_t start;
1492         struct sockaddr_in sin;
1493         int fd;
1494         char inbuf[SKINNY_MAX_PACKET];
1495         char outbuf[SKINNY_MAX_PACKET];
1496         struct skinny_device *device;
1497         AST_LIST_ENTRY(skinnysession) list;
1498 };
1499
1500 static struct ast_channel *skinny_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
1501 static AST_LIST_HEAD_STATIC(sessions, skinnysession);
1502
1503 static int skinny_devicestate(const char *data);
1504 static int skinny_call(struct ast_channel *ast, const char *dest, int timeout);
1505 static int skinny_hangup(struct ast_channel *ast);
1506 static int skinny_answer(struct ast_channel *ast);
1507 static struct ast_frame *skinny_read(struct ast_channel *ast);
1508 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1509 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1510 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1511 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1512 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1513 static void mwi_event_cb(const struct ast_event *event, void *userdata);
1514 static int skinny_dialer_cb(const void *data);
1515 static int skinny_reload(void);
1516
1517 static void setsubstate(struct skinny_subchannel *sub, int state);
1518 static void dumpsub(struct skinny_subchannel *sub, int forcehangup);
1519 static void activatesub(struct skinny_subchannel *sub, int state);
1520 static void dialandactivatesub(struct skinny_subchannel *sub, char exten[AST_MAX_EXTENSION]);
1521
1522 static struct ast_channel_tech skinny_tech = {
1523         .type = "Skinny",
1524         .description = tdesc,
1525         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1526         .requester = skinny_request,
1527         .devicestate = skinny_devicestate,
1528         .call = skinny_call,
1529         .hangup = skinny_hangup,
1530         .answer = skinny_answer,
1531         .read = skinny_read,
1532         .write = skinny_write,
1533         .indicate = skinny_indicate,
1534         .fixup = skinny_fixup,
1535         .send_digit_begin = skinny_senddigit_begin,
1536         .send_digit_end = skinny_senddigit_end,
1537         .bridge = ast_rtp_instance_bridge,
1538 };
1539
1540 static int skinny_extensionstate_cb(char *context, char *id, struct ast_state_cb_info *info, void *data);
1541 static int skinny_transfer(struct skinny_subchannel *sub);
1542
1543 static struct skinny_line *skinny_line_alloc(void)
1544 {
1545         struct skinny_line *l;
1546         if (!(l = ast_calloc(1, sizeof(*l)))) {
1547                 return NULL;
1548         }
1549
1550         l->cap = ast_format_cap_alloc_nolock();
1551         l->confcap = ast_format_cap_alloc_nolock();
1552         if (!l->cap || !l->confcap) {
1553                 l->cap = ast_format_cap_destroy(l->cap);
1554                 l->confcap = ast_format_cap_destroy(l->confcap);
1555                 ast_free(l);
1556                 return NULL;
1557         }
1558         return l;
1559 }
1560 static struct skinny_line *skinny_line_destroy(struct skinny_line *l)
1561 {
1562         l->cap = ast_format_cap_destroy(l->cap);
1563         l->confcap = ast_format_cap_destroy(l->confcap);
1564         l->named_callgroups = ast_unref_namedgroups(l->named_callgroups);
1565         l->named_pickupgroups = ast_unref_namedgroups(l->named_pickupgroups);
1566         ast_free(l->container);
1567         ast_free(l);
1568         return NULL;
1569 }
1570 static struct skinny_device *skinny_device_alloc(void)
1571 {
1572         struct skinny_device *d;
1573         if (!(d = ast_calloc(1, sizeof(*d)))) {
1574                 return NULL;
1575         }
1576
1577         d->cap = ast_format_cap_alloc_nolock();
1578         d->confcap = ast_format_cap_alloc_nolock();
1579         if (!d->cap || !d->confcap) {
1580                 d->cap = ast_format_cap_destroy(d->cap);
1581                 d->confcap = ast_format_cap_destroy(d->confcap);
1582                 ast_free(d);
1583                 return NULL;
1584         }
1585         return d;
1586 }
1587 static struct skinny_device *skinny_device_destroy(struct skinny_device *d)
1588 {
1589         d->cap = ast_format_cap_destroy(d->cap);
1590         d->confcap = ast_format_cap_destroy(d->confcap);
1591         ast_free(d);
1592         return NULL;
1593 }
1594
1595 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1596 {
1597         struct skinny_device *d = s->device;
1598         struct skinny_addon *a;
1599         int i;
1600
1601         switch (d->type) {
1602                 case SKINNY_DEVICE_30SPPLUS:
1603                 case SKINNY_DEVICE_30VIP:
1604                         /* 13 rows, 2 columns */
1605                         for (i = 0; i < 4; i++)
1606                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1607                         (btn++)->buttonDefinition = BT_REDIAL;
1608                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1609                         (btn++)->buttonDefinition = BT_CALLPARK;
1610                         (btn++)->buttonDefinition = BT_FORWARDALL;
1611                         (btn++)->buttonDefinition = BT_CONFERENCE;
1612                         for (i = 0; i < 4; i++)
1613                                 (btn++)->buttonDefinition = BT_NONE;
1614                         for (i = 0; i < 13; i++)
1615                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1616
1617                         break;
1618                 case SKINNY_DEVICE_12SPPLUS:
1619                 case SKINNY_DEVICE_12SP:
1620                 case SKINNY_DEVICE_12:
1621                         /* 6 rows, 2 columns */
1622                         for (i = 0; i < 2; i++)
1623                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1624                         for (i = 0; i < 4; i++)
1625                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1626                         (btn++)->buttonDefinition = BT_HOLD;
1627                         (btn++)->buttonDefinition = BT_REDIAL;
1628                         (btn++)->buttonDefinition = BT_TRANSFER;
1629                         (btn++)->buttonDefinition = BT_FORWARDALL;
1630                         (btn++)->buttonDefinition = BT_CALLPARK;
1631                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1632                         break;
1633                 case SKINNY_DEVICE_7910:
1634                         (btn++)->buttonDefinition = BT_LINE;
1635                         (btn++)->buttonDefinition = BT_HOLD;
1636                         (btn++)->buttonDefinition = BT_TRANSFER;
1637                         (btn++)->buttonDefinition = BT_DISPLAY;
1638                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1639                         (btn++)->buttonDefinition = BT_CONFERENCE;
1640                         (btn++)->buttonDefinition = BT_FORWARDALL;
1641                         for (i = 0; i < 2; i++)
1642                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1643                         (btn++)->buttonDefinition = BT_REDIAL;
1644                         break;
1645                 case SKINNY_DEVICE_7960:
1646                 case SKINNY_DEVICE_7961:
1647                 case SKINNY_DEVICE_7961GE:
1648                 case SKINNY_DEVICE_7962:
1649                 case SKINNY_DEVICE_7965:
1650                         for (i = 0; i < 6; i++)
1651                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1652                         break;
1653                 case SKINNY_DEVICE_7940:
1654                 case SKINNY_DEVICE_7941:
1655                 case SKINNY_DEVICE_7941GE:
1656                 case SKINNY_DEVICE_7942:
1657                 case SKINNY_DEVICE_7945:
1658                         for (i = 0; i < 2; i++)
1659                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1660                         break;
1661                 case SKINNY_DEVICE_7935:
1662                 case SKINNY_DEVICE_7936:
1663                         for (i = 0; i < 2; i++)
1664                                 (btn++)->buttonDefinition = BT_LINE;
1665                         break;
1666                 case SKINNY_DEVICE_ATA186:
1667                         (btn++)->buttonDefinition = BT_LINE;
1668                         break;
1669                 case SKINNY_DEVICE_7970:
1670                 case SKINNY_DEVICE_7971:
1671                 case SKINNY_DEVICE_7975:
1672                 case SKINNY_DEVICE_CIPC:
1673                         for (i = 0; i < 8; i++)
1674                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1675                         break;
1676                 case SKINNY_DEVICE_7985:
1677                         /* XXX I have no idea what the buttons look like on these. */
1678                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1679                         break;
1680                 case SKINNY_DEVICE_7912:
1681                 case SKINNY_DEVICE_7911:
1682                 case SKINNY_DEVICE_7905:
1683                         (btn++)->buttonDefinition = BT_LINE;
1684                         (btn++)->buttonDefinition = BT_HOLD;
1685                         break;
1686                 case SKINNY_DEVICE_7920:
1687                         /* XXX I don't know if this is right. */
1688                         for (i = 0; i < 4; i++)
1689                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1690                         break;
1691                 case SKINNY_DEVICE_7921:
1692                         for (i = 0; i < 6; i++)
1693                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1694                         break;
1695                 case SKINNY_DEVICE_7902:
1696                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1697                         break;
1698                 case SKINNY_DEVICE_7906:
1699                         ast_log(LOG_WARNING, "Unsupported device type '%d (7906)' found.\n", d->type);
1700                         break;
1701                 case SKINNY_DEVICE_7931:
1702                         ast_log(LOG_WARNING, "Unsupported device type '%d (7931)' found.\n", d->type);
1703                         break;
1704                 case SKINNY_DEVICE_7937:
1705                         ast_log(LOG_WARNING, "Unsupported device type '%d (7937)' found.\n", d->type);
1706                         break;
1707                 case SKINNY_DEVICE_7914:
1708                         ast_log(LOG_WARNING, "Unsupported device type '%d (7914)' found.  Expansion module registered by itself?\n", d->type);
1709                         break;
1710                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1711                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1712                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1713                         break;
1714                 default:
1715                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1716                         break;
1717         }
1718
1719         AST_LIST_LOCK(&d->addons);
1720         AST_LIST_TRAVERSE(&d->addons, a, list) {
1721                 if (!strcasecmp(a->type, "7914")) {
1722                         for (i = 0; i < 14; i++)
1723                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1724                 } else {
1725                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1726                 }
1727         }
1728         AST_LIST_UNLOCK(&d->addons);
1729
1730         return btn;
1731 }
1732
1733 static struct skinny_req *req_alloc(size_t size, int response_message)
1734 {
1735         struct skinny_req *req;
1736
1737         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1738                 return NULL;
1739
1740         req->len = htolel(size+4);
1741         req->e = htolel(response_message);
1742
1743         return req;
1744 }
1745
1746 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1747 {
1748         struct skinny_line *l;
1749
1750         /*Dialing from on hook or on a 7920 uses instance 0 in requests
1751           but we need to start looking at instance 1 */
1752
1753         if (!instance)
1754                 instance = 1;
1755
1756         AST_LIST_TRAVERSE(&d->lines, l, list){
1757                 if (l->instance == instance)
1758                         break;
1759         }
1760
1761         if (!l) {
1762                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1763         }
1764         return l;
1765 }
1766
1767 static struct skinny_line *find_line_by_name(const char *dest)
1768 {
1769         struct skinny_line *l;
1770         struct skinny_line *tmpl = NULL;
1771         struct skinny_device *d;
1772         char line[256];
1773         char *at;
1774         char *device;
1775         int checkdevice = 0;
1776
1777         ast_copy_string(line, dest, sizeof(line));
1778         at = strchr(line, '@');
1779         if (at)
1780                 *at++ = '\0';
1781         device = at;
1782
1783         if (!ast_strlen_zero(device))
1784                 checkdevice = 1;
1785
1786         AST_LIST_LOCK(&devices);
1787         AST_LIST_TRAVERSE(&devices, d, list){
1788                 if (checkdevice && tmpl)
1789                         break;
1790                 else if (!checkdevice) {
1791                         /* This is a match, since we're checking for line on every device. */
1792                 } else if (!strcasecmp(d->name, device)) {
1793                 } else
1794                         continue;
1795
1796                 /* Found the device (or we don't care which device) */
1797                 AST_LIST_TRAVERSE(&d->lines, l, list){
1798                         /* Search for the right line */
1799                         if (!strcasecmp(l->name, line)) {
1800                                 if (tmpl) {
1801                                         ast_log(LOG_WARNING, "Ambiguous line name: %s\n", line);
1802                                         AST_LIST_UNLOCK(&devices);
1803                                         return NULL;
1804                                 } else
1805                                         tmpl = l;
1806                         }
1807                 }
1808         }
1809         AST_LIST_UNLOCK(&devices);
1810         return tmpl;
1811 }
1812
1813 static struct skinny_subline *find_subline_by_name(const char *dest)
1814 {
1815         struct skinny_line *l;
1816         struct skinny_subline *subline;
1817         struct skinny_subline *tmpsubline = NULL;
1818         struct skinny_device *d;
1819
1820         AST_LIST_LOCK(&devices);
1821         AST_LIST_TRAVERSE(&devices, d, list){
1822                 AST_LIST_TRAVERSE(&d->lines, l, list){
1823                         AST_LIST_TRAVERSE(&l->sublines, subline, list){
1824                                 if (!strcasecmp(subline->name, dest)) {
1825                                         if (tmpsubline) {
1826                                                 ast_verb(2, "Ambiguous subline name: %s\n", dest);
1827                                                 AST_LIST_UNLOCK(&devices);
1828                                                 return NULL;
1829                                         } else
1830                                                 tmpsubline = subline;
1831                                 }
1832                         }
1833                 }
1834         }
1835         AST_LIST_UNLOCK(&devices);
1836         return tmpsubline;
1837 }
1838
1839 static struct skinny_subline *find_subline_by_callid(struct skinny_device *d, int callid)
1840 {
1841         struct skinny_subline *subline;
1842         struct skinny_line *l;
1843
1844         AST_LIST_TRAVERSE(&d->lines, l, list){
1845                 AST_LIST_TRAVERSE(&l->sublines, subline, list){
1846                         if (subline->callid == callid) {
1847                                 return subline;
1848                         }
1849                 }
1850         }
1851         return NULL;
1852 }
1853
1854 /*!
1855  * implement the setvar config line
1856  */
1857 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
1858 {
1859         struct ast_variable *tmpvar = NULL;
1860         char *varname = ast_strdupa(buf), *varval = NULL;
1861
1862         if ((varval = strchr(varname,'='))) {
1863                 *varval++ = '\0';
1864                 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
1865                         tmpvar->next = list;
1866                         list = tmpvar;
1867                 }
1868         }
1869         return list;
1870 }
1871
1872 static int skinny_sched_del(int sched_id, struct skinny_subchannel *sub)
1873 {
1874         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Deleting SCHED %d\n",
1875                 sub->callid, sched_id);
1876         return ast_sched_del(sched, sched_id);
1877 }
1878
1879 static int skinny_sched_add(int when, ast_sched_cb callback, struct skinny_subchannel *sub)
1880 {
1881         int ret;
1882         ret = ast_sched_add(sched, when, callback, sub);
1883         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Added SCHED %d\n",
1884                 sub->callid, ret);
1885         return ret;
1886 }
1887
1888 /* It's quicker/easier to find the subchannel when we know the instance number too */
1889 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
1890 {
1891         struct skinny_line *l = find_line_by_instance(d, instance);
1892         struct skinny_subchannel *sub;
1893
1894         if (!l) {
1895                 return NULL;
1896         }
1897
1898         /* 7920 phones set call reference to 0, so use the first
1899            sub-channel on the list.
1900            This MIGHT need more love to be right */
1901         if (!reference)
1902                 sub = AST_LIST_FIRST(&l->sub);
1903         else {
1904                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
1905                         if (sub->callid == reference)
1906                                 break;
1907                 }
1908         }
1909         if (!sub) {
1910                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
1911         }
1912         return sub;
1913 }
1914
1915 /* Find the subchannel when we only have the callid - this shouldn't happen often */
1916 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
1917 {
1918         struct skinny_line *l;
1919         struct skinny_subchannel *sub = NULL;
1920
1921         AST_LIST_TRAVERSE(&d->lines, l, list){
1922                 AST_LIST_TRAVERSE(&l->sub, sub, list){
1923                         if (sub->callid == reference)
1924                                 break;
1925                 }
1926                 if (sub)
1927                         break;
1928         }
1929
1930         if (!l) {
1931                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
1932         } else {
1933                 if (!sub) {
1934                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
1935                 }
1936         }
1937         return sub;
1938 }
1939
1940 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
1941 {
1942         struct skinny_speeddial *sd;
1943
1944         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1945                 if (sd->isHint == isHint && sd->instance == instance)
1946                         break;
1947         }
1948
1949         if (!sd) {
1950                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
1951         }
1952         return sd;
1953 }
1954
1955 static struct ast_format *codec_skinny2ast(enum skinny_codecs skinnycodec, struct ast_format *result)
1956 {
1957         switch (skinnycodec) {
1958         case SKINNY_CODEC_ALAW:
1959                 return ast_format_set(result, AST_FORMAT_ALAW, 0);
1960         case SKINNY_CODEC_ULAW:
1961                 return ast_format_set(result, AST_FORMAT_ULAW, 0);
1962         case SKINNY_CODEC_G722:
1963                 return ast_format_set(result, AST_FORMAT_G722, 0);
1964         case SKINNY_CODEC_G723_1:
1965                 return ast_format_set(result, AST_FORMAT_G723_1, 0);
1966         case SKINNY_CODEC_G729A:
1967                 return ast_format_set(result, AST_FORMAT_G729A, 0);
1968         case SKINNY_CODEC_G726_32:
1969                 return ast_format_set(result, AST_FORMAT_G726_AAL2, 0); /* XXX Is this right? */
1970         case SKINNY_CODEC_H261:
1971                 return ast_format_set(result, AST_FORMAT_H261, 0);
1972         case SKINNY_CODEC_H263:
1973                 return ast_format_set(result, AST_FORMAT_H263 ,0);
1974         default:
1975                 ast_format_clear(result);
1976                 return result;
1977         }
1978 }
1979
1980 static int codec_ast2skinny(const struct ast_format *astcodec)
1981 {
1982         switch (astcodec->id) {
1983         case AST_FORMAT_ALAW:
1984                 return SKINNY_CODEC_ALAW;
1985         case AST_FORMAT_ULAW:
1986                 return SKINNY_CODEC_ULAW;
1987         case AST_FORMAT_G722:
1988                 return SKINNY_CODEC_G722;
1989         case AST_FORMAT_G723_1:
1990                 return SKINNY_CODEC_G723_1;
1991         case AST_FORMAT_G729A:
1992                 return SKINNY_CODEC_G729A;
1993         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
1994                 return SKINNY_CODEC_G726_32;
1995         case AST_FORMAT_H261:
1996                 return SKINNY_CODEC_H261;
1997         case AST_FORMAT_H263:
1998                 return SKINNY_CODEC_H263;
1999         default:
2000                 return 0;
2001         }
2002 }
2003
2004 static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
2005 {
2006         if (!l)
2007                 return 0;
2008
2009         if (!ast_strlen_zero(cfwd)) {
2010                 if (cfwdtype & SKINNY_CFWD_ALL) {
2011                         l->cfwdtype |= SKINNY_CFWD_ALL;
2012                         ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
2013                 }
2014                 if (cfwdtype & SKINNY_CFWD_BUSY) {
2015                         l->cfwdtype |= SKINNY_CFWD_BUSY;
2016                         ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
2017                 }
2018                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2019                         l->cfwdtype |= SKINNY_CFWD_NOANSWER;
2020                         ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
2021                 }
2022         } else {
2023                 if (cfwdtype & SKINNY_CFWD_ALL) {
2024                         l->cfwdtype &= ~SKINNY_CFWD_ALL;
2025                         memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
2026                 }
2027                 if (cfwdtype & SKINNY_CFWD_BUSY) {
2028                         l->cfwdtype &= ~SKINNY_CFWD_BUSY;
2029                         memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
2030                 }
2031                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
2032                         l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
2033                         memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
2034                 }
2035         }
2036         return l->cfwdtype;
2037 }
2038
2039 static void cleanup_stale_contexts(char *new, char *old)
2040 {
2041         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
2042
2043         while ((oldcontext = strsep(&old, "&"))) {
2044                 stalecontext = '\0';
2045                 ast_copy_string(newlist, new, sizeof(newlist));
2046                 stringp = newlist;
2047                 while ((newcontext = strsep(&stringp, "&"))) {
2048                         if (strcmp(newcontext, oldcontext) == 0) {
2049                                 /* This is not the context you're looking for */
2050                                 stalecontext = '\0';
2051                                 break;
2052                         } else if (strcmp(newcontext, oldcontext)) {
2053                                 stalecontext = oldcontext;
2054                         }
2055
2056                 }
2057                 if (stalecontext)
2058                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
2059         }
2060 }
2061
2062 static void register_exten(struct skinny_line *l)
2063 {
2064         char multi[256];
2065         char *stringp, *ext, *context;
2066
2067         if (ast_strlen_zero(regcontext))
2068                 return;
2069
2070         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2071         stringp = multi;
2072         while ((ext = strsep(&stringp, "&"))) {
2073                 if ((context = strchr(ext, '@'))) {
2074                         *context++ = '\0'; /* split ext@context */
2075                         if (!ast_context_find(context)) {
2076                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2077                                 continue;
2078                         }
2079                 } else {
2080                         context = regcontext;
2081                 }
2082                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
2083                          ast_strdup(l->name), ast_free_ptr, "Skinny");
2084         }
2085 }
2086
2087 static void unregister_exten(struct skinny_line *l)
2088 {
2089         char multi[256];
2090         char *stringp, *ext, *context;
2091
2092         if (ast_strlen_zero(regcontext))
2093                 return;
2094
2095         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
2096         stringp = multi;
2097         while ((ext = strsep(&stringp, "&"))) {
2098                 if ((context = strchr(ext, '@'))) {
2099                         *context++ = '\0'; /* split ext@context */
2100                         if (!ast_context_find(context)) {
2101                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
2102                                 continue;
2103                         }
2104                 } else {
2105                         context = regcontext;
2106                 }
2107                 ast_context_remove_extension(context, ext, 1, NULL);
2108         }
2109 }
2110
2111 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
2112 {
2113         struct skinny_device *d;
2114         struct skinny_line *l;
2115         struct skinny_subline *subline;
2116         struct skinny_speeddial *sd;
2117         struct sockaddr_in sin;
2118         socklen_t slen;
2119         int instance;
2120
2121         AST_LIST_LOCK(&devices);
2122         AST_LIST_TRAVERSE(&devices, d, list){
2123                 struct ast_sockaddr addr;
2124                 ast_sockaddr_from_sin(&addr, &s->sin);
2125                 if (!d->session && !strcasecmp(req->data.reg.name, d->id)
2126                                 && ast_apply_ha(d->ha, &addr)) {
2127                         s->device = d;
2128                         d->type = letohl(req->data.reg.type);
2129                         d->protocolversion = letohl(req->data.reg.protocolVersion);
2130                         if (ast_strlen_zero(d->version_id)) {
2131                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
2132                         }
2133                         d->session = s;
2134
2135                         slen = sizeof(sin);
2136                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
2137                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
2138                                 sin.sin_addr = __ourip;
2139                         }
2140                         d->ourip = sin.sin_addr;
2141
2142                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2143                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd->container);
2144                         }
2145                         instance = 0;
2146                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2147                                 instance++;
2148                         }
2149                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2150                                 ast_format_cap_joint_copy(l->confcap, d->cap, l->cap);
2151                                 l->prefs = l->confprefs;
2152                                 if (!l->prefs.order[0]) {
2153                                         l->prefs = d->confprefs;
2154                                 }
2155                                 /* l->capability = d->capability;
2156                                 l->prefs = d->prefs; */
2157                                 l->instance = instance;
2158                                 l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
2159                                 set_callforwards(l, NULL, 0);
2160                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Registered\r\n", l->name, d->name);
2161                                 register_exten(l);
2162                                 /* initialize MWI on line and device */
2163                                 mwi_event_cb(0, l);
2164                                 AST_LIST_TRAVERSE(&l->sublines, subline, list) {
2165                                         ast_extension_state_add(subline->context, subline->exten, skinny_extensionstate_cb, subline->container);
2166                                 }
2167                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
2168                                 --instance;
2169                         }
2170                         break;
2171                 }
2172         }
2173         AST_LIST_UNLOCK(&devices);
2174         if (!d) {
2175                 return 0;
2176         }
2177         return 1;
2178 }
2179
2180 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
2181 {
2182         struct skinny_device *d;
2183         struct skinny_line *l;
2184         struct skinny_speeddial *sd;
2185
2186         d = s->device;
2187
2188         if (d) {
2189                 d->session = NULL;
2190
2191                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2192                         if (sd->stateid > -1)
2193                                 ast_extension_state_del(sd->stateid, NULL);
2194                 }
2195                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2196                         if (l->device == d) {
2197                                 ast_format_cap_remove_all(l->cap);
2198                                 ast_parse_allow_disallow(&l->prefs, l->cap, "all", 0);
2199                                 l->instance = 0;
2200                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Unregistered\r\n", l->name, d->name);
2201                                 unregister_exten(l);
2202                                 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "Skinny/%s", l->name);
2203                         }
2204                 }
2205         }
2206
2207         return -1; /* main loop will destroy the session */
2208 }
2209
2210 #ifdef AST_DEVMODE
2211 static char *callstate2str(int ind)
2212 {
2213         char *tmp;
2214
2215         switch (ind) {
2216         case SKINNY_OFFHOOK:
2217                 return "SKINNY_OFFHOOK";
2218         case SKINNY_ONHOOK:
2219                 return "SKINNY_ONHOOK";
2220         case SKINNY_RINGOUT:
2221                 return "SKINNY_RINGOUT";
2222         case SKINNY_RINGIN:
2223                 return "SKINNY_RINGIN";
2224         case SKINNY_CONNECTED:
2225                 return "SKINNY_CONNECTED";
2226         case SKINNY_BUSY:
2227                 return "SKINNY_BUSY";
2228         case SKINNY_CONGESTION:
2229                 return "SKINNY_CONGESTION";
2230         case SKINNY_PROGRESS:
2231                 return "SKINNY_PROGRESS";
2232         case SKINNY_HOLD:
2233                 return "SKINNY_HOLD";
2234         case SKINNY_CALLWAIT:
2235                 return "SKINNY_CALLWAIT";
2236         default:
2237                 if (!(tmp = ast_threadstorage_get(&callstate2str_threadbuf, CALLSTATE2STR_BUFSIZE)))
2238                         return "Unknown";
2239                 snprintf(tmp, CALLSTATE2STR_BUFSIZE, "UNKNOWN-%d", ind);
2240                 return tmp;
2241         }
2242 }
2243
2244 #endif
2245
2246 static int transmit_response_bysession(struct skinnysession *s, struct skinny_req *req)
2247 {
2248         int res = 0;
2249
2250         if (!s) {
2251                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2252                 return -1;
2253         }
2254
2255         ast_mutex_lock(&s->lock);
2256
2257         if ((letohl(req->len) > SKINNY_MAX_PACKET) || (letohl(req->len) < 0)) {
2258                 ast_log(LOG_WARNING, "transmit_response: the length of the request (%d) is out of bounds (%d)\n", letohl(req->len), SKINNY_MAX_PACKET);
2259                 ast_mutex_unlock(&s->lock);
2260                 return -1;
2261         }
2262
2263         memset(s->outbuf, 0, sizeof(s->outbuf));
2264         memcpy(s->outbuf, req, skinny_header_size);
2265         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2266
2267         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2268
2269         if (res != letohl(req->len)+8) {
2270                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2271                 if (res == -1) {
2272                         ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2273                         skinny_unregister(NULL, s);
2274                 }
2275
2276         }
2277
2278         ast_free(req);
2279         ast_mutex_unlock(&s->lock);
2280         return 1;
2281 }
2282
2283 static void transmit_response(struct skinny_device *d, struct skinny_req *req)
2284 {
2285         transmit_response_bysession(d->session, req);
2286 }
2287
2288 static void transmit_registerrej(struct skinnysession *s)
2289 {
2290         struct skinny_req *req;
2291         char name[16];
2292
2293         if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
2294                 return;
2295
2296         memcpy(&name, req->data.reg.name, sizeof(name));
2297         snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2298
2299         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_REJ_MESSAGE to UNKNOWN_DEVICE\n");
2300         transmit_response_bysession(s, req);
2301 }
2302
2303 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2304 {
2305         struct skinny_req *req;
2306
2307         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2308                 return;
2309
2310         req->data.setspeaker.mode = htolel(mode);
2311
2312         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_SPEAKER_MESSAGE to %s, mode %d\n", d->name, mode);
2313         transmit_response(d, req);
2314 }
2315
2316 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2317 {
2318         struct skinny_req *req;
2319
2320         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2321                 return;
2322
2323         req->data.setmicrophone.mode = htolel(mode);
2324
2325         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_MICROPHONE_MESSAGE to %s, mode %d\n", d->name, mode);
2326         transmit_response(d, req);
2327 }
2328
2329 //static void transmit_callinfo(struct skinny_subchannel *sub)
2330 static void transmit_callinfo(struct skinny_device *d, int instance, int callid, char *fromname, char *fromnum, char *toname, char *tonum, int calldirection)
2331 {
2332         struct skinny_req *req;
2333
2334         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2335                 return;
2336
2337         ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2338         ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2339         ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2340         ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2341         req->data.callinfo.instance = htolel(instance);
2342         req->data.callinfo.reference = htolel(callid);
2343         req->data.callinfo.type = htolel(calldirection);
2344
2345         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_INFO_MESSAGE to %s, to %s(%s) from %s(%s) (dir=%d) on %s(%d)\n",
2346                 d->name, toname, tonum, fromname, fromnum, calldirection, d->name, instance);
2347         transmit_response(d, req);
2348 }
2349
2350 static void send_callinfo(struct skinny_subchannel *sub)
2351 {
2352         struct ast_channel *ast;
2353         struct skinny_device *d;
2354         struct skinny_line *l;
2355         char *fromname;
2356         char *fromnum;
2357         char *toname;
2358         char *tonum;
2359
2360         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2361                 return;
2362         }
2363
2364         ast = sub->owner;
2365         l = sub->line;
2366         d = l->device;
2367
2368         if (sub->calldirection == SKINNY_INCOMING) {
2369                 fromname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2370                 fromnum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, "");
2371                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2372                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2373         } else if (sub->calldirection == SKINNY_OUTGOING) {
2374                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2375                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2376                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, l->lastnumberdialed);
2377                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2378         } else {
2379                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2380                 return;
2381         }
2382         transmit_callinfo(d, l->instance, sub->callid, fromname, fromnum, toname, tonum, sub->calldirection);
2383 }
2384
2385 static void push_callinfo(struct skinny_subline *subline, struct skinny_subchannel *sub)
2386 {
2387         struct ast_channel *ast;
2388         struct skinny_device *d;
2389         struct skinny_line *l;
2390         char *fromname;
2391         char *fromnum;
2392         char *toname;
2393         char *tonum;
2394
2395         if (!sub || !sub->owner || !sub->line || !sub->line->device) {
2396                 return;
2397         }
2398
2399         ast = sub->owner;
2400         l = sub->line;
2401         d = l->device;
2402
2403         if (sub->calldirection == SKINNY_INCOMING) {
2404                 fromname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, "");
2405                 fromnum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, "");
2406                 toname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2407                 tonum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2408         } else if (sub->calldirection == SKINNY_OUTGOING) {
2409                 fromname = S_COR(ast_channel_caller(ast)->id.name.valid, ast_channel_caller(ast)->id.name.str, "");
2410                 fromnum = S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, "");
2411                 toname = S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, l->lastnumberdialed);
2412                 tonum = S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, l->lastnumberdialed);
2413         } else {
2414                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2415                 return;
2416         }
2417         transmit_callinfo(subline->line->device, subline->line->instance, subline->callid, fromname, fromnum, toname, tonum, sub->calldirection);
2418 }
2419
2420 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2421 {
2422         struct skinny_req *req;
2423         struct skinny_line *l = sub->line;
2424         struct ast_format_list fmt;
2425         struct ast_format tmpfmt;
2426
2427         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2428                 return;
2429         ast_best_codec(l->cap, &tmpfmt);
2430         fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
2431
2432         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2433         req->data.openreceivechannel.partyId = htolel(sub->callid);
2434         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2435         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(&fmt.format));
2436         req->data.openreceivechannel.echo = htolel(0);
2437         req->data.openreceivechannel.bitrate = htolel(0);
2438
2439         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",
2440                 d->name, sub->callid, sub->callid, fmt.cur_ms, codec_ast2skinny(&fmt.format), 0, 0);
2441         transmit_response(d, req);
2442 }
2443
2444 static void transmit_start_tone(struct skinny_device *d, int tone, int instance, int reference)
2445 {
2446         struct skinny_req *req;
2447         if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2448                 return;
2449         req->data.starttone.tone = htolel(tone);
2450         req->data.starttone.instance = htolel(instance);
2451         req->data.starttone.reference = htolel(reference);
2452
2453         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting START_TONE_MESSAGE to %s, tone %d, inst %d, ref %d\n",
2454                 d->name, tone, instance, reference);
2455         transmit_response(d, req);
2456 }
2457
2458 static void transmit_stop_tone(struct skinny_device *d, int instance, int reference)
2459 {
2460         struct skinny_req *req;
2461         if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2462                 return;
2463         req->data.stoptone.instance = htolel(instance);
2464         req->data.stoptone.reference = htolel(reference);
2465
2466         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_TONE_MESSAGE to %s, inst %d, ref %d\n",
2467                 d->name, instance, reference);
2468         transmit_response(d, req);
2469 }
2470
2471 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey)
2472 {
2473         struct skinny_req *req;
2474
2475         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2476                 return;
2477
2478         req->data.selectsoftkey.instance = htolel(instance);
2479         req->data.selectsoftkey.reference = htolel(callid);
2480         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2481         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
2482
2483         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SELECT_SOFT_KEYS_MESSAGE to %s, inst %d, callid %d, softkey %d, mask 0xFFFFFFFF\n",
2484                 d->name, instance, callid, softkey);
2485         transmit_response(d, req);
2486 }
2487
2488 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2489 {
2490         struct skinny_req *req;
2491
2492         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2493                 return;
2494
2495         req->data.setlamp.stimulus = htolel(stimulus);
2496         req->data.setlamp.stimulusInstance = htolel(instance);
2497         req->data.setlamp.deviceStimulus = htolel(indication);
2498
2499         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_LAMP_MESSAGE to %s, stim %d, inst %d, ind %d\n",
2500                 d->name, stimulus, instance, indication);
2501         transmit_response(d, req);
2502 }
2503
2504 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2505 {
2506         struct skinny_req *req;
2507
2508         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2509                 return;
2510
2511         req->data.setringer.ringerMode = htolel(mode);
2512         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2513            Note: The phone will always show as ringing on the display.
2514
2515            1: phone will audibly ring over and over
2516            2: phone will audibly ring only once
2517            any other value, will NOT cause the phone to audibly ring
2518         */
2519         req->data.setringer.unknown1 = htolel(1);
2520         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2521            Perhaps a packet capture can shed some light on this. */
2522         req->data.setringer.unknown2 = htolel(1);
2523
2524         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SET_RINGER_MESSAGE to %s, mode %d, unk1 1, unk2 1\n",
2525                 d->name, mode);
2526         transmit_response(d, req);
2527 }
2528
2529 static void transmit_clear_display_message(struct skinny_device *d, int instance, int reference)
2530 {
2531         struct skinny_req *req;
2532         if (!(req = req_alloc(sizeof(struct clear_display_message), CLEAR_DISPLAY_MESSAGE)))
2533                 return;
2534
2535         //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2536         //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2537         //req->data.clearpromptstatus.lineInstance = instance;
2538         //req->data.clearpromptstatus.callReference = reference;
2539
2540         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_DISPLAY_MESSAGE to %s\n", d->name);
2541         transmit_response(d, req);
2542 }
2543
2544 /* This function is not currently used, but will be (wedhorn)*/
2545 /* static void transmit_display_message(struct skinny_device *d, const char *text, int instance, int reference)
2546 {
2547         struct skinny_req *req;
2548
2549         if (text == 0) {
2550                 ast_verb(1, "Bug, Asked to display empty message\n");
2551                 return;
2552         }
2553
2554         if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2555                 return;
2556
2557         ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2558         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAYTEXT_MESSAGE to %s, text %s\n", d->name, text);
2559         transmit_response(d, req);
2560 } */
2561
2562 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2563 {
2564         struct skinny_req *req;
2565
2566         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2567                 return;
2568
2569         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2570         req->data.displaynotify.displayTimeout = htolel(t);
2571
2572         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_NOTIFY_MESSAGE to %s, text %s\n", d->name, text);
2573         transmit_response(d, req);
2574 }
2575
2576 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
2577 {
2578         struct skinny_req *req;
2579
2580         if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2581                 return;
2582
2583         ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2584         req->data.displaypromptstatus.messageTimeout = htolel(t);
2585         req->data.displaypromptstatus.lineInstance = htolel(instance);
2586         req->data.displaypromptstatus.callReference = htolel(callid);
2587
2588         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DISPLAY_PROMPT_STATUS_MESSAGE to %s, text %s\n", d->name, text);
2589         transmit_response(d, req);
2590 }
2591
2592 static void transmit_clearpromptmessage(struct skinny_device *d, int instance, int callid)
2593 {
2594         struct skinny_req *req;
2595
2596         if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2597                 return;
2598
2599         req->data.clearpromptstatus.lineInstance = htolel(instance);
2600         req->data.clearpromptstatus.callReference = htolel(callid);
2601
2602         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLEAR_PROMPT_MESSAGE to %s, inst %d, callid %d\n",
2603                 d->name, instance, callid);
2604         transmit_response(d, req);
2605 }
2606
2607 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2608 {
2609         struct skinny_req *req;
2610
2611         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2612                 return;
2613
2614         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2615         req->data.dialednumber.lineInstance = htolel(instance);
2616         req->data.dialednumber.callReference = htolel(callid);
2617
2618         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DIALED_NUMBER_MESSAGE to %s, num %s, inst %d, callid %d\n",
2619                 d->name, text, instance, callid);
2620         transmit_response(d, req);
2621 }
2622
2623 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2624 {
2625         struct skinny_req *req;
2626
2627         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2628                 return;
2629
2630         req->data.closereceivechannel.conferenceId = htolel(0);
2631         req->data.closereceivechannel.partyId = htolel(sub->callid);
2632
2633         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CLOSE_RECEIVE_CHANNEL_MESSAGE to %s, confid %d, callid %d\n",
2634                 d->name, 0, sub->callid);
2635         transmit_response(d, req);
2636 }
2637
2638 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2639 {
2640         struct skinny_req *req;
2641
2642         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2643                 return;
2644
2645         req->data.stopmedia.conferenceId = htolel(0);
2646         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2647
2648         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting STOP_MEDIA_TRANSMISSION_MESSAGE to %s, confid %d, passthrupartyid %d\n",
2649                 d->name, 0, sub->callid);
2650         transmit_response(d, req);
2651 }
2652
2653 static void transmit_startmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub, struct sockaddr_in dest, struct ast_format_list fmt)
2654 {
2655         struct skinny_req *req;
2656
2657         if (d->protocolversion < 17) {
2658                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip4), START_MEDIA_TRANSMISSION_MESSAGE)))
2659                         return;
2660                 req->data.startmedia_ip4.conferenceId = htolel(sub->callid);
2661                 req->data.startmedia_ip4.passThruPartyId = htolel(sub->callid);
2662                 req->data.startmedia_ip4.remoteIp = dest.sin_addr.s_addr;
2663                 req->data.startmedia_ip4.remotePort = htolel(ntohs(dest.sin_port));
2664                 req->data.startmedia_ip4.packetSize = htolel(fmt.cur_ms);
2665                 req->data.startmedia_ip4.payloadType = htolel(codec_ast2skinny(&fmt.format));
2666                 req->data.startmedia_ip4.qualifier.precedence = htolel(127);
2667                 req->data.startmedia_ip4.qualifier.vad = htolel(0);
2668                 req->data.startmedia_ip4.qualifier.packets = htolel(0);
2669                 req->data.startmedia_ip4.qualifier.bitRate = htolel(0);
2670         } else {
2671                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message_ip6), START_MEDIA_TRANSMISSION_MESSAGE)))
2672                         return;
2673                 req->data.startmedia_ip6.conferenceId = htolel(sub->callid);
2674                 req->data.startmedia_ip6.passThruPartyId = htolel(sub->callid);
2675                 memcpy(req->data.startmedia_ip6.remoteIp, &dest.sin_addr.s_addr, sizeof(dest.sin_addr.s_addr));
2676                 req->data.startmedia_ip6.remotePort = htolel(ntohs(dest.sin_port));
2677                 req->data.startmedia_ip6.packetSize = htolel(fmt.cur_ms);
2678                 req->data.startmedia_ip6.payloadType = htolel(codec_ast2skinny(&fmt.format));
2679                 req->data.startmedia_ip6.qualifier.precedence = htolel(127);
2680                 req->data.startmedia_ip6.qualifier.vad = htolel(0);
2681                 req->data.startmedia_ip6.qualifier.packets = htolel(0);
2682                 req->data.startmedia_ip6.qualifier.bitRate = htolel(0);
2683         }
2684
2685         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",
2686                 d->name, sub->callid, sub->callid, ast_inet_ntoa(dest.sin_addr), dest.sin_port, fmt.cur_ms, codec_ast2skinny(&fmt.format));
2687         transmit_response(d, req);
2688 }
2689
2690 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
2691 {
2692         struct skinny_req *req;
2693
2694         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2695                 return;
2696
2697         req->data.activatecallplane.lineInstance = htolel(l->instance);
2698
2699         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting ACTIVATE_CALL_PLANE_MESSAGE to %s, inst %d\n",
2700                 d->name, l->instance);
2701         transmit_response(d, req);
2702 }
2703
2704 static void transmit_callstate(struct skinny_device *d, int buttonInstance, unsigned callid, int state)
2705 {
2706         struct skinny_req *req;
2707
2708         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2709                 return;
2710
2711         req->data.callstate.callState = htolel(state);
2712         req->data.callstate.lineInstance = htolel(buttonInstance);
2713         req->data.callstate.callReference = htolel(callid);
2714
2715         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CALL_STATE_MESSAGE to %s, state %s, inst %d, callid %d\n",
2716                 d->name, callstate2str(state), buttonInstance, callid);
2717         transmit_response(d, req);
2718 }
2719
2720 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
2721 {
2722         struct skinny_req *req;
2723         int anyon = 0;
2724
2725         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
2726                 return;
2727
2728         if (l->cfwdtype & SKINNY_CFWD_ALL) {
2729                 if (!ast_strlen_zero(l->call_forward_all)) {
2730                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
2731                         req->data.forwardstat.fwdall = htolel(1);
2732                         anyon++;
2733                 } else {
2734                         req->data.forwardstat.fwdall = htolel(0);
2735                 }
2736         }
2737         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
2738                 if (!ast_strlen_zero(l->call_forward_busy)) {
2739                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
2740                         req->data.forwardstat.fwdbusy = htolel(1);
2741                         anyon++;
2742                 } else {
2743                         req->data.forwardstat.fwdbusy = htolel(0);
2744                 }
2745         }
2746         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
2747                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
2748                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
2749                         req->data.forwardstat.fwdnoanswer = htolel(1);
2750                         anyon++;
2751                 } else {
2752                         req->data.forwardstat.fwdnoanswer = htolel(0);
2753                 }
2754         }
2755         req->data.forwardstat.lineNumber = htolel(l->instance);
2756         if (anyon)
2757                 req->data.forwardstat.activeforward = htolel(7);
2758         else
2759                 req->data.forwardstat.activeforward = htolel(0);
2760
2761         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting FORWARD_STAT_MESSAGE to %s, inst %d, all %s, busy %s, noans %s, acitve %d\n",
2762                 d->name, l->instance, l->call_forward_all, l->call_forward_busy, l->call_forward_noanswer, anyon ? 7 : 0);
2763         transmit_response(d, req);
2764 }
2765
2766 static void transmit_speeddialstatres(struct skinny_device *d, struct skinny_speeddial *sd)
2767 {
2768         struct skinny_req *req;
2769
2770         if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
2771                 return;
2772
2773         req->data.speeddialreq.speedDialNumber = htolel(sd->instance);
2774         ast_copy_string(req->data.speeddial.speedDialDirNumber, sd->exten, sizeof(req->data.speeddial.speedDialDirNumber));
2775         ast_copy_string(req->data.speeddial.speedDialDisplayName, sd->label, sizeof(req->data.speeddial.speedDialDisplayName));
2776
2777         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SPEED_DIAL_STAT_RES_MESSAGE to %s, inst %d, dir %s, display %s\n",
2778                 d->name, sd->instance, sd->exten, sd->label);
2779         transmit_response(d, req);
2780 }
2781
2782 //static void transmit_linestatres(struct skinny_device *d, struct skinny_line *l)
2783 static void transmit_linestatres(struct skinny_device *d, int instance)
2784 {
2785         struct skinny_req *req;
2786         struct skinny_line *l;
2787         struct skinny_speeddial *sd;
2788
2789         if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
2790                 return;
2791
2792         if ((l = find_line_by_instance(d, instance))) {
2793                 req->data.linestat.lineNumber = letohl(l->instance);
2794                 memcpy(req->data.linestat.lineDirNumber, l->name, sizeof(req->data.linestat.lineDirNumber));
2795                 memcpy(req->data.linestat.lineDisplayName, l->label, sizeof(req->data.linestat.lineDisplayName));
2796         } else if ((sd = find_speeddial_by_instance(d, instance, 1))) {
2797                 req->data.linestat.lineNumber = letohl(sd->instance);
2798                 memcpy(req->data.linestat.lineDirNumber, sd->label, sizeof(req->data.linestat.lineDirNumber));
2799                 memcpy(req->data.linestat.lineDisplayName, sd->label, sizeof(req->data.linestat.lineDisplayName));
2800         }
2801
2802         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting LINE_STAT_RES_MESSAGE to %s, inst %d, num %s, label %s\n",
2803                 d->name, l->instance, req->data.linestat.lineDirNumber, req->data.linestat.lineDisplayName);
2804         transmit_response(d, req);
2805 }
2806
2807 static void transmit_definetimedate(struct skinny_device *d)
2808 {
2809         struct skinny_req *req;
2810         struct timeval now = ast_tvnow();
2811         struct ast_tm cmtime;
2812
2813         if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
2814                 return;
2815
2816         ast_localtime(&now, &cmtime, NULL);
2817         req->data.definetimedate.year = htolel(cmtime.tm_year+1900);
2818         req->data.definetimedate.month = htolel(cmtime.tm_mon+1);
2819         req->data.definetimedate.dayofweek = htolel(cmtime.tm_wday);
2820         req->data.definetimedate.day = htolel(cmtime.tm_mday);
2821         req->data.definetimedate.hour = htolel(cmtime.tm_hour);
2822         req->data.definetimedate.minute = htolel(cmtime.tm_min);
2823         req->data.definetimedate.seconds = htolel(cmtime.tm_sec);
2824         req->data.definetimedate.milliseconds = htolel(cmtime.tm_usec / 1000);
2825         req->data.definetimedate.timestamp = htolel(now.tv_sec);
2826
2827         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting DEFINETIMEDATE_MESSAGE to %s, date %d %d %d dow %d time %d:%d:%d.%d\n",
2828                 d->name, req->data.definetimedate.year, req->data.definetimedate.month, req->data.definetimedate.day, req->data.definetimedate.dayofweek,
2829                 req->data.definetimedate.hour, req->data.definetimedate.minute, req->data.definetimedate.seconds, req->data.definetimedate.milliseconds);
2830         transmit_response(d, req);
2831 }
2832
2833 static void transmit_versionres(struct skinny_device *d)
2834 {
2835         struct skinny_req *req;
2836         if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
2837                 return;
2838
2839         ast_copy_string(req->data.version.version, d->version_id, sizeof(req->data.version.version));
2840
2841         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting VERSION_RES_MESSAGE to %s, version %s\n", d->name, d->version_id);
2842         transmit_response(d, req);
2843 }
2844
2845 static void transmit_serverres(struct skinny_device *d)
2846 {
2847         struct skinny_req *req;
2848         if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
2849                 return;
2850
2851         memcpy(req->data.serverres.server[0].serverName, ourhost,
2852                         sizeof(req->data.serverres.server[0].serverName));
2853         req->data.serverres.serverListenPort[0] = htolel(ourport);
2854         req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
2855
2856         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SERVER_RES_MESSAGE to %s, srvname %s %s:%d\n",
2857                 d->name, ourhost, ast_inet_ntoa(d->ourip), ourport);
2858         transmit_response(d, req);
2859 }
2860
2861 static void transmit_softkeysetres(struct skinny_device *d)
2862 {
2863         struct skinny_req *req;
2864         int i;
2865         int x;
2866         int y;
2867         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
2868
2869         if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
2870                 return;
2871
2872         SKINNY_DEBUG(DEBUG_TEMPLATE, 3, "Creating Softkey Template\n");
2873
2874         req->data.softkeysets.softKeySetOffset = htolel(0);
2875         req->data.softkeysets.softKeySetCount = htolel(13);
2876         req->data.softkeysets.totalSoftKeySetCount = htolel(13);
2877         for (x = 0; x < sizeof(soft_key_default_definitions) / sizeof(struct soft_key_definitions); x++) {
2878                 const uint8_t *defaults = softkeymode->defaults;
2879                 /* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
2880                    This will have to do for now. */
2881                 for (y = 0; y < softkeymode->count; y++) {
2882                         for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
2883                                 if (defaults[y] == i+1) {
2884                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = (i+1);
2885                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyInfoIndex[y] = htoles(i+301);
2886                                         SKINNY_DEBUG(DEBUG_TEMPLATE, 4, "softKeySetDefinition : softKeyTemplateIndex: %d softKeyInfoIndex: %d\n",
2887                                                 i+1, i+301);
2888                                 }
2889                         }
2890                 }
2891                 softkeymode++;
2892         }
2893
2894         SKINNY_DEBUG(DEBUG_PACKET | DEBUG_TEMPLATE, 3, "Transmitting SOFT_KEY_SET_RES_MESSAGE to %s, template data\n",
2895                 d->name);
2896         transmit_response(d, req);
2897 }
2898
2899 static void transmit_softkeytemplateres(struct skinny_device *d)
2900 {
2901         struct skinny_req *req;
2902         if (!(req = req_alloc(sizeof(struct soft_key_template_res_message), SOFT_KEY_TEMPLATE_RES_MESSAGE)))
2903                 return;
2904
2905         req->data.softkeytemplate.softKeyOffset = htolel(0);
2906         req->data.softkeytemplate.softKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
2907         req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
2908         memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
2909                 soft_key_template_default,
2910                 sizeof(soft_key_template_default));
2911
2912         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting SOFT_KEY_TEMPLATE_RES_MESSAGE to %s, offset 0, keycnt %d, totalkeycnt %d, template data\n",
2913                 d->name, req->data.softkeytemplate.softKeyCount, req->data.softkeytemplate.totalSoftKeyCount);
2914         transmit_response(d, req);
2915 }
2916
2917 static void transmit_reset(struct skinny_device *d, int fullrestart)
2918 {
2919         struct skinny_req *req;
2920
2921         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
2922                 return;
2923
2924         if (fullrestart)
2925                 req->data.reset.resetType = 2;
2926         else
2927                 req->data.reset.resetType = 1;
2928
2929         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting RESET_MESSAGE to %s, type %s\n",
2930                 d->name, (fullrestart) ? "Restarting" : "Resetting");
2931         transmit_response(d, req);
2932 }
2933
2934 static void transmit_keepaliveack(struct skinny_device *d)
2935 {
2936         struct skinny_req *req;
2937
2938         if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
2939                 return;
2940
2941         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting KEEP_ALIVE_ACK_MESSAGE to %s\n", d->name);
2942         transmit_response(d, req);
2943 }
2944
2945 static void transmit_registerack(struct skinny_device *d)
2946 {
2947         struct skinny_req *req;
2948
2949         if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
2950                 return;
2951
2952         req->data.regack.res[0] = '0';
2953         req->data.regack.res[1] = '\0';
2954         req->data.regack.keepAlive = htolel(keep_alive);
2955         memcpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate));
2956         req->data.regack.res2[0] = '0';
2957         req->data.regack.res2[1] = '\0';
2958         req->data.regack.secondaryKeepAlive = htolel(keep_alive);
2959
2960 #ifdef AST_DEVMODE
2961         {
2962         short res = req->data.regack.res[0] << 8 | req->data.regack.res[1];
2963         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];
2964         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting REGISTER_ACK_MESSAGE to %s, keepalive %d, datetemplate %s, seckeepalive %d, res 0x%04x, res2 0x%08x\n",
2965                 d->name, keep_alive, date_format, keep_alive, res, res2);
2966         }
2967 #endif
2968
2969         transmit_response(d, req);
2970 }
2971
2972 static void transmit_capabilitiesreq(struct skinny_device *d)
2973 {
2974         struct skinny_req *req;
2975
2976         if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
2977                 return;
2978
2979         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting CAPABILITIES_REQ_MESSAGE to %s\n", d->name);
2980         transmit_response(d, req);
2981 }
2982
2983 static void transmit_backspace(struct skinny_device *d, int instance, unsigned callid)
2984 {
2985         struct skinny_req *req;
2986
2987         if (!(req = req_alloc(sizeof(struct bksp_req_message), BKSP_REQ_MESSAGE)))
2988                 return;
2989
2990         req->data.bkspmessage.instance = htolel(instance);
2991         req->data.bkspmessage.callreference = htolel(callid);
2992
2993         SKINNY_DEBUG(DEBUG_PACKET, 3, "Transmitting BKSP_REQ_MESSAGE to %s, inst %d, callid %d \n",
2994                 d->name, instance, callid);
2995         transmit_response(d, req);
2996 }
2997
2998 static int skinny_extensionstate_cb(char *context, char *exten, struct ast_state_cb_info *info, void *data)
2999 {
3000         struct skinny_container *container = data;
3001         struct skinny_device *d = NULL;
3002         char hint[AST_MAX_EXTENSION];
3003         int state = info->exten_state;
3004
3005         /* only interested in device state here */
3006         if (info->reason != AST_HINT_UPDATE_DEVICE) {
3007                 return 0;
3008         }
3009
3010         if (container->type == SKINNY_SDCONTAINER) {
3011                 struct skinny_speeddial *sd = container->data;
3012                 d = sd->parent;
3013
3014                 SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on speeddial %s\n", ast_extension_state2str(state), sd->label);
3015
3016                 if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
3017                         /* If they are not registered, we will override notification and show no availability */
3018                         if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
3019                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_FLASH);
3020                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3021                                 return 0;
3022                         }
3023                         switch (state) {
3024                         case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
3025                         case AST_EXTENSION_REMOVED:     /* Extension is gone */
3026                                 SKINNY_DEBUG(DEBUG_HINT, 3, "Extension state: Watcher for hint %s %s. Notify Device %s\n",
3027                                         exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
3028                                 sd->stateid = -1;
3029                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
3030                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3031                                 break;
3032                         case AST_EXTENSION_RINGING:
3033                         case AST_EXTENSION_UNAVAILABLE:
3034                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_BLINK);
3035                                 transmit_callstate(d, sd->instance, 0, SKINNY_RINGIN);
3036                                 break;
3037                         case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
3038                         case AST_EXTENSION_INUSE:
3039                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_ON);
3040                                 transmit_callstate(d, sd->instance, 0, SKINNY_CALLREMOTEMULTILINE);
3041                                 break;
3042                         case AST_EXTENSION_ONHOLD:
3043                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_WINK);
3044                                 transmit_callstate(d, sd->instance, 0, SKINNY_HOLD);
3045                                 break;
3046                         case AST_EXTENSION_NOT_INUSE:
3047                         default:
3048                                 transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
3049                                 transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
3050                                 break;
3051                         }
3052                 }
3053                 sd->laststate = state;
3054         } else if (container->type == SKINNY_SUBLINECONTAINER) {
3055                 struct skinny_subline *subline = container->data;
3056                 struct skinny_line *l = subline->line;
3057                 d = l->device;
3058
3059                 SKINNY_DEBUG(DEBUG_HINT, 3, "Got hint %s on subline %s (%s@%s)\n", ast_extension_state2str(state), subline->name, exten, context);
3060
3061                 subline->extenstate = state;
3062
3063                 if (subline->callid == 0) {
3064                         return 0;
3065                 }
3066
3067                 switch (state) {
3068                 case AST_EXTENSION_RINGING: /* Handled by normal ringin */
3069                         break;
3070                 case AST_EXTENSION_INUSE:
3071                         if (subline->sub && (subline->sub->substate == SKINNY_CONNECTED)) { /* Device has a real call */
3072                                 transmit_callstate(d, l->instance, subline->callid, SKINNY_CONNECTED);
3073                                 transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_CONNECTED);
3074                                 transmit_displaypromptstatus(d, "Connected", 0, l->instance, subline->callid);
3075                         } else { /* Some other device has active call */
3076                                 transmit_callstate(d, l->instance, subline->callid, SKINNY_CALLREMOTEMULTILINE);
3077                                 transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLACONNECTEDNOTACTIVE);
3078                                 transmit_displaypromptstatus(d, "In Use", 0, l->instance, subline->callid);
3079                         }
3080                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3081                         transmit_ringer_mode(d, SKINNY_RING_OFF);
3082                         transmit_activatecallplane(d, l);
3083                         break;
3084                 case AST_EXTENSION_ONHOLD:
3085                         transmit_callstate(d, l->instance, subline->callid, SKINNY_HOLD);
3086                         transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_SLAHOLD);
3087                         transmit_displaypromptstatus(d, "Hold", 0, l->instance, subline->callid);
3088                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3089                         transmit_activatecallplane(d, l);
3090                         break;
3091                 case AST_EXTENSION_NOT_INUSE:
3092                         transmit_callstate(d, l->instance, subline->callid, SKINNY_ONHOOK);
3093                         transmit_selectsoftkeys(d, l->instance, subline->callid, KEYDEF_ONHOOK);
3094                         transmit_clearpromptmessage(d, l->instance, subline->callid);
3095                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
3096                         transmit_activatecallplane(d, l);
3097                         subline->callid = 0;
3098                         break;
3099                 default:
3100                         ast_log(LOG_WARNING, "AST_EXTENSION_STATE %s not configured\n", ast_extension_state2str(state));
3101                 }
3102         } else {
3103                 ast_log(LOG_WARNING, "Invalid data supplied to skinny_extensionstate_cb\n");
3104         }
3105
3106         return 0;
3107 }
3108
3109 static void update_connectedline(struct skinny_subchannel *sub, const void *data, size_t datalen)
3110 {
3111         struct ast_channel *c = sub->owner;
3112         struct skinny_line *l = sub->line;
3113         struct skinny_device *d = l->device;
3114
3115         if (!d->session) {
3116                 return;
3117         }
3118
3119         if (!ast_channel_caller(c)->id.number.valid
3120                 || ast_strlen_zero(ast_channel_caller(c)->id.number.str)
3121                 || !ast_channel_connected(c)->id.number.valid
3122                 || ast_strlen_zero(ast_channel_connected(c)->id.number.str))
3123                 return;
3124
3125         SKINNY_DEBUG(DEBUG_SUB, 3, "Sub %d - Updating\n", sub->callid);
3126
3127         send_callinfo(sub);
3128         if (ast_channel_state(sub->owner) == AST_STATE_UP) {
3129                 transmit_callstate(d, l->instance, sub->callid, SKINNY_CONNECTED);
3130                 transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
3131         } else {
3132                 if (sub->calldirection == SKINNY_INCOMING) {
3133                         transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGIN);
3134                         transmit_displaypromptstatus(d, "Ring-In", 0, l->instance, sub->callid);
3135                 } else {
3136                         if (!sub->ringing) {
3137                                 transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGOUT);
3138                                 transmit_displaypromptstatus(d, "Ring-Out", 0, l->instance, sub->callid);
3139                                 sub->ringing = 1;
3140                         } else {
3141                                 transmit_callstate(d, l->instance, sub->callid, SKINNY_PROGRESS);
3142                                 transmit_displaypromptstatus(d, "Call Progress", 0, l->instance, sub->callid);
3143                                 sub->progress = 1;
3144                         }
3145                 }
3146         }
3147 }
3148
3149 static void mwi_event_cb(const struct ast_event *event, void *userdata)
3150 {
3151         struct skinny_line *l = userdata;
3152         struct skinny_device *d = l->device;
3153         struct skinny_line *l2;
3154         int dev_msgs = 0;
3155
3156         if (!d || !d->session) {
3157                 return;
3158         }
3159
3160         if (event) {
3161                 l->newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
3162         }
3163
3164         if (l->newmsgs) {
3165                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
3166         } else {
3167                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
3168         }
3169
3170         /* find out wether the device lamp should be on or off */
3171         AST_LIST_TRAVERSE(&d->lines, l2, list) {
3172                 if (l2->newmsgs) {
3173                         dev_msgs++;
3174                 }
3175         }
3176
3177         if (dev_msgs) {
3178                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
3179         } else {
3180                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
3181         }
3182         ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", l->newmsgs);
3183 }
3184
3185 /* I do not believe skinny can deal with video.
3186    Anyone know differently? */
3187 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
3188 static enum ast_rtp_glue_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
3189 {
3190         struct skinny_subchannel *sub = NULL;
3191
3192         if (!(sub = ast_channel_tech_pvt(c)) || !(sub->vrtp))
3193                 return AST_RTP_GLUE_RESULT_FORBID;
3194
3195         ao2_ref(sub->vrtp, +1);
3196         *instance = sub->vrtp;
3197
3198         return AST_RTP_GLUE_RESULT_REMOTE;
3199 }
3200
3201 static enum ast_rtp_glue_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
3202 {
3203         struct skinny_subchannel *sub = NULL;
3204         struct skinny_line *l;
3205         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE;
3206
3207         SKINNY_DEBUG(DEBUG_AUDIO, 4, "skinny_get_rtp_peer() Channel = %s\n", ast_channel_name(c));
3208
3209         if (!(sub = ast_channel_tech_pvt(c)))
3210                 return AST_RTP_GLUE_RESULT_FORBID;
3211
3212         ast_mutex_lock(&sub->lock);
3213
3214         if (!(sub->rtp)){
3215                 ast_mutex_unlock(&sub->lock);
3216                 return AST_RTP_GLUE_RESULT_FORBID;
3217         }
3218
3219         ao2_ref(sub->rtp, +1);
3220         *instance = sub->rtp;
3221
3222         l = sub->line;
3223
3224         if (!l->directmedia || l->nat){
3225                 res = AST_RTP_GLUE_RESULT_LOCAL;
3226                 SKINNY_DEBUG(DEBUG_AUDIO, 4, "skinny_get_rtp_peer() Using AST_RTP_GLUE_RESULT_LOCAL \n");
3227         }
3228
3229         ast_mutex_unlock(&sub->lock);
3230
3231         return res;
3232
3233 }
3234
3235 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)
3236 {
3237         struct skinny_subchannel *sub;
3238         struct skinny_line *l;
3239         struct skinny_device *d;
3240         struct ast_format_list fmt;
3241         struct sockaddr_in us = { 0, };
3242         struct sockaddr_in them = { 0, };
3243         struct ast_sockaddr them_tmp;
3244         struct ast_sockaddr us_tmp;
3245
3246         sub = ast_channel_tech_pvt(c);
3247
3248         if (ast_channel_state(c) != AST_STATE_UP)
3249                 return 0;
3250
3251         if (!sub) {
3252                 return -1;
3253         }
3254
3255         l = sub->line;
3256         d = l->device;
3257
3258         if (rtp){
3259                 struct ast_format tmpfmt;
3260                 ast_rtp_instance_get_remote_address(rtp, &them_tmp);
3261                 ast_sockaddr_to_sin(&them_tmp, &them);
3262
3263                 /* Shutdown any early-media or previous media on re-invite */
3264                 transmit_stopmediatransmission(d, sub);
3265
3266                 SKINNY_DEBUG(DEBUG_AUDIO, 4, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
3267
3268                 ast_best_codec(l->cap, &tmpfmt);
3269                 fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
3270
3271                 SKINNY_DEBUG(DEBUG_AUDIO, 4, "Setting payloadType to '%s' (%d ms)\n", ast_getformatname(&fmt.format), fmt.cur_ms);
3272
3273                 if (!(l->directmedia) || (l->nat)){
3274                         ast_rtp_instance_get_local_address(rtp, &us_tmp);
3275                         ast_sockaddr_to_sin(&us_tmp, &us);
3276                         us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->ourip.s_addr;
3277                         transmit_startmediatransmission(d, sub, us, fmt);
3278                 } else {
3279                         transmit_startmediatransmission(d, sub, them, fmt);
3280                 }
3281
3282                 return 0;
3283         }
3284         /* Need a return here to break the bridge */
3285         return 0;
3286 }
3287
3288 static struct ast_rtp_glue skinny_rtp_glue = {
3289         .type = "Skinny",
3290         .get_rtp_info = skinny_get_rtp_peer,
3291         .get_vrtp_info = skinny_get_vrtp_peer,
3292         .update_peer = skinny_set_rtp_peer,
3293 };
3294
3295 #ifdef AST_DEVMODE
3296 static char *skinny_debugs(void)
3297 {
3298         char *ptr;
3299         int posn = 0;
3300
3301         ptr = dbgcli_buf;
3302         strncpy(ptr, "\0", 1);
3303         if (skinnydebug & DEBUG_GENERAL) {
3304                 strncpy(ptr, "general ", 8);
3305                 posn += 8;