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