Merge the new Channel Event Logging (CEL) subsystem.
[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 canreinvite;                                \
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         .canreinvite = 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                                         ast_verb(1, "Line %s already connected to %s. Not connecting to %s.\n", l->name, l->device->name, d->name);
1908                                 } else {
1909                                         l->device = d;
1910                                         l->capability = l->confcapability & d->capability;
1911                                         l->prefs = l->confprefs;
1912                                         if (!l->prefs.order[0]) {
1913                                                 l->prefs = d->confprefs;
1914                                         }
1915                                         /* l->capability = d->capability;
1916                                         l->prefs = d->prefs; */
1917                                         l->instance = instance;
1918                                         l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
1919                                         set_callforwards(l, NULL, 0);
1920                                         register_exten(l);
1921                                         /* initialize MWI on line and device */
1922                                         mwi_event_cb(0, l);
1923                                         ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s@%s", l->name, d->name);
1924                                 }
1925                                 --instance;
1926                         }
1927                         break;
1928                 }
1929         }
1930         AST_LIST_UNLOCK(&devices);
1931         if (!d) {
1932                 return 0;
1933         }
1934         return 1;
1935 }
1936
1937 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
1938 {
1939         struct skinny_device *d;
1940         struct skinny_line *l;
1941         struct skinny_speeddial *sd;
1942
1943         d = s->device;
1944
1945         if (d) {
1946                 d->session = NULL;
1947                 d->registered = 0;
1948
1949                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1950                         if (sd->stateid > -1)
1951                                 ast_extension_state_del(sd->stateid, NULL);
1952                 }
1953                 AST_LIST_TRAVERSE(&d->lines, l, list) {
1954                         if (l->device == d) {
1955                                 l->device = NULL;
1956                                 l->capability = 0;
1957                                 ast_parse_allow_disallow(&l->prefs, &l->capability, "all", 0);                  
1958                                 l->instance = 0;
1959                                 unregister_exten(l);
1960                                 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "Skinny/%s@%s", l->name, d->name);
1961                         }
1962                 }
1963         }
1964
1965         return -1; /* main loop will destroy the session */
1966 }
1967
1968 #ifdef SKINNY_DEVMODE
1969 static char *message2str(int type)
1970 {
1971         char *tmp;
1972
1973         switch (type) {
1974         case KEEP_ALIVE_MESSAGE:
1975                 return "KEEP_ALIVE_MESSAGE";
1976         case REGISTER_MESSAGE:
1977                 return "REGISTER_MESSAGE";
1978         case IP_PORT_MESSAGE:
1979                 return "IP_PORT_MESSAGE";
1980         case KEYPAD_BUTTON_MESSAGE:
1981                 return "KEYPAD_BUTTON_MESSAGE";
1982         case ENBLOC_CALL_MESSAGE:
1983                 return "ENBLOC_CALL_MESSAGE";
1984         case STIMULUS_MESSAGE:
1985                 return "STIMULUS_MESSAGE";
1986         case OFFHOOK_MESSAGE:
1987                 return "OFFHOOK_MESSAGE";
1988         case ONHOOK_MESSAGE:
1989                 return "ONHOOK_MESSAGE";
1990         case CAPABILITIES_RES_MESSAGE:
1991                 return "CAPABILITIES_RES_MESSAGE";
1992         case SPEED_DIAL_STAT_REQ_MESSAGE:
1993                 return "SPEED_DIAL_STAT_REQ_MESSAGE";
1994         case LINE_STATE_REQ_MESSAGE:
1995                 return "LINE_STATE_REQ_MESSAGE";
1996         case TIME_DATE_REQ_MESSAGE:
1997                 return "TIME_DATE_REQ_MESSAGE";
1998         case BUTTON_TEMPLATE_REQ_MESSAGE:
1999                 return "BUTTON_TEMPLATE_REQ_MESSAGE";
2000         case VERSION_REQ_MESSAGE:
2001                 return "VERSION_REQ_MESSAGE";
2002         case SERVER_REQUEST_MESSAGE:
2003                 return "SERVER_REQUEST_MESSAGE";
2004         case ALARM_MESSAGE:
2005                 return "ALARM_MESSAGE";
2006         case OPEN_RECEIVE_CHANNEL_ACK_MESSAGE:
2007                 return "OPEN_RECEIVE_CHANNEL_ACK_MESSAGE";
2008         case SOFT_KEY_SET_REQ_MESSAGE:
2009                 return "SOFT_KEY_SET_REQ_MESSAGE";
2010         case SOFT_KEY_EVENT_MESSAGE:
2011                 return "SOFT_KEY_EVENT_MESSAGE";
2012         case UNREGISTER_MESSAGE:
2013                 return "UNREGISTER_MESSAGE";
2014         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
2015                 return "SOFT_KEY_TEMPLATE_REQ_MESSAGE";
2016         case HEADSET_STATUS_MESSAGE:
2017                 return "HEADSET_STATUS_MESSAGE";
2018         case REGISTER_AVAILABLE_LINES_MESSAGE:
2019                 return "REGISTER_AVAILABLE_LINES_MESSAGE";
2020         case REGISTER_ACK_MESSAGE:
2021                 return "REGISTER_ACK_MESSAGE";
2022         case START_TONE_MESSAGE:
2023                 return "START_TONE_MESSAGE";
2024         case STOP_TONE_MESSAGE:
2025                 return "STOP_TONE_MESSAGE";
2026         case SET_RINGER_MESSAGE:
2027                 return "SET_RINGER_MESSAGE";
2028         case SET_LAMP_MESSAGE:
2029                 return "SET_LAMP_MESSAGE";
2030         case SET_SPEAKER_MESSAGE:
2031                 return "SET_SPEAKER_MESSAGE";
2032         case SET_MICROPHONE_MESSAGE:
2033                 return "SET_MICROPHONE_MESSAGE";
2034         case START_MEDIA_TRANSMISSION_MESSAGE:
2035                 return "START_MEDIA_TRANSMISSION_MESSAGE";
2036         case STOP_MEDIA_TRANSMISSION_MESSAGE:
2037                 return "STOP_MEDIA_TRANSMISSION_MESSAGE";
2038         case CALL_INFO_MESSAGE:
2039                 return "CALL_INFO_MESSAGE";
2040         case FORWARD_STAT_MESSAGE:
2041                 return "FORWARD_STAT_MESSAGE";
2042         case SPEED_DIAL_STAT_RES_MESSAGE:
2043                 return "SPEED_DIAL_STAT_RES_MESSAGE";
2044         case LINE_STAT_RES_MESSAGE:
2045                 return "LINE_STAT_RES_MESSAGE";
2046         case DEFINETIMEDATE_MESSAGE:
2047                 return "DEFINETIMEDATE_MESSAGE";
2048         case BUTTON_TEMPLATE_RES_MESSAGE:
2049                 return "BUTTON_TEMPLATE_RES_MESSAGE";
2050         case VERSION_RES_MESSAGE:
2051                 return "VERSION_RES_MESSAGE";
2052         case DISPLAYTEXT_MESSAGE:
2053                 return "DISPLAYTEXT_MESSAGE";
2054         case CLEAR_NOTIFY_MESSAGE:
2055                 return "CLEAR_NOTIFY_MESSAGE";
2056         case CLEAR_DISPLAY_MESSAGE:
2057                 return "CLEAR_DISPLAY_MESSAGE";
2058         case CAPABILITIES_REQ_MESSAGE:
2059                 return "CAPABILITIES_REQ_MESSAGE";
2060         case REGISTER_REJ_MESSAGE:
2061                 return "REGISTER_REJ_MESSAGE";
2062         case SERVER_RES_MESSAGE:
2063                 return "SERVER_RES_MESSAGE";
2064         case RESET_MESSAGE:
2065                 return "RESET_MESSAGE";
2066         case KEEP_ALIVE_ACK_MESSAGE:
2067                 return "KEEP_ALIVE_ACK_MESSAGE";
2068         case OPEN_RECEIVE_CHANNEL_MESSAGE:
2069                 return "OPEN_RECEIVE_CHANNEL_MESSAGE";
2070         case CLOSE_RECEIVE_CHANNEL_MESSAGE:
2071                 return "CLOSE_RECEIVE_CHANNEL_MESSAGE";
2072         case SOFT_KEY_TEMPLATE_RES_MESSAGE:
2073                 return "SOFT_KEY_TEMPLATE_RES_MESSAGE";
2074         case SOFT_KEY_SET_RES_MESSAGE:
2075                 return "SOFT_KEY_SET_RES_MESSAGE";
2076         case SELECT_SOFT_KEYS_MESSAGE:
2077                 return "SELECT_SOFT_KEYS_MESSAGE";
2078         case CALL_STATE_MESSAGE:
2079                 return "CALL_STATE_MESSAGE";
2080         case DISPLAY_PROMPT_STATUS_MESSAGE:
2081                 return "DISPLAY_PROMPT_STATUS_MESSAGE";
2082         case CLEAR_PROMPT_MESSAGE:
2083                 return "CLEAR_PROMPT_MESSAGE";
2084         case DISPLAY_NOTIFY_MESSAGE:
2085                 return "DISPLAY_NOTIFY_MESSAGE";
2086         case ACTIVATE_CALL_PLANE_MESSAGE:
2087                 return "ACTIVATE_CALL_PLANE_MESSAGE";
2088         case DIALED_NUMBER_MESSAGE:
2089                 return "DIALED_NUMBER_MESSAGE";
2090         default:
2091                 if (!(tmp = ast_threadstorage_get(&message2str_threadbuf, MESSAGE2STR_BUFSIZE)))
2092                         return "Unknown";
2093                 snprintf(tmp, MESSAGE2STR_BUFSIZE, "UNKNOWN_MESSAGE-%d", type);
2094                 return tmp;
2095         }
2096 }
2097 #endif
2098
2099 static int transmit_response(struct skinny_device *d, struct skinny_req *req)
2100 {
2101         struct skinnysession *s = d->session;
2102         int res = 0;
2103
2104         if (!s) {
2105                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2106                 return -1;
2107         }
2108
2109         ast_mutex_lock(&s->lock);
2110
2111         SKINNY_DEVONLY(if (skinnydebug>1) ast_verb(4, "Transmitting %s to %s\n", message2str(req->e), d->name);)
2112
2113         if (letohl(req->len > SKINNY_MAX_PACKET) || letohl(req->len < 0)) {
2114                 ast_log(LOG_WARNING, "transmit_response: the length of the request is out of bounds\n");
2115                 ast_mutex_unlock(&s->lock);
2116                 return -1;
2117         }
2118
2119         memset(s->outbuf, 0, sizeof(s->outbuf));
2120         memcpy(s->outbuf, req, skinny_header_size);
2121         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2122
2123         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2124         
2125         if (res != letohl(req->len)+8) {
2126                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2127                 if (res == -1) {
2128                         if (skinnydebug)
2129                                 ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2130                         skinny_unregister(NULL, s);
2131                 }
2132                 
2133         }
2134         
2135         ast_free(req);
2136         ast_mutex_unlock(&s->lock);
2137         return 1;
2138 }
2139
2140 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2141 {
2142         struct skinny_req *req;
2143
2144         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2145                 return;
2146
2147         req->data.setspeaker.mode = htolel(mode);
2148         transmit_response(d, req);
2149 }
2150 /*
2151 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2152 {
2153         struct skinny_req *req;
2154
2155         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2156                 return;
2157
2158         req->data.setmicrophone.mode = htolel(mode);
2159         transmit_response(d, req);
2160 }
2161 */
2162
2163 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)
2164 {
2165         struct skinny_req *req;
2166
2167         /* We should not be able to get here without a device */
2168         if (!d)
2169                 return;
2170
2171         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2172                 return;
2173
2174         if (skinnydebug)
2175                         ast_verb(1, "Setting Callinfo to %s(%s) from %s(%s) on %s(%d)\n", fromname, fromnum, toname, tonum, d->name, instance);
2176
2177         if (fromname) {
2178                 ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2179         }
2180         if (fromnum) {
2181                 ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2182         }
2183         if (toname) {
2184                 ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2185         }
2186         if (tonum) {
2187                 ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2188         }
2189         req->data.callinfo.instance = htolel(instance);
2190         req->data.callinfo.reference = htolel(callid);
2191         req->data.callinfo.type = htolel(calltype);
2192         transmit_response(d, req);
2193 }
2194
2195 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2196 {
2197         struct skinny_req *req;
2198         struct skinny_line *l = sub->parent;
2199         struct ast_format_list fmt;
2200
2201         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2202                 return;
2203
2204         fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
2205
2206         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2207         req->data.openreceivechannel.partyId = htolel(sub->callid);
2208         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2209         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(fmt.bits));
2210         req->data.openreceivechannel.echo = htolel(0);
2211         req->data.openreceivechannel.bitrate = htolel(0);
2212         transmit_response(d, req);
2213 }
2214
2215 static void transmit_tone(struct skinny_device *d, int tone, int instance, int reference)
2216 {
2217         struct skinny_req *req;
2218
2219         if (tone == SKINNY_NOTONE) {
2220                 /* This is bad, mmm'kay? */
2221                 return;
2222         }
2223
2224         if (tone > 0) {
2225                 if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2226                         return;
2227                 req->data.starttone.tone = htolel(tone);
2228                 req->data.starttone.instance = htolel(instance);
2229                 req->data.starttone.reference = htolel(reference);
2230         } else {
2231                 if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2232                         return;
2233                 req->data.stoptone.instance = htolel(instance);
2234                 req->data.stoptone.reference = htolel(reference);
2235         }
2236
2237         //Bad, tone is already set so this is redundant and a change to the if above
2238         //may lead to issues where we try to set a tone to a stop_tone_message
2239         //if (tone > 0) {
2240         //      req->data.starttone.tone = htolel(tone);
2241         //}
2242         transmit_response(d, req);
2243 }
2244
2245 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey)
2246 {
2247         struct skinny_req *req;
2248
2249         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2250                 return;
2251
2252         req->data.selectsoftkey.instance = htolel(instance);
2253         req->data.selectsoftkey.reference = htolel(callid);
2254         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2255         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
2256         transmit_response(d, req);
2257 }
2258
2259 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2260 {
2261         struct skinny_req *req;
2262
2263         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2264                 return;
2265
2266         req->data.setlamp.stimulus = htolel(stimulus);
2267         req->data.setlamp.stimulusInstance = htolel(instance);
2268         req->data.setlamp.deviceStimulus = htolel(indication);
2269         transmit_response(d, req);
2270 }
2271
2272 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2273 {
2274         struct skinny_req *req;
2275
2276         if (skinnydebug)
2277                 ast_verb(1, "Setting ringer mode to '%d'.\n", mode);
2278
2279         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2280                 return;
2281
2282         req->data.setringer.ringerMode = htolel(mode);
2283         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2284            Note: The phone will always show as ringing on the display.
2285
2286            1: phone will audibly ring over and over
2287            2: phone will audibly ring only once
2288            any other value, will NOT cause the phone to audibly ring
2289         */
2290         req->data.setringer.unknown1 = htolel(1);
2291         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2292            Perhaps a packet capture can shed some light on this. */
2293         req->data.setringer.unknown2 = htolel(1);
2294         transmit_response(d, req);
2295 }
2296
2297 static void transmit_displaymessage(struct skinny_device *d, const char *text, int instance, int reference)
2298 {
2299         struct skinny_req *req;
2300
2301         if (text == 0) {
2302                 if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
2303                         return;
2304
2305                 //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2306                 //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2307                 //req->data.clearpromptstatus.lineInstance = instance;
2308                 //req->data.clearpromptstatus.callReference = reference;
2309
2310                 /* send datetime message. We have to do it here because it will clear the display on the phone if we do it elsewhere */
2311                 handle_time_date_req_message(NULL, d->session);
2312
2313                 if (skinnydebug)
2314                         ast_verb(1, "Clearing Display\n");
2315         } else {
2316                 if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2317                         return;
2318
2319                 ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2320                 if (skinnydebug)
2321                         ast_verb(1, "Displaying message '%s'\n", req->data.displaytext.text);
2322         }
2323
2324         transmit_response(d, req);
2325 }
2326
2327 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2328 {
2329         struct skinny_req *req;
2330
2331         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2332                 return;
2333
2334         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2335         req->data.displaynotify.displayTimeout = htolel(t);
2336
2337         if (skinnydebug)
2338                 ast_verb(1, "Displaying notify '%s'\n", text);
2339
2340         transmit_response(d, req);
2341 }
2342
2343 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
2344 {
2345         struct skinny_req *req;
2346
2347         if (text == 0) {
2348                 if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2349                         return;
2350
2351                 req->data.clearpromptstatus.lineInstance = htolel(instance);
2352                 req->data.clearpromptstatus.callReference = htolel(callid);
2353
2354                 if (skinnydebug)
2355                         ast_verb(1, "Clearing Prompt\n");
2356         } else {
2357                 if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2358                         return;
2359
2360                 ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2361                 req->data.displaypromptstatus.messageTimeout = htolel(t);
2362                 req->data.displaypromptstatus.lineInstance = htolel(instance);
2363                 req->data.displaypromptstatus.callReference = htolel(callid);
2364
2365                 if (skinnydebug)
2366                         ast_verb(1, "Displaying Prompt Status '%s'\n", text);
2367         }
2368
2369         transmit_response(d, req);
2370 }
2371
2372 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2373 {
2374         struct skinny_req *req;
2375
2376         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2377                 return;
2378
2379         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2380         req->data.dialednumber.lineInstance = htolel(instance);
2381         req->data.dialednumber.callReference = htolel(callid);
2382
2383         transmit_response(d, req);
2384 }
2385
2386 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2387 {
2388         struct skinny_req *req;
2389
2390         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2391                 return;
2392
2393         req->data.closereceivechannel.conferenceId = htolel(0);
2394         req->data.closereceivechannel.partyId = htolel(sub->callid);
2395         transmit_response(d, req);
2396 }
2397
2398 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2399 {
2400         struct skinny_req *req;
2401
2402         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2403                 return;
2404
2405         req->data.stopmedia.conferenceId = htolel(0);
2406         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2407         transmit_response(d, req);
2408 }
2409
2410 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
2411 {
2412         struct skinny_req *req;
2413
2414         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2415                 return;
2416
2417         req->data.activatecallplane.lineInstance = htolel(l->instance);
2418         transmit_response(d, req);
2419 }
2420
2421 static void transmit_callstateonly(struct skinny_device *d, struct skinny_subchannel *sub, int state)
2422 {
2423         struct skinny_req *req;
2424
2425         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2426                 return;
2427
2428         req->data.callstate.callState = htolel(state);
2429         req->data.callstate.lineInstance = htolel(sub->parent->instance);
2430         req->data.callstate.callReference = htolel(sub->callid);
2431         transmit_response(d, req);
2432 }
2433
2434 static void transmit_callstate(struct skinny_device *d, int instance, int state, unsigned callid)
2435 {
2436         struct skinny_req *req;
2437
2438         if (state == SKINNY_ONHOOK) {
2439                 if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2440                         return;
2441
2442                 req->data.closereceivechannel.conferenceId = htolel(callid);
2443                 req->data.closereceivechannel.partyId = htolel(callid);
2444                 transmit_response(d, req);
2445
2446                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2447                         return;
2448
2449                 req->data.stopmedia.conferenceId = htolel(callid);
2450                 req->data.stopmedia.passThruPartyId = htolel(callid);
2451                 transmit_response(d, req);
2452
2453                 transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
2454
2455                 transmit_displaypromptstatus(d, NULL, 0, instance, callid);
2456         }
2457
2458         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2459                 return;
2460
2461         req->data.callstate.callState = htolel(state);
2462         req->data.callstate.lineInstance = htolel(instance);
2463         req->data.callstate.callReference = htolel(callid);
2464         transmit_response(d, req);
2465
2466         if (state == SKINNY_ONHOOK) {
2467                 transmit_selectsoftkeys(d, 0, 0, KEYDEF_ONHOOK);
2468         }
2469
2470         if (state == SKINNY_OFFHOOK || state == SKINNY_ONHOOK) {
2471                 if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2472                         return;
2473
2474                 req->data.activatecallplane.lineInstance = htolel(instance);
2475                 transmit_response(d, req);
2476         }
2477 }
2478
2479
2480 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
2481 {
2482         struct skinny_req *req;
2483         int anyon = 0;
2484
2485         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
2486                 return;
2487
2488         if (l->cfwdtype & SKINNY_CFWD_ALL) {
2489                 if (!ast_strlen_zero(l->call_forward_all)) {
2490                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
2491                         req->data.forwardstat.fwdall = htolel(1);
2492                         anyon++;
2493                 } else {
2494                         req->data.forwardstat.fwdall = htolel(0);
2495                 }
2496         }
2497         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
2498                 if (!ast_strlen_zero(l->call_forward_busy)) {
2499                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
2500                         req->data.forwardstat.fwdbusy = htolel(1);
2501                         anyon++;
2502                 } else {
2503                         req->data.forwardstat.fwdbusy = htolel(0);
2504                 }
2505         }
2506         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
2507                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
2508                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
2509                         req->data.forwardstat.fwdnoanswer = htolel(1);
2510                         anyon++;
2511                 } else {
2512                         req->data.forwardstat.fwdnoanswer = htolel(0);
2513                 }
2514         }
2515         req->data.forwardstat.lineNumber = htolel(l->instance);
2516         if (anyon)
2517                 req->data.forwardstat.activeforward = htolel(7);
2518         else
2519                 req->data.forwardstat.activeforward = htolel(0);
2520
2521         transmit_response(d, req);
2522 }
2523
2524 static int skinny_extensionstate_cb(char *context, char *exten, int state, void *data)
2525 {
2526         struct skinny_speeddial *sd = data;
2527         struct skinny_device *d = sd->parent;
2528         char hint[AST_MAX_EXTENSION];
2529         int callstate = SKINNY_CALLREMOTEMULTILINE;
2530         int lamp = SKINNY_LAMP_OFF;
2531
2532         switch (state) {
2533         case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
2534         case AST_EXTENSION_REMOVED:     /* Extension is gone */
2535                 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify Device %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
2536                 sd->stateid = -1;
2537                 callstate = SKINNY_ONHOOK;
2538                 lamp = SKINNY_LAMP_OFF;
2539                 break;
2540         case AST_EXTENSION_RINGING:
2541         case AST_EXTENSION_UNAVAILABLE:
2542                 callstate = SKINNY_RINGIN;
2543                 lamp = SKINNY_LAMP_BLINK;
2544                 break;
2545         case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
2546         case AST_EXTENSION_INUSE:
2547                 callstate = SKINNY_CALLREMOTEMULTILINE;
2548                 lamp = SKINNY_LAMP_ON;
2549                 break;
2550         case AST_EXTENSION_ONHOLD:
2551                 callstate = SKINNY_HOLD;
2552                 lamp = SKINNY_LAMP_WINK;
2553                 break;
2554         case AST_EXTENSION_NOT_INUSE:
2555         default:
2556                 callstate = SKINNY_ONHOOK;
2557                 lamp = SKINNY_LAMP_OFF;
2558                 break;
2559         }
2560
2561         if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
2562                 /* If they are not registered, we will override notification and show no availability */
2563                 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
2564                         callstate = SKINNY_ONHOOK;
2565                         lamp = SKINNY_LAMP_FLASH;
2566                 }
2567         }
2568
2569         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, lamp);
2570         transmit_callstate(d, sd->instance, callstate, 0);
2571         sd->laststate = state;
2572
2573         return 0;
2574 }
2575
2576 static void update_connectedline(struct skinny_subchannel *sub, const void *data, size_t datalen)
2577 {
2578         struct ast_channel *c = sub->owner;
2579         struct skinny_line *l = sub->parent;
2580         struct skinny_device *d = l->device;
2581
2582         if (ast_strlen_zero(c->cid.cid_num) || ast_strlen_zero(c->connected.id.number))
2583                 return;
2584
2585         if (sub->owner->_state == AST_STATE_UP) {
2586                 transmit_callstate(d, l->instance, SKINNY_CONNECTED, sub->callid);
2587                 transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
2588                 if (sub->outgoing)
2589                         transmit_callinfo(d, c->connected.id.name, c->connected.id.number, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
2590                 else
2591                         transmit_callinfo(d, l->cid_name, l->cid_num, c->connected.id.name, c->connected.id.number, l->instance, sub->callid, 2);
2592         } else {
2593                 if (sub->outgoing) {
2594                         transmit_callstate(d, l->instance, SKINNY_RINGIN, sub->callid);
2595                         transmit_displaypromptstatus(d, "Ring-In", 0, l->instance, sub->callid);
2596                         transmit_callinfo(d, c->connected.id.name, c->connected.id.number, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
2597                 } else {
2598                         if (!sub->ringing) {
2599                                 transmit_callstate(d, l->instance, SKINNY_RINGOUT, sub->callid);
2600                                 transmit_displaypromptstatus(d, "Ring-Out", 0, l->instance, sub->callid);
2601                                 sub->ringing = 1;
2602                         } else {
2603                                 transmit_callstate(d, l->instance, SKINNY_PROGRESS, sub->callid);
2604                                 transmit_displaypromptstatus(d, "Call Progress", 0, l->instance, sub->callid);
2605                                 sub->progress = 1;
2606                         }
2607
2608                         transmit_callinfo(d, l->cid_name, l->cid_num, c->connected.id.name, c->connected.id.number, l->instance, sub->callid, 2);
2609                 }
2610         }
2611 }
2612
2613 static void mwi_event_cb(const struct ast_event *event, void *userdata)
2614 {
2615         struct skinny_line *l = userdata;
2616         struct skinny_device *d = l->device;
2617         if (d) {
2618                 struct skinnysession *s = d->session;
2619                 struct skinny_line *l2;
2620                 int new_msgs = 0;
2621                 int dev_msgs = 0;
2622
2623                 if (s) {
2624                         if (event) {
2625                                 l->newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
2626                         }
2627
2628                         if (l->newmsgs) {
2629                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2630                         } else {
2631                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
2632                         }
2633
2634                         /* find out wether the device lamp should be on or off */
2635                         AST_LIST_TRAVERSE(&d->lines, l2, list) {
2636                                 if (l2->newmsgs) {
2637                                         dev_msgs++;
2638                                 }
2639                         }
2640
2641                         if (dev_msgs) {
2642                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2643                         } else {
2644                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
2645                         }
2646                         ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", new_msgs);
2647                 }
2648         }
2649 }
2650
2651 /* I do not believe skinny can deal with video.
2652    Anyone know differently? */
2653 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
2654 static enum ast_rtp_glue_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
2655 {
2656         struct skinny_subchannel *sub = NULL;
2657
2658         if (!(sub = c->tech_pvt) || !(sub->vrtp))
2659                 return AST_RTP_GLUE_RESULT_FORBID;
2660
2661         ao2_ref(sub->vrtp, +1);
2662         *instance = sub->vrtp;
2663
2664         return AST_RTP_GLUE_RESULT_REMOTE;
2665 }
2666
2667 static enum ast_rtp_glue_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
2668 {
2669         struct skinny_subchannel *sub = NULL;
2670         struct skinny_line *l;
2671         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE;
2672
2673         if (skinnydebug)
2674                 ast_verb(1, "skinny_get_rtp_peer() Channel = %s\n", c->name);
2675
2676
2677         if (!(sub = c->tech_pvt))
2678                 return AST_RTP_GLUE_RESULT_FORBID;
2679
2680         ast_mutex_lock(&sub->lock);
2681
2682         if (!(sub->rtp)){
2683                 ast_mutex_unlock(&sub->lock);
2684                 return AST_RTP_GLUE_RESULT_FORBID;
2685         }
2686
2687         ao2_ref(sub->rtp, +1);
2688         *instance = sub->rtp;
2689
2690         l = sub->parent;
2691
2692         if (!l->canreinvite || l->nat){
2693                 res = AST_RTP_GLUE_RESULT_LOCAL;
2694                 if (skinnydebug)
2695                         ast_verb(1, "skinny_get_rtp_peer() Using AST_RTP_GLUE_RESULT_LOCAL \n");
2696         }
2697
2698         ast_mutex_unlock(&sub->lock);
2699
2700         return res;
2701
2702 }
2703
2704 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)
2705 {
2706         struct skinny_subchannel *sub;
2707         struct skinny_line *l;
2708         struct skinny_device *d;
2709         struct skinnysession *s;
2710         struct ast_format_list fmt;
2711         struct sockaddr_in us = { 0, };
2712         struct sockaddr_in them = { 0, };
2713         struct skinny_req *req;
2714         
2715         sub = c->tech_pvt;
2716
2717         if (c->_state != AST_STATE_UP)
2718                 return 0;
2719
2720         if (!sub) {
2721                 return -1;
2722         }
2723
2724         l = sub->parent;
2725         d = l->device;
2726         s = d->session;
2727
2728         if (rtp){
2729                 ast_rtp_instance_get_remote_address(rtp, &them);
2730
2731                 /* Shutdown any early-media or previous media on re-invite */
2732                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2733                         return -1;
2734
2735                 req->data.stopmedia.conferenceId = htolel(sub->callid);
2736                 req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2737                 transmit_response(d, req);
2738
2739                 if (skinnydebug)
2740                         ast_verb(1, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
2741
2742                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message), START_MEDIA_TRANSMISSION_MESSAGE)))
2743                         return -1;
2744
2745                 fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
2746
2747                 if (skinnydebug)
2748                         ast_verb(1, "Setting payloadType to '%d' (%d ms)\n", fmt.bits, fmt.cur_ms);
2749
2750                 req->data.startmedia.conferenceId = htolel(sub->callid);
2751                 req->data.startmedia.passThruPartyId = htolel(sub->callid);
2752                 if (!(l->canreinvite) || (l->nat)){
2753                         ast_rtp_instance_get_local_address(rtp, &us);
2754                         req->data.startmedia.remoteIp = htolel(d->ourip.s_addr);
2755                         req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
2756                 } else {
2757                         req->data.startmedia.remoteIp = htolel(them.sin_addr.s_addr);
2758                         req->data.startmedia.remotePort = htolel(ntohs(them.sin_port));
2759                 }
2760                 req->data.startmedia.packetSize = htolel(fmt.cur_ms);
2761                 req->data.startmedia.payloadType = htolel(codec_ast2skinny(fmt.bits));
2762                 req->data.startmedia.qualifier.precedence = htolel(127);
2763                 req->data.startmedia.qualifier.vad = htolel(0);
2764                 req->data.startmedia.qualifier.packets = htolel(0);
2765                 req->data.startmedia.qualifier.bitRate = htolel(0);
2766                 transmit_response(d, req);
2767
2768                 return 0;
2769         }
2770         /* Need a return here to break the bridge */
2771         return 0;
2772 }
2773
2774 static struct ast_rtp_glue skinny_rtp_glue = {
2775         .type = "Skinny",
2776         .get_rtp_info = skinny_get_rtp_peer,
2777         .get_vrtp_info = skinny_get_vrtp_peer,
2778         .update_peer = skinny_set_rtp_peer,
2779 };
2780
2781 static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2782 {
2783         switch (cmd) {
2784         case CLI_INIT:
2785 #ifdef SKINNY_DEVMODE
2786                 e->command = "skinny set debug {off|on|packet}";
2787                 e->usage =
2788                         "Usage: skinny set debug {off|on|packet}\n"
2789                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2790 #else
2791                 e->command = "skinny set debug {off|on}";
2792                 e->usage =
2793                         "Usage: skinny set debug {off|on}\n"
2794                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2795 #endif
2796                 return NULL;
2797         case CLI_GENERATE:
2798                 return NULL;
2799         }
2800         
2801         if (a->argc != e->args)
2802                 return CLI_SHOWUSAGE;
2803
2804         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
2805                 skinnydebug = 1;
2806                 ast_cli(a->fd, "Skinny Debugging Enabled\n");
2807                 return CLI_SUCCESS;
2808         } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
2809                 skinnydebug = 0;
2810                 ast_cli(a->fd, "Skinny Debugging Disabled\n");
2811                 return CLI_SUCCESS;
2812 #ifdef SKINNY_DEVMODE
2813         } else if (!strncasecmp(a->argv[e->args - 1], "packet", 6)) {
2814                 skinnydebug = 2;
2815                 ast_cli(a->fd, "Skinny Debugging Enabled including Packets\n");
2816                 return CLI_SUCCESS;
2817 #endif
2818         } else {
2819                 return CLI_SHOWUSAGE;
2820         }
2821 }
2822
2823 static char *handle_skinny_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2824 {
2825         switch (cmd) {
2826         case CLI_INIT:
2827                 e->command = "skinny reload";
2828                 e->usage =
2829                         "Usage: skinny reload\n"
2830                         "       Reloads the chan_skinny configuration\n";
2831                 return NULL;
2832         case CLI_GENERATE:
2833                 return NULL;
2834         }
2835         
2836         if (a->argc != e->args)
2837                 return CLI_SHOWUSAGE;
2838
2839         skinny_reload();
2840         return CLI_SUCCESS;
2841
2842 }
2843
2844 static char *complete_skinny_devices(const char *word, int state)
2845 {
2846         struct skinny_device *d;
2847         char *result = NULL;
2848         int wordlen = strlen(word), which = 0;
2849
2850         AST_LIST_TRAVERSE(&devices, d, list) {
2851                 if (!strncasecmp(word, d->id, wordlen) && ++which > state)
2852                         result = ast_strdup(d->id);
2853         }
2854
2855         return result;
2856 }
2857
2858 static char *complete_skinny_show_device(const char *line, const char *word, int pos, int state)
2859 {
2860         return (pos == 3 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2861 }
2862
2863 static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
2864 {
2865         return (pos == 2 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2866 }
2867
2868 static char *complete_skinny_show_line(const char *line, const char *word, int pos, int state)
2869 {
2870         struct skinny_device *d;
2871         struct skinny_line *l;
2872         char *result = NULL;
2873         int wordlen = strlen(word), which = 0;
2874
2875         if (pos != 3)
2876                 return NULL;
2877         
2878         AST_LIST_TRAVERSE(&devices, d, list) {
2879                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2880                         if (!strncasecmp(word, l->name, wordlen) && ++which > state)
2881                                 result = ast_strdup(l->name);
2882                 }
2883         }
2884
2885         return result;
2886 }
2887
2888 static char *handle_skinny_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2889 {
2890         struct skinny_device *d;
2891         struct skinny_req *req;
2892
2893         switch (cmd) {
2894         case CLI_INIT:
2895                 e->command = "skinny reset";
2896                 e->usage =
2897                         "Usage: skinny reset <DeviceId|DeviceName|all> [restart]\n"
2898                         "       Causes a Skinny device to reset itself, optionally with a full restart\n";
2899                 return NULL;
2900         case CLI_GENERATE:
2901                 return complete_skinny_reset(a->line, a->word, a->pos, a->n);
2902         }
2903
2904         if (a->argc < 3 || a->argc > 4)
2905                 return CLI_SHOWUSAGE;
2906
2907         AST_LIST_LOCK(&devices);
2908         AST_LIST_TRAVERSE(&devices, d, list) {
2909                 int fullrestart = 0;
2910                 if (!strcasecmp(a->argv[2], d->id) || !strcasecmp(a->argv[2], d->name) || !strcasecmp(a->argv[2], "all")) {
2911                         if (!(d->session))
2912                                 continue;
2913
2914                         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
2915                                 continue;
2916
2917                         if (a->argc == 4 && !strcasecmp(a->argv[3], "restart"))
2918                                 fullrestart = 1;
2919
2920                         if (fullrestart)
2921                                 req->data.reset.resetType = 2;
2922                         else
2923                                 req->data.reset.resetType = 1;
2924
2925                         ast_verb(3, "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
2926                         transmit_response(d, req);
2927                 }
2928         }
2929         AST_LIST_UNLOCK(&devices);
2930         return CLI_SUCCESS;
2931 }
2932
2933 static char *device2str(int type)
2934 {
2935         char *tmp;
2936
2937         switch (type) {
2938         case SKINNY_DEVICE_NONE:
2939                 return "No Device";
2940         case SKINNY_DEVICE_30SPPLUS:
2941                 return "30SP Plus";
2942         case SKINNY_DEVICE_12SPPLUS:
2943                 return "12SP Plus";
2944         case SKINNY_DEVICE_12SP:
2945                 return "12SP";
2946         case SKINNY_DEVICE_12:
2947                 return "12";
2948         case SKINNY_DEVICE_30VIP:
2949                 return "30VIP";
2950         case SKINNY_DEVICE_7910:
2951                 return "7910";
2952         case SKINNY_DEVICE_7960:
2953                 return "7960";
2954         case SKINNY_DEVICE_7940:
2955                 return "7940";
2956         case SKINNY_DEVICE_7935:
2957                 return "7935";
2958         case SKINNY_DEVICE_ATA186:
2959                 return "ATA186";
2960         case SKINNY_DEVICE_7941:
2961                 return "7941";
2962         case SKINNY_DEVICE_7971:
2963                 return "7971";
2964         case SKINNY_DEVICE_7914:
2965                 return "7914";
2966         case SKINNY_DEVICE_7985:
2967                 return "7985";
2968         case SKINNY_DEVICE_7911:
2969                 return "7911";
2970         case SKINNY_DEVICE_7961GE:
2971                 return "7961GE";
2972         case SKINNY_DEVICE_7941GE:
2973                 return "7941GE";
2974         case SKINNY_DEVICE_7931:
2975                 return "7931";
2976         case SKINNY_DEVICE_7921:
2977                 return "7921";
2978         case SKINNY_DEVICE_7906:
2979                 return "7906";
2980         case SKINNY_DEVICE_7962:
2981                 return "7962";
2982         case SKINNY_DEVICE_7937:
2983                 return "7937";
2984         case SKINNY_DEVICE_7942:
2985                 return "7942";
2986         case SKINNY_DEVICE_7945:
2987                 return "7945";
2988         case SKINNY_DEVICE_7965:
2989                 return "7965";
2990         case SKINNY_DEVICE_7975:
2991                 return "7975";
2992         case SKINNY_DEVICE_7905:
2993                 return "7905";
2994         case SKINNY_DEVICE_7920:
2995                 return "7920";
2996         case SKINNY_DEVICE_7970:
2997                 return "7970";
2998         case SKINNY_DEVICE_7912:
2999                 return "7912";
3000         case SKINNY_DEVICE_7902:
3001                 return "7902";
3002         case SKINNY_DEVICE_CIPC:
3003                 return "IP Communicator";
3004         case SKINNY_DEVICE_7961:
3005                 return "7961";
3006         case SKINNY_DEVICE_7936:
3007                 return "7936";
3008         case SKINNY_DEVICE_SCCPGATEWAY_AN:
3009                 return "SCCPGATEWAY_AN";
3010         case SKINNY_DEVICE_SCCPGATEWAY_BRI:
3011                 return "SCCPGATEWAY_BRI";
3012         case SKINNY_DEVICE_UNKNOWN:
3013                 return "Unknown";
3014         default:
3015                 if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
3016                         return "Unknown";
3017                 snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
3018                 return tmp;
3019         }
3020 }
3021
3022 /*! \brief Print codec list from preference to CLI/manager */
3023 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
3024 {
3025         int x, codec;
3026
3027         for(x = 0; x < 32 ; x++) {
3028                 codec = ast_codec_pref_index(pref, x);
3029                 if (!codec)
3030                         break;
3031                 ast_cli(fd, "%s", ast_getformatname(codec));
3032                 ast_cli(fd, ":%d", pref->framing[x]);
3033                 if (x < 31 && ast_codec_pref_index(pref, x + 1))
3034                         ast_cli(fd, ",");
3035         }
3036         if (!x)
3037                 ast_cli(fd, "none");
3038 }
3039
3040 static char *_skinny_show_devices(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
3041 {
3042         struct skinny_device *d;
3043         struct skinny_line *l;
3044         const char *id;
3045         char idtext[256] = "";
3046         int total_devices = 0;
3047
3048         if (s) {        /* Manager - get ActionID */
3049                 id = astman_get_header(m, "ActionID");
3050                 if (!ast_strlen_zero(id))
3051                         snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3052         }
3053
3054         switch (argc) {
3055         case 3:
3056                 break;
3057         default:
3058                 return CLI_SHOWUSAGE;
3059         }
3060
3061         if (!s) {
3062                 ast_cli(fd, "Name                 DeviceId         IP              Type            R NL\n");
3063                 ast_cli(fd, "-------------------- ---------------- --------------- --------------- - --\n");
3064         }
3065
3066         AST_LIST_LOCK(&devices);
3067         AST_LIST_TRAVERSE(&devices, d, list) {
3068                 int numlines = 0;
3069                 total_devices++;
3070                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3071                         numlines++;
3072                 }
3073                 if (!s) {
3074                         ast_cli(fd, "%-20s %-16s %-15s %-15s %c %2d\n",
3075                                 d->name,
3076                                 d->id,
3077                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
3078                                 device2str(d->type),
3079                                 d->registered?'Y':'N',
3080                                 numlines);
3081                 } else {
3082                         astman_append(s,
3083                                 "Event: DeviceEntry\r\n%s"
3084                                 "Channeltype: SKINNY\r\n"
3085                                 "ObjectName: %s\r\n"
3086                                 "ChannelObjectType: device\r\n"
3087                                 "DeviceId: %s\r\n"
3088                                 "IPaddress: %s\r\n"
3089                                 "Type: %s\r\n"
3090                                 "Devicestatus: %s\r\n"
3091                                 "NumberOfLines: %d\r\n",
3092                                 idtext,
3093                                 d->name,
3094                                 d->id,
3095                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"-none-",
3096                                 device2str(d->type),
3097                                 d->registered?"registered":"unregistered",
3098                                 numlines);
3099                 }
3100         }
3101         AST_LIST_UNLOCK(&devices);
3102
3103         if (total)
3104                 *total = total_devices;
3105         
3106         return CLI_SUCCESS;
3107 }
3108
3109 /*! \brief  Show SKINNY devices in the manager API */
3110 /*    Inspired from chan_sip */
3111 static int manager_skinny_show_devices(struct mansession *s, const struct message *m)
3112 {
3113         const char *id = astman_get_header(m, "ActionID");
3114         const char *a[] = {"skinny", "show", "devices"};
3115         char idtext[256] = "";
3116         int total = 0;
3117
3118         if (!ast_strlen_zero(id))
3119                 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3120
3121         astman_send_listack(s, m, "Device status list will follow", "start");
3122         /* List the devices in separate manager events */
3123         _skinny_show_devices(-1, &total, s, m, 3, a);
3124         /* Send final confirmation */
3125         astman_append(s,
3126         "Event: DevicelistComplete\r\n"
3127         "EventList: Complete\r\n"
3128         "ListItems: %d\r\n"
3129         "%s"
3130         "\r\n", total, idtext);
3131         return 0;
3132 }
3133
3134 static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3135 {
3136
3137         switch (cmd) {
3138         case CLI_INIT:
3139                 e->command = "skinny show devices";
3140                 e->usage =
3141                         "Usage: skinny show devices\n"
3142                         "       Lists all devices known to the Skinny subsystem.\n";
3143                 return NULL;
3144         case CLI_GENERATE:
3145                 return NULL;
3146         }
3147
3148         return _skinny_show_devices(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
3149 }
3150
3151 static char *_skinny_show_device(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
3152 {
3153         struct skinny_device *d;
3154         struct skinny_line *l;
3155         struct skinny_speeddial *sd;
3156         struct skinny_addon *sa;
3157         char codec_buf[512];
3158
3159         if (argc < 4) {
3160                 return CLI_SHOWUSAGE;
3161         }
3162
3163         AST_LIST_LOCK(&devices);
3164         AST_LIST_TRAVERSE(&devices, d, list) {
3165                 if (!strcasecmp(argv[3], d->id) || !strcasecmp(argv[3], d->name)) {
3166                         int numlines = 0, numaddons = 0, numspeeddials = 0;
3167
3168                         AST_LIST_TRAVERSE(&d->lines, l, list){
3169                                 numlines++;
3170                         }
3171
3172                         AST_LIST_TRAVERSE(&d->addons, sa, list) {
3173                                 numaddons++;
3174                         }
3175
3176                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3177                                 numspeeddials++;
3178                         }
3179
3180                         if (type == 0) { /* CLI */
3181                                 ast_cli(fd, "Name:        %s\n", d->name);
3182                                 ast_cli(fd, "Id:          %s\n", d->id);
3183                                 ast_cli(fd, "version:     %s\n", S_OR(d->version_id, "Unknown"));
3184                                 ast_cli(fd, "Ip address:  %s\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
3185                                 ast_cli(fd, "Port:        %d\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
3186                                 ast_cli(fd, "Device Type: %s\n", device2str(d->type));
3187                                 ast_cli(fd, "Conf Codecs:");
3188                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->confcapability);
3189                                 ast_cli(fd, "%s\n", codec_buf);
3190                                 ast_cli(fd, "Neg Codecs: ");
3191                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->capability);
3192                                 ast_cli(fd, "%s\n", codec_buf);
3193                                 ast_cli(fd, "Registered:  %s\n", (d->registered ? "Yes" : "No"));
3194                                 ast_cli(fd, "Lines:       %d\n", numlines);
3195                                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3196                                         ast_cli(fd, "  %s (%s)\n", l->name, l->label);
3197                                 }
3198                                 AST_LIST_TRAVERSE(&d->addons, sa, list) {
3199                                         numaddons++;
3200                                 }       
3201                                 ast_cli(fd, "Addons:      %d\n", numaddons);
3202                                 AST_LIST_TRAVERSE(&d->addons, sa, list) {
3203                                         ast_cli(fd, "  %s\n", sa->type);
3204                                 }
3205                                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3206                                         numspeeddials++;
3207                                 }
3208                                 ast_cli(fd, "Speeddials:  %d\n", numspeeddials);
3209                                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3210                                         ast_cli(fd, "  %s (%s) ishint: %d\n", sd->exten, sd->label, sd->isHint);
3211                                 }
3212                         } else { /* manager */
3213                                 astman_append(s, "Channeltype: SKINNY\r\n");
3214                                 astman_append(s, "ObjectName: %s\r\n", d->name);
3215                                 astman_append(s, "ChannelObjectType: device\r\n");
3216                                 astman_append(s, "Id: %s\r\n", d->id);
3217                                 astman_append(s, "version: %s\r\n", S_OR(d->version_id, "Unknown"));
3218                                 astman_append(s, "Ipaddress: %s\r\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
3219                                 astman_append(s, "Port: %d\r\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
3220                                 astman_append(s, "DeviceType: %s\r\n", device2str(d->type));
3221                                 astman_append(s, "Codecs: ");
3222                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, d->confcapability);
3223                                 astman_append(s, "%s\r\n", codec_buf);
3224                                 astman_append(s, "CodecOrder: ");
3225                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, d->capability);
3226                                 astman_append(s, "%s\r\n", codec_buf);
3227                                 astman_append(s, "Devicestatus: %s\r\n", (d->registered?"registered":"unregistered"));
3228                                 astman_append(s, "NumberOfLines: %d\r\n", numlines);
3229                                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3230                                         astman_append(s, "Line: %s (%s)\r\n", l->name, l->label);
3231                                 }
3232                                 astman_append(s, "NumberOfAddons: %d\r\n", numaddons);
3233                                 AST_LIST_TRAVERSE(&d->addons, sa, list) {
3234                                         astman_append(s, "Addon: %s\r\n", sa->type);
3235                                 }
3236                                 astman_append(s, "NumberOfSpeeddials: %d\r\n", numspeeddials);
3237                                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3238                                         astman_append(s, "Speeddial: %s (%s) ishint: %d\r\n", sd->exten, sd->label, sd->isHint);
3239                                 }
3240                         }
3241                 }
3242         }
3243         AST_LIST_UNLOCK(&devices);
3244         return CLI_SUCCESS;
3245 }
3246
3247 static int manager_skinny_show_device(struct mansession *s, const struct message *m)
3248 {
3249         const char *a[4];
3250         const char *device;
3251
3252         device = astman_get_header(m, "Device");
3253         if (ast_strlen_zero(device)) {
3254                 astman_send_error(s, m, "Device: <name> missing.");
3255                 return 0;
3256         }
3257         a[0] = "skinny";
3258         a[1] = "show";
3259         a[2] = "device";
3260         a[3] = device;
3261
3262         _skinny_show_device(1, -1, s, m, 4, a);
3263         astman_append(s, "\r\n\r\n" );
3264         return 0;
3265 }
3266
3267 /*! \brief Show device information */
3268 static char *handle_skinny_show_device(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3269 {
3270         switch (cmd) {
3271         case CLI_INIT:
3272                 e->command = "skinny show device";
3273                 e->usage =
3274                         "Usage: skinny show device <DeviceId|DeviceName>\n"
3275                         "       Lists all deviceinformation of a specific device known to the Skinny subsystem.\n";
3276                 return NULL;
3277         case CLI_GENERATE:
3278                 return complete_skinny_show_device(a->line, a->word, a->pos, a->n);
3279         }
3280
3281         return _skinny_show_device(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
3282 }
3283
3284 static char *_skinny_show_lines(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
3285 {
3286         struct skinny_line *l;
3287         struct skinny_subchannel *sub;
3288         int total_lines = 0;
3289         int verbose = 0;
3290         const char *id;
3291         char idtext[256] = "";
3292
3293         if (s) {        /* Manager - get ActionID */
3294                 id = astman_get_header(m, "ActionID");
3295                 if (!ast_strlen_zero(id))
3296                         snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3297         }
3298
3299         switch (argc) {
3300         case 4:
3301                 verbose = 1;
3302                 break;
3303         case 3:
3304                 verbose = 0;
3305                 break;
3306         default:
3307                 return CLI_SHOWUSAGE;
3308         }
3309
3310         if (!s) {
3311                 ast_cli(fd, "Name                 Device Name          Instance Label               \n");
3312                 ast_cli(fd, "-------------------- -------------------- -------- --------------------\n");
3313         }
3314         AST_LIST_LOCK(&lines);
3315         AST_LIST_TRAVERSE(&lines, l, all) {
3316                 total_lines++;
3317                 if (!s) {
3318                         ast_cli(fd, "%-20s %-20s %8d %-20s\n",
3319                                 l->name,
3320                                 (l->device ? l->device->name : "Not connected"),
3321                                 l->instance,
3322                                 l->label);
3323                         if (verbose) {
3324                                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
3325                                         ast_cli(fd, "  %s> %s to %s\n",
3326                                                 (sub == l->activesub?"Active  ":"Inactive"),
3327                                                 sub->owner->name,
3328                                                 (ast_bridged_channel(sub->owner)?ast_bridged_channel(sub->owner)->name:"")
3329                                         );
3330                                 }
3331                         }
3332                 } else {
3333                         astman_append(s,
3334                                 "Event: LineEntry\r\n%s"
3335                                 "Channeltype: SKINNY\r\n"
3336                                 "ObjectName: %s\r\n"
3337                                 "ChannelObjectType: line\r\n"
3338                                 "Device: %s\r\n"
3339                                 "Instance: %d\r\n"
3340                                 "Label: %s\r\n",
3341                                 idtext,
3342                                 l->name,
3343                                 (l->device?l->device->name:"None"),
3344                                 l->instance,
3345                                 l->label);
3346                 }
3347                 AST_LIST_UNLOCK(&lines);
3348         }
3349
3350         if (total) {
3351                 *total = total_lines;
3352         }
3353
3354         return CLI_SUCCESS;
3355 }
3356
3357 /*! \brief  Show Skinny lines in the manager API */
3358 /*    Inspired from chan_sip */
3359 static int manager_skinny_show_lines(struct mansession *s, const struct message *m)
3360 {
3361         const char *id = astman_get_header(m, "ActionID");
3362         const char *a[] = {"skinny", "show", "lines"};
3363         char idtext[256] = "";
3364         int total = 0;
3365
3366         if (!ast_strlen_zero(id))
3367                 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3368
3369         astman_send_listack(s, m, "Line status list will follow", "start");
3370         /* List the lines in separate manager events */
3371         _skinny_show_lines(-1, &total, s, m, 3, a);
3372         /* Send final confirmation */
3373         astman_append(s,
3374         "Event: LinelistComplete\r\n"
3375         "EventList: Complete\r\n"
3376         "ListItems: %d\r\n"
3377         "%s"
3378         "\r\n", total, idtext);
3379         return 0;
3380 }
3381
3382 static char *handle_skinny_show_lines(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3383 {
3384         int verbose = 0;
3385
3386         switch (cmd) {
3387         case CLI_INIT:
3388                 e->command = "skinny show lines [verbose]";
3389                 e->usage =
3390                         "Usage: skinny show lines\n"
3391                         "       Lists all lines known to the Skinny subsystem.\n"
3392                         "       If 'verbose' is specified, the output includes\n"
3393                         "       information about subs for each line.\n";
3394                 return NULL;
3395         case CLI_GENERATE:
3396                 return NULL;
3397         }
3398
3399         if (a->argc == e->args) {
3400                 if (!strcasecmp(a->argv[e->args-1], "verbose")) {
3401                         verbose = 1;
3402                 } else {
3403                         return CLI_SHOWUSAGE;
3404                 }
3405         } else if (a->argc != e->args - 1) {
3406                 return CLI_SHOWUSAGE;
3407         }
3408
3409         return _skinny_show_lines(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
3410 }
3411
3412 static char *_skinny_show_line(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
3413 {
3414         struct skinny_device *d;
3415         struct skinny_line *l;
3416         struct ast_codec_pref *pref;
3417         int x = 0, codec = 0;
3418         char codec_buf[512];
3419         char group_buf[256];
3420         char cbuf[256];
3421
3422         switch (argc) {
3423         case 4:
3424                 break;
3425         case 6:
3426                 break;
3427         default:
3428                 return CLI_SHOWUSAGE;
3429         }
3430
3431         AST_LIST_LOCK(&devices);
3432
3433         /* Show all lines matching the one supplied */
3434         AST_LIST_TRAVERSE(&devices, d, list) {
3435                 if (argc == 6 && (strcasecmp(argv[5], d->id) && strcasecmp(argv[5], d->name))) {
3436                         continue;
3437                 }
3438                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3439                         if (strcasecmp(argv[3], l->name)) {
3440                                 continue;
3441                         }
3442                         if (type == 0) { /* CLI */
3443                                 ast_cli(fd, "Line:             %s\n", l->name);
3444                                 ast_cli(fd, "On Device:        %s\n", d->name);
3445                                 ast_cli(fd, "Line Label:       %s\n", l->label);
3446                                 ast_cli(fd, "Extension:        %s\n", S_OR(l->exten, "<not set>"));
3447                                 ast_cli(fd, "Context:          %s\n", l->context);
3448                                 ast_cli(fd, "CallGroup:        %s\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
3449                                 ast_cli(fd, "PickupGroup:      %s\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
3450                                 ast_cli(fd, "Language:         %s\n", S_OR(l->language, "<not set>"));
3451                                 ast_cli(fd, "Accountcode:      %s\n", S_OR(l->accountcode, "<not set>"));
3452                                 ast_cli(fd, "AmaFlag:          %s\n", ast_cdr_flags2str(l->amaflags));
3453                                 ast_cli(fd, "CallerId Number:  %s\n", S_OR(l->cid_num, "<not set>"));
3454                                 ast_cli(fd, "CallerId Name:    %s\n", S_OR(l->cid_name, "<not set>"));
3455                                 ast_cli(fd, "Hide CallerId:    %s\n", (l->hidecallerid ? "Yes" : "No"));
3456                                 ast_cli(fd, "CFwdAll:          %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
3457                                 ast_cli(fd, "CFwdBusy:         %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
3458                                 ast_cli(fd, "CFwdNoAnswer:     %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
3459                                 ast_cli(fd, "VoicemailBox:     %s\n", S_OR(l->mailbox, "<not set>"));
3460                                 ast_cli(fd, "VoicemailNumber:  %s\n", S_OR(l->vmexten, "<not set>"));
3461                                 ast_cli(fd, "MWIblink:         %d\n", l->mwiblink);
3462                                 ast_cli(fd, "Regextension:     %s\n", S_OR(l->regexten, "<not set>"));
3463                                 ast_cli(fd, "Regcontext:       %s\n", S_OR(l->regcontext, "<not set>"));
3464                                 ast_cli(fd, "MoHInterpret:     %s\n", S_OR(l->mohinterpret, "<not set>"));
3465                                 ast_cli(fd, "MoHSuggest:       %s\n", S_OR(l->mohsuggest, "<not set>"));
3466                                 ast_cli(fd, "Last dialed nr:   %s\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
3467                                 ast_cli(fd, "Last CallerID:    %s\n", S_OR(l->lastcallerid, "<not set>"));
3468                                 ast_cli(fd, "Transfer enabled: %s\n", (l->transfer ? "Yes" : "No"));
3469                                 ast_cli(fd, "Callwaiting:      %s\n", (l->callwaiting ? "Yes" : "No"));
3470                                 ast_cli(fd, "3Way Calling:     %s\n", (l->threewaycalling ? "Yes" : "No"));
3471                                 ast_cli(fd, "Can forward:      %s\n", (l->cancallforward ? "Yes" : "No"));
3472                                 ast_cli(fd, "Do Not Disturb:   %s\n", (l->dnd ? "Yes" : "No"));
3473                                 ast_cli(fd, "NAT:              %s\n", (l->nat ? "Yes" : "No"));
3474                                 ast_cli(fd, "immediate:        %s\n", (l->immediate ? "Yes" : "No"));
3475                                 ast_cli(fd, "Group:            %d\n", l->group);
3476                                 ast_cli(fd, "Conf Codecs:      ");
3477                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->confcapability);
3478                                 ast_cli(fd, "%s\n", codec_buf);
3479                                 ast_cli(fd, "Neg Codecs:       ");
3480                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->capability);
3481                                 ast_cli(fd, "%s\n", codec_buf);
3482                                 ast_cli(fd, "Codec Order:      (");
3483                                 print_codec_to_cli(fd, &l->prefs);
3484                                 ast_cli(fd, ")\n");
3485                                 ast_cli(fd, "\n");
3486                         } else { /* manager */
3487                                 astman_append(s, "Channeltype: SKINNY\r\n");
3488                                 astman_append(s, "ObjectName: %s\r\n", l->name);
3489                                 astman_append(s, "ChannelObjectType: line\r\n");
3490                                 astman_append(s, "Device: %s\r\n", d->name);
3491                                 astman_append(s, "LineLabel: %s\r\n", l->label);
3492                                 astman_append(s, "Extension: %s\r\n", S_OR(l->exten, "<not set>"));
3493                                 astman_append(s, "Context: %s\r\n", l->context);
3494                                 astman_append(s, "CallGroup: %s\r\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
3495                                 astman_append(s, "PickupGroup: %s\r\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
3496                                 astman_append(s, "Language: %s\r\n", S_OR(l->language, "<not set>"));
3497                                 astman_append(s, "Accountcode: %s\r\n", S_OR(l->accountcode, "<not set>"));
3498                                 astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(l->amaflags));
3499                                 astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), l->cid_name, l->cid_num, ""));
3500                                 astman_append(s, "HideCallerId: %s\r\n", (l->hidecallerid ? "Yes" : "No"));
3501                                 astman_append(s, "CFwdAll: %s\r\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
3502                                 astman_append(s, "CFwdBusy: %s\r\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
3503                                 astman_append(s, "CFwdNoAnswer: %s\r\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
3504                                 astman_append(s, "VoicemailBox: %s\r\n", S_OR(l->mailbox, "<not set>"));
3505                                 astman_append(s, "VoicemailNumber: %s\r\n", S_OR(l->vmexten, "<not set>"));
3506                                 astman_append(s, "MWIblink: %d\r\n", l->mwiblink);
3507                                 astman_append(s, "RegExtension: %s\r\n", S_OR(l->regexten, "<not set>"));
3508                                 astman_append(s, "Regcontext: %s\r\n", S_OR(l->regcontext, "<not set>"));
3509                                 astman_append(s, "MoHInterpret: %s\r\n", S_OR(l->mohinterpret, "<not set>"));
3510                                 astman_append(s, "MoHSuggest: %s\r\n", S_OR(l->mohsuggest, "<not set>"));
3511                                 astman_append(s, "LastDialedNr: %s\r\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
3512                                 astman_append(s, "LastCallerID: %s\r\n", S_OR(l->lastcallerid, "<not set>"));
3513                                 astman_append(s, "Transfer: %s\r\n", (l->transfer ? "Yes" : "No"));
3514                                 astman_append(s, "Callwaiting: %s\r\n", (l->callwaiting ? "Yes" : "No"));
3515                                 astman_append(s, "3WayCalling: %s\r\n", (l->threewaycalling ? "Yes" : "No"));
3516                                 astman_append(s, "CanForward: %s\r\n", (l->cancallforward ? "Yes" : "No"));
3517                                 astman_append(s, "DoNotDisturb: %s\r\n", (l->dnd ? "Yes" : "No"));
3518                                 astman_append(s, "NAT: %s\r\n", (l->nat ? "Yes" : "No"));
3519                                 astman_append(s, "immediate: %s\r\n", (l->immediate ? "Yes" : "No"));
3520                                 astman_append(s, "Group: %d\r\n", l->group);
3521                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->confcapability);
3522                                 astman_append(s, "Codecs: %s\r\n", codec_buf);
3523                                 astman_append(s, "CodecOrder: ");
3524                                 pref = &l->prefs;
3525                                 for(x = 0; x < 32 ; x++) {
3526                                         codec = ast_codec_pref_index(pref, x);
3527                                         if (!codec)
3528                                                 break;
3529                                         astman_append(s, "%s", ast_getformatname(codec));
3530                                         if (x < 31 && ast_codec_pref_index(pref, x+1))
3531                                                 astman_append(s, ",");
3532                                 }
3533                                 astman_append(s, "\r\n");
3534                         }
3535                 }
3536         }
3537         
3538         AST_LIST_UNLOCK(&devices);
3539         return CLI_SUCCESS;
3540 }
3541
3542 static int manager_skinny_show_line(struct mansession *s, const struct message *m)
3543 {
3544         const char *a[4];
3545         const char *line;
3546
3547         line = astman_get_header(m, "Line");
3548         if (ast_strlen_zero(line)) {
3549                 astman_send_error(s, m, "Line: <name> missing.");
3550                 return 0;
3551         }
3552         a[0] = "skinny";
3553         a[1] = "show";
3554         a[2] = "line";
3555         a[3] = line;
3556
3557         _skinny_show_line(1, -1, s, m, 4, a);
3558         astman_append(s, "\r\n\r\n" );
3559         return 0;
3560 }
3561
3562 /*! \brief List line information. */
3563 static char *handle_skinny_show_line(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3564 {
3565         switch (cmd) {
3566         case CLI_INIT:
3567                 e->command = "skinny show line";
3568                 e->usage =
3569                         "Usage: skinny show line <Line> [ on <DeviceID|DeviceName> ]\n"
3570                         "       List all lineinformation of a specific line known to the Skinny subsystem.\n";
3571                 return NULL;
3572         case CLI_GENERATE:
3573                 return complete_skinny_show_line(a->line, a->word, a->pos, a->n);
3574         }
3575
3576         return _skinny_show_line(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
3577 }
3578
3579 /*! \brief List global settings for the Skinny subsystem. */
3580 static char *handle_skinny_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3581 {
3582         switch (cmd) {
3583         case CLI_INIT:
3584                 e->command = "skinny show settings";
3585                 e->usage =
3586                         "Usage: skinny show settings\n"
3587                         "       Lists all global configuration settings of the Skinny subsystem.\n";
3588                 return NULL;
3589         case CLI_GENERATE:
3590                 return NULL;
3591         }       
3592
3593         if (a->argc != 3)
3594                 return CLI_SHOWUSAGE;
3595
3596         ast_cli(a->fd, "\nGlobal Settings:\n");
3597         ast_cli(a->fd, "  Skinny Port:            %d\n", ntohs(bindaddr.sin_port));
3598         ast_cli(a->fd, "  Bindaddress:            %s\n", ast_inet_ntoa(bindaddr.sin_addr));
3599         ast_cli(a->fd, "  KeepAlive:              %d\n", keep_alive);
3600         ast_cli(a->fd, "  Date Format:            %s\n", date_format);
3601         ast_cli(a->fd, "  Voice Mail Extension:   %s\n", S_OR(global_vmexten, "(not set)"));
3602         ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(regcontext, "(not set)"));
3603         ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", (ast_test_flag(&global_jbconf, AST_JB_ENABLED) ? "Yes" : "No"));
3604         ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", (ast_test_flag(&global_jbconf, AST_JB_FORCED) ? "Yes" : "No"));
3605         ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
3606         ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
3607         ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
3608         ast_cli(a->fd, "  Jitterbuffer log:       %s\n", (ast_test_flag(&global_jbconf, AST_JB_LOG) ? "Yes" : "No"));
3609
3610         return CLI_SUCCESS;
3611 }
3612
3613 static struct ast_cli_entry cli_skinny[] = {
3614         AST_CLI_DEFINE(handle_skinny_show_devices, "List defined Skinny devices"),
3615         AST_CLI_DEFINE(handle_skinny_show_device, "List Skinny device information"),
3616         AST_CLI_DEFINE(handle_skinny_show_lines, "List defined Skinny lines per device"),
3617         AST_CLI_DEFINE(handle_skinny_show_line, "List Skinny line information"),
3618         AST_CLI_DEFINE(handle_skinny_show_settings, "List global Skinny settings"),
3619         AST_CLI_DEFINE(handle_skinny_set_debug, "Enable/Disable Skinny debugging"),
3620         AST_CLI_DEFINE(handle_skinny_reset, "Reset Skinny device(s)"),
3621         AST_CLI_DEFINE(handle_skinny_reload, "Reload Skinny config"),
3622 };
3623
3624 static void start_rtp(struct skinny_subchannel *sub)
3625 {
3626         struct skinny_line *l = sub->parent;
3627         struct skinny_device *d = l->device;
3628         int hasvideo = 0;
3629
3630         ast_mutex_lock(&sub->lock);
3631         /* Allocate the RTP */
3632         sub->rtp = ast_rtp_instance_new(NULL, sched, &bindaddr, NULL);
3633         if (hasvideo)
3634                 sub->vrtp = ast_rtp_instance_new(NULL, sched, &bindaddr, NULL);
3635
3636         if (sub->rtp) {
3637                 ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_RTCP, 1);
3638         }
3639         if (sub->vrtp) {
3640                 ast_rtp_instance_set_prop(sub->vrtp, AST_RTP_PROPERTY_RTCP, 1);
3641         }
3642
3643         if (sub->rtp && sub->owner) {
3644                 ast_channel_set_fd(sub->owner, 0, ast_rtp_instance_fd(sub->rtp, 0));
3645                 ast_channel_set_fd(sub->owner, 1, ast_rtp_instance_fd(sub->rtp, 1));
3646         }
3647         if (hasvideo && sub->vrtp && sub->owner) {
3648                 ast_channel_set_fd(sub->owner, 2, ast_rtp_instance_fd(sub->vrtp, 0));
3649                 ast_channel_set_fd(sub->owner, 3, ast_rtp_instance_fd(sub->vrtp, 1));
3650         }
3651         if (sub->rtp) {
3652                 ast_rtp_instance_set_qos(sub->rtp, qos.tos_audio, qos.cos_audio, "Skinny RTP");
3653                 ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_NAT, l->nat);
3654         }
3655         if (sub->vrtp) {
3656                 ast_rtp_instance_set_qos(sub->vrtp, qos.tos_video, qos.cos_video, "Skinny VRTP");
3657                 ast_rtp_instance_set_prop(sub->vrtp, AST_RTP_PROPERTY_NAT, l->nat);
3658         }
3659         /* Set Frame packetization */
3660         if (sub->rtp)
3661                 ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, &l->prefs);
3662
3663         /* Create the RTP connection */
3664         transmit_connect(d, sub);
3665         ast_mutex_unlock(&sub->lock);
3666 }
3667
3668 static void *skinny_newcall(void *data)
3669 {
3670         struct ast_channel *c = data;