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