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