Add a couple of manager commands to chan_skinny
[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
974 /* a hostname, portnumber, socket and such is usefull for VoIP protocols */
975 static struct sockaddr_in bindaddr;
976 static char ourhost[256];
977 static int ourport;
978 static struct in_addr __ourip;
979 struct ast_hostent ahp;
980 struct hostent *hp;
981 static int skinnysock = -1;
982 static pthread_t accept_t;
983 static int callnums = 1;
984
985 #define SKINNY_DEVICE_UNKNOWN -1
986 #define SKINNY_DEVICE_NONE 0
987 #define SKINNY_DEVICE_30SPPLUS 1
988 #define SKINNY_DEVICE_12SPPLUS 2
989 #define SKINNY_DEVICE_12SP 3
990 #define SKINNY_DEVICE_12 4
991 #define SKINNY_DEVICE_30VIP 5
992 #define SKINNY_DEVICE_7910 6
993 #define SKINNY_DEVICE_7960 7
994 #define SKINNY_DEVICE_7940 8
995 #define SKINNY_DEVICE_7935 9
996 #define SKINNY_DEVICE_ATA186 12 /* Cisco ATA-186 */
997 #define SKINNY_DEVICE_7941 115
998 #define SKINNY_DEVICE_7971 119
999 #define SKINNY_DEVICE_7914 124 /* Expansion module */
1000 #define SKINNY_DEVICE_7985 302
1001 #define SKINNY_DEVICE_7911 307
1002 #define SKINNY_DEVICE_7961GE 308
1003 #define SKINNY_DEVICE_7941GE 309
1004 #define SKINNY_DEVICE_7931 348
1005 #define SKINNY_DEVICE_7921 365
1006 #define SKINNY_DEVICE_7906 369
1007 #define SKINNY_DEVICE_7962 404 /* Not found */
1008 #define SKINNY_DEVICE_7937 431
1009 #define SKINNY_DEVICE_7942 434
1010 #define SKINNY_DEVICE_7945 435
1011 #define SKINNY_DEVICE_7965 436
1012 #define SKINNY_DEVICE_7975 437
1013 #define SKINNY_DEVICE_7905 20000
1014 #define SKINNY_DEVICE_7920 30002
1015 #define SKINNY_DEVICE_7970 30006
1016 #define SKINNY_DEVICE_7912 30007
1017 #define SKINNY_DEVICE_7902 30008
1018 #define SKINNY_DEVICE_CIPC 30016 /* Cisco IP Communicator */
1019 #define SKINNY_DEVICE_7961 30018
1020 #define SKINNY_DEVICE_7936 30019
1021 #define SKINNY_DEVICE_SCCPGATEWAY_AN 30027 /* Analog gateway */
1022 #define SKINNY_DEVICE_SCCPGATEWAY_BRI 30028 /* BRI gateway */
1023
1024 #define SKINNY_SPEAKERON 1
1025 #define SKINNY_SPEAKEROFF 2
1026
1027 #define SKINNY_MICON 1
1028 #define SKINNY_MICOFF 2
1029
1030 #define SKINNY_OFFHOOK 1
1031 #define SKINNY_ONHOOK 2
1032 #define SKINNY_RINGOUT 3
1033 #define SKINNY_RINGIN 4
1034 #define SKINNY_CONNECTED 5
1035 #define SKINNY_BUSY 6
1036 #define SKINNY_CONGESTION 7
1037 #define SKINNY_HOLD 8
1038 #define SKINNY_CALLWAIT 9
1039 #define SKINNY_TRANSFER 10
1040 #define SKINNY_PARK 11
1041 #define SKINNY_PROGRESS 12
1042 #define SKINNY_CALLREMOTEMULTILINE 13
1043 #define SKINNY_INVALID 14
1044
1045 #define SKINNY_SILENCE 0x00
1046 #define SKINNY_DIALTONE 0x21
1047 #define SKINNY_BUSYTONE 0x23
1048 #define SKINNY_ALERT 0x24
1049 #define SKINNY_REORDER 0x25
1050 #define SKINNY_CALLWAITTONE 0x2D
1051 #define SKINNY_NOTONE 0x7F
1052
1053 #define SKINNY_LAMP_OFF 1
1054 #define SKINNY_LAMP_ON 2
1055 #define SKINNY_LAMP_WINK 3
1056 #define SKINNY_LAMP_FLASH 4
1057 #define SKINNY_LAMP_BLINK 5
1058
1059 #define SKINNY_RING_OFF 1
1060 #define SKINNY_RING_INSIDE 2
1061 #define SKINNY_RING_OUTSIDE 3
1062 #define SKINNY_RING_FEATURE 4
1063
1064 #define SKINNY_CFWD_ALL       (1 << 0)
1065 #define SKINNY_CFWD_BUSY      (1 << 1)
1066 #define SKINNY_CFWD_NOANSWER  (1 << 2)
1067
1068 /* Skinny rtp stream modes. Do we really need this? */
1069 #define SKINNY_CX_SENDONLY 0
1070 #define SKINNY_CX_RECVONLY 1
1071 #define SKINNY_CX_SENDRECV 2
1072 #define SKINNY_CX_CONF 3
1073 #define SKINNY_CX_CONFERENCE 3
1074 #define SKINNY_CX_MUTE 4
1075 #define SKINNY_CX_INACTIVE 4
1076
1077 #if 0
1078 static char *skinny_cxmodes[] = {
1079         "sendonly",
1080         "recvonly",
1081         "sendrecv",
1082         "confrnce",
1083         "inactive"
1084 };
1085 #endif
1086
1087 /* driver scheduler */
1088 static struct sched_context *sched = NULL;
1089 static struct io_context *io;
1090
1091 /* Protect the monitoring thread, so only one process can kill or start it, and not
1092    when it's doing something critical. */
1093 AST_MUTEX_DEFINE_STATIC(monlock);
1094 /* Protect the network socket */
1095 AST_MUTEX_DEFINE_STATIC(netlock);
1096
1097 /* This is the thread for the monitor which checks for input on the channels
1098    which are not currently in use. */
1099 static pthread_t monitor_thread = AST_PTHREADT_NULL;
1100
1101 /* Wait up to 16 seconds for first digit */
1102 static int firstdigittimeout = 16000;
1103
1104 /* How long to wait for following digits */
1105 static int gendigittimeout = 8000;
1106
1107 /* How long to wait for an extra digit, if there is an ambiguous match */
1108 static int matchdigittimeout = 3000;
1109
1110 struct skinny_subchannel {
1111         ast_mutex_t lock;
1112         struct ast_channel *owner;
1113         struct ast_rtp *rtp;
1114         struct ast_rtp *vrtp;
1115         unsigned int callid;
1116         /* time_t lastouttime; */ /* Unused */
1117         int progress;
1118         int ringing;
1119         int onhold;
1120         /* int lastout; */ /* Unused */
1121         int cxmode;
1122         int nat;
1123         int outgoing;
1124         int alreadygone;
1125         int blindxfer;
1126         int xferor;
1127
1128
1129         AST_LIST_ENTRY(skinny_subchannel) list;
1130         struct skinny_subchannel *related;
1131         struct skinny_line *parent;
1132 };
1133
1134 #define SKINNY_LINE_OPTIONS                             \
1135         char name[80];                                  \
1136         char label[24];                                 \
1137         char accountcode[AST_MAX_ACCOUNT_CODE];         \
1138         char exten[AST_MAX_EXTENSION];                  \
1139         char context[AST_MAX_CONTEXT];                  \
1140         char language[MAX_LANGUAGE];                    \
1141         char cid_num[AST_MAX_EXTENSION];                \
1142         char cid_name[AST_MAX_EXTENSION];               \
1143         char lastcallerid[AST_MAX_EXTENSION];           \
1144         int cfwdtype;                                   \
1145         char call_forward_all[AST_MAX_EXTENSION];       \
1146         char call_forward_busy[AST_MAX_EXTENSION];      \
1147         char call_forward_noanswer[AST_MAX_EXTENSION];  \
1148         char mailbox[AST_MAX_EXTENSION];                \
1149         char vmexten[AST_MAX_EXTENSION];                \
1150         char regexten[AST_MAX_EXTENSION];               \
1151         char regcontext[AST_MAX_CONTEXT];               \
1152         char parkinglot[AST_MAX_CONTEXT];               \
1153         char mohinterpret[MAX_MUSICCLASS];              \
1154         char mohsuggest[MAX_MUSICCLASS];                \
1155         char lastnumberdialed[AST_MAX_EXTENSION];       \
1156         int curtone;                                    \
1157         ast_group_t callgroup;                          \
1158         ast_group_t pickupgroup;                        \
1159         int callwaiting;                                \
1160         int transfer;                                   \
1161         int threewaycalling;                            \
1162         int mwiblink;                                   \
1163         int cancallforward;                             \
1164         int getforward;                                 \
1165         int callreturn;                                 \
1166         int dnd;                                        \
1167         int hascallerid;                                \
1168         int hidecallerid;                               \
1169         int amaflags;                                   \
1170         int type;                                       \
1171         int instance;                                   \
1172         int group;                                      \
1173         int needdestroy;                                \
1174         int confcapability;                             \
1175         struct ast_codec_pref confprefs;                \
1176         int capability;                                 \
1177         struct ast_codec_pref prefs;                    \
1178         int nonCodecCapability;                         \
1179         int onhooktime;                                 \
1180         int msgstate;                                   \
1181         int immediate;                                  \
1182         int hookstate;                                  \
1183         int nat;                                        \
1184         int canreinvite;
1185
1186 struct skinny_line {
1187         SKINNY_LINE_OPTIONS
1188         ast_mutex_t lock;
1189         struct ast_event_sub *mwi_event_sub; /* Event based MWI */
1190         struct skinny_subchannel *activesub;
1191         AST_LIST_HEAD(, skinny_subchannel) sub;
1192         AST_LIST_ENTRY(skinny_line) list;
1193         AST_LIST_ENTRY(skinny_line) all;
1194         struct skinny_device *device;
1195         struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1196         int newmsgs;
1197 };
1198
1199 struct skinny_line_options{
1200         SKINNY_LINE_OPTIONS
1201 } default_line_struct = {
1202         .callwaiting = 1,
1203         .transfer = 1,
1204         .mwiblink = 0,
1205         .dnd = 0,
1206         .hidecallerid = 0,
1207         .amaflags = 0,
1208         .instance = 0,
1209         .canreinvite = 0,
1210         .nat = 0,
1211         .confcapability = AST_FORMAT_ULAW | AST_FORMAT_ALAW,
1212         .capability = 0,
1213         .getforward = 0,
1214         .needdestroy = 0,
1215         .hookstate = SKINNY_ONHOOK,
1216 };
1217 struct skinny_line_options *default_line = &default_line_struct;
1218
1219 static AST_LIST_HEAD_STATIC(lines, skinny_line);
1220
1221 struct skinny_speeddial {
1222         ast_mutex_t lock;
1223         char label[42];
1224         char context[AST_MAX_CONTEXT];
1225         char exten[AST_MAX_EXTENSION];
1226         int instance;
1227         int stateid;
1228         int laststate;
1229         int isHint;
1230
1231         AST_LIST_ENTRY(skinny_speeddial) list;
1232         struct skinny_device *parent;
1233 };
1234
1235 struct skinny_addon {
1236         ast_mutex_t lock;
1237         char type[10];
1238         AST_LIST_ENTRY(skinny_addon) list;
1239         struct skinny_device *parent;
1240 };
1241
1242 #define SKINNY_DEVICE_OPTIONS                                   \
1243         char name[80];                                          \
1244         char id[16];                                            \
1245         char version_id[16];                                    \
1246         char exten[AST_MAX_EXTENSION];                          \
1247         char vmexten[AST_MAX_EXTENSION];                        \
1248         int type;                                               \
1249         int registered;                                         \
1250         int lastlineinstance;                                   \
1251         int lastcallreference;                                  \
1252         int confcapability;                                     \
1253         struct ast_codec_pref confprefs;                        \
1254         int capability;                                         \
1255         int earlyrtp;                                           \
1256         int transfer;                                           \
1257         int callwaiting;                                        \
1258         int mwiblink;                                           \
1259         int dnd;
1260
1261 struct skinny_device {
1262         SKINNY_DEVICE_OPTIONS
1263         struct type *first;
1264         struct type *last;
1265         ast_mutex_t lock;
1266         struct sockaddr_in addr;
1267         struct in_addr ourip;
1268         struct ast_ha *ha;
1269         struct skinnysession *session;
1270         struct skinny_line *activeline;
1271         AST_LIST_HEAD(, skinny_line) lines;
1272         AST_LIST_HEAD(, skinny_speeddial) speeddials;
1273         AST_LIST_HEAD(, skinny_addon) addons;
1274         AST_LIST_ENTRY(skinny_device) list;
1275 };
1276
1277 struct skinny_device_options{
1278         SKINNY_DEVICE_OPTIONS
1279 } default_device_struct = {
1280         .transfer = 1,
1281         .earlyrtp = 1,
1282         .callwaiting = 1,
1283         .mwiblink = 0,
1284         .dnd = 0,
1285         .confcapability = AST_FORMAT_ULAW | AST_FORMAT_ALAW,
1286         .capability = 0,
1287 };
1288 struct skinny_device_options *default_device = &default_device_struct;
1289         
1290 static AST_LIST_HEAD_STATIC(devices, skinny_device);
1291
1292 /*static struct ast_jb_conf default_jbconf =
1293 {
1294         .flags = 0,
1295         .max_size = -1,
1296         .resync_threshold = -1,
1297         .impl = ""
1298 };
1299 static struct ast_jb_conf global_jbconf;*/
1300
1301 struct skinnysession {
1302         pthread_t t;
1303         ast_mutex_t lock;
1304         struct sockaddr_in sin;
1305         int fd;
1306         char inbuf[SKINNY_MAX_PACKET];
1307         char outbuf[SKINNY_MAX_PACKET];
1308         struct skinny_device *device;
1309         AST_LIST_ENTRY(skinnysession) list;
1310 };
1311
1312 static AST_LIST_HEAD_STATIC(sessions, skinnysession);
1313
1314 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause);
1315 static int skinny_devicestate(void *data);
1316 static int skinny_call(struct ast_channel *ast, char *dest, int timeout);
1317 static int skinny_hangup(struct ast_channel *ast);
1318 static int skinny_answer(struct ast_channel *ast);
1319 static struct ast_frame *skinny_read(struct ast_channel *ast);
1320 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1321 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1322 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1323 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1324 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1325 static int handle_time_date_req_message(struct skinny_req *req, struct skinnysession *s);
1326 static void mwi_event_cb(const struct ast_event *event, void *userdata);
1327
1328 static const struct ast_channel_tech skinny_tech = {
1329         .type = "Skinny",
1330         .description = tdesc,
1331         .capabilities = AST_FORMAT_AUDIO_MASK,
1332         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1333         .requester = skinny_request,
1334         .devicestate = skinny_devicestate,
1335         .call = skinny_call,
1336         .hangup = skinny_hangup,
1337         .answer = skinny_answer,
1338         .read = skinny_read,
1339         .write = skinny_write,
1340         .indicate = skinny_indicate,
1341         .fixup = skinny_fixup,
1342         .send_digit_begin = skinny_senddigit_begin,
1343         .send_digit_end = skinny_senddigit_end,
1344         .bridge = ast_rtp_bridge,  
1345 };
1346
1347 static int skinny_extensionstate_cb(char *context, char* exten, int state, void *data);
1348 static int skinny_transfer(struct skinny_subchannel *sub);
1349
1350 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1351 {
1352         struct skinny_device *d = s->device;
1353         struct skinny_addon *a;
1354         int i;
1355
1356         switch (d->type) {
1357                 case SKINNY_DEVICE_30SPPLUS:
1358                 case SKINNY_DEVICE_30VIP:
1359                         /* 13 rows, 2 columns */
1360                         for (i = 0; i < 4; i++)
1361                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1362                         (btn++)->buttonDefinition = BT_REDIAL;
1363                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1364                         (btn++)->buttonDefinition = BT_CALLPARK;
1365                         (btn++)->buttonDefinition = BT_FORWARDALL;
1366                         (btn++)->buttonDefinition = BT_CONFERENCE;
1367                         for (i = 0; i < 4; i++)
1368                                 (btn++)->buttonDefinition = BT_NONE;
1369                         for (i = 0; i < 13; i++)
1370                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1371                         
1372                         break;
1373                 case SKINNY_DEVICE_12SPPLUS:
1374                 case SKINNY_DEVICE_12SP:
1375                 case SKINNY_DEVICE_12:
1376                         /* 6 rows, 2 columns */
1377                         for (i = 0; i < 2; i++)
1378                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1379                         for (i = 0; i < 4; i++)
1380                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1381                         (btn++)->buttonDefinition = BT_HOLD;
1382                         (btn++)->buttonDefinition = BT_REDIAL;
1383                         (btn++)->buttonDefinition = BT_TRANSFER;
1384                         (btn++)->buttonDefinition = BT_FORWARDALL;
1385                         (btn++)->buttonDefinition = BT_CALLPARK;
1386                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1387                         break;
1388                 case SKINNY_DEVICE_7910:
1389                         (btn++)->buttonDefinition = BT_LINE;
1390                         (btn++)->buttonDefinition = BT_HOLD;
1391                         (btn++)->buttonDefinition = BT_TRANSFER;
1392                         (btn++)->buttonDefinition = BT_DISPLAY;
1393                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1394                         (btn++)->buttonDefinition = BT_CONFERENCE;
1395                         (btn++)->buttonDefinition = BT_FORWARDALL;
1396                         for (i = 0; i < 2; i++)
1397                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1398                         (btn++)->buttonDefinition = BT_REDIAL;
1399                         break;
1400                 case SKINNY_DEVICE_7960:
1401                 case SKINNY_DEVICE_7961:
1402                 case SKINNY_DEVICE_7961GE:
1403                 case SKINNY_DEVICE_7962:
1404                 case SKINNY_DEVICE_7965:
1405                         for (i = 0; i < 6; i++)
1406                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1407                         break;
1408                 case SKINNY_DEVICE_7940:
1409                 case SKINNY_DEVICE_7941:
1410                 case SKINNY_DEVICE_7941GE:
1411                 case SKINNY_DEVICE_7942:
1412                 case SKINNY_DEVICE_7945:
1413                         for (i = 0; i < 2; i++)
1414                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1415                         break;
1416                 case SKINNY_DEVICE_7935:
1417                 case SKINNY_DEVICE_7936:
1418                         for (i = 0; i < 2; i++)
1419                                 (btn++)->buttonDefinition = BT_LINE;
1420                         break;
1421                 case SKINNY_DEVICE_ATA186:
1422                         (btn++)->buttonDefinition = BT_LINE;
1423                         break;
1424                 case SKINNY_DEVICE_7970:
1425                 case SKINNY_DEVICE_7971:
1426                 case SKINNY_DEVICE_7975:
1427                 case SKINNY_DEVICE_CIPC:
1428                         for (i = 0; i < 8; i++)
1429                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1430                         break;
1431                 case SKINNY_DEVICE_7985:
1432                         /* XXX I have no idea what the buttons look like on these. */
1433                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1434                         break;
1435                 case SKINNY_DEVICE_7912:
1436                 case SKINNY_DEVICE_7911:
1437                 case SKINNY_DEVICE_7905:
1438                         (btn++)->buttonDefinition = BT_LINE;
1439                         (btn++)->buttonDefinition = BT_HOLD;
1440                         break;
1441                 case SKINNY_DEVICE_7920:
1442                         /* XXX I don't know if this is right. */
1443                         for (i = 0; i < 4; i++)
1444                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1445                         break;
1446                 case SKINNY_DEVICE_7921:
1447                         for (i = 0; i < 6; i++)
1448                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1449                         break;
1450                 case SKINNY_DEVICE_7902:
1451                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1452                         break;
1453                 case SKINNY_DEVICE_7906:
1454                         ast_log(LOG_WARNING, "Unsupported device type '%d (7906)' found.\n", d->type);
1455                         break;
1456                 case SKINNY_DEVICE_7931:
1457                         ast_log(LOG_WARNING, "Unsupported device type '%d (7931)' found.\n", d->type);
1458                         break;
1459                 case SKINNY_DEVICE_7937:
1460                         ast_log(LOG_WARNING, "Unsupported device type '%d (7937)' found.\n", d->type);
1461                         break;
1462                 case SKINNY_DEVICE_7914:
1463                         ast_log(LOG_WARNING, "Unsupported device type '%d (7914)' found.  Expansion module registered by itself?\n", d->type);
1464                         break;
1465                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1466                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1467                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1468                         break;
1469                 default:
1470                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1471                         break;
1472         }
1473
1474         AST_LIST_LOCK(&d->addons);
1475         AST_LIST_TRAVERSE(&d->addons, a, list) {
1476                 if (!strcasecmp(a->type, "7914")) {
1477                         for (i = 0; i < 14; i++)
1478                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1479                 } else {
1480                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1481                 }
1482         }
1483         AST_LIST_UNLOCK(&d->addons);
1484
1485         return btn;
1486 }
1487
1488 static struct skinny_req *req_alloc(size_t size, int response_message)
1489 {
1490         struct skinny_req *req;
1491
1492         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1493                 return NULL;
1494
1495         req->len = htolel(size+4);
1496         req->e = htolel(response_message);
1497
1498         return req;
1499 }
1500
1501 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1502 {
1503         struct skinny_line *l;
1504
1505         /*Dialing from on hook or on a 7920 uses instance 0 in requests
1506           but we need to start looking at instance 1 */
1507
1508         if (!instance)
1509                 instance = 1;
1510
1511         AST_LIST_TRAVERSE(&d->lines, l, list){
1512                 if (l->instance == instance)
1513                         break;
1514         }
1515
1516         if (!l) {
1517                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1518         }
1519         return l;
1520 }
1521
1522 static struct skinny_line *find_line_by_name(const char *dest)
1523 {
1524         struct skinny_line *l;
1525         struct skinny_line *tmpl = NULL;
1526         struct skinny_device *d;
1527         char line[256];
1528         char *at;
1529         char *device;
1530         int checkdevice = 0;
1531
1532         ast_copy_string(line, dest, sizeof(line));
1533         at = strchr(line, '@');
1534         if (at)
1535                 *at++ = '\0';
1536         device = at;
1537
1538         if (!ast_strlen_zero(device))
1539                 checkdevice = 1;
1540
1541         AST_LIST_LOCK(&devices);
1542         AST_LIST_TRAVERSE(&devices, d, list){
1543                 if (checkdevice && tmpl)
1544                         break;
1545                 else if (!checkdevice) {
1546                         /* This is a match, since we're checking for line on every device. */
1547                 } else if (!strcasecmp(d->name, device)) {
1548                         if (skinnydebug)
1549                                 ast_verb(2, "Found device: %s\n", d->name);
1550                 } else
1551                         continue;
1552
1553                 /* Found the device (or we don't care which device) */
1554                 AST_LIST_TRAVERSE(&d->lines, l, list){
1555                         /* Search for the right line */
1556                         if (!strcasecmp(l->name, line)) {
1557                                 if (tmpl) {
1558                                         ast_verb(2, "Ambiguous line name: %s\n", line);
1559                                         AST_LIST_UNLOCK(&devices);
1560                                         return NULL;
1561                                 } else
1562                                         tmpl = l;
1563                         }
1564                 }
1565         }
1566         AST_LIST_UNLOCK(&devices);
1567         return tmpl;
1568 }
1569
1570 /*!
1571  * implement the setvar config line
1572  */
1573 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
1574 {
1575         struct ast_variable *tmpvar = NULL;
1576         char *varname = ast_strdupa(buf), *varval = NULL;
1577
1578         if ((varval = strchr(varname,'='))) {
1579                 *varval++ = '\0';
1580                 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
1581                         tmpvar->next = list;
1582                         list = tmpvar;
1583                 }
1584         }
1585         return list;
1586 }
1587
1588 /* It's quicker/easier to find the subchannel when we know the instance number too */
1589 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
1590 {
1591         struct skinny_line *l = find_line_by_instance(d, instance);
1592         struct skinny_subchannel *sub;
1593
1594         if (!l) {
1595                 return NULL;
1596         }
1597
1598         /* 7920 phones set call reference to 0, so use the first
1599            sub-channel on the list.
1600            This MIGHT need more love to be right */
1601         if (!reference)
1602                 sub = AST_LIST_FIRST(&l->sub);
1603         else {
1604                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
1605                         if (sub->callid == reference)
1606                                 break;
1607                 }
1608         }
1609         if (!sub) {
1610                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
1611         }
1612         return sub;
1613 }
1614
1615 /* Find the subchannel when we only have the callid - this shouldn't happen often */
1616 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
1617 {
1618         struct skinny_line *l;
1619         struct skinny_subchannel *sub = NULL;
1620
1621         AST_LIST_TRAVERSE(&d->lines, l, list){
1622                 AST_LIST_TRAVERSE(&l->sub, sub, list){
1623                         if (sub->callid == reference)
1624                                 break;
1625                 }
1626                 if (sub)
1627                         break;
1628         }
1629
1630         if (!l) {
1631                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
1632         } else {
1633                 if (!sub) {
1634                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
1635                 }
1636         }
1637         return sub;
1638 }
1639
1640 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
1641 {
1642         struct skinny_speeddial *sd;
1643
1644         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1645                 if (sd->isHint == isHint && sd->instance == instance)
1646                         break;
1647         }
1648
1649         if (!sd) {
1650                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
1651         }
1652         return sd;
1653 }
1654
1655 static int codec_skinny2ast(enum skinny_codecs skinnycodec)
1656 {
1657         switch (skinnycodec) {
1658         case SKINNY_CODEC_ALAW:
1659                 return AST_FORMAT_ALAW;
1660         case SKINNY_CODEC_ULAW:
1661                 return AST_FORMAT_ULAW;
1662         case SKINNY_CODEC_G723_1:
1663                 return AST_FORMAT_G723_1;
1664         case SKINNY_CODEC_G729A:
1665                 return AST_FORMAT_G729A;
1666         case SKINNY_CODEC_G726_32:
1667                 return AST_FORMAT_G726_AAL2; /* XXX Is this right? */
1668         case SKINNY_CODEC_H261:
1669                 return AST_FORMAT_H261;
1670         case SKINNY_CODEC_H263:
1671                 return AST_FORMAT_H263;
1672         default:
1673                 return 0;
1674         }
1675 }
1676
1677 static int codec_ast2skinny(int astcodec)
1678 {
1679         switch (astcodec) {
1680         case AST_FORMAT_ALAW:
1681                 return SKINNY_CODEC_ALAW;
1682         case AST_FORMAT_ULAW:
1683                 return SKINNY_CODEC_ULAW;
1684         case AST_FORMAT_G723_1:
1685                 return SKINNY_CODEC_G723_1;
1686         case AST_FORMAT_G729A:
1687                 return SKINNY_CODEC_G729A;
1688         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
1689                 return SKINNY_CODEC_G726_32;
1690         case AST_FORMAT_H261:
1691                 return SKINNY_CODEC_H261;
1692         case AST_FORMAT_H263:
1693                 return SKINNY_CODEC_H263;
1694         default:
1695                 return 0;
1696         }
1697 }
1698
1699 static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
1700 {
1701         if (!l)
1702                 return 0;
1703
1704         if (!ast_strlen_zero(cfwd)) {
1705                 if (cfwdtype & SKINNY_CFWD_ALL) {
1706                         l->cfwdtype |= SKINNY_CFWD_ALL;
1707                         ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
1708                 }
1709                 if (cfwdtype & SKINNY_CFWD_BUSY) {
1710                         l->cfwdtype |= SKINNY_CFWD_BUSY;
1711                         ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
1712                 }
1713                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
1714                         l->cfwdtype |= SKINNY_CFWD_NOANSWER;
1715                         ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
1716                 }
1717         } else {
1718                 if (cfwdtype & SKINNY_CFWD_ALL) {
1719                         l->cfwdtype &= ~SKINNY_CFWD_ALL;
1720                         memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
1721                 }
1722                 if (cfwdtype & SKINNY_CFWD_BUSY) {
1723                         l->cfwdtype &= ~SKINNY_CFWD_BUSY;
1724                         memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
1725                 }
1726                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
1727                         l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
1728                         memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
1729                 }
1730         }
1731         return l->cfwdtype;
1732 }
1733
1734 static void cleanup_stale_contexts(char *new, char *old)
1735 {
1736         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
1737
1738         while ((oldcontext = strsep(&old, "&"))) {
1739                 stalecontext = '\0';
1740                 ast_copy_string(newlist, new, sizeof(newlist));
1741                 stringp = newlist;
1742                 while ((newcontext = strsep(&stringp, "&"))) {
1743                         if (strcmp(newcontext, oldcontext) == 0) {
1744                                 /* This is not the context you're looking for */
1745                                 stalecontext = '\0';
1746                                 break;
1747                         } else if (strcmp(newcontext, oldcontext)) {
1748                                 stalecontext = oldcontext;
1749                         }
1750                         
1751                 }
1752                 if (stalecontext)
1753                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
1754         }
1755 }
1756
1757 static void register_exten(struct skinny_line *l)
1758 {
1759         char multi[256];
1760         char *stringp, *ext, *context;
1761
1762         if (ast_strlen_zero(regcontext))
1763                 return;
1764
1765         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1766         stringp = multi;
1767         while ((ext = strsep(&stringp, "&"))) {
1768                 if ((context = strchr(ext, '@'))) {
1769                         *context++ = '\0'; /* split ext@context */
1770                         if (!ast_context_find(context)) {
1771                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1772                                 continue;
1773                         }
1774                 } else {
1775                         context = regcontext;
1776                 }
1777                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
1778                          ast_strdup(l->name), ast_free_ptr, "Skinny");
1779         }
1780 }
1781
1782 static void unregister_exten(struct skinny_line *l)
1783 {
1784         char multi[256];
1785         char *stringp, *ext, *context;
1786
1787         if (ast_strlen_zero(regcontext))
1788                 return;
1789
1790         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1791         stringp = multi;
1792         while ((ext = strsep(&stringp, "&"))) {
1793                 if ((context = strchr(ext, '@'))) {
1794                         *context++ = '\0'; /* split ext@context */
1795                         if (!ast_context_find(context)) {
1796                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1797                                 continue;
1798                         }
1799                 } else {
1800                         context = regcontext;
1801                 }
1802                 ast_context_remove_extension(context, ext, 1, NULL);
1803         }
1804 }
1805
1806 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
1807 {
1808         struct skinny_device *d;
1809         struct skinny_line *l;
1810         struct skinny_speeddial *sd;
1811         struct sockaddr_in sin;
1812         socklen_t slen;
1813         int instance;
1814
1815         AST_LIST_LOCK(&devices);
1816         AST_LIST_TRAVERSE(&devices, d, list){
1817                 if (!strcasecmp(req->data.reg.name, d->id)
1818                                 && ast_apply_ha(d->ha, &(s->sin))) {
1819                         s->device = d;
1820                         d->type = letohl(req->data.reg.type);
1821                         if (ast_strlen_zero(d->version_id)) {
1822                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
1823                         }
1824                         d->registered = 1;
1825                         d->session = s;
1826
1827                         slen = sizeof(sin);
1828                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
1829                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
1830                                 sin.sin_addr = __ourip;
1831                         }
1832                         d->ourip = sin.sin_addr;
1833
1834                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1835                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd);
1836                         }
1837                         instance = 0;
1838                         AST_LIST_TRAVERSE(&d->lines, l, list) {
1839                                 instance++;
1840                         }
1841                         AST_LIST_TRAVERSE(&d->lines, l, list) {
1842                                 /* FIXME: All sorts of issues will occur if this line is already connected to a device */
1843                                 if (l->device) {
1844                                         ast_verb(1, "Line %s already connected to %s. Not connecting to %s.\n", l->name, l->device->name, d->name);
1845                                 } else {
1846                                         l->device = d;
1847                                         l->capability = l->confcapability & d->capability;
1848                                         l->prefs = l->confprefs;
1849                                         if (!l->prefs.order[0]) {
1850                                                 l->prefs = d->confprefs;
1851                                         }
1852                                         /* l->capability = d->capability;
1853                                         l->prefs = d->prefs; */
1854                                         l->instance = instance;
1855                                         l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
1856                                         set_callforwards(l, NULL, 0);
1857                                         register_exten(l);
1858                                         /* initialize MWI on line and device */
1859                                         mwi_event_cb(0, l);
1860                                         ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s@%s", l->name, d->name);
1861                                 }
1862                                 --instance;
1863                         }
1864                         break;
1865                 }
1866         }
1867         AST_LIST_UNLOCK(&devices);
1868         if (!d) {
1869                 return 0;
1870         }
1871         return 1;
1872 }
1873
1874 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
1875 {
1876         struct skinny_device *d;
1877         struct skinny_line *l;
1878         struct skinny_speeddial *sd;
1879
1880         d = s->device;
1881
1882         if (d) {
1883                 d->session = NULL;
1884                 d->registered = 0;
1885
1886                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1887                         if (sd->stateid > -1)
1888                                 ast_extension_state_del(sd->stateid, NULL);
1889                 }
1890                 AST_LIST_TRAVERSE(&d->lines, l, list) {
1891                         if (l->device == d) {
1892                                 l->device = NULL;
1893                                 l->capability = 0;
1894                                 ast_parse_allow_disallow(&l->prefs, &l->capability, "all", 0);                  
1895                                 l->instance = 0;
1896                                 unregister_exten(l);
1897                                 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "Skinny/%s@%s", l->name, d->name);
1898                         }
1899                 }
1900         }
1901
1902         return -1; /* main loop will destroy the session */
1903 }
1904
1905 #ifdef SKINNY_DEVMODE
1906 static char *message2str(int type)
1907 {
1908         char *tmp;
1909
1910         switch (type) {
1911         case KEEP_ALIVE_MESSAGE:
1912                 return "KEEP_ALIVE_MESSAGE";
1913         case REGISTER_MESSAGE:
1914                 return "REGISTER_MESSAGE";
1915         case IP_PORT_MESSAGE:
1916                 return "IP_PORT_MESSAGE";
1917         case KEYPAD_BUTTON_MESSAGE:
1918                 return "KEYPAD_BUTTON_MESSAGE";
1919         case ENBLOC_CALL_MESSAGE:
1920                 return "ENBLOC_CALL_MESSAGE";
1921         case STIMULUS_MESSAGE:
1922                 return "STIMULUS_MESSAGE";
1923         case OFFHOOK_MESSAGE:
1924                 return "OFFHOOK_MESSAGE";
1925         case ONHOOK_MESSAGE:
1926                 return "ONHOOK_MESSAGE";
1927         case CAPABILITIES_RES_MESSAGE:
1928                 return "CAPABILITIES_RES_MESSAGE";
1929         case SPEED_DIAL_STAT_REQ_MESSAGE:
1930                 return "SPEED_DIAL_STAT_REQ_MESSAGE";
1931         case LINE_STATE_REQ_MESSAGE:
1932                 return "LINE_STATE_REQ_MESSAGE";
1933         case TIME_DATE_REQ_MESSAGE:
1934                 return "TIME_DATE_REQ_MESSAGE";
1935         case BUTTON_TEMPLATE_REQ_MESSAGE:
1936                 return "BUTTON_TEMPLATE_REQ_MESSAGE";
1937         case VERSION_REQ_MESSAGE:
1938                 return "VERSION_REQ_MESSAGE";
1939         case SERVER_REQUEST_MESSAGE:
1940                 return "SERVER_REQUEST_MESSAGE";
1941         case ALARM_MESSAGE:
1942                 return "ALARM_MESSAGE";
1943         case OPEN_RECEIVE_CHANNEL_ACK_MESSAGE:
1944                 return "OPEN_RECEIVE_CHANNEL_ACK_MESSAGE";
1945         case SOFT_KEY_SET_REQ_MESSAGE:
1946                 return "SOFT_KEY_SET_REQ_MESSAGE";
1947         case SOFT_KEY_EVENT_MESSAGE:
1948                 return "SOFT_KEY_EVENT_MESSAGE";
1949         case UNREGISTER_MESSAGE:
1950                 return "UNREGISTER_MESSAGE";
1951         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
1952                 return "SOFT_KEY_TEMPLATE_REQ_MESSAGE";
1953         case HEADSET_STATUS_MESSAGE:
1954                 return "HEADSET_STATUS_MESSAGE";
1955         case REGISTER_AVAILABLE_LINES_MESSAGE:
1956                 return "REGISTER_AVAILABLE_LINES_MESSAGE";
1957         case REGISTER_ACK_MESSAGE:
1958                 return "REGISTER_ACK_MESSAGE";
1959         case START_TONE_MESSAGE:
1960                 return "START_TONE_MESSAGE";
1961         case STOP_TONE_MESSAGE:
1962                 return "STOP_TONE_MESSAGE";
1963         case SET_RINGER_MESSAGE:
1964                 return "SET_RINGER_MESSAGE";
1965         case SET_LAMP_MESSAGE:
1966                 return "SET_LAMP_MESSAGE";
1967         case SET_SPEAKER_MESSAGE:
1968                 return "SET_SPEAKER_MESSAGE";
1969         case SET_MICROPHONE_MESSAGE:
1970                 return "SET_MICROPHONE_MESSAGE";
1971         case START_MEDIA_TRANSMISSION_MESSAGE:
1972                 return "START_MEDIA_TRANSMISSION_MESSAGE";
1973         case STOP_MEDIA_TRANSMISSION_MESSAGE:
1974                 return "STOP_MEDIA_TRANSMISSION_MESSAGE";
1975         case CALL_INFO_MESSAGE:
1976                 return "CALL_INFO_MESSAGE";
1977         case FORWARD_STAT_MESSAGE:
1978                 return "FORWARD_STAT_MESSAGE";
1979         case SPEED_DIAL_STAT_RES_MESSAGE:
1980                 return "SPEED_DIAL_STAT_RES_MESSAGE";
1981         case LINE_STAT_RES_MESSAGE:
1982                 return "LINE_STAT_RES_MESSAGE";
1983         case DEFINETIMEDATE_MESSAGE:
1984                 return "DEFINETIMEDATE_MESSAGE";
1985         case BUTTON_TEMPLATE_RES_MESSAGE:
1986                 return "BUTTON_TEMPLATE_RES_MESSAGE";
1987         case VERSION_RES_MESSAGE:
1988                 return "VERSION_RES_MESSAGE";
1989         case DISPLAYTEXT_MESSAGE:
1990                 return "DISPLAYTEXT_MESSAGE";
1991         case CLEAR_NOTIFY_MESSAGE:
1992                 return "CLEAR_NOTIFY_MESSAGE";
1993         case CLEAR_DISPLAY_MESSAGE:
1994                 return "CLEAR_DISPLAY_MESSAGE";
1995         case CAPABILITIES_REQ_MESSAGE:
1996                 return "CAPABILITIES_REQ_MESSAGE";
1997         case REGISTER_REJ_MESSAGE:
1998                 return "REGISTER_REJ_MESSAGE";
1999         case SERVER_RES_MESSAGE:
2000                 return "SERVER_RES_MESSAGE";
2001         case RESET_MESSAGE:
2002                 return "RESET_MESSAGE";
2003         case KEEP_ALIVE_ACK_MESSAGE:
2004                 return "KEEP_ALIVE_ACK_MESSAGE";
2005         case OPEN_RECEIVE_CHANNEL_MESSAGE:
2006                 return "OPEN_RECEIVE_CHANNEL_MESSAGE";
2007         case CLOSE_RECEIVE_CHANNEL_MESSAGE:
2008                 return "CLOSE_RECEIVE_CHANNEL_MESSAGE";
2009         case SOFT_KEY_TEMPLATE_RES_MESSAGE:
2010                 return "SOFT_KEY_TEMPLATE_RES_MESSAGE";
2011         case SOFT_KEY_SET_RES_MESSAGE:
2012                 return "SOFT_KEY_SET_RES_MESSAGE";
2013         case SELECT_SOFT_KEYS_MESSAGE:
2014                 return "SELECT_SOFT_KEYS_MESSAGE";
2015         case CALL_STATE_MESSAGE:
2016                 return "CALL_STATE_MESSAGE";
2017         case DISPLAY_PROMPT_STATUS_MESSAGE:
2018                 return "DISPLAY_PROMPT_STATUS_MESSAGE";
2019         case CLEAR_PROMPT_MESSAGE:
2020                 return "CLEAR_PROMPT_MESSAGE";
2021         case DISPLAY_NOTIFY_MESSAGE:
2022                 return "DISPLAY_NOTIFY_MESSAGE";
2023         case ACTIVATE_CALL_PLANE_MESSAGE:
2024                 return "ACTIVATE_CALL_PLANE_MESSAGE";
2025         case DIALED_NUMBER_MESSAGE:
2026                 return "DIALED_NUMBER_MESSAGE";
2027         default:
2028                 if (!(tmp = ast_threadstorage_get(&message2str_threadbuf, MESSAGE2STR_BUFSIZE)))
2029                         return "Unknown";
2030                 snprintf(tmp, MESSAGE2STR_BUFSIZE, "UNKNOWN_MESSAGE-%d", type);
2031                 return tmp;
2032         }
2033 }
2034 #endif
2035
2036 static int transmit_response(struct skinny_device *d, struct skinny_req *req)
2037 {
2038         struct skinnysession *s = d->session;
2039         int res = 0;
2040
2041         if (!s) {
2042                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2043                 return -1;
2044         }
2045
2046         ast_mutex_lock(&s->lock);
2047
2048         SKINNY_DEVONLY(if (skinnydebug>1) ast_verb(4, "Transmitting %s to %s\n", message2str(req->e), d->name);)
2049
2050         if (letohl(req->len > SKINNY_MAX_PACKET) || letohl(req->len < 0)) {
2051                 ast_log(LOG_WARNING, "transmit_response: the length of the request is out of bounds\n");
2052                 ast_mutex_unlock(&s->lock);
2053                 return -1;
2054         }
2055
2056         memset(s->outbuf, 0, sizeof(s->outbuf));
2057         memcpy(s->outbuf, req, skinny_header_size);
2058         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2059
2060         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2061         
2062         if (res != letohl(req->len)+8) {
2063                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2064                 if (res == -1) {
2065                         if (skinnydebug)
2066                                 ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2067                         skinny_unregister(NULL, s);
2068                 }
2069                 
2070         }
2071         
2072         ast_free(req);
2073         ast_mutex_unlock(&s->lock);
2074         return 1;
2075 }
2076
2077 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2078 {
2079         struct skinny_req *req;
2080
2081         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2082                 return;
2083
2084         req->data.setspeaker.mode = htolel(mode);
2085         transmit_response(d, req);
2086 }
2087 /*
2088 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2089 {
2090         struct skinny_req *req;
2091
2092         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2093                 return;
2094
2095         req->data.setmicrophone.mode = htolel(mode);
2096         transmit_response(d, req);
2097 }
2098 */
2099
2100 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)
2101 {
2102         struct skinny_req *req;
2103
2104         /* We should not be able to get here without a device */
2105         if (!d)
2106                 return;
2107
2108         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2109                 return;
2110
2111         if (skinnydebug)
2112                         ast_verb(1, "Setting Callinfo to %s(%s) from %s(%s) on %s(%d)\n", fromname, fromnum, toname, tonum, d->name, instance);
2113
2114         if (fromname) {
2115                 ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2116         }
2117         if (fromnum) {
2118                 ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2119         }
2120         if (toname) {
2121                 ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2122         }
2123         if (tonum) {
2124                 ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2125         }
2126         req->data.callinfo.instance = htolel(instance);
2127         req->data.callinfo.reference = htolel(callid);
2128         req->data.callinfo.type = htolel(calltype);
2129         transmit_response(d, req);
2130 }
2131
2132 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2133 {
2134         struct skinny_req *req;
2135         struct skinny_line *l = sub->parent;
2136         struct ast_format_list fmt;
2137
2138         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2139                 return;
2140
2141         fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
2142
2143         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2144         req->data.openreceivechannel.partyId = htolel(sub->callid);
2145         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2146         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(fmt.bits));
2147         req->data.openreceivechannel.echo = htolel(0);
2148         req->data.openreceivechannel.bitrate = htolel(0);
2149         transmit_response(d, req);
2150 }
2151
2152 static void transmit_tone(struct skinny_device *d, int tone, int instance, int reference)
2153 {
2154         struct skinny_req *req;
2155
2156         if (tone == SKINNY_NOTONE) {
2157                 /* This is bad, mmm'kay? */
2158                 return;
2159         }
2160
2161         if (tone > 0) {
2162                 if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2163                         return;
2164                 req->data.starttone.tone = htolel(tone);
2165                 req->data.starttone.instance = htolel(instance);
2166                 req->data.starttone.reference = htolel(reference);
2167         } else {
2168                 if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2169                         return;
2170                 req->data.stoptone.instance = htolel(instance);
2171                 req->data.stoptone.reference = htolel(reference);
2172         }
2173
2174         //Bad, tone is already set so this is redundant and a change to the if above
2175         //may lead to issues where we try to set a tone to a stop_tone_message
2176         //if (tone > 0) {
2177         //      req->data.starttone.tone = htolel(tone);
2178         //}
2179         transmit_response(d, req);
2180 }
2181
2182 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey)
2183 {
2184         struct skinny_req *req;
2185
2186         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2187                 return;
2188
2189         req->data.selectsoftkey.instance = htolel(instance);
2190         req->data.selectsoftkey.reference = htolel(callid);
2191         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2192         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
2193         transmit_response(d, req);
2194 }
2195
2196 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2197 {
2198         struct skinny_req *req;
2199
2200         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2201                 return;
2202
2203         req->data.setlamp.stimulus = htolel(stimulus);
2204         req->data.setlamp.stimulusInstance = htolel(instance);
2205         req->data.setlamp.deviceStimulus = htolel(indication);
2206         transmit_response(d, req);
2207 }
2208
2209 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2210 {
2211         struct skinny_req *req;
2212
2213         if (skinnydebug)
2214                 ast_verb(1, "Setting ringer mode to '%d'.\n", mode);
2215
2216         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2217                 return;
2218
2219         req->data.setringer.ringerMode = htolel(mode);
2220         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2221            Note: The phone will always show as ringing on the display.
2222
2223            1: phone will audibly ring over and over
2224            2: phone will audibly ring only once
2225            any other value, will NOT cause the phone to audibly ring
2226         */
2227         req->data.setringer.unknown1 = htolel(1);
2228         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2229            Perhaps a packet capture can shed some light on this. */
2230         req->data.setringer.unknown2 = htolel(1);
2231         transmit_response(d, req);
2232 }
2233
2234 static void transmit_displaymessage(struct skinny_device *d, const char *text, int instance, int reference)
2235 {
2236         struct skinny_req *req;
2237
2238         if (text == 0) {
2239                 if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
2240                         return;
2241
2242                 //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2243                 //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2244                 //req->data.clearpromptstatus.lineInstance = instance;
2245                 //req->data.clearpromptstatus.callReference = reference;
2246
2247                 /* send datetime message. We have to do it here because it will clear the display on the phone if we do it elsewhere */
2248                 handle_time_date_req_message(NULL, d->session);
2249
2250                 if (skinnydebug)
2251                         ast_verb(1, "Clearing Display\n");
2252         } else {
2253                 if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2254                         return;
2255
2256                 ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2257                 if (skinnydebug)
2258                         ast_verb(1, "Displaying message '%s'\n", req->data.displaytext.text);
2259         }
2260
2261         transmit_response(d, req);
2262 }
2263
2264 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2265 {
2266         struct skinny_req *req;
2267
2268         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2269                 return;
2270
2271         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2272         req->data.displaynotify.displayTimeout = htolel(t);
2273
2274         if (skinnydebug)
2275                 ast_verb(1, "Displaying notify '%s'\n", text);
2276
2277         transmit_response(d, req);
2278 }
2279
2280 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
2281 {
2282         struct skinny_req *req;
2283
2284         if (text == 0) {
2285                 if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2286                         return;
2287
2288                 req->data.clearpromptstatus.lineInstance = htolel(instance);
2289                 req->data.clearpromptstatus.callReference = htolel(callid);
2290
2291                 if (skinnydebug)
2292                         ast_verb(1, "Clearing Prompt\n");
2293         } else {
2294                 if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2295                         return;
2296
2297                 ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2298                 req->data.displaypromptstatus.messageTimeout = htolel(t);
2299                 req->data.displaypromptstatus.lineInstance = htolel(instance);
2300                 req->data.displaypromptstatus.callReference = htolel(callid);
2301
2302                 if (skinnydebug)
2303                         ast_verb(1, "Displaying Prompt Status '%s'\n", text);
2304         }
2305
2306         transmit_response(d, req);
2307 }
2308
2309 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2310 {
2311         struct skinny_req *req;
2312
2313         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2314                 return;
2315
2316         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2317         req->data.dialednumber.lineInstance = htolel(instance);
2318         req->data.dialednumber.callReference = htolel(callid);
2319
2320         transmit_response(d, req);
2321 }
2322
2323 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2324 {
2325         struct skinny_req *req;
2326
2327         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2328                 return;
2329
2330         req->data.closereceivechannel.conferenceId = htolel(0);
2331         req->data.closereceivechannel.partyId = htolel(sub->callid);
2332         transmit_response(d, req);
2333 }
2334
2335 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2336 {
2337         struct skinny_req *req;
2338
2339         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2340                 return;
2341
2342         req->data.stopmedia.conferenceId = htolel(0);
2343         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2344         transmit_response(d, req);
2345 }
2346
2347 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
2348 {
2349         struct skinny_req *req;
2350
2351         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2352                 return;
2353
2354         req->data.activatecallplane.lineInstance = htolel(l->instance);
2355         transmit_response(d, req);
2356 }
2357
2358 static void transmit_callstateonly(struct skinny_device *d, struct skinny_subchannel *sub, int state)
2359 {
2360         struct skinny_req *req;
2361
2362         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2363                 return;
2364
2365         req->data.callstate.callState = htolel(state);
2366         req->data.callstate.lineInstance = htolel(sub->parent->instance);
2367         req->data.callstate.callReference = htolel(sub->callid);
2368         transmit_response(d, req);
2369 }
2370
2371 static void transmit_callstate(struct skinny_device *d, int instance, int state, unsigned callid)
2372 {
2373         struct skinny_req *req;
2374
2375         if (state == SKINNY_ONHOOK) {
2376                 if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2377                         return;
2378
2379                 req->data.closereceivechannel.conferenceId = htolel(callid);
2380                 req->data.closereceivechannel.partyId = htolel(callid);
2381                 transmit_response(d, req);
2382
2383                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2384                         return;
2385
2386                 req->data.stopmedia.conferenceId = htolel(callid);
2387                 req->data.stopmedia.passThruPartyId = htolel(callid);
2388                 transmit_response(d, req);
2389
2390                 transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
2391
2392                 transmit_displaypromptstatus(d, NULL, 0, instance, callid);
2393         }
2394
2395         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2396                 return;
2397
2398         req->data.callstate.callState = htolel(state);
2399         req->data.callstate.lineInstance = htolel(instance);
2400         req->data.callstate.callReference = htolel(callid);
2401         transmit_response(d, req);
2402
2403         if (state == SKINNY_ONHOOK) {
2404                 transmit_selectsoftkeys(d, 0, 0, KEYDEF_ONHOOK);
2405         }
2406
2407         if (state == SKINNY_OFFHOOK || state == SKINNY_ONHOOK) {
2408                 if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2409                         return;
2410
2411                 req->data.activatecallplane.lineInstance = htolel(instance);
2412                 transmit_response(d, req);
2413         }
2414 }
2415
2416
2417 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
2418 {
2419         struct skinny_req *req;
2420         int anyon = 0;
2421
2422         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
2423                 return;
2424
2425         if (l->cfwdtype & SKINNY_CFWD_ALL) {
2426                 if (!ast_strlen_zero(l->call_forward_all)) {
2427                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
2428                         req->data.forwardstat.fwdall = htolel(1);
2429                         anyon++;
2430                 } else {
2431                         req->data.forwardstat.fwdall = htolel(0);
2432                 }
2433         }
2434         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
2435                 if (!ast_strlen_zero(l->call_forward_busy)) {
2436                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
2437                         req->data.forwardstat.fwdbusy = htolel(1);
2438                         anyon++;
2439                 } else {
2440                         req->data.forwardstat.fwdbusy = htolel(0);
2441                 }
2442         }
2443         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
2444                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
2445                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
2446                         req->data.forwardstat.fwdnoanswer = htolel(1);
2447                         anyon++;
2448                 } else {
2449                         req->data.forwardstat.fwdnoanswer = htolel(0);
2450                 }
2451         }
2452         req->data.forwardstat.lineNumber = htolel(l->instance);
2453         if (anyon)
2454                 req->data.forwardstat.activeforward = htolel(7);
2455         else
2456                 req->data.forwardstat.activeforward = htolel(0);
2457
2458         transmit_response(d, req);
2459 }
2460
2461 static int skinny_extensionstate_cb(char *context, char *exten, int state, void *data)
2462 {
2463         struct skinny_speeddial *sd = data;
2464         struct skinny_device *d = sd->parent;
2465         char hint[AST_MAX_EXTENSION];
2466         int callstate = SKINNY_CALLREMOTEMULTILINE;
2467         int lamp = SKINNY_LAMP_OFF;
2468
2469         switch (state) {
2470         case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
2471         case AST_EXTENSION_REMOVED:     /* Extension is gone */
2472                 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify Device %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
2473                 sd->stateid = -1;
2474                 callstate = SKINNY_ONHOOK;
2475                 lamp = SKINNY_LAMP_OFF;
2476                 break;
2477         case AST_EXTENSION_RINGING:
2478         case AST_EXTENSION_UNAVAILABLE:
2479                 callstate = SKINNY_RINGIN;
2480                 lamp = SKINNY_LAMP_BLINK;
2481                 break;
2482         case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
2483         case AST_EXTENSION_INUSE:
2484                 callstate = SKINNY_CALLREMOTEMULTILINE;
2485                 lamp = SKINNY_LAMP_ON;
2486                 break;
2487         case AST_EXTENSION_ONHOLD:
2488                 callstate = SKINNY_HOLD;
2489                 lamp = SKINNY_LAMP_WINK;
2490                 break;
2491         case AST_EXTENSION_NOT_INUSE:
2492         default:
2493                 callstate = SKINNY_ONHOOK;
2494                 lamp = SKINNY_LAMP_OFF;
2495                 break;
2496         }
2497
2498         if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
2499                 /* If they are not registered, we will override notification and show no availability */
2500                 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
2501                         callstate = SKINNY_ONHOOK;
2502                         lamp = SKINNY_LAMP_FLASH;
2503                 }
2504         }
2505
2506         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, lamp);
2507         transmit_callstate(d, sd->instance, callstate, 0);
2508         sd->laststate = state;
2509
2510         return 0;
2511 }
2512
2513 static void mwi_event_cb(const struct ast_event *event, void *userdata)
2514 {
2515         struct skinny_line *l = userdata;
2516         struct skinny_device *d = l->device;
2517         if (d) {
2518                 struct skinnysession *s = d->session;
2519                 struct skinny_line *l2;
2520                 int new_msgs = 0;
2521                 int dev_msgs = 0;
2522
2523                 if (s) {
2524                         if (event) {
2525                                 l->newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
2526                         }
2527
2528                         if (l->newmsgs) {
2529                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2530                         } else {
2531                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
2532                         }
2533
2534                         /* find out wether the device lamp should be on or off */
2535                         AST_LIST_TRAVERSE(&d->lines, l2, list) {
2536                                 if (l2->newmsgs) {
2537                                         dev_msgs++;
2538                                 }
2539                         }
2540
2541                         if (dev_msgs) {
2542                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2543                         } else {
2544                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
2545                         }
2546                         ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", new_msgs);
2547                 }
2548         }
2549 }
2550
2551 /* I do not believe skinny can deal with video.
2552    Anyone know differently? */
2553 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
2554 static enum ast_rtp_get_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
2555 {
2556         struct skinny_subchannel *sub = NULL;
2557
2558         if (!(sub = c->tech_pvt) || !(sub->vrtp))
2559                 return AST_RTP_GET_FAILED;
2560
2561         *rtp = sub->vrtp;
2562
2563         return AST_RTP_TRY_NATIVE;
2564 }
2565
2566 static enum ast_rtp_get_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
2567 {
2568         struct skinny_subchannel *sub = NULL;
2569         struct skinny_line *l;
2570         enum ast_rtp_get_result res = AST_RTP_TRY_NATIVE;
2571
2572         if (skinnydebug)
2573                 ast_verb(1, "skinny_get_rtp_peer() Channel = %s\n", c->name);
2574
2575
2576         if (!(sub = c->tech_pvt))
2577                 return AST_RTP_GET_FAILED;
2578
2579         ast_mutex_lock(&sub->lock);
2580
2581         if (!(sub->rtp)){
2582                 ast_mutex_unlock(&sub->lock);
2583                 return AST_RTP_GET_FAILED;
2584         }
2585         
2586         *rtp = sub->rtp;
2587
2588         l = sub->parent;
2589
2590         if (!l->canreinvite || l->nat){
2591                 res = AST_RTP_TRY_PARTIAL;
2592                 if (skinnydebug)
2593                         ast_verb(1, "skinny_get_rtp_peer() Using AST_RTP_TRY_PARTIAL \n");
2594         }
2595
2596         ast_mutex_unlock(&sub->lock);
2597
2598         return res;
2599
2600 }
2601
2602 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)
2603 {
2604         struct skinny_subchannel *sub;
2605         struct skinny_line *l;
2606         struct skinny_device *d;
2607         struct skinnysession *s;
2608         struct ast_format_list fmt;
2609         struct sockaddr_in us;
2610         struct sockaddr_in them;
2611         struct skinny_req *req;
2612         
2613         sub = c->tech_pvt;
2614
2615         if (c->_state != AST_STATE_UP)
2616                 return 0;
2617
2618         if (!sub) {
2619                 return -1;
2620         }
2621
2622         l = sub->parent;
2623         d = l->device;
2624         s = d->session;
2625
2626         if (rtp){
2627                 ast_rtp_get_peer(rtp, &them);
2628
2629                 /* Shutdown any early-media or previous media on re-invite */
2630                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2631                         return -1;
2632
2633                 req->data.stopmedia.conferenceId = htolel(sub->callid);
2634                 req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2635                 transmit_response(d, req);
2636
2637                 if (skinnydebug)
2638                         ast_verb(1, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
2639
2640                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message), START_MEDIA_TRANSMISSION_MESSAGE)))
2641                         return -1;
2642
2643                 fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
2644
2645                 if (skinnydebug)
2646                         ast_verb(1, "Setting payloadType to '%d' (%d ms)\n", fmt.bits, fmt.cur_ms);
2647
2648                 req->data.startmedia.conferenceId = htolel(sub->callid);
2649                 req->data.startmedia.passThruPartyId = htolel(sub->callid);
2650                 if (!(l->canreinvite) || (l->nat)){
2651                         ast_rtp_get_us(rtp, &us);
2652                         req->data.startmedia.remoteIp = htolel(d->ourip.s_addr);
2653                         req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
2654                 } else {
2655                         req->data.startmedia.remoteIp = htolel(them.sin_addr.s_addr);
2656                         req->data.startmedia.remotePort = htolel(ntohs(them.sin_port));
2657                 }
2658                 req->data.startmedia.packetSize = htolel(fmt.cur_ms);
2659                 req->data.startmedia.payloadType = htolel(codec_ast2skinny(fmt.bits));
2660                 req->data.startmedia.qualifier.precedence = htolel(127);
2661                 req->data.startmedia.qualifier.vad = htolel(0);
2662                 req->data.startmedia.qualifier.packets = htolel(0);
2663                 req->data.startmedia.qualifier.bitRate = htolel(0);
2664                 transmit_response(d, req);
2665
2666                 return 0;
2667         }
2668         /* Need a return here to break the bridge */
2669         return 0;
2670 }
2671
2672 static struct ast_rtp_protocol skinny_rtp = {
2673         .type = "Skinny",
2674         .get_rtp_info = skinny_get_rtp_peer,
2675         .get_vrtp_info = skinny_get_vrtp_peer,
2676         .set_rtp_peer = skinny_set_rtp_peer,
2677 };
2678
2679 static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2680 {
2681         switch (cmd) {
2682         case CLI_INIT:
2683 #ifdef SKINNY_DEVMODE
2684                 e->command = "skinny set debug {off|on|packet}";
2685                 e->usage =
2686                         "Usage: skinny set debug {off|on|packet}\n"
2687                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2688 #else
2689                 e->command = "skinny set debug {off|on}";
2690                 e->usage =
2691                         "Usage: skinny set debug {off|on}\n"
2692                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2693 #endif
2694                 return NULL;
2695         case CLI_GENERATE:
2696                 return NULL;
2697         }
2698         
2699         if (a->argc != e->args)
2700                 return CLI_SHOWUSAGE;
2701
2702         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
2703                 skinnydebug = 1;
2704                 ast_cli(a->fd, "Skinny Debugging Enabled\n");
2705                 return CLI_SUCCESS;
2706         } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
2707                 skinnydebug = 0;
2708                 ast_cli(a->fd, "Skinny Debugging Disabled\n");
2709                 return CLI_SUCCESS;
2710 #ifdef SKINNY_DEVMODE
2711         } else if (!strncasecmp(a->argv[e->args - 1], "packet", 6)) {
2712                 skinnydebug = 2;
2713                 ast_cli(a->fd, "Skinny Debugging Enabled including Packets\n");
2714                 return CLI_SUCCESS;
2715 #endif
2716         } else {
2717                 return CLI_SHOWUSAGE;
2718         }
2719 }
2720
2721 static char *complete_skinny_devices(const char *word, int state)
2722 {
2723         struct skinny_device *d;
2724         char *result = NULL;
2725         int wordlen = strlen(word), which = 0;
2726
2727         AST_LIST_TRAVERSE(&devices, d, list) {
2728                 if (!strncasecmp(word, d->id, wordlen) && ++which > state)
2729                         result = ast_strdup(d->id);
2730         }
2731
2732         return result;
2733 }
2734
2735 static char *complete_skinny_show_device(const char *line, const char *word, int pos, int state)
2736 {
2737         return (pos == 3 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2738 }
2739
2740 static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
2741 {
2742         return (pos == 2 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2743 }
2744
2745 static char *complete_skinny_show_line(const char *line, const char *word, int pos, int state)
2746 {
2747         struct skinny_device *d;
2748         struct skinny_line *l;
2749         char *result = NULL;
2750         int wordlen = strlen(word), which = 0;
2751
2752         if (pos != 3)
2753                 return NULL;
2754         
2755         AST_LIST_TRAVERSE(&devices, d, list) {
2756                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2757                         if (!strncasecmp(word, l->name, wordlen) && ++which > state)
2758                                 result = ast_strdup(l->name);
2759                 }
2760         }
2761
2762         return result;
2763 }
2764
2765 static char *handle_skinny_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2766 {
2767         struct skinny_device *d;
2768         struct skinny_req *req;
2769
2770         switch (cmd) {
2771         case CLI_INIT:
2772                 e->command = "skinny reset";
2773                 e->usage =
2774                         "Usage: skinny reset <DeviceId|DeviceName|all> [restart]\n"
2775                         "       Causes a Skinny device to reset itself, optionally with a full restart\n";
2776                 return NULL;
2777         case CLI_GENERATE:
2778                 return complete_skinny_reset(a->line, a->word, a->pos, a->n);
2779         }
2780
2781         if (a->argc < 3 || a->argc > 4)
2782                 return CLI_SHOWUSAGE;
2783
2784         AST_LIST_LOCK(&devices);
2785         AST_LIST_TRAVERSE(&devices, d, list) {
2786                 int fullrestart = 0;
2787                 if (!strcasecmp(a->argv[2], d->id) || !strcasecmp(a->argv[2], d->name) || !strcasecmp(a->argv[2], "all")) {
2788                         if (!(d->session))
2789                                 continue;
2790
2791                         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
2792                                 continue;
2793
2794                         if (a->argc == 4 && !strcasecmp(a->argv[3], "restart"))
2795                                 fullrestart = 1;
2796
2797                         if (fullrestart)
2798                                 req->data.reset.resetType = 2;
2799                         else
2800                                 req->data.reset.resetType = 1;
2801
2802                         ast_verb(3, "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
2803                         transmit_response(d, req);
2804                 }
2805         }
2806         AST_LIST_UNLOCK(&devices);
2807         return CLI_SUCCESS;
2808 }
2809
2810 static char *device2str(int type)
2811 {
2812         char *tmp;
2813
2814         switch (type) {
2815         case SKINNY_DEVICE_NONE:
2816                 return "No Device";
2817         case SKINNY_DEVICE_30SPPLUS:
2818                 return "30SP Plus";
2819         case SKINNY_DEVICE_12SPPLUS:
2820                 return "12SP Plus";
2821         case SKINNY_DEVICE_12SP:
2822                 return "12SP";
2823         case SKINNY_DEVICE_12:
2824                 return "12";
2825         case SKINNY_DEVICE_30VIP:
2826                 return "30VIP";
2827         case SKINNY_DEVICE_7910:
2828                 return "7910";
2829         case SKINNY_DEVICE_7960:
2830                 return "7960";
2831         case SKINNY_DEVICE_7940:
2832                 return "7940";
2833         case SKINNY_DEVICE_7935:
2834                 return "7935";
2835         case SKINNY_DEVICE_ATA186:
2836                 return "ATA186";
2837         case SKINNY_DEVICE_7941:
2838                 return "7941";
2839         case SKINNY_DEVICE_7971:
2840                 return "7971";
2841         case SKINNY_DEVICE_7914:
2842                 return "7914";
2843         case SKINNY_DEVICE_7985:
2844                 return "7985";
2845         case SKINNY_DEVICE_7911:
2846                 return "7911";
2847         case SKINNY_DEVICE_7961GE:
2848                 return "7961GE";
2849         case SKINNY_DEVICE_7941GE:
2850                 return "7941GE";
2851         case SKINNY_DEVICE_7931:
2852                 return "7931";
2853         case SKINNY_DEVICE_7921:
2854                 return "7921";
2855         case SKINNY_DEVICE_7906:
2856                 return "7906";
2857         case SKINNY_DEVICE_7962:
2858                 return "7962";
2859         case SKINNY_DEVICE_7937:
2860                 return "7937";
2861         case SKINNY_DEVICE_7942:
2862                 return "7942";
2863         case SKINNY_DEVICE_7945:
2864                 return "7945";
2865         case SKINNY_DEVICE_7965:
2866                 return "7965";
2867         case SKINNY_DEVICE_7975:
2868                 return "7975";
2869         case SKINNY_DEVICE_7905:
2870                 return "7905";
2871         case SKINNY_DEVICE_7920:
2872                 return "7920";
2873         case SKINNY_DEVICE_7970:
2874                 return "7970";
2875         case SKINNY_DEVICE_7912:
2876                 return "7912";
2877         case SKINNY_DEVICE_7902:
2878                 return "7902";
2879         case SKINNY_DEVICE_CIPC:
2880                 return "IP Communicator";
2881         case SKINNY_DEVICE_7961:
2882                 return "7961";
2883         case SKINNY_DEVICE_7936:
2884                 return "7936";
2885         case SKINNY_DEVICE_SCCPGATEWAY_AN:
2886                 return "SCCPGATEWAY_AN";
2887         case SKINNY_DEVICE_SCCPGATEWAY_BRI:
2888                 return "SCCPGATEWAY_BRI";
2889         case SKINNY_DEVICE_UNKNOWN:
2890                 return "Unknown";
2891         default:
2892                 if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
2893                         return "Unknown";
2894                 snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
2895                 return tmp;
2896         }
2897 }
2898
2899 /*! \brief Print codec list from preference to CLI/manager */
2900 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
2901 {
2902         int x, codec;
2903
2904         for(x = 0; x < 32 ; x++) {
2905                 codec = ast_codec_pref_index(pref, x);
2906                 if (!codec)
2907                         break;
2908                 ast_cli(fd, "%s", ast_getformatname(codec));
2909                 ast_cli(fd, ":%d", pref->framing[x]);
2910                 if (x < 31 && ast_codec_pref_index(pref, x + 1))
2911                         ast_cli(fd, ",");
2912         }
2913         if (!x)
2914                 ast_cli(fd, "none");
2915 }
2916
2917 static char *_skinny_show_devices(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
2918 {
2919         struct skinny_device *d;
2920         struct skinny_line *l;
2921         const char *id;
2922         char idtext[256] = "";
2923         int total_devices = 0;
2924
2925         if (s) {        /* Manager - get ActionID */
2926                 id = astman_get_header(m, "ActionID");
2927                 if (!ast_strlen_zero(id))
2928                         snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
2929         }
2930
2931         switch (argc) {
2932         case 3:
2933                 break;
2934         default:
2935                 return CLI_SHOWUSAGE;
2936         }
2937
2938         if (!s) {
2939                 ast_cli(fd, "Name                 DeviceId         IP              Type            R NL\n");
2940                 ast_cli(fd, "-------------------- ---------------- --------------- --------------- - --\n");
2941         }
2942
2943         AST_LIST_LOCK(&devices);
2944         AST_LIST_TRAVERSE(&devices, d, list) {
2945                 int numlines = 0;
2946                 total_devices++;
2947                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2948                         numlines++;
2949                 }
2950                 if (!s) {
2951                         ast_cli(fd, "%-20s %-16s %-15s %-15s %c %2d\n",
2952                                 d->name,
2953                                 d->id,
2954                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
2955                                 device2str(d->type),
2956                                 d->registered?'Y':'N',
2957                                 numlines);
2958                 } else {
2959                         astman_append(s,
2960                                 "Event: DeviceEntry\r\n%s"
2961                                 "Channeltype: SKINNY\r\n"
2962                                 "ObjectName: %s\r\n"
2963                                 "ChannelObjectType: device\r\n"
2964                                 "DeviceId: %s\r\n"
2965                                 "IPaddress: %s\r\n"
2966                                 "Type: %s\r\n"
2967                                 "Registered: %s\r\n"
2968                                 "NumberOfLines: %d\r\n",
2969                                 idtext,
2970                                 d->name,
2971                                 d->id,
2972                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"-none-",
2973                                 device2str(d->type),
2974                                 d->registered?"yes":"no",
2975                                 numlines);
2976                 }
2977         }
2978         AST_LIST_UNLOCK(&devices);
2979
2980         if (total)
2981                 *total = total_devices;
2982         
2983         return CLI_SUCCESS;
2984 }
2985
2986 static char mandescr_show_devices[] =
2987 "Description: Lists Skinny devices in text format with details on current status.\n"
2988 "Devicelist will follow as separate events, followed by a final event called\n"
2989 "DevicelistComplete.\n"
2990 "Variables: \n"
2991 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
2992
2993 /*! \brief  Show SKINNY devices in the manager API */
2994 /*    Inspired from chan_sip */
2995 static int manager_skinny_show_devices(struct mansession *s, const struct message *m)
2996 {
2997         const char *id = astman_get_header(m, "ActionID");
2998         const char *a[] = {"skinny", "show", "devices"};
2999         char idtext[256] = "";
3000         int total = 0;
3001
3002         if (!ast_strlen_zero(id))
3003                 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3004
3005         astman_send_listack(s, m, "Device status list will follow", "start");
3006         /* List the devices in separate manager events */
3007         _skinny_show_devices(-1, &total, s, m, 3, a);
3008         /* Send final confirmation */
3009         astman_append(s,
3010         "Event: DevicelistComplete\r\n"
3011         "EventList: Complete\r\n"
3012         "ListItems: %d\r\n"
3013         "%s"
3014         "\r\n", total, idtext);
3015         return 0;
3016 }
3017
3018 static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3019 {
3020
3021         switch (cmd) {
3022         case CLI_INIT:
3023                 e->command = "skinny show devices";
3024                 e->usage =
3025                         "Usage: skinny show devices\n"
3026                         "       Lists all devices known to the Skinny subsystem.\n";
3027                 return NULL;
3028         case CLI_GENERATE:
3029                 return NULL;
3030         }
3031
3032         return _skinny_show_devices(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
3033 }
3034
3035 static char *_skinny_show_device(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
3036 {
3037         struct skinny_device *d;
3038         struct skinny_line *l;
3039         struct skinny_speeddial *sd;
3040         struct skinny_addon *sa;
3041         char codec_buf[512];
3042
3043         if (argc < 4) {
3044                 return CLI_SHOWUSAGE;
3045         }
3046
3047         AST_LIST_LOCK(&devices);
3048         AST_LIST_TRAVERSE(&devices, d, list) {
3049                 if (!strcasecmp(argv[3], d->id) || !strcasecmp(argv[3], d->name)) {
3050                         int numlines = 0, numaddons = 0, numspeeddials = 0;
3051
3052                         AST_LIST_TRAVERSE(&d->lines, l, list){
3053                                 numlines++;
3054                         }
3055
3056                         AST_LIST_TRAVERSE(&d->addons, sa, list) {
3057                                 numaddons++;
3058                         }
3059
3060                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3061                                 numspeeddials++;
3062                         }
3063
3064                         if (type == 0) { /* CLI */
3065                                 ast_cli(fd, "Name:        %s\n", d->name);
3066                                 ast_cli(fd, "Id:          %s\n", d->id);
3067                                 ast_cli(fd, "version:     %s\n", S_OR(d->version_id, "Unknown"));
3068                                 ast_cli(fd, "Ip address:  %s\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
3069                                 ast_cli(fd, "Port:        %d\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
3070                                 ast_cli(fd, "Device Type: %s\n", device2str(d->type));
3071                                 ast_cli(fd, "Conf Codecs:");
3072                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->confcapability);
3073                                 ast_cli(fd, "%s\n", codec_buf);
3074                                 ast_cli(fd, "Neg Codecs: ");
3075                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->capability);
3076                                 ast_cli(fd, "%s\n", codec_buf);
3077                                 ast_cli(fd, "Registered:  %s\n", (d->registered ? "Yes" : "No"));
3078                                 ast_cli(fd, "Lines:       %d\n", numlines);
3079                                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3080                                         ast_cli(fd, "  %s (%s)\n", l->name, l->label);
3081                                 }
3082                                 AST_LIST_TRAVERSE(&d->addons, sa, list) {
3083                                         numaddons++;
3084                                 }       
3085                                 ast_cli(fd, "Addons:      %d\n", numaddons);
3086                                 AST_LIST_TRAVERSE(&d->addons, sa, list) {
3087                                         ast_cli(fd, "  %s\n", sa->type);
3088                                 }
3089                                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3090                                         numspeeddials++;
3091                                 }
3092                                 ast_cli(fd, "Speeddials:  %d\n", numspeeddials);
3093                                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3094                                         ast_cli(fd, "  %s (%s) ishint: %d\n", sd->exten, sd->label, sd->isHint);
3095                                 }
3096                         } else { /* manager */
3097                                 astman_append(s, "Channeltype: SKINNY\r\n");
3098                                 astman_append(s, "ObjectName: %s\r\n", d->name);
3099                                 astman_append(s, "ChannelObjectType: device\r\n");
3100                                 astman_append(s, "Id: %s\r\n", d->id);
3101                                 astman_append(s, "version: %s\r\n", S_OR(d->version_id, "Unknown"));
3102                                 astman_append(s, "Ipaddress: %s\r\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
3103                                 astman_append(s, "Port: %d\r\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
3104                                 astman_append(s, "DeviceType: %s\r\n", device2str(d->type));
3105                                 astman_append(s, "Codecs: ");
3106                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, d->confcapability);
3107                                 astman_append(s, "%s\r\n", codec_buf);
3108                                 astman_append(s, "CodecOrder: ");
3109                                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, d->capability);
3110                                 astman_append(s, "%s\r\n", codec_buf);
3111                                 astman_append(s, "Registered: %s\r\n", (d->registered?"yes":"no"));
3112                                 astman_append(s, "NumberOfLines: %d\r\n", numlines);
3113                                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3114                                         astman_append(s, "Line: %s (%s)\r\n", l->name, l->label);
3115                                 }
3116                                 astman_append(s, "NumberOfAddons: %d\r\n", numaddons);
3117                                 AST_LIST_TRAVERSE(&d->addons, sa, list) {
3118                                         astman_append(s, "Addon: %s\r\n", sa->type);
3119                                 }
3120                                 astman_append(s, "NumberOfSpeeddials: %d\r\n", numspeeddials);
3121                                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3122                                         astman_append(s, "Speeddial: %s (%s) ishint: %d\r\n", sd->exten, sd->label, sd->isHint);
3123                                 }
3124                         }
3125                 }
3126         }
3127         AST_LIST_UNLOCK(&devices);
3128         return CLI_SUCCESS;
3129 }
3130
3131 static char mandescr_show_device[] =
3132 "Description: Show one SKINNY device with details on current status.\n"
3133 "Variables: \n"
3134 "  Device: <name>           The device name you want to check.\n"
3135 "  ActionID: <id>         Optional action ID for this AMI transaction.\n";
3136
3137 static int manager_skinny_show_device(struct mansession *s, const struct message *m)
3138 {
3139         const char *a[4];
3140         const char *device;
3141
3142         device = astman_get_header(m, "Device");
3143         if (ast_strlen_zero(device)) {
3144                 astman_send_error(s, m, "Device: <name> missing.");
3145                 return 0;
3146         }
3147         a[0] = "skinny";
3148         a[1] = "show";
3149         a[2] = "device";
3150         a[3] = device;
3151
3152         _skinny_show_device(1, -1, s, m, 4, a);
3153         astman_append(s, "\r\n\r\n" );
3154         return 0;
3155 }
3156
3157 /*! \brief Show device information */
3158 static char *handle_skinny_show_device(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3159 {
3160         switch (cmd) {
3161         case CLI_INIT:
3162                 e->command = "skinny show device";
3163                 e->usage =
3164                         "Usage: skinny show device <DeviceId|DeviceName>\n"
3165                         "       Lists all deviceinformation of a specific device known to the Skinny subsystem.\n";
3166                 return NULL;
3167         case CLI_GENERATE:
3168                 return complete_skinny_show_device(a->line, a->word, a->pos, a->n);
3169         }
3170
3171         return _skinny_show_device(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
3172 }
3173
3174 static char *_skinny_show_lines(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
3175 {
3176         struct skinny_line *l;
3177         struct skinny_subchannel *sub;
3178         int total_lines = 0;
3179         int verbose = 0;
3180         const char *id;
3181         char idtext[256] = "";
3182
3183         if (s) {        /* Manager - get ActionID */
3184                 id = astman_get_header(m, "ActionID");
3185                 if (!ast_strlen_zero(id))
3186                         snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3187         }
3188
3189         switch (argc) {
3190         case 4:
3191                 verbose = 1;
3192                 break;
3193         case 3:
3194                 verbose = 0;
3195                 break;
3196         default:
3197                 return CLI_SHOWUSAGE;
3198         }
3199
3200         if (!s) {
3201                 ast_cli(fd, "Name                 Device Name          Instance Label               \n");
3202                 ast_cli(fd, "-------------------- -------------------- -------- --------------------\n");
3203         }
3204         AST_LIST_LOCK(&lines);
3205         AST_LIST_TRAVERSE(&lines, l, all) {
3206                 total_lines++;
3207                 if (!s) {
3208                         ast_cli(fd, "%-20s %-20s %8d %-20s\n",
3209                                 l->name,
3210                                 (l->device ? l->device->name : "Not connected"),
3211                                 l->instance,
3212                                 l->label);
3213                         if (verbose) {
3214                                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
3215                                         ast_cli(fd, "  %s> %s to %s\n",
3216                                                 (sub == l->activesub?"Active  ":"Inactive"),
3217                                                 sub->owner->name,
3218                                                 (ast_bridged_channel(sub->owner)?ast_bridged_channel(sub->owner)->name:"")
3219                                         );
3220                                 }
3221                         }
3222                 } else {
3223                         astman_append(s,
3224                                 "Event: LineEntry\r\n%s"
3225                                 "Channeltype: SKINNY\r\n"
3226                                 "ObjectName: %s\r\n"
3227                                 "ChannelObjectType: line\r\n"
3228                                 "Device: %s\r\n"
3229                                 "Instance: %d\r\n"
3230                                 "Label: %s\r\n",
3231                                 idtext,
3232                                 l->name,
3233                                 (l->device?l->device->name:"None"),
3234                                 l->instance,
3235                                 l->label);
3236                 }
3237                 AST_LIST_UNLOCK(&lines);
3238         }
3239
3240         if (total) {
3241                 *total = total_lines;
3242         }
3243
3244         return CLI_SUCCESS;
3245 }
3246
3247 static char mandescr_show_lines[] =
3248 "Description: Lists Skinny lines in text format with details on current status.\n"
3249 "Linelist will follow as separate events, followed by a final event called\n"
3250 "LinelistComplete.\n"
3251 "Variables: \n"
3252 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
3253
3254 /*! \brief  Show Skinny lines in the manager API */
3255 /*    Inspired from chan_sip */
3256 static int manager_skinny_show_lines(struct mansession *s, const struct message *m)
3257 {
3258         const char *id = astman_get_header(m, "ActionID");
3259         const char *a[] = {"skinny", "show", "lines"};
3260         char idtext[256] = "";
3261         int total = 0;
3262
3263         if (!ast_strlen_zero(id))
3264                 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3265