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