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