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