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