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