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