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