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