be9668e412c2ef07876617b36de3831912551e29
[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         int curtone;                                    \
1248         ast_group_t callgroup;                          \
1249         ast_group_t pickupgroup;                        \
1250         int callwaiting;                                \
1251         int transfer;                                   \
1252         int threewaycalling;                            \
1253         int mwiblink;                                   \
1254         int cancallforward;                             \
1255         int getforward;                                 \
1256         int callreturn;                                 \
1257         int dnd;                                        \
1258         int hascallerid;                                \
1259         int hidecallerid;                               \
1260         int amaflags;                                   \
1261         int type;                                       \
1262         int instance;                                   \
1263         int group;                                      \
1264         int needdestroy;                                \
1265         struct ast_format_cap *confcap;                         \
1266         struct ast_codec_pref confprefs;                \
1267         struct ast_format_cap *cap;                                     \
1268         struct ast_codec_pref prefs;                    \
1269         int nonCodecCapability;                         \
1270         int onhooktime;                                 \
1271         int msgstate;                                   \
1272         int immediate;                                  \
1273         int nat;                                        \
1274         int directmedia;                                \
1275         int prune;
1276
1277 struct skinny_line {
1278         SKINNY_LINE_OPTIONS
1279         ast_mutex_t lock;
1280         struct ast_event_sub *mwi_event_sub; /* Event based MWI */
1281         struct skinny_subchannel *activesub;
1282         AST_LIST_HEAD(, skinny_subchannel) sub;
1283         AST_LIST_ENTRY(skinny_line) list;
1284         AST_LIST_ENTRY(skinny_line) all;
1285         struct skinny_device *device;
1286         struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1287         int newmsgs;
1288 };
1289
1290 static struct skinny_line_options{
1291         SKINNY_LINE_OPTIONS
1292 } default_line_struct = {
1293         .callwaiting = 1,
1294         .transfer = 1,
1295         .mwiblink = 0,
1296         .dnd = 0,
1297         .hidecallerid = 0,
1298         .amaflags = 0,
1299         .instance = 0,
1300         .directmedia = 0,
1301         .nat = 0,
1302         .getforward = 0,
1303         .needdestroy = 0,
1304         .prune = 0,
1305 };
1306 static struct skinny_line_options *default_line = &default_line_struct;
1307
1308 static AST_LIST_HEAD_STATIC(lines, skinny_line);
1309
1310 struct skinny_speeddial {
1311         ast_mutex_t lock;
1312         char label[42];
1313         char context[AST_MAX_CONTEXT];
1314         char exten[AST_MAX_EXTENSION];
1315         int instance;
1316         int stateid;
1317         int laststate;
1318         int isHint;
1319
1320         AST_LIST_ENTRY(skinny_speeddial) list;
1321         struct skinny_device *parent;
1322 };
1323
1324 struct skinny_addon {
1325         ast_mutex_t lock;
1326         char type[10];
1327         AST_LIST_ENTRY(skinny_addon) list;
1328         struct skinny_device *parent;
1329 };
1330
1331 #define SKINNY_DEVICE_OPTIONS                                   \
1332         char name[80];                                          \
1333         char id[16];                                            \
1334         char version_id[16];                                    \
1335         char vmexten[AST_MAX_EXTENSION];                        \
1336         int type;                                               \
1337         int registered;                                         \
1338         int hookstate;                                  \
1339         int lastlineinstance;                                   \
1340         int lastcallreference;                                  \
1341         struct ast_format_cap *confcap;                                 \
1342         struct ast_codec_pref confprefs;                        \
1343         struct ast_format_cap *cap;                                             \
1344         int earlyrtp;                                           \
1345         int transfer;                                           \
1346         int callwaiting;                                        \
1347         int mwiblink;                                           \
1348         int dnd;                                                \
1349         int prune;
1350
1351 struct skinny_device {
1352         SKINNY_DEVICE_OPTIONS
1353         struct type *first;
1354         struct type *last;
1355         ast_mutex_t lock;
1356         struct sockaddr_in addr;
1357         struct in_addr ourip;
1358         struct ast_ha *ha;
1359         struct skinnysession *session;
1360         struct skinny_line *activeline;
1361         AST_LIST_HEAD(, skinny_line) lines;
1362         AST_LIST_HEAD(, skinny_speeddial) speeddials;
1363         AST_LIST_HEAD(, skinny_addon) addons;
1364         AST_LIST_ENTRY(skinny_device) list;
1365 };
1366
1367 static struct skinny_device_options {
1368         SKINNY_DEVICE_OPTIONS
1369 } default_device_struct = {
1370         .transfer = 1,
1371         .earlyrtp = 1,
1372         .callwaiting = 1,
1373         .mwiblink = 0,
1374         .dnd = 0,
1375         .prune = 0,
1376         .hookstate = SKINNY_ONHOOK,
1377 };
1378 static struct skinny_device_options *default_device = &default_device_struct;
1379         
1380 static AST_LIST_HEAD_STATIC(devices, skinny_device);
1381
1382 struct skinnysession {
1383         pthread_t t;
1384         ast_mutex_t lock;
1385         time_t start;
1386         struct sockaddr_in sin;
1387         int fd;
1388         char inbuf[SKINNY_MAX_PACKET];
1389         char outbuf[SKINNY_MAX_PACKET];
1390         struct skinny_device *device;
1391         AST_LIST_ENTRY(skinnysession) list;
1392 };
1393
1394 static struct ast_channel *skinny_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, void *data, int *cause);
1395 static AST_LIST_HEAD_STATIC(sessions, skinnysession);
1396
1397 static int skinny_devicestate(void *data);
1398 static int skinny_call(struct ast_channel *ast, char *dest, int timeout);
1399 static int skinny_hangup(struct ast_channel *ast);
1400 static int skinny_answer(struct ast_channel *ast);
1401 static struct ast_frame *skinny_read(struct ast_channel *ast);
1402 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1403 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1404 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1405 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1406 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1407 static void mwi_event_cb(const struct ast_event *event, void *userdata);
1408 static int skinny_reload(void);
1409
1410 static void setsubstate(struct skinny_subchannel *sub, int state);
1411 static void dumpsub(struct skinny_subchannel *sub, int forcehangup);
1412 static void activatesub(struct skinny_subchannel *sub, int state);
1413 static void dialandactivatesub(struct skinny_subchannel *sub, char exten[AST_MAX_EXTENSION]);
1414
1415 static struct ast_channel_tech skinny_tech = {
1416         .type = "Skinny",
1417         .description = tdesc,
1418         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1419         .requester = skinny_request,
1420         .devicestate = skinny_devicestate,
1421         .call = skinny_call,
1422         .hangup = skinny_hangup,
1423         .answer = skinny_answer,
1424         .read = skinny_read,
1425         .write = skinny_write,
1426         .indicate = skinny_indicate,
1427         .fixup = skinny_fixup,
1428         .send_digit_begin = skinny_senddigit_begin,
1429         .send_digit_end = skinny_senddigit_end,
1430         .bridge = ast_rtp_instance_bridge, 
1431 };
1432
1433 static int skinny_extensionstate_cb(char *context, char* exten, int state, void *data);
1434 static int skinny_transfer(struct skinny_subchannel *sub);
1435
1436 static struct skinny_line *skinny_line_alloc(void)
1437 {
1438         struct skinny_line *l;
1439         if (!(l = ast_calloc(1, sizeof(*l)))) {
1440                 return NULL;
1441         }
1442
1443         l->cap = ast_format_cap_alloc_nolock();
1444         l->confcap = ast_format_cap_alloc_nolock();
1445         if (!l->cap || !l->confcap) {
1446                 l->cap = ast_format_cap_destroy(l->cap);
1447                 l->confcap = ast_format_cap_destroy(l->confcap);
1448                 ast_free(l);
1449                 return NULL;
1450         }
1451         return l;
1452 }
1453 static struct skinny_line *skinny_line_destroy(struct skinny_line *l)
1454 {
1455         l->cap = ast_format_cap_destroy(l->cap);
1456         l->confcap = ast_format_cap_destroy(l->confcap);
1457         ast_free(l);
1458         return NULL;
1459 }
1460 static struct skinny_device *skinny_device_alloc(void)
1461 {
1462         struct skinny_device *d;
1463         if (!(d = ast_calloc(1, sizeof(*d)))) {
1464                 return NULL;
1465         }
1466
1467         d->cap = ast_format_cap_alloc_nolock();
1468         d->confcap = ast_format_cap_alloc_nolock();
1469         if (!d->cap || !d->confcap) {
1470                 d->cap = ast_format_cap_destroy(d->cap);
1471                 d->confcap = ast_format_cap_destroy(d->confcap);
1472                 ast_free(d);
1473                 return NULL;
1474         }
1475         return d;
1476 }
1477 static struct skinny_device *skinny_device_destroy(struct skinny_device *d)
1478 {
1479         d->cap = ast_format_cap_destroy(d->cap);
1480         d->confcap = ast_format_cap_destroy(d->confcap);
1481         ast_free(d);
1482         return NULL;
1483 }
1484
1485 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1486 {
1487         struct skinny_device *d = s->device;
1488         struct skinny_addon *a;
1489         int i;
1490
1491         switch (d->type) {
1492                 case SKINNY_DEVICE_30SPPLUS:
1493                 case SKINNY_DEVICE_30VIP:
1494                         /* 13 rows, 2 columns */
1495                         for (i = 0; i < 4; i++)
1496                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1497                         (btn++)->buttonDefinition = BT_REDIAL;
1498                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1499                         (btn++)->buttonDefinition = BT_CALLPARK;
1500                         (btn++)->buttonDefinition = BT_FORWARDALL;
1501                         (btn++)->buttonDefinition = BT_CONFERENCE;
1502                         for (i = 0; i < 4; i++)
1503                                 (btn++)->buttonDefinition = BT_NONE;
1504                         for (i = 0; i < 13; i++)
1505                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1506                         
1507                         break;
1508                 case SKINNY_DEVICE_12SPPLUS:
1509                 case SKINNY_DEVICE_12SP:
1510                 case SKINNY_DEVICE_12:
1511                         /* 6 rows, 2 columns */
1512                         for (i = 0; i < 2; i++)
1513                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1514                         for (i = 0; i < 4; i++)
1515                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1516                         (btn++)->buttonDefinition = BT_HOLD;
1517                         (btn++)->buttonDefinition = BT_REDIAL;
1518                         (btn++)->buttonDefinition = BT_TRANSFER;
1519                         (btn++)->buttonDefinition = BT_FORWARDALL;
1520                         (btn++)->buttonDefinition = BT_CALLPARK;
1521                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1522                         break;
1523                 case SKINNY_DEVICE_7910:
1524                         (btn++)->buttonDefinition = BT_LINE;
1525                         (btn++)->buttonDefinition = BT_HOLD;
1526                         (btn++)->buttonDefinition = BT_TRANSFER;
1527                         (btn++)->buttonDefinition = BT_DISPLAY;
1528                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1529                         (btn++)->buttonDefinition = BT_CONFERENCE;
1530                         (btn++)->buttonDefinition = BT_FORWARDALL;
1531                         for (i = 0; i < 2; i++)
1532                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1533                         (btn++)->buttonDefinition = BT_REDIAL;
1534                         break;
1535                 case SKINNY_DEVICE_7960:
1536                 case SKINNY_DEVICE_7961:
1537                 case SKINNY_DEVICE_7961GE:
1538                 case SKINNY_DEVICE_7962:
1539                 case SKINNY_DEVICE_7965:
1540                         for (i = 0; i < 6; i++)
1541                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1542                         break;
1543                 case SKINNY_DEVICE_7940:
1544                 case SKINNY_DEVICE_7941:
1545                 case SKINNY_DEVICE_7941GE:
1546                 case SKINNY_DEVICE_7942:
1547                 case SKINNY_DEVICE_7945:
1548                         for (i = 0; i < 2; i++)
1549                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1550                         break;
1551                 case SKINNY_DEVICE_7935:
1552                 case SKINNY_DEVICE_7936:
1553                         for (i = 0; i < 2; i++)
1554                                 (btn++)->buttonDefinition = BT_LINE;
1555                         break;
1556                 case SKINNY_DEVICE_ATA186:
1557                         (btn++)->buttonDefinition = BT_LINE;
1558                         break;
1559                 case SKINNY_DEVICE_7970:
1560                 case SKINNY_DEVICE_7971:
1561                 case SKINNY_DEVICE_7975:
1562                 case SKINNY_DEVICE_CIPC:
1563                         for (i = 0; i < 8; i++)
1564                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1565                         break;
1566                 case SKINNY_DEVICE_7985:
1567                         /* XXX I have no idea what the buttons look like on these. */
1568                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1569                         break;
1570                 case SKINNY_DEVICE_7912:
1571                 case SKINNY_DEVICE_7911:
1572                 case SKINNY_DEVICE_7905:
1573                         (btn++)->buttonDefinition = BT_LINE;
1574                         (btn++)->buttonDefinition = BT_HOLD;
1575                         break;
1576                 case SKINNY_DEVICE_7920:
1577                         /* XXX I don't know if this is right. */
1578                         for (i = 0; i < 4; i++)
1579                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1580                         break;
1581                 case SKINNY_DEVICE_7921:
1582                         for (i = 0; i < 6; i++)
1583                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1584                         break;
1585                 case SKINNY_DEVICE_7902:
1586                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1587                         break;
1588                 case SKINNY_DEVICE_7906:
1589                         ast_log(LOG_WARNING, "Unsupported device type '%d (7906)' found.\n", d->type);
1590                         break;
1591                 case SKINNY_DEVICE_7931:
1592                         ast_log(LOG_WARNING, "Unsupported device type '%d (7931)' found.\n", d->type);
1593                         break;
1594                 case SKINNY_DEVICE_7937:
1595                         ast_log(LOG_WARNING, "Unsupported device type '%d (7937)' found.\n", d->type);
1596                         break;
1597                 case SKINNY_DEVICE_7914:
1598                         ast_log(LOG_WARNING, "Unsupported device type '%d (7914)' found.  Expansion module registered by itself?\n", d->type);
1599                         break;
1600                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1601                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1602                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1603                         break;
1604                 default:
1605                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1606                         break;
1607         }
1608
1609         AST_LIST_LOCK(&d->addons);
1610         AST_LIST_TRAVERSE(&d->addons, a, list) {
1611                 if (!strcasecmp(a->type, "7914")) {
1612                         for (i = 0; i < 14; i++)
1613                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1614                 } else {
1615                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1616                 }
1617         }
1618         AST_LIST_UNLOCK(&d->addons);
1619
1620         return btn;
1621 }
1622
1623 static struct skinny_req *req_alloc(size_t size, int response_message)
1624 {
1625         struct skinny_req *req;
1626
1627         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1628                 return NULL;
1629
1630         req->len = htolel(size+4);
1631         req->e = htolel(response_message);
1632
1633         return req;
1634 }
1635
1636 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1637 {
1638         struct skinny_line *l;
1639
1640         /*Dialing from on hook or on a 7920 uses instance 0 in requests
1641           but we need to start looking at instance 1 */
1642
1643         if (!instance)
1644                 instance = 1;
1645
1646         AST_LIST_TRAVERSE(&d->lines, l, list){
1647                 if (l->instance == instance)
1648                         break;
1649         }
1650
1651         if (!l) {
1652                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1653         }
1654         return l;
1655 }
1656
1657 static struct skinny_line *find_line_by_name(const char *dest)
1658 {
1659         struct skinny_line *l;
1660         struct skinny_line *tmpl = NULL;
1661         struct skinny_device *d;
1662         char line[256];
1663         char *at;
1664         char *device;
1665         int checkdevice = 0;
1666
1667         ast_copy_string(line, dest, sizeof(line));
1668         at = strchr(line, '@');
1669         if (at)
1670                 *at++ = '\0';
1671         device = at;
1672
1673         if (!ast_strlen_zero(device))
1674                 checkdevice = 1;
1675
1676         AST_LIST_LOCK(&devices);
1677         AST_LIST_TRAVERSE(&devices, d, list){
1678                 if (checkdevice && tmpl)
1679                         break;
1680                 else if (!checkdevice) {
1681                         /* This is a match, since we're checking for line on every device. */
1682                 } else if (!strcasecmp(d->name, device)) {
1683                         if (skinnydebug)
1684                                 ast_verb(2, "Found device: %s\n", d->name);
1685                 } else
1686                         continue;
1687
1688                 /* Found the device (or we don't care which device) */
1689                 AST_LIST_TRAVERSE(&d->lines, l, list){
1690                         /* Search for the right line */
1691                         if (!strcasecmp(l->name, line)) {
1692                                 if (tmpl) {
1693                                         ast_verb(2, "Ambiguous line name: %s\n", line);
1694                                         AST_LIST_UNLOCK(&devices);
1695                                         return NULL;
1696                                 } else
1697                                         tmpl = l;
1698                         }
1699                 }
1700         }
1701         AST_LIST_UNLOCK(&devices);
1702         return tmpl;
1703 }
1704
1705 /*!
1706  * implement the setvar config line
1707  */
1708 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
1709 {
1710         struct ast_variable *tmpvar = NULL;
1711         char *varname = ast_strdupa(buf), *varval = NULL;
1712
1713         if ((varval = strchr(varname,'='))) {
1714                 *varval++ = '\0';
1715                 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
1716                         tmpvar->next = list;
1717                         list = tmpvar;
1718                 }
1719         }
1720         return list;
1721 }
1722
1723 /* It's quicker/easier to find the subchannel when we know the instance number too */
1724 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
1725 {
1726         struct skinny_line *l = find_line_by_instance(d, instance);
1727         struct skinny_subchannel *sub;
1728
1729         if (!l) {
1730                 return NULL;
1731         }
1732
1733         /* 7920 phones set call reference to 0, so use the first
1734            sub-channel on the list.
1735            This MIGHT need more love to be right */
1736         if (!reference)
1737                 sub = AST_LIST_FIRST(&l->sub);
1738         else {
1739                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
1740                         if (sub->callid == reference)
1741                                 break;
1742                 }
1743         }
1744         if (!sub) {
1745                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
1746         }
1747         return sub;
1748 }
1749
1750 /* Find the subchannel when we only have the callid - this shouldn't happen often */
1751 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
1752 {
1753         struct skinny_line *l;
1754         struct skinny_subchannel *sub = NULL;
1755
1756         AST_LIST_TRAVERSE(&d->lines, l, list){
1757                 AST_LIST_TRAVERSE(&l->sub, sub, list){
1758                         if (sub->callid == reference)
1759                                 break;
1760                 }
1761                 if (sub)
1762                         break;
1763         }
1764
1765         if (!l) {
1766                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
1767         } else {
1768                 if (!sub) {
1769                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
1770                 }
1771         }
1772         return sub;
1773 }
1774
1775 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
1776 {
1777         struct skinny_speeddial *sd;
1778
1779         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1780                 if (sd->isHint == isHint && sd->instance == instance)
1781                         break;
1782         }
1783
1784         if (!sd) {
1785                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
1786         }
1787         return sd;
1788 }
1789
1790 static struct ast_format *codec_skinny2ast(enum skinny_codecs skinnycodec, struct ast_format *result)
1791 {
1792         switch (skinnycodec) {
1793         case SKINNY_CODEC_ALAW:
1794                 return ast_format_set(result, AST_FORMAT_ALAW, 0);
1795         case SKINNY_CODEC_ULAW:
1796                 return ast_format_set(result, AST_FORMAT_ULAW, 0);
1797         case SKINNY_CODEC_G723_1:
1798                 return ast_format_set(result, AST_FORMAT_G723_1, 0);
1799         case SKINNY_CODEC_G729A:
1800                 return ast_format_set(result, AST_FORMAT_G729A, 0);
1801         case SKINNY_CODEC_G726_32:
1802                 return ast_format_set(result, AST_FORMAT_G726_AAL2, 0); /* XXX Is this right? */
1803         case SKINNY_CODEC_H261:
1804                 return ast_format_set(result, AST_FORMAT_H261, 0);
1805         case SKINNY_CODEC_H263:
1806                 return ast_format_set(result, AST_FORMAT_H263 ,0);
1807         default:
1808                 ast_format_clear(result);
1809                 return result;
1810         }
1811 }
1812
1813 static int codec_ast2skinny(const struct ast_format *astcodec)
1814 {
1815         switch (astcodec->id) {
1816         case AST_FORMAT_ALAW:
1817                 return SKINNY_CODEC_ALAW;
1818         case AST_FORMAT_ULAW:
1819                 return SKINNY_CODEC_ULAW;
1820         case AST_FORMAT_G723_1:
1821                 return SKINNY_CODEC_G723_1;
1822         case AST_FORMAT_G729A:
1823                 return SKINNY_CODEC_G729A;
1824         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
1825                 return SKINNY_CODEC_G726_32;
1826         case AST_FORMAT_H261:
1827                 return SKINNY_CODEC_H261;
1828         case AST_FORMAT_H263:
1829                 return SKINNY_CODEC_H263;
1830         default:
1831                 return 0;
1832         }
1833 }
1834
1835 static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
1836 {
1837         if (!l)
1838                 return 0;
1839
1840         if (!ast_strlen_zero(cfwd)) {
1841                 if (cfwdtype & SKINNY_CFWD_ALL) {
1842                         l->cfwdtype |= SKINNY_CFWD_ALL;
1843                         ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
1844                 }
1845                 if (cfwdtype & SKINNY_CFWD_BUSY) {
1846                         l->cfwdtype |= SKINNY_CFWD_BUSY;
1847                         ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
1848                 }
1849                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
1850                         l->cfwdtype |= SKINNY_CFWD_NOANSWER;
1851                         ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
1852                 }
1853         } else {
1854                 if (cfwdtype & SKINNY_CFWD_ALL) {
1855                         l->cfwdtype &= ~SKINNY_CFWD_ALL;
1856                         memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
1857                 }
1858                 if (cfwdtype & SKINNY_CFWD_BUSY) {
1859                         l->cfwdtype &= ~SKINNY_CFWD_BUSY;
1860                         memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
1861                 }
1862                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
1863                         l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
1864                         memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
1865                 }
1866         }
1867         return l->cfwdtype;
1868 }
1869
1870 static void cleanup_stale_contexts(char *new, char *old)
1871 {
1872         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
1873
1874         while ((oldcontext = strsep(&old, "&"))) {
1875                 stalecontext = '\0';
1876                 ast_copy_string(newlist, new, sizeof(newlist));
1877                 stringp = newlist;
1878                 while ((newcontext = strsep(&stringp, "&"))) {
1879                         if (strcmp(newcontext, oldcontext) == 0) {
1880                                 /* This is not the context you're looking for */
1881                                 stalecontext = '\0';
1882                                 break;
1883                         } else if (strcmp(newcontext, oldcontext)) {
1884                                 stalecontext = oldcontext;
1885                         }
1886                         
1887                 }
1888                 if (stalecontext)
1889                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
1890         }
1891 }
1892
1893 static void register_exten(struct skinny_line *l)
1894 {
1895         char multi[256];
1896         char *stringp, *ext, *context;
1897
1898         if (ast_strlen_zero(regcontext))
1899                 return;
1900
1901         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1902         stringp = multi;
1903         while ((ext = strsep(&stringp, "&"))) {
1904                 if ((context = strchr(ext, '@'))) {
1905                         *context++ = '\0'; /* split ext@context */
1906                         if (!ast_context_find(context)) {
1907                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1908                                 continue;
1909                         }
1910                 } else {
1911                         context = regcontext;
1912                 }
1913                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
1914                          ast_strdup(l->name), ast_free_ptr, "Skinny");
1915         }
1916 }
1917
1918 static void unregister_exten(struct skinny_line *l)
1919 {
1920         char multi[256];
1921         char *stringp, *ext, *context;
1922
1923         if (ast_strlen_zero(regcontext))
1924                 return;
1925
1926         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1927         stringp = multi;
1928         while ((ext = strsep(&stringp, "&"))) {
1929                 if ((context = strchr(ext, '@'))) {
1930                         *context++ = '\0'; /* split ext@context */
1931                         if (!ast_context_find(context)) {
1932                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1933                                 continue;
1934                         }
1935                 } else {
1936                         context = regcontext;
1937                 }
1938                 ast_context_remove_extension(context, ext, 1, NULL);
1939         }
1940 }
1941
1942 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
1943 {
1944         struct skinny_device *d;
1945         struct skinny_line *l;
1946         struct skinny_speeddial *sd;
1947         struct sockaddr_in sin;
1948         socklen_t slen;
1949         int instance;
1950
1951         AST_LIST_LOCK(&devices);
1952         AST_LIST_TRAVERSE(&devices, d, list){
1953                 struct ast_sockaddr addr;
1954                 ast_sockaddr_from_sin(&addr, &s->sin);
1955                 if (!strcasecmp(req->data.reg.name, d->id)
1956                                 && ast_apply_ha(d->ha, &addr)) {
1957                         s->device = d;
1958                         d->type = letohl(req->data.reg.type);
1959                         if (ast_strlen_zero(d->version_id)) {
1960                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
1961                         }
1962                         d->registered = 1;
1963                         d->session = s;
1964
1965                         slen = sizeof(sin);
1966                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
1967                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
1968                                 sin.sin_addr = __ourip;
1969                         }
1970                         d->ourip = sin.sin_addr;
1971
1972                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1973                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd);
1974                         }
1975                         instance = 0;
1976                         AST_LIST_TRAVERSE(&d->lines, l, list) {
1977                                 instance++;
1978                         }
1979                         AST_LIST_TRAVERSE(&d->lines, l, list) {
1980                                 /* FIXME: All sorts of issues will occur if this line is already connected to a device */
1981                                 if (l->device) {
1982                                         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); 
1983                                         ast_verb(1, "Line %s already connected to %s. Not connecting to %s.\n", l->name, l->device->name, d->name);
1984                                 } else {
1985                                         l->device = d;
1986                                         ast_format_cap_joint_copy(l->confcap, d->cap, l->cap);
1987                                         l->prefs = l->confprefs;
1988                                         if (!l->prefs.order[0]) {
1989                                                 l->prefs = d->confprefs;
1990                                         }
1991                                         /* l->capability = d->capability;
1992                                         l->prefs = d->prefs; */
1993                                         l->instance = instance;
1994                                         l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
1995                                         set_callforwards(l, NULL, 0);
1996                                         manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Registered\r\n", l->name, d->name);
1997                                         register_exten(l);
1998                                         /* initialize MWI on line and device */
1999                                         mwi_event_cb(0, l);
2000                                         ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s", l->name);
2001                                 }
2002                                 --instance;
2003                         }
2004                         break;
2005                 }
2006         }
2007         AST_LIST_UNLOCK(&devices);
2008         if (!d) {
2009                 return 0;
2010         }
2011         return 1;
2012 }
2013
2014 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
2015 {
2016         struct skinny_device *d;
2017         struct skinny_line *l;
2018         struct skinny_speeddial *sd;
2019
2020         d = s->device;
2021
2022         if (d) {
2023                 d->session = NULL;
2024                 d->registered = 0;
2025
2026                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2027                         if (sd->stateid > -1)
2028                                 ast_extension_state_del(sd->stateid, NULL);
2029                 }
2030                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2031                         if (l->device == d) {
2032                                 l->device = NULL;
2033                                 ast_format_cap_remove_all(l->cap);
2034                                 ast_parse_allow_disallow(&l->prefs, l->cap, "all", 0);
2035                                 l->instance = 0;
2036                                 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: Skinny\r\nPeer: Skinny/%s@%s\r\nPeerStatus: Unregistered\r\n", l->name, d->name);
2037                                 unregister_exten(l);
2038                                 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "Skinny/%s", l->name);
2039                         }
2040                 }
2041         }
2042
2043         return -1; /* main loop will destroy the session */
2044 }
2045
2046 #ifdef SKINNY_DEVMODE
2047 static char *message2str(int type)
2048 {
2049         char *tmp;
2050
2051         switch (letohl(type)) {
2052         case KEEP_ALIVE_MESSAGE:
2053                 return "KEEP_ALIVE_MESSAGE";
2054         case REGISTER_MESSAGE:
2055                 return "REGISTER_MESSAGE";
2056         case IP_PORT_MESSAGE:
2057                 return "IP_PORT_MESSAGE";
2058         case KEYPAD_BUTTON_MESSAGE:
2059                 return "KEYPAD_BUTTON_MESSAGE";
2060         case ENBLOC_CALL_MESSAGE:
2061                 return "ENBLOC_CALL_MESSAGE";
2062         case STIMULUS_MESSAGE:
2063                 return "STIMULUS_MESSAGE";
2064         case OFFHOOK_MESSAGE:
2065                 return "OFFHOOK_MESSAGE";
2066         case ONHOOK_MESSAGE:
2067                 return "ONHOOK_MESSAGE";
2068         case CAPABILITIES_RES_MESSAGE:
2069                 return "CAPABILITIES_RES_MESSAGE";
2070         case SPEED_DIAL_STAT_REQ_MESSAGE:
2071                 return "SPEED_DIAL_STAT_REQ_MESSAGE";
2072         case LINE_STATE_REQ_MESSAGE:
2073                 return "LINE_STATE_REQ_MESSAGE";
2074         case TIME_DATE_REQ_MESSAGE:
2075                 return "TIME_DATE_REQ_MESSAGE";
2076         case BUTTON_TEMPLATE_REQ_MESSAGE:
2077                 return "BUTTON_TEMPLATE_REQ_MESSAGE";
2078         case VERSION_REQ_MESSAGE:
2079                 return "VERSION_REQ_MESSAGE";
2080         case SERVER_REQUEST_MESSAGE:
2081                 return "SERVER_REQUEST_MESSAGE";
2082         case ALARM_MESSAGE:
2083                 return "ALARM_MESSAGE";
2084         case OPEN_RECEIVE_CHANNEL_ACK_MESSAGE:
2085                 return "OPEN_RECEIVE_CHANNEL_ACK_MESSAGE";
2086         case SOFT_KEY_SET_REQ_MESSAGE:
2087                 return "SOFT_KEY_SET_REQ_MESSAGE";
2088         case SOFT_KEY_EVENT_MESSAGE:
2089                 return "SOFT_KEY_EVENT_MESSAGE";
2090         case UNREGISTER_MESSAGE:
2091                 return "UNREGISTER_MESSAGE";
2092         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
2093                 return "SOFT_KEY_TEMPLATE_REQ_MESSAGE";
2094         case HEADSET_STATUS_MESSAGE:
2095                 return "HEADSET_STATUS_MESSAGE";
2096         case REGISTER_AVAILABLE_LINES_MESSAGE:
2097                 return "REGISTER_AVAILABLE_LINES_MESSAGE";
2098         case REGISTER_ACK_MESSAGE:
2099                 return "REGISTER_ACK_MESSAGE";
2100         case START_TONE_MESSAGE:
2101                 return "START_TONE_MESSAGE";
2102         case STOP_TONE_MESSAGE:
2103                 return "STOP_TONE_MESSAGE";
2104         case SET_RINGER_MESSAGE:
2105                 return "SET_RINGER_MESSAGE";
2106         case SET_LAMP_MESSAGE:
2107                 return "SET_LAMP_MESSAGE";
2108         case SET_SPEAKER_MESSAGE:
2109                 return "SET_SPEAKER_MESSAGE";
2110         case SET_MICROPHONE_MESSAGE:
2111                 return "SET_MICROPHONE_MESSAGE";
2112         case START_MEDIA_TRANSMISSION_MESSAGE:
2113                 return "START_MEDIA_TRANSMISSION_MESSAGE";
2114         case STOP_MEDIA_TRANSMISSION_MESSAGE:
2115                 return "STOP_MEDIA_TRANSMISSION_MESSAGE";
2116         case CALL_INFO_MESSAGE:
2117                 return "CALL_INFO_MESSAGE";
2118         case FORWARD_STAT_MESSAGE:
2119                 return "FORWARD_STAT_MESSAGE";
2120         case SPEED_DIAL_STAT_RES_MESSAGE:
2121                 return "SPEED_DIAL_STAT_RES_MESSAGE";
2122         case LINE_STAT_RES_MESSAGE:
2123                 return "LINE_STAT_RES_MESSAGE";
2124         case DEFINETIMEDATE_MESSAGE:
2125                 return "DEFINETIMEDATE_MESSAGE";
2126         case BUTTON_TEMPLATE_RES_MESSAGE:
2127                 return "BUTTON_TEMPLATE_RES_MESSAGE";
2128         case VERSION_RES_MESSAGE:
2129                 return "VERSION_RES_MESSAGE";
2130         case DISPLAYTEXT_MESSAGE:
2131                 return "DISPLAYTEXT_MESSAGE";
2132         case CLEAR_NOTIFY_MESSAGE:
2133                 return "CLEAR_NOTIFY_MESSAGE";
2134         case CLEAR_DISPLAY_MESSAGE:
2135                 return "CLEAR_DISPLAY_MESSAGE";
2136         case CAPABILITIES_REQ_MESSAGE:
2137                 return "CAPABILITIES_REQ_MESSAGE";
2138         case REGISTER_REJ_MESSAGE:
2139                 return "REGISTER_REJ_MESSAGE";
2140         case SERVER_RES_MESSAGE:
2141                 return "SERVER_RES_MESSAGE";
2142         case RESET_MESSAGE:
2143                 return "RESET_MESSAGE";
2144         case KEEP_ALIVE_ACK_MESSAGE:
2145                 return "KEEP_ALIVE_ACK_MESSAGE";
2146         case OPEN_RECEIVE_CHANNEL_MESSAGE:
2147                 return "OPEN_RECEIVE_CHANNEL_MESSAGE";
2148         case CLOSE_RECEIVE_CHANNEL_MESSAGE:
2149                 return "CLOSE_RECEIVE_CHANNEL_MESSAGE";
2150         case SOFT_KEY_TEMPLATE_RES_MESSAGE:
2151                 return "SOFT_KEY_TEMPLATE_RES_MESSAGE";
2152         case SOFT_KEY_SET_RES_MESSAGE:
2153                 return "SOFT_KEY_SET_RES_MESSAGE";
2154         case SELECT_SOFT_KEYS_MESSAGE:
2155                 return "SELECT_SOFT_KEYS_MESSAGE";
2156         case CALL_STATE_MESSAGE:
2157                 return "CALL_STATE_MESSAGE";
2158         case DISPLAY_PROMPT_STATUS_MESSAGE:
2159                 return "DISPLAY_PROMPT_STATUS_MESSAGE";
2160         case CLEAR_PROMPT_MESSAGE:
2161                 return "CLEAR_PROMPT_MESSAGE";
2162         case DISPLAY_NOTIFY_MESSAGE:
2163                 return "DISPLAY_NOTIFY_MESSAGE";
2164         case ACTIVATE_CALL_PLANE_MESSAGE:
2165                 return "ACTIVATE_CALL_PLANE_MESSAGE";
2166         case DIALED_NUMBER_MESSAGE:
2167                 return "DIALED_NUMBER_MESSAGE";
2168         default:
2169                 if (!(tmp = ast_threadstorage_get(&message2str_threadbuf, MESSAGE2STR_BUFSIZE)))
2170                         return "Unknown";
2171                 snprintf(tmp, MESSAGE2STR_BUFSIZE, "UNKNOWN_MESSAGE-%d", type);
2172                 return tmp;
2173         }
2174 }
2175 #endif
2176
2177 static int transmit_response_bysession(struct skinnysession *s, struct skinny_req *req)
2178 {
2179         int res = 0;
2180
2181         if (!s) {
2182                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2183                 return -1;
2184         }
2185
2186         ast_mutex_lock(&s->lock);
2187
2188         SKINNY_DEVONLY(if (skinnydebug>1) ast_verb(4, "Transmitting %s to %s\n", message2str(req->e), s->device->name);)
2189
2190         if ((letohl(req->len) > SKINNY_MAX_PACKET) || (letohl(req->len) < 0)) {
2191                 ast_log(LOG_WARNING, "transmit_response: the length of the request (%d) is out of bounds (%d)\n", letohl(req->len), SKINNY_MAX_PACKET);
2192                 ast_mutex_unlock(&s->lock);
2193                 return -1;
2194         }
2195
2196         memset(s->outbuf, 0, sizeof(s->outbuf));
2197         memcpy(s->outbuf, req, skinny_header_size);
2198         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2199
2200         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2201         
2202         if (res != letohl(req->len)+8) {
2203                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2204                 if (res == -1) {
2205                         if (skinnydebug)
2206                                 ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2207                         skinny_unregister(NULL, s);
2208                 }
2209                 
2210         }
2211         
2212         ast_free(req);
2213         ast_mutex_unlock(&s->lock);
2214         return 1;
2215 }
2216
2217 static void transmit_response(struct skinny_device *d, struct skinny_req *req)
2218 {
2219         transmit_response_bysession(d->session, req);
2220 }
2221
2222 static void transmit_registerrej(struct skinnysession *s)
2223 {
2224         struct skinny_req *req;
2225         char name[16];
2226
2227         if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
2228                 return;
2229
2230         memcpy(&name, req->data.reg.name, sizeof(name));
2231         snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2232
2233         transmit_response_bysession(s, req);
2234 }       
2235
2236 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2237 {
2238         struct skinny_req *req;
2239
2240         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2241                 return;
2242
2243         req->data.setspeaker.mode = htolel(mode);
2244         transmit_response(d, req);
2245 }
2246 /*
2247 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2248 {
2249         struct skinny_req *req;
2250
2251         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2252                 return;
2253
2254         req->data.setmicrophone.mode = htolel(mode);
2255         transmit_response(d, req);
2256 }
2257 */
2258
2259 static void transmit_callinfo(struct skinny_subchannel *sub)
2260 {
2261         struct skinny_device *d;
2262         struct skinny_line *l;
2263         struct skinny_req *req;
2264         struct ast_channel *ast;
2265         char *fromname;
2266         char *fromnum;
2267         char *toname;
2268         char *tonum;
2269
2270         if (!sub || !(l=sub->line) || !(d=l->device) || !(ast=sub->owner)) {
2271                 return;
2272         }
2273
2274         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2275                 return;
2276
2277         if (sub->calldirection == SKINNY_INCOMING) {
2278                 fromname = S_COR(ast->connected.id.name.valid, ast->connected.id.name.str, "");
2279                 fromnum = S_COR(ast->connected.id.number.valid, ast->connected.id.number.str, "");
2280                 toname = S_COR(ast->caller.id.name.valid, ast->caller.id.name.str, "");
2281                 tonum = S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, "");
2282         } else if (sub->calldirection == SKINNY_OUTGOING) {
2283                 fromname = S_COR(ast->caller.id.name.valid, ast->caller.id.name.str, "");
2284                 fromnum = S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, "");
2285                 toname = S_COR(ast->connected.id.name.valid, ast->connected.id.name.str, l->lastnumberdialed);
2286                 tonum = S_COR(ast->connected.id.number.valid, ast->connected.id.number.str, l->lastnumberdialed);
2287         } else {
2288                 ast_verb(1, "Error sending Callinfo to %s(%d) - No call direction in sub\n", d->name, l->instance);
2289                 return;
2290         }
2291
2292         if (skinnydebug) {
2293                 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);
2294         }
2295         
2296         ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2297         ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2298         ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2299         ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2300         req->data.callinfo.instance = htolel(l->instance);
2301         req->data.callinfo.reference = htolel(sub->callid);
2302         req->data.callinfo.type = htolel(sub->calldirection);
2303         transmit_response(d, req);
2304 }
2305
2306 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2307 {
2308         struct skinny_req *req;
2309         struct skinny_line *l = sub->line;
2310         struct ast_format_list fmt;
2311         struct ast_format tmpfmt;
2312
2313         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2314                 return;
2315         ast_best_codec(l->cap, &tmpfmt);
2316         fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
2317
2318         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2319         req->data.openreceivechannel.partyId = htolel(sub->callid);
2320         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2321         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(&fmt.format));
2322         req->data.openreceivechannel.echo = htolel(0);
2323         req->data.openreceivechannel.bitrate = htolel(0);
2324         transmit_response(d, req);
2325 }
2326
2327 static void transmit_start_tone(struct skinny_device *d, int tone, int instance, int reference)
2328 {
2329         struct skinny_req *req;
2330         if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2331                 return;
2332         req->data.starttone.tone = htolel(tone);
2333         req->data.starttone.instance = htolel(instance);
2334         req->data.starttone.reference = htolel(reference);
2335         transmit_response(d, req);
2336 }
2337
2338 static void transmit_stop_tone(struct skinny_device *d, int instance, int reference)
2339 {
2340         struct skinny_req *req;
2341         if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2342                 return;
2343         req->data.stoptone.instance = htolel(instance);
2344         req->data.stoptone.reference = htolel(reference);
2345         transmit_response(d, req);
2346 }
2347
2348 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey)
2349 {
2350         struct skinny_req *req;
2351
2352         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2353                 return;
2354
2355         req->data.selectsoftkey.instance = htolel(instance);
2356         req->data.selectsoftkey.reference = htolel(callid);
2357         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2358         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
2359         transmit_response(d, req);
2360 }
2361
2362 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2363 {
2364         struct skinny_req *req;
2365
2366         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2367                 return;
2368
2369         req->data.setlamp.stimulus = htolel(stimulus);
2370         req->data.setlamp.stimulusInstance = htolel(instance);
2371         req->data.setlamp.deviceStimulus = htolel(indication);
2372         transmit_response(d, req);
2373 }
2374
2375 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2376 {
2377         struct skinny_req *req;
2378
2379         if (skinnydebug)
2380                 ast_verb(1, "Setting ringer mode to '%d'.\n", mode);
2381
2382         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2383                 return;
2384
2385         req->data.setringer.ringerMode = htolel(mode);
2386         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2387            Note: The phone will always show as ringing on the display.
2388
2389            1: phone will audibly ring over and over
2390            2: phone will audibly ring only once
2391            any other value, will NOT cause the phone to audibly ring
2392         */
2393         req->data.setringer.unknown1 = htolel(1);
2394         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2395            Perhaps a packet capture can shed some light on this. */
2396         req->data.setringer.unknown2 = htolel(1);
2397         transmit_response(d, req);
2398 }
2399
2400 static void transmit_clear_display_message(struct skinny_device *d, int instance, int reference)
2401 {
2402         struct skinny_req *req;
2403         if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
2404                 return;
2405
2406         //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2407         //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2408         //req->data.clearpromptstatus.lineInstance = instance;
2409         //req->data.clearpromptstatus.callReference = reference;
2410
2411         if (skinnydebug)
2412                 ast_verb(1, "Clearing Display\n");
2413         transmit_response(d, req);
2414 }
2415
2416 /* This function is not currently used, but will be (wedhorn)*/
2417 /* static void transmit_display_message(struct skinny_device *d, const char *text, int instance, int reference)
2418 {
2419         struct skinny_req *req;
2420
2421         if (text == 0) {
2422                 ast_verb(1, "Bug, Asked to display empty message\n");
2423                 return;
2424         }
2425
2426         if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2427                 return;
2428
2429         ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2430         if (skinnydebug)
2431                 ast_verb(1, "Displaying message '%s'\n", req->data.displaytext.text);
2432         transmit_response(d, req);
2433 } */
2434
2435 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2436 {
2437         struct skinny_req *req;
2438
2439         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2440                 return;
2441
2442         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2443         req->data.displaynotify.displayTimeout = htolel(t);
2444
2445         if (skinnydebug)
2446                 ast_verb(1, "Displaying notify '%s'\n", text);
2447
2448         transmit_response(d, req);
2449 }
2450
2451 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
2452 {
2453         struct skinny_req *req;
2454
2455         if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2456                 return;
2457
2458         ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2459         req->data.displaypromptstatus.messageTimeout = htolel(t);
2460         req->data.displaypromptstatus.lineInstance = htolel(instance);
2461         req->data.displaypromptstatus.callReference = htolel(callid);
2462
2463         if (skinnydebug)
2464                 ast_verb(1, "Displaying Prompt Status '%s'\n", text);
2465
2466         transmit_response(d, req);
2467 }
2468
2469 static void transmit_clearpromptmessage(struct skinny_device *d, int instance, int callid)
2470 {
2471         struct skinny_req *req;
2472
2473         if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2474                 return;
2475
2476         req->data.clearpromptstatus.lineInstance = htolel(instance);
2477         req->data.clearpromptstatus.callReference = htolel(callid);
2478
2479         if (skinnydebug)
2480                 ast_verb(1, "Clearing Prompt\n");
2481
2482         transmit_response(d, req);
2483 }
2484
2485 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2486 {
2487         struct skinny_req *req;
2488
2489         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2490                 return;
2491
2492         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2493         req->data.dialednumber.lineInstance = htolel(instance);
2494         req->data.dialednumber.callReference = htolel(callid);
2495
2496         transmit_response(d, req);
2497 }
2498
2499 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2500 {
2501         struct skinny_req *req;
2502
2503         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2504                 return;
2505
2506         req->data.closereceivechannel.conferenceId = htolel(0);
2507         req->data.closereceivechannel.partyId = htolel(sub->callid);
2508         transmit_response(d, req);
2509 }
2510
2511 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2512 {
2513         struct skinny_req *req;
2514
2515         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2516                 return;
2517
2518         req->data.stopmedia.conferenceId = htolel(0);
2519         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2520         transmit_response(d, req);
2521 }
2522
2523 static void transmit_startmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub, struct sockaddr_in dest, struct ast_format_list fmt)
2524 {
2525         struct skinny_req *req;
2526
2527         if (!(req = req_alloc(sizeof(struct start_media_transmission_message), START_MEDIA_TRANSMISSION_MESSAGE)))
2528                 return;
2529
2530         req->data.startmedia.conferenceId = htolel(sub->callid);
2531         req->data.startmedia.passThruPartyId = htolel(sub->callid);
2532         req->data.startmedia.remoteIp = dest.sin_addr.s_addr;
2533         req->data.startmedia.remotePort = htolel(ntohs(dest.sin_port));
2534         req->data.startmedia.packetSize = htolel(fmt.cur_ms);
2535         req->data.startmedia.payloadType = htolel(codec_ast2skinny(&fmt.format));
2536         req->data.startmedia.qualifier.precedence = htolel(127);
2537         req->data.startmedia.qualifier.vad = htolel(0);
2538         req->data.startmedia.qualifier.packets = htolel(0);
2539         req->data.startmedia.qualifier.bitRate = htolel(0);
2540         transmit_response(d, req);
2541 }
2542
2543 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
2544 {
2545         struct skinny_req *req;
2546
2547         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2548                 return;
2549
2550         req->data.activatecallplane.lineInstance = htolel(l->instance);
2551         transmit_response(d, req);
2552 }
2553
2554 static void transmit_callstate(struct skinny_device *d, int buttonInstance, unsigned callid, int state)
2555 {
2556         struct skinny_req *req;
2557
2558         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2559                 return;
2560
2561         req->data.callstate.callState = htolel(state);
2562         req->data.callstate.lineInstance = htolel(buttonInstance);
2563         req->data.callstate.callReference = htolel(callid);
2564         transmit_response(d, req);
2565 }
2566
2567 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
2568 {
2569         struct skinny_req *req;
2570         int anyon = 0;
2571
2572         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
2573                 return;
2574
2575         if (l->cfwdtype & SKINNY_CFWD_ALL) {
2576                 if (!ast_strlen_zero(l->call_forward_all)) {
2577                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
2578                         req->data.forwardstat.fwdall = htolel(1);
2579                         anyon++;
2580                 } else {
2581                         req->data.forwardstat.fwdall = htolel(0);
2582                 }
2583         }
2584         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
2585                 if (!ast_strlen_zero(l->call_forward_busy)) {
2586                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
2587                         req->data.forwardstat.fwdbusy = htolel(1);
2588                         anyon++;
2589                 } else {
2590                         req->data.forwardstat.fwdbusy = htolel(0);
2591                 }
2592         }
2593         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
2594                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
2595                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
2596                         req->data.forwardstat.fwdnoanswer = htolel(1);
2597                         anyon++;
2598                 } else {
2599                         req->data.forwardstat.fwdnoanswer = htolel(0);
2600                 }
2601         }
2602         req->data.forwardstat.lineNumber = htolel(l->instance);
2603         if (anyon)
2604                 req->data.forwardstat.activeforward = htolel(7);
2605         else
2606                 req->data.forwardstat.activeforward = htolel(0);
2607
2608         transmit_response(d, req);
2609 }
2610
2611 static void transmit_speeddialstatres(struct skinny_device *d, struct skinny_speeddial *sd)
2612 {
2613         struct skinny_req *req;
2614
2615         if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
2616                 return;
2617
2618         req->data.speeddialreq.speedDialNumber = htolel(sd->instance);
2619         ast_copy_string(req->data.speeddial.speedDialDirNumber, sd->exten, sizeof(req->data.speeddial.speedDialDirNumber));
2620         ast_copy_string(req->data.speeddial.speedDialDisplayName, sd->label, sizeof(req->data.speeddial.speedDialDisplayName));
2621
2622         transmit_response(d, req);
2623 }
2624
2625 //static void transmit_linestatres(struct skinny_device *d, struct skinny_line *l)
2626 static void transmit_linestatres(struct skinny_device *d, int instance)
2627 {
2628         struct skinny_req *req;
2629         struct skinny_line *l;
2630         struct skinny_speeddial *sd;
2631
2632         if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
2633                 return;
2634
2635         if ((l = find_line_by_instance(d, instance))) {
2636                 req->data.linestat.lineNumber = letohl(l->instance);
2637                 memcpy(req->data.linestat.lineDirNumber, l->name, sizeof(req->data.linestat.lineDirNumber));
2638                 memcpy(req->data.linestat.lineDisplayName, l->label, sizeof(req->data.linestat.lineDisplayName));
2639         } else if ((sd = find_speeddial_by_instance(d, instance, 1))) {
2640                 req->data.linestat.lineNumber = letohl(sd->instance);
2641                 memcpy(req->data.linestat.lineDirNumber, sd->label, sizeof(req->data.linestat.lineDirNumber));
2642                 memcpy(req->data.linestat.lineDisplayName, sd->label, sizeof(req->data.linestat.lineDisplayName));
2643         }
2644         transmit_response(d, req);
2645 }
2646
2647 static void transmit_definetimedate(struct skinny_device *d)
2648 {
2649         struct skinny_req *req;
2650         struct timeval now = ast_tvnow();
2651         struct ast_tm cmtime;
2652
2653         if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
2654                 return;
2655
2656         ast_localtime(&now, &cmtime, NULL);
2657         req->data.definetimedate.year = htolel(cmtime.tm_year+1900);
2658         req->data.definetimedate.month = htolel(cmtime.tm_mon+1);
2659         req->data.definetimedate.dayofweek = htolel(cmtime.tm_wday);
2660         req->data.definetimedate.day = htolel(cmtime.tm_mday);
2661         req->data.definetimedate.hour = htolel(cmtime.tm_hour);
2662         req->data.definetimedate.minute = htolel(cmtime.tm_min);
2663         req->data.definetimedate.seconds = htolel(cmtime.tm_sec);
2664         req->data.definetimedate.milliseconds = htolel(cmtime.tm_usec / 1000);
2665         req->data.definetimedate.timestamp = htolel(now.tv_sec);
2666         transmit_response(d, req);
2667 }
2668
2669 static void transmit_versionres(struct skinny_device *d)
2670 {
2671         struct skinny_req *req;
2672         if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
2673                 return;
2674
2675         ast_copy_string(req->data.version.version, d->version_id, sizeof(req->data.version.version));
2676         transmit_response(d, req);
2677 }
2678
2679 static void transmit_serverres(struct skinny_device *d)
2680 {
2681         struct skinny_req *req;
2682         if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
2683                 return;
2684
2685         memcpy(req->data.serverres.server[0].serverName, ourhost,
2686                         sizeof(req->data.serverres.server[0].serverName));
2687         req->data.serverres.serverListenPort[0] = htolel(ourport);
2688         req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
2689         transmit_response(d, req);
2690 }
2691
2692 static void transmit_softkeysetres(struct skinny_device *d)
2693 {
2694         struct skinny_req *req;
2695         int i;
2696         int x;
2697         int y;
2698         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
2699
2700         if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
2701                 return;
2702
2703         req->data.softkeysets.softKeySetOffset = htolel(0);
2704         req->data.softkeysets.softKeySetCount = htolel(11);
2705         req->data.softkeysets.totalSoftKeySetCount = htolel(11);
2706         for (x = 0; x < sizeof(soft_key_default_definitions) / sizeof(struct soft_key_definitions); x++) {
2707                 const uint8_t *defaults = softkeymode->defaults;
2708                 /* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
2709                    This will have to do for now. */
2710                 for (y = 0; y < softkeymode->count; y++) {
2711                         for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
2712                                 if (defaults[y] == i+1) {
2713                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = (i+1);
2714                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyInfoIndex[y] = htoles(i+301);
2715                                         if (skinnydebug)        
2716                                                 ast_verbose("softKeySetDefinition : softKeyTemplateIndex: %d softKeyInfoIndex: %d\n", i+1, i+301);
2717                                 }
2718                         }
2719                 }
2720                 softkeymode++;
2721         }
2722         transmit_response(d, req);
2723 }
2724
2725 static void transmit_softkeytemplateres(struct skinny_device *d)
2726 {
2727         struct skinny_req *req;
2728         if (!(req = req_alloc(sizeof(struct soft_key_template_res_message), SOFT_KEY_TEMPLATE_RES_MESSAGE)))
2729                 return;
2730
2731         req->data.softkeytemplate.softKeyOffset = htolel(0);
2732         req->data.softkeytemplate.softKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
2733         req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
2734         memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
2735                 soft_key_template_default,
2736                 sizeof(soft_key_template_default));
2737         transmit_response(d, req);
2738 }
2739
2740 static void transmit_reset(struct skinny_device *d, int fullrestart)
2741 {
2742         struct skinny_req *req;
2743   
2744         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
2745                 return;
2746   
2747         if (fullrestart)
2748                 req->data.reset.resetType = 2;
2749         else
2750                 req->data.reset.resetType = 1;
2751
2752         ast_verb(3, "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
2753         transmit_response(d, req);
2754 }
2755
2756 static void transmit_keepaliveack(struct skinny_device *d)
2757 {
2758         struct skinny_req *req;
2759
2760         if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
2761                 return;
2762
2763         transmit_response(d, req);
2764 }
2765
2766 static void transmit_registerack(struct skinny_device *d)
2767 {
2768         struct skinny_req *req;
2769
2770         if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
2771                 return;
2772
2773         req->data.regack.res[0] = '0';
2774         req->data.regack.res[1] = '\0';
2775         req->data.regack.keepAlive = htolel(keep_alive);
2776         memcpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate));
2777         req->data.regack.res2[0] = '0';
2778         req->data.regack.res2[1] = '\0';
2779         req->data.regack.secondaryKeepAlive = htolel(keep_alive);
2780
2781         transmit_response(d, req);
2782 }
2783
2784 static void transmit_capabilitiesreq(struct skinny_device *d)
2785 {
2786         struct skinny_req *req;
2787
2788         if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
2789                 return;
2790
2791         if (skinnydebug)
2792                 ast_verb(1, "Requesting capabilities\n");
2793
2794         transmit_response(d, req);
2795 }
2796
2797 static int skinny_extensionstate_cb(char *context, char *exten, int state, void *data)
2798 {
2799         struct skinny_speeddial *sd = data;
2800         struct skinny_device *d = sd->parent;
2801         char hint[AST_MAX_EXTENSION];
2802
2803         if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
2804                 /* If they are not registered, we will override notification and show no availability */
2805                 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
2806                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_FLASH);
2807                         transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
2808                         return 0;
2809                 }
2810                 switch (state) {
2811                 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
2812                 case AST_EXTENSION_REMOVED:     /* Extension is gone */
2813                         ast_verb(2, "Extension state: Watcher for hint %s %s. Notify Device %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
2814                         sd->stateid = -1;
2815                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
2816                         transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
2817                         break;
2818                 case AST_EXTENSION_RINGING:
2819                 case AST_EXTENSION_UNAVAILABLE:
2820                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_BLINK);
2821                         transmit_callstate(d, sd->instance, 0, SKINNY_RINGIN);
2822                         break;
2823                 case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
2824                 case AST_EXTENSION_INUSE:
2825                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_ON);
2826                         transmit_callstate(d, sd->instance, 0, SKINNY_CALLREMOTEMULTILINE);
2827                         break;
2828                 case AST_EXTENSION_ONHOLD:
2829                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_WINK);
2830                         transmit_callstate(d, sd->instance, 0, SKINNY_HOLD);
2831                         break;
2832                 case AST_EXTENSION_NOT_INUSE:
2833                 default:
2834                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
2835                         transmit_callstate(d, sd->instance, 0, SKINNY_ONHOOK);
2836                         break;
2837                 }
2838         }
2839
2840         sd->laststate = state;
2841
2842         return 0;
2843 }
2844
2845 static void update_connectedline(struct skinny_subchannel *sub, const void *data, size_t datalen)
2846 {
2847         struct ast_channel *c = sub->owner;
2848         struct skinny_line *l = sub->line;
2849         struct skinny_device *d = l->device;
2850
2851         if (!c->caller.id.number.valid
2852                 || ast_strlen_zero(c->caller.id.number.str)
2853                 || !c->connected.id.number.valid
2854                 || ast_strlen_zero(c->connected.id.number.str))
2855                 return;
2856
2857         if (skinnydebug) {
2858                 ast_verb(3,"Sub %d - Updating\n", sub->callid);
2859         }
2860         
2861         transmit_callinfo(sub);
2862         if (sub->owner->_state == AST_STATE_UP) {
2863                 transmit_callstate(d, l->instance, sub->callid, SKINNY_CONNECTED);
2864                 transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
2865         } else {
2866                 if (sub->calldirection == SKINNY_INCOMING) {
2867                         transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGIN);
2868                         transmit_displaypromptstatus(d, "Ring-In", 0, l->instance, sub->callid);
2869                 } else {
2870                         if (!sub->ringing) {
2871                                 transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGOUT);
2872                                 transmit_displaypromptstatus(d, "Ring-Out", 0, l->instance, sub->callid);
2873                                 sub->ringing = 1;
2874                         } else {
2875                                 transmit_callstate(d, l->instance, sub->callid, SKINNY_PROGRESS);
2876                                 transmit_displaypromptstatus(d, "Call Progress", 0, l->instance, sub->callid);
2877                                 sub->progress = 1;
2878                         }
2879                 }
2880         }
2881 }
2882
2883 static void mwi_event_cb(const struct ast_event *event, void *userdata)
2884 {
2885         struct skinny_line *l = userdata;
2886         struct skinny_device *d = l->device;
2887         if (d) {
2888                 struct skinnysession *s = d->session;
2889                 struct skinny_line *l2;
2890                 int new_msgs = 0;
2891                 int dev_msgs = 0;
2892
2893                 if (s) {
2894                         if (event) {
2895                                 l->newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
2896                         }
2897
2898                         if (l->newmsgs) {
2899                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2900                         } else {
2901                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
2902                         }
2903
2904                         /* find out wether the device lamp should be on or off */
2905                         AST_LIST_TRAVERSE(&d->lines, l2, list) {
2906                                 if (l2->newmsgs) {
2907                                         dev_msgs++;
2908                                 }
2909                         }
2910
2911                         if (dev_msgs) {
2912                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2913                         } else {
2914                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
2915                         }
2916                         ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", new_msgs);
2917                 }
2918         }
2919 }
2920
2921 /* I do not believe skinny can deal with video.
2922    Anyone know differently? */
2923 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
2924 static enum ast_rtp_glue_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
2925 {
2926         struct skinny_subchannel *sub = NULL;
2927
2928         if (!(sub = c->tech_pvt) || !(sub->vrtp))
2929                 return AST_RTP_GLUE_RESULT_FORBID;
2930
2931         ao2_ref(sub->vrtp, +1);
2932         *instance = sub->vrtp;
2933
2934         return AST_RTP_GLUE_RESULT_REMOTE;
2935 }
2936
2937 static enum ast_rtp_glue_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
2938 {
2939         struct skinny_subchannel *sub = NULL;
2940         struct skinny_line *l;
2941         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE;
2942
2943         if (skinnydebug)
2944                 ast_verb(1, "skinny_get_rtp_peer() Channel = %s\n", c->name);
2945
2946
2947         if (!(sub = c->tech_pvt))
2948                 return AST_RTP_GLUE_RESULT_FORBID;
2949
2950         ast_mutex_lock(&sub->lock);
2951
2952         if (!(sub->rtp)){
2953                 ast_mutex_unlock(&sub->lock);
2954                 return AST_RTP_GLUE_RESULT_FORBID;
2955         }
2956
2957         ao2_ref(sub->rtp, +1);
2958         *instance = sub->rtp;
2959
2960         l = sub->line;
2961
2962         if (!l->directmedia || l->nat){
2963                 res = AST_RTP_GLUE_RESULT_LOCAL;
2964                 if (skinnydebug)
2965                         ast_verb(1, "skinny_get_rtp_peer() Using AST_RTP_GLUE_RESULT_LOCAL \n");
2966         }
2967
2968         ast_mutex_unlock(&sub->lock);
2969
2970         return res;
2971
2972 }
2973
2974 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)
2975 {
2976         struct skinny_subchannel *sub;
2977         struct skinny_line *l;
2978         struct skinny_device *d;
2979         struct ast_format_list fmt;
2980         struct sockaddr_in us = { 0, };
2981         struct sockaddr_in them = { 0, };
2982         struct ast_sockaddr them_tmp;
2983         struct ast_sockaddr us_tmp;
2984         
2985         sub = c->tech_pvt;
2986
2987         if (c->_state != AST_STATE_UP)
2988                 return 0;
2989
2990         if (!sub) {
2991                 return -1;
2992         }
2993
2994         l = sub->line;
2995         d = l->device;
2996
2997         if (rtp){
2998                 struct ast_format tmpfmt;
2999                 ast_rtp_instance_get_remote_address(rtp, &them_tmp);
3000                 ast_sockaddr_to_sin(&them_tmp, &them);
3001
3002                 /* Shutdown any early-media or previous media on re-invite */
3003                 transmit_stopmediatransmission(d, sub);
3004                 
3005                 if (skinnydebug)
3006                         ast_verb(1, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
3007
3008                 ast_best_codec(l->cap, &tmpfmt);
3009                 fmt = ast_codec_pref_getsize(&l->prefs, &tmpfmt);
3010
3011                 if (skinnydebug)
3012                         ast_verb(1, "Setting payloadType to '%s' (%d ms)\n", ast_getformatname(&fmt.format), fmt.cur_ms);
3013
3014                 if (!(l->directmedia) || (l->nat)){
3015                         ast_rtp_instance_get_local_address(rtp, &us_tmp);
3016                         ast_sockaddr_to_sin(&us_tmp, &us);
3017                         us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->ourip.s_addr;
3018                         transmit_startmediatransmission(d, sub, us, fmt);
3019                 } else {
3020                         transmit_startmediatransmission(d, sub, them, fmt);
3021                 }
3022
3023                 return 0;
3024         }
3025         /* Need a return here to break the bridge */
3026         return 0;
3027 }
3028
3029 static struct ast_rtp_glue skinny_rtp_glue = {
3030         .type = "Skinny",
3031         .get_rtp_info = skinny_get_rtp_peer,
3032         .get_vrtp_info = skinny_get_vrtp_peer,
3033         .update_peer = skinny_set_rtp_peer,
3034 };
3035
3036 static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3037 {
3038         switch (cmd) {
3039         case CLI_INIT:
3040 #ifdef SKINNY_DEVMODE
3041                 e->command = "skinny set debug {off|on|packet}";
3042                 e->usage =
3043                         "Usage: skinny set debug {off|on|packet}\n"
3044                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
3045 #else
3046                 e->command = "skinny set debug {off|on}";
3047                 e->usage =
3048                         "Usage: skinny set debug {off|on}\n"
3049                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
3050 #endif
3051                 return NULL;
3052         case CLI_GENERATE:
3053                 return NULL;
3054         }
3055         
3056         if (a->argc != e->args)
3057                 return CLI_SHOWUSAGE;
3058
3059         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
3060                 skinnydebug = 1;
3061                 ast_cli(a->fd, "Skinny Debugging Enabled\n");
3062                 return CLI_SUCCESS;
3063         } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
3064                 skinnydebug = 0;
3065                 ast_cli(a->fd, "Skinny Debugging Disabled\n");
3066                 return CLI_SUCCESS;
3067 #ifdef SKINNY_DEVMODE
3068         } else if (!strncasecmp(a->argv[e->args - 1], "packet", 6)) {
3069                 skinnydebug = 2;
3070                 ast_cli(a->fd, "Skinny Debugging Enabled including Packets\n");
3071                 return CLI_SUCCESS;
3072 #endif
3073         } else {
3074                 return CLI_SHOWUSAGE;
3075         }
3076 }
3077
3078 static char *handle_skinny_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3079 {
3080         switch (cmd) {
3081         case CLI_INIT:
3082                 e->command = "skinny reload";
3083                 e->usage =
3084                         "Usage: skinny reload\n"
3085                         "       Reloads the chan_skinny configuration\n";
3086                 return NULL;
3087         case CLI_GENERATE:
3088                 return NULL;
3089         }
3090         
3091         if (a->argc != e->args)
3092                 return CLI_SHOWUSAGE;
3093
3094         skinny_reload();
3095         return CLI_SUCCESS;
3096
3097 }
3098
3099 static char *complete_skinny_devices(const char *word, int state)
3100 {
3101         struct skinny_device *d;
3102         char *result = NULL;
3103         int wordlen = strlen(word), which = 0;
3104
3105         AST_LIST_TRAVERSE(&devices, d, list) {
3106                 if (!strncasecmp(word, d->id, wordlen) && ++which > state)
3107                         result = ast_strdup(d->id);
3108         }
3109
3110         return result;
3111 }
3112
3113 static char *complete_skinny_show_device(const char *line, const char *word, int pos, int state)
3114 {
3115         return (pos == 3 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
3116 }
3117
3118 static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
3119 {
3120         return (pos == 2 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
3121 }
3122
3123 static char *complete_skinny_show_line(const char *line, const char *word, int pos, int state)
3124 {
3125         struct skinny_device *d;
3126         struct skinny_line *l;
3127         char *result = NULL;
3128         int wordlen = strlen(word), which = 0;
3129
3130         if (pos != 3)
3131                 return NULL;
3132         
3133         AST_LIST_TRAVERSE(&devices, d, list) {
3134                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3135                         if (!strncasecmp(word, l->name, wordlen) && ++which > state)
3136                                 result = ast_strdup(l->name);
3137                 }
3138         }
3139
3140         return result;
3141 }
3142
3143 static char *handle_skinny_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3144 {
3145         struct skinny_device *d;
3146
3147         switch (cmd) {
3148         case CLI_INIT:
3149                 e->command = "skinny reset";
3150                 e->usage =
3151                         "Usage: skinny reset <DeviceId|DeviceName|all> [restart]\n"
3152                         "       Causes a Skinny device to reset itself, optionally with a full restart\n";
3153                 return NULL;
3154         case CLI_GENERATE:
3155                 return complete_skinny_reset(a->line, a->word, a->pos, a->n);
3156         }
3157
3158         if (a->argc < 3 || a->argc > 4)
3159                 return CLI_SHOWUSAGE;
3160
3161         AST_LIST_LOCK(&devices);
3162         AST_LIST_TRAVERSE(&devices, d, list) {
3163                 int fullrestart = 0;
3164                 if (!strcasecmp(a->argv[2], d->id) || !strcasecmp(a->argv[2], d->name) || !strcasecmp(a->argv[2], "all")) {
3165                         if (!(d->session))
3166                                 continue;
3167
3168                         if (a->argc == 4 && !strcasecmp(a->argv[3], "restart"))
3169                                 fullrestart = 1;
3170                         
3171                         transmit_reset(d, fullrestart);
3172                 }
3173         }
3174         AST_LIST_UNLOCK(&devices);
3175         return CLI_SUCCESS;
3176 }
3177
3178 static char *device2str(int type)
3179 {
3180         char *tmp;
3181
3182         switch (type) {
3183         case SKINNY_DEVICE_NONE:
3184                 return "No Device";
3185         case SKINNY_DEVICE_30SPPLUS:
3186                 return "30SP Plus";
3187         case SKINNY_DEVICE_12SPPLUS:
3188                 return "12SP Plus";
3189         case SKINNY_DEVICE_12SP:
3190                 return "12SP";
3191         case SKINNY_DEVICE_12:
3192                 return "12";
3193         case SKINNY_DEVICE_30VIP:
3194                 return "30VIP";
3195         case SKINNY_DEVICE_7910:
3196                 return "7910";
3197         case SKINNY_DEVICE_7960:
3198                 return "7960";
3199         case SKINNY_DEVICE_7940:
3200                 return "7940";
3201         case SKINNY_DEVICE_7935:
3202                 return "7935";
3203         case SKINNY_DEVICE_ATA186:
3204                 return "ATA186";
3205         case SKINNY_DEVICE_7941:
3206                 return "7941";
3207         case SKINNY_DEVICE_7971:
3208                 return "7971";
3209         case SKINNY_DEVICE_7914:
3210                 return "7914";
3211         case SKINNY_DEVICE_7985:
3212                 return "7985";
3213         case SKINNY_DEVICE_7911:
3214                 return "7911";
3215         case SKINNY_DEVICE_7961GE:
3216                 return "7961GE";
3217         case SKINNY_DEVICE_7941GE:
3218                 return "7941GE";
3219         case SKINNY_DEVICE_7931:
3220                 return "7931";
3221         case SKINNY_DEVICE_7921:
3222                 return "7921";
3223         case SKINNY_DEVICE_7906:
3224                 return "7906";
3225         case SKINNY_DEVICE_7962:
3226                 return "7962";
3227         case SKINNY_DEVICE_7937:
3228                 return "7937";
3229         case SKINNY_DEVICE_7942:
3230                 return "7942";
3231         case SKINNY_DEVICE_7945:
3232                 return "7945";
3233         case SKINNY_DEVICE_7965:
3234                 return "7965";
3235         case SKINNY_DEVICE_7975:
3236                 return "7975";
3237         case SKINNY_DEVICE_7905:
3238                 return "7905";
3239         case SKINNY_DEVICE_7920:
3240                 return "7920";
3241         case SKINNY_DEVICE_7970:
3242                 return "7970";
3243         case SKINNY_DEVICE_7912:
3244                 return "7912";
3245         case SKINNY_DEVICE_7902:
3246                 return "7902";
3247         case SKINNY_DEVICE_CIPC:
3248                 return "IP Communicator";
3249         case SKINNY_DEVICE_7961:
3250                 return "7961";
3251         case SKINNY_DEVICE_7936:
3252                 return "7936";
3253         case SKINNY_DEVICE_SCCPGATEWAY_AN:
3254                 return "SCCPGATEWAY_AN";
3255         case SKINNY_DEVICE_SCCPGATEWAY_BRI:
3256                 return "SCCPGATEWAY_BRI";
3257         case SKINNY_DEVICE_UNKNOWN:
3258                 return "Unknown";
3259         default:
3260                 if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
3261                         return "Unknown";
3262                 snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
3263                 return tmp;
3264         }
3265 }
3266
3267 /*! \brief Print codec list from preference to CLI/manager */
3268 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
3269 {
3270         int x;
3271         struct ast_format tmpfmt;
3272
3273         for(x = 0; x < 32 ; x++) {
3274                 ast_codec_pref_index(pref, x, &tmpfmt);
3275                 if (!tmpfmt.id)
3276                         break;
3277                 ast_cli(fd, "%s", ast_getformatname(&tmpfmt));
3278                 ast_cli(fd, ":%d", pref->framing[x]);
3279                 if (x < 31 && ast_codec_pref_index(pref, x + 1, &tmpfmt))
3280                         ast_cli(fd, ",");
3281         }
3282         if (!x)
3283                 ast_cli(fd, "none");
3284 }
3285
3286 static char *_skinny_show_devices(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
3287 {
3288         struct skinny_device *d;
3289         struct skinny_line *l;
3290         const char *id;
3291         char idtext[256] = "";
3292         int total_devices = 0;
3293
3294         if (s) {        /* Manager - get ActionID */
3295                 id = astman_get_header(m, "ActionID");
3296                 if (!ast_strlen_zero(id))
3297                         snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3298         }
3299
3300         switch (argc) {
3301         case 3:
3302                 break;
3303         default:
3304                 return CLI_SHOWUSAGE;
3305         }
3306
3307         if (!s) {
3308                 ast_cli(fd, "Name                 DeviceId         IP              Type            R NL\n");
3309                 ast_cli(fd, "-------------------- ---------------- --------------- --------------- - --\n");
3310         }
3311
3312         AST_LIST_LOCK(&devices);
3313         AST_LIST_TRAVERSE(&devices, d, list) {
3314                 int numlines = 0;
3315                 total_devices++;
3316                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3317                         numlines++;
3318                 }
3319                 if (!s) {
3320                         ast_cli(fd, "%-20s %-16s %-15s %-15s %c %2d\n",
3321                                 d->name,
3322                                 d->id,
3323                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
3324                                 device2str(d->type),
3325                                 d->registered?'Y':'N',
3326                                 numlines);
3327                 } else {
3328                         astman_append(s,
3329                                 "Event: DeviceEntry\r\n%s"
3330                                 "Channeltype: SKINNY\r\n"
3331                                 "ObjectName: %s\r\n"
3332                                 "ChannelObjectType: device\r\n"
3333                                 "DeviceId: %s\r\n"
3334                                 "IPaddress: %s\r\n"
3335                                 "Type: %s\r\n"
3336                                 "Devicestatus: %s\r\n"
3337                                 "NumberOfLines: %d\r\n",
3338                                 idtext,
3339                                 d->name,
3340                                 d->id,
3341                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"-none-",
3342                                 device2str(d->type),
3343                                 d->registered?"registered":"unregistered",
3344                                 numlines);
3345                 }
3346         }
3347         AST_LIST_UNLOCK(&devices);
3348
3349         if (total)
3350                 *total = total_devices;
3351         
3352         return CLI_SUCCESS;
3353 }
3354
3355 /*! \brief  Show SKINNY devices in the manager API */
3356 /*    Inspired from chan_sip */
3357 static int manager_skinny_show_devices(struct mansession *s, const struct message *m)
3358 {
3359         const char *id = astman_get_header(m, "ActionID");
3360         const char *a[] = {"skinny", "show", "devices"};
3361         char idtext[256] = "";
3362         int total = 0;
3363
3364         if (!ast_strlen_zero(id))
3365                 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3366
3367         astman_send_listack(s, m, "Device status list will follow", "start");
3368         /* List the devices in separate manager events */
3369         _skinny_show_devices(-1, &total, s, m, 3, a);
3370         /* Send final confirmation */
3371         astman_append(s,
3372         "Event: DevicelistComplete\r\n"
3373         "EventList: Complete\r\n"
3374         "ListItems: %d\r\n"
3375         "%s"
3376         "\r\n", total, idtext);
3377         return 0;
3378 }
3379
3380 static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3381 {
3382
3383         switch (cmd) {
3384         case CLI_INIT:
3385                 e->command = "skinny show devices";
3386                 e->usage =
3387                         "Usage: skinny show devices\n"
3388                         "       Lists all devices known to the Skinny subsystem.\n";
3389                 return NULL;
3390         case CLI_GENERATE:
3391                 return NULL;
3392         }
3393
3394         return _skinny_show_devices(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
3395 }
3396
3397 static char *_skinny_show_device(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
3398 {
3399         struct skinny_device *d;
3400         struct skinny_line *l;
3401         struct skinny_speeddial *sd;
3402         struct skinny_addon *sa;
3403         char codec_buf[512];
3404
3405         if (argc < 4) {
3406                 return CLI_SHOWUSAGE;
3407         }
3408
3409         AST_LIST_LOCK(&devices);
3410         AST_LIST_TRAVERSE(&devices, d, list) {
3411                 if (!strcasecmp(argv[3], d->id) || !strcasecmp(argv[3], d->name)) {
3412                         int numlines = 0, numaddons = 0, numspeeddials = 0;
3413
3414                         AST_LIST_TRAVERSE(&d->lines, l, list){
3415                                 numlines++;
3416                         }
3417
3418                         AST_LIST_TRAVERSE(&d->addons, sa, list) {
3419                                 numaddons++;
3420                         }
3421
3422                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3423                                 numspeeddials++;
3424                         }
3425
3426                         if (type == 0) { /* CLI */
3427                                 ast_cli(fd, "Name:        %s\n", d->name);
3428                                 ast_cli(fd, "Id:          %s\n", d->id);
3429                                 ast_cli(fd, "version:     %s\n", S_OR(d->version_id, "Unknown"));
3430                                 ast_cli(fd, "Ip address:  %s\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
3431                                 ast_cli(fd, "Port:        %d\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
3432                                 ast_cli(fd, "Device Type: %s\n", device2str(d->type));
3433                                 ast_cli(fd, "Conf Codecs:");
3434                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->confcap);
3435                                 ast_cli(fd, "%s\n", codec_buf);
3436                                 ast_cli(fd, "Neg Codecs: ");
3437                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->cap);
3438                                 ast_cli(fd, "%s\n", codec_buf);
3439                                 ast_cli(fd, "Registered:  %s\n", (d->registered ? "Yes" : "No"));
3440                                 ast_cli(fd, "Lines:       %d\n", numlines);
3441                                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3442                                         ast_cli(fd, "  %s (%s)\n", l->name, l->label);
3443                                 }
3444                                 AST_LIST_TRAVERSE(&d->addons, sa, list) {
3445                                         numaddons++;
3446                                 }       
3447                                 ast_cli(fd, "Addons:      %d\n", numaddons);
3448                                 AST_LIST_TRAVERSE(&d->addons, sa, list) {
3449                                         ast_cli(fd, "  %s\n", sa->type);
3450                                 }
3451                                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3452                                         numspeeddials++;
3453                                 }
3454                                 ast_cli(fd, "Speeddials:  %d\n", numspeeddials);
3455                                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3456                                         ast_cli(fd, "  %s (%s) ishint: %d\n", sd->exten, sd->label, sd->isHint);
3457                                 }
3458                         } else { /* manager */
3459                                 astman_append(s, "Channeltype: SKINNY\r\n");
3460                                 astman_append(s, "ObjectName: %s\r\n", d->name);
3461                                 astman_append(s, "ChannelObjectType: device\r\n");
3462                                 astman_append(s, "Id: %s\r\n", d->id);
3463                                 astman_append(s, "version: %s\r\n", S_OR(d->version_id, "Unknown"));
3464                                 astman_append(s, "Ipaddress: %s\r\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
3465                                 astman_append(s, "Port: %d\r\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
3466                                 astman_append(s, "DeviceType: %s\r\n", device2str(d->type));
3467                                 astman_append(s, "Codecs: ");
3468                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, d->confcap);
3469                                 astman_append(s, "%s\r\n", codec_buf);
3470                                 astman_append(s, "CodecOrder: ");
3471                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, d->cap);
3472                                 astman_append(s, "%s\r\n", codec_buf);
3473                                 astman_append(s, "Devicestatus: %s\r\n", (d->registered?"registered":"unregistered"));
3474                                 astman_append(s, "NumberOfLines: %d\r\n", numlines);
3475                                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3476                                         astman_append(s, "Line: %s (%s)\r\n", l->name, l->label);
3477                                 }
3478                                 astman_append(s, "NumberOfAddons: %d\r\n", numaddons);
3479                                 AST_LIST_TRAVERSE(&d->addons, sa, list) {
3480                                         astman_append(s, "Addon: %s\r\n", sa->type);
3481                                 }
3482                                 astman_append(s, "NumberOfSpeeddials: %d\r\n", numspeeddials);
3483                                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3484                                         astman_append(s, "Speeddial: %s (%s) ishint: %d\r\n", sd->exten, sd->label, sd->isHint);
3485                                 }
3486                         }
3487                 }
3488         }
3489         AST_LIST_UNLOCK(&devices);
3490         return CLI_SUCCESS;
3491 }
3492
3493 static int manager_skinny_show_device(struct mansession *s, const struct message *m)
3494 {
3495         const char *a[4];
3496         const char *device;
3497
3498         device = astman_get_header(m, "Device");
3499         if (ast_strlen_zero(device)) {
3500                 astman_send_error(s, m, "Device: <name> missing.");
3501                 return 0;
3502         }
3503         a[0] = "skinny";
3504         a[1] = "show";
3505         a[2] = "device";
3506         a[3] = device;
3507
3508         _skinny_show_device(1, -1, s, m, 4, a);
3509         astman_append(s, "\r\n\r\n" );
3510         return 0;
3511 }
3512
3513 /*! \brief Show device information */
3514 static char *handle_skinny_show_device(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3515 {
3516         switch (cmd) {
3517         case CLI_INIT:
3518                 e->command = "skinny show device";
3519                 e->usage =
3520                         "Usage: skinny show device <DeviceId|DeviceName>\n"
3521                         "       Lists all deviceinformation of a specific device known to the Skinny subsystem.\n";
3522                 return NULL;
3523         case CLI_GENERATE:
3524                 return complete_skinny_show_device(a->line, a->word, a->pos, a->n);
3525         }
3526
3527         return _skinny_show_device(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
3528 }
3529
3530 static char *_skinny_show_lines(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
3531 {
3532         struct skinny_line *l;
3533         struct skinny_subchannel *sub;
3534         int total_lines = 0;
3535         int verbose = 0;
3536         const char *id;
3537         char idtext[256] = "";
3538
3539         if (s) {        /* Manager - get ActionID */
3540                 id = astman_get_header(m, "ActionID");
3541                 if (!ast_strlen_zero(id))
3542                         snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3543         }
3544
3545         switch (argc) {
3546         case 4:
3547                 verbose = 1;
3548                 break;
3549         case 3:
3550                 verbose = 0;
3551                 break;
3552         default:
3553                 return CLI_SHOWUSAGE;
3554         }
3555
3556         if (!s) {
3557                 ast_cli(fd, "Name                 Device Name          Instance Label               \n");
3558                 ast_cli(fd, "-------------------- -------------------- -------- --------------------\n");
3559         }
3560         AST_LIST_LOCK(&lines);
3561         AST_LIST_TRAVERSE(&lines, l, all) {
3562                 total_lines++;
3563                 if (!s) {
3564                         ast_cli(fd, "%-20s %-20s %8d %-20s\n",
3565                                 l->name,
3566                                 (l->device ? l->device->name : "Not connected"),
3567                                 l->instance,
3568                                 l->label);
3569                         if (verbose) {
3570                                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
3571                                         ast_cli(fd, "  %s> %s to %s\n",
3572                                                 (sub == l->activesub?"Active  ":"Inactive"),
3573                                                 sub->owner->name,
3574                                                 (ast_bridged_channel(sub->owner)?ast_bridged_channel(sub->owner)->name:"")
3575                                         );
3576                                 }
3577                         }
3578                 } else {
3579                         astman_append(s,
3580                                 "Event: LineEntry\r\n%s"
3581                                 "Channeltype: SKINNY\r\n"
3582                                 "ObjectName: %s\r\n"
3583                                 "ChannelObjectType: line\r\n"
3584                                 "Device: %s\r\n"
3585                                 "Instance: %d\r\n"
3586                                 "Label: %s\r\n",
3587                                 idtext,
3588                                 l->name,
3589                                 (l->device?l->device->name:"None"),
3590                                 l->instance,
3591                                 l->label);
3592                 }
3593         }
3594         AST_LIST_UNLOCK(&lines);
3595
3596         if (total) {
3597                 *total = total_lines;
3598         }
3599
3600         return CLI_SUCCESS;
3601 }
3602
3603 /*! \brief  Show Skinny lines in the manager API */
3604 /*    Inspired from chan_sip */
3605 static int manager_skinny_show_lines(struct mansession *s, const struct message *m)
3606 {
3607         const char *id = astman_get_header(m, "ActionID");
3608         const char *a[] = {"skinny", "show", "lines"};
3609         char idtext[256] = "";
3610         int total = 0;
3611
3612         if (!ast_strlen_zero(id))
3613                 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3614
3615         astman_send_listack(s, m, "Line status list will follow", "start");
3616         /* List the lines in separate manager events */
3617         _skinny_show_lines(-1, &total, s, m, 3, a);
3618         /* Send final confirmation */
3619         astman_append(s,
3620         "Event: LinelistComplete\r\n"
3621         "EventList: Complete\r\n"
3622         "ListItems: %d\r\n"
3623         "%s"
3624         "\r\n", total, idtext);
3625         return 0;
3626 }
3627
3628 static char *handle_skinny_show_lines(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3629 {
3630         switch (cmd) {
3631         case CLI_INIT:
3632                 e->command = "skinny show lines [verbose]";
3633                 e->usage =
3634                         "Usage: skinny show lines\n"
3635                         "       Lists all lines known to the Skinny subsystem.\n"
3636                         "       If 'verbose' is specified, the output includes\n"
3637                         "       information about subs for each line.\n";
3638                 return NULL;
3639         case CLI_GENERATE:
3640                 return NULL;
3641         }
3642
3643         if (a->argc == e->args) {
3644                 if (strcasecmp(a->argv[e->args-1], "verbose")) {
3645                         return CLI_SHOWUSAGE;
3646                 }
3647         } else if (a->argc != e->args - 1) {
3648                 return CLI_SHOWUSAGE;
3649         }
3650
3651         return _skinny_show_lines(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
3652 }
3653
3654 static char *_skinny_show_line(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
3655 {
3656         struct skinny_device *d;
3657         struct skinny_line *l;
3658         struct ast_codec_pref *pref;
3659         int x = 0;
3660         char codec_buf[512];
3661         char group_buf[256];
3662         char cbuf[256];
3663
3664         switch (argc) {
3665         case 4:
3666                 break;
3667         case 6:
3668                 break;
3669         default:
3670                 return CLI_SHOWUSAGE;
3671         }
3672
3673         AST_LIST_LOCK(&devices);
3674
3675         /* Show all lines matching the one supplied */
3676         AST_LIST_TRAVERSE(&devices, d, list) {
3677                 if (argc == 6 && (strcasecmp(argv[5], d->id) && strcasecmp(argv[5], d->name))) {
3678                         continue;
3679                 }
3680                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3681                         if (strcasecmp(argv[3], l->name)) {
3682                                 continue;
3683                         }
3684                         if (type == 0) { /* CLI */
3685                                 ast_cli(fd, "Line:             %s\n", l->name);
3686                                 ast_cli(fd, "On Device:        %s\n", d->name);
3687                                 ast_cli(fd, "Line Label:       %s\n", l->label);
3688                                 ast_cli(fd, "Extension:        %s\n", S_OR(l->exten, "<not set>"));
3689                                 ast_cli(fd, "Context:          %s\n", l->context);
3690                                 ast_cli(fd, "CallGroup:        %s\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
3691                                 ast_cli(fd, "PickupGroup:      %s\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
3692                                 ast_cli(fd, "Language:         %s\n", S_OR(l->language, "<not set>"));
3693                                 ast_cli(fd, "Accountcode:      %s\n", S_OR(l->accountcode, "<not set>"));
3694                                 ast_cli(fd, "AmaFlag:          %s\n", ast_cdr_flags2str(l->amaflags));
3695                                 ast_cli(fd, "CallerId Number:  %s\n", S_OR(l->cid_num, "<not set>"));
3696                                 ast_cli(fd, "CallerId Name:    %s\n", S_OR(l->cid_name, "<not set>"));
3697                                 ast_cli(fd, "Hide CallerId:    %s\n", (l->hidecallerid ? "Yes" : "No"));
3698                                 ast_cli(fd, "CFwdAll:          %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
3699                                 ast_cli(fd, "CFwdBusy:         %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
3700                                 ast_cli(fd, "CFwdNoAnswer:     %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
3701                                 ast_cli(fd, "VoicemailBox:     %s\n", S_OR(l->mailbox, "<not set>"));
3702                                 ast_cli(fd, "VoicemailNumber:  %s\n", S_OR(l->vmexten, "<not set>"));
3703                                 ast_cli(fd, "MWIblink:         %d\n", l->mwiblink);
3704                                 ast_cli(fd, "Regextension:     %s\n", S_OR(l->regexten, "<not set>"));
3705                                 ast_cli(fd, "Regcontext:       %s\n", S_OR(l->regcontext, "<not set>"));
3706                                 ast_cli(fd, "MoHInterpret:     %s\n", S_OR(l->mohinterpret, "<not set>"));
3707                                 ast_cli(fd, "MoHSuggest:       %s\n", S_OR(l->mohsuggest, "<not set>"));
3708                                 ast_cli(fd, "Last dialed nr:   %s\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
3709                                 ast_cli(fd, "Last CallerID:    %s\n", S_OR(l->lastcallerid, "<not set>"));
3710                                 ast_cli(fd, "Transfer enabled: %s\n", (l->transfer ? "Yes" : "No"));
3711                                 ast_cli(fd, "Callwaiting:      %s\n", (l->callwaiting ? "Yes" : "No"));
3712                                 ast_cli(fd, "3Way Calling:     %s\n", (l->threewaycalling ? "Yes" : "No"));
3713                                 ast_cli(fd, "Can forward:      %s\n", (l->cancallforward ? "Yes" : "No"));
3714                                 ast_cli(fd, "Do Not Disturb:   %s\n", (l->dnd ? "Yes" : "No"));
3715                                 ast_cli(fd, "NAT:              %s\n", (l->nat ? "Yes" : "No"));
3716                                 ast_cli(fd, "immediate:        %s\n", (l->immediate ? "Yes" : "No"));
3717                                 ast_cli(fd, "Group:            %d\n", l->group);
3718                                 ast_cli(fd, "Parkinglot:       %s\n", S_OR(l->parkinglot, "<not set>"));
3719                                 ast_cli(fd, "Conf Codecs:      ");
3720                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->confcap);
3721                                 ast_cli(fd, "%s\n", codec_buf);
3722                                 ast_cli(fd, "Neg Codecs:       ");
3723                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->cap);
3724                                 ast_cli(fd, "%s\n", codec_buf);
3725                                 ast_cli(fd, "Codec Order:      (");
3726                                 print_codec_to_cli(fd, &l->prefs);
3727                                 ast_cli(fd, ")\n");
3728                                 ast_cli(fd, "\n");
3729                         } else { /* manager */
3730                                 astman_append(s, "Channeltype: SKINNY\r\n");
3731                                 astman_append(s, "ObjectName: %s\r\n", l->name);
3732                                 astman_append(s, "ChannelObjectType: line\r\n");
3733                                 astman_append(s, "Device: %s\r\n", d->name);
3734                                 astman_append(s, "LineLabel: %s\r\n", l->label);
3735                                 astman_append(s, "Extension: %s\r\n", S_OR(l->exten, "<not set>"));
3736                                 astman_append(s, "Context: %s\r\n", l->context);