fde90cdc681f026818a68b34ccb4f37ad400aaac
[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 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 char global_context[AST_MAX_CONTEXT] = "default";
971 static char language[MAX_LANGUAGE] = "";
972 static char mohinterpret[MAX_MUSICCLASS] = "default";
973 static char mohsuggest[MAX_MUSICCLASS] = "";
974 static char cid_num[AST_MAX_EXTENSION] = "";
975 static char cid_name[AST_MAX_EXTENSION] = "";
976 static char linelabel[AST_MAX_EXTENSION] ="";
977 static char parkinglot[AST_MAX_CONTEXT] ="";
978 static int nat = 0;
979 static ast_group_t cur_callergroup = 0;
980 static ast_group_t cur_pickupgroup = 0;
981 static int immediate = 0;
982 static int callwaiting = 0;
983 static int callreturn = 0;
984 static int threewaycalling = 0;
985 static int mwiblink = 0;
986 /* This is for flashhook transfers */
987 static int transfer = 0;
988 static int cancallforward = 0;
989 /* static int busycount = 3;*/
990 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
991 static char mailbox[AST_MAX_EXTENSION];
992 static char regexten[AST_MAX_EXTENSION];
993 static int amaflags = 0;
994 static int callnums = 1;
995 static int canreinvite = 0;
996
997 #define SKINNY_DEVICE_UNKNOWN -1
998 #define SKINNY_DEVICE_NONE 0
999 #define SKINNY_DEVICE_30SPPLUS 1
1000 #define SKINNY_DEVICE_12SPPLUS 2
1001 #define SKINNY_DEVICE_12SP 3
1002 #define SKINNY_DEVICE_12 4
1003 #define SKINNY_DEVICE_30VIP 5
1004 #define SKINNY_DEVICE_7910 6
1005 #define SKINNY_DEVICE_7960 7
1006 #define SKINNY_DEVICE_7940 8
1007 #define SKINNY_DEVICE_7935 9
1008 #define SKINNY_DEVICE_ATA186 12 /* Cisco ATA-186 */
1009 #define SKINNY_DEVICE_7941 115
1010 #define SKINNY_DEVICE_7971 119
1011 #define SKINNY_DEVICE_7914 124 /* Expansion module */
1012 #define SKINNY_DEVICE_7985 302
1013 #define SKINNY_DEVICE_7911 307
1014 #define SKINNY_DEVICE_7961GE 308
1015 #define SKINNY_DEVICE_7941GE 309
1016 #define SKINNY_DEVICE_7931 348
1017 #define SKINNY_DEVICE_7921 365
1018 #define SKINNY_DEVICE_7906 369
1019 #define SKINNY_DEVICE_7962 404 /* Not found */
1020 #define SKINNY_DEVICE_7937 431
1021 #define SKINNY_DEVICE_7942 434
1022 #define SKINNY_DEVICE_7945 435
1023 #define SKINNY_DEVICE_7965 436
1024 #define SKINNY_DEVICE_7975 437
1025 #define SKINNY_DEVICE_7905 20000
1026 #define SKINNY_DEVICE_7920 30002
1027 #define SKINNY_DEVICE_7970 30006
1028 #define SKINNY_DEVICE_7912 30007
1029 #define SKINNY_DEVICE_7902 30008
1030 #define SKINNY_DEVICE_CIPC 30016 /* Cisco IP Communicator */
1031 #define SKINNY_DEVICE_7961 30018
1032 #define SKINNY_DEVICE_7936 30019
1033 #define SKINNY_DEVICE_SCCPGATEWAY_AN 30027 /* Analog gateway */
1034 #define SKINNY_DEVICE_SCCPGATEWAY_BRI 30028 /* BRI gateway */
1035
1036 #define SKINNY_SPEAKERON 1
1037 #define SKINNY_SPEAKEROFF 2
1038
1039 #define SKINNY_MICON 1
1040 #define SKINNY_MICOFF 2
1041
1042 #define SKINNY_OFFHOOK 1
1043 #define SKINNY_ONHOOK 2
1044 #define SKINNY_RINGOUT 3
1045 #define SKINNY_RINGIN 4
1046 #define SKINNY_CONNECTED 5
1047 #define SKINNY_BUSY 6
1048 #define SKINNY_CONGESTION 7
1049 #define SKINNY_HOLD 8
1050 #define SKINNY_CALLWAIT 9
1051 #define SKINNY_TRANSFER 10
1052 #define SKINNY_PARK 11
1053 #define SKINNY_PROGRESS 12
1054 #define SKINNY_CALLREMOTEMULTILINE 13
1055 #define SKINNY_INVALID 14
1056
1057 #define SKINNY_SILENCE 0x00
1058 #define SKINNY_DIALTONE 0x21
1059 #define SKINNY_BUSYTONE 0x23
1060 #define SKINNY_ALERT 0x24
1061 #define SKINNY_REORDER 0x25
1062 #define SKINNY_CALLWAITTONE 0x2D
1063 #define SKINNY_NOTONE 0x7F
1064
1065 #define SKINNY_LAMP_OFF 1
1066 #define SKINNY_LAMP_ON 2
1067 #define SKINNY_LAMP_WINK 3
1068 #define SKINNY_LAMP_FLASH 4
1069 #define SKINNY_LAMP_BLINK 5
1070
1071 #define SKINNY_RING_OFF 1
1072 #define SKINNY_RING_INSIDE 2
1073 #define SKINNY_RING_OUTSIDE 3
1074 #define SKINNY_RING_FEATURE 4
1075
1076 #define SKINNY_CFWD_ALL       (1 << 0)
1077 #define SKINNY_CFWD_BUSY      (1 << 1)
1078 #define SKINNY_CFWD_NOANSWER  (1 << 2)
1079
1080 #define TYPE_TRUNK 1
1081 #define TYPE_LINE 2
1082
1083 /* Skinny rtp stream modes. Do we really need this? */
1084 #define SKINNY_CX_SENDONLY 0
1085 #define SKINNY_CX_RECVONLY 1
1086 #define SKINNY_CX_SENDRECV 2
1087 #define SKINNY_CX_CONF 3
1088 #define SKINNY_CX_CONFERENCE 3
1089 #define SKINNY_CX_MUTE 4
1090 #define SKINNY_CX_INACTIVE 4
1091
1092 #if 0
1093 static char *skinny_cxmodes[] = {
1094         "sendonly",
1095         "recvonly",
1096         "sendrecv",
1097         "confrnce",
1098         "inactive"
1099 };
1100 #endif
1101
1102 /* driver scheduler */
1103 static struct sched_context *sched = NULL;
1104 static struct io_context *io;
1105
1106 /* Protect the monitoring thread, so only one process can kill or start it, and not
1107    when it's doing something critical. */
1108 AST_MUTEX_DEFINE_STATIC(monlock);
1109 /* Protect the network socket */
1110 AST_MUTEX_DEFINE_STATIC(netlock);
1111
1112 /* This is the thread for the monitor which checks for input on the channels
1113    which are not currently in use. */
1114 static pthread_t monitor_thread = AST_PTHREADT_NULL;
1115
1116 /* Wait up to 16 seconds for first digit */
1117 static int firstdigittimeout = 16000;
1118
1119 /* How long to wait for following digits */
1120 static int gendigittimeout = 8000;
1121
1122 /* How long to wait for an extra digit, if there is an ambiguous match */
1123 static int matchdigittimeout = 3000;
1124
1125 struct skinny_subchannel {
1126         ast_mutex_t lock;
1127         struct ast_channel *owner;
1128         struct ast_rtp *rtp;
1129         struct ast_rtp *vrtp;
1130         unsigned int callid;
1131         /* time_t lastouttime; */ /* Unused */
1132         int progress;
1133         int ringing;
1134         int onhold;
1135         /* int lastout; */ /* Unused */
1136         int cxmode;
1137         int nat;
1138         int outgoing;
1139         int alreadygone;
1140         int blindxfer;
1141         int xferor;
1142
1143
1144         AST_LIST_ENTRY(skinny_subchannel) list;
1145         struct skinny_subchannel *related;
1146         struct skinny_line *parent;
1147 };
1148
1149 struct skinny_line {
1150         ast_mutex_t lock;
1151         char name[80];
1152         char label[24]; /* Label that shows next to the line buttons */
1153         char accountcode[AST_MAX_ACCOUNT_CODE];
1154         char exten[AST_MAX_EXTENSION]; /* Extension where to start */
1155         char context[AST_MAX_CONTEXT];
1156         char language[MAX_LANGUAGE];
1157         char cid_num[AST_MAX_EXTENSION]; /* Caller*ID */
1158         char cid_name[AST_MAX_EXTENSION]; /* Caller*ID */
1159         char lastcallerid[AST_MAX_EXTENSION]; /* Last Caller*ID */
1160         int cfwdtype;
1161         char call_forward_all[AST_MAX_EXTENSION];
1162         char call_forward_busy[AST_MAX_EXTENSION];
1163         char call_forward_noanswer[AST_MAX_EXTENSION];
1164         char mailbox[AST_MAX_EXTENSION];
1165         char vmexten[AST_MAX_EXTENSION];
1166         char regexten[AST_MAX_EXTENSION]; /* Extension for auto-extensions */
1167         char regcontext[AST_MAX_CONTEXT]; /* Context for auto-extensions */
1168         char parkinglot[AST_MAX_CONTEXT]; /* Parkinglot for parkedcalls */
1169         char mohinterpret[MAX_MUSICCLASS];
1170         char mohsuggest[MAX_MUSICCLASS];
1171         char lastnumberdialed[AST_MAX_EXTENSION]; /* Last number that was dialed - used for redial */
1172         int curtone; /* Current tone being played */
1173         ast_group_t callgroup;
1174         ast_group_t pickupgroup;
1175         struct ast_event_sub *mwi_event_sub; /* Event based MWI */
1176         int callwaiting;
1177         int transfer;
1178         int threewaycalling;
1179         int mwiblink;
1180         int cancallforward;
1181         int getforward;
1182         int callreturn;
1183         int dnd; /* How does this affect callwait?  Do we just deny a skinny_request if we're dnd? */
1184         int hascallerid;
1185         int hidecallerid;
1186         int amaflags;
1187         int type;
1188         int instance;
1189         int group;
1190         int needdestroy;
1191         int capability;
1192         int nonCodecCapability;
1193         int onhooktime;
1194         int msgstate; /* voicemail message state */
1195         int immediate;
1196         int hookstate;
1197         int nat;
1198         int canreinvite;
1199
1200         struct ast_codec_pref prefs;
1201         struct skinny_subchannel *activesub;
1202         AST_LIST_HEAD(, skinny_subchannel) sub;
1203         AST_LIST_ENTRY(skinny_line) list;
1204         struct skinny_device *parent;
1205         struct ast_variable *chanvars; /*!< Channel variables to set for inbound call */
1206 };
1207
1208 struct skinny_speeddial {
1209         ast_mutex_t lock;
1210         char label[42];
1211         char context[AST_MAX_CONTEXT];
1212         char exten[AST_MAX_EXTENSION];
1213         int instance;
1214         int stateid;
1215         int laststate;
1216         int isHint;
1217
1218         AST_LIST_ENTRY(skinny_speeddial) list;
1219         struct skinny_device *parent;
1220 };
1221
1222 struct skinny_addon {
1223         ast_mutex_t lock;
1224         char type[10];
1225         AST_LIST_ENTRY(skinny_addon) list;
1226         struct skinny_device *parent;
1227 };
1228
1229 struct skinny_device {
1230         /* A device containing one or more lines */
1231         char name[80];
1232         char id[16];
1233         char version_id[16];
1234         char exten[AST_MAX_EXTENSION]; /* Cruddy variable name, pick a better one */
1235         int type;
1236         int registered;
1237         int lastlineinstance;
1238         int lastcallreference;
1239         int capability;
1240         int earlyrtp;
1241         struct sockaddr_in addr;
1242         struct in_addr ourip;
1243         AST_LIST_HEAD(, skinny_line) lines;
1244         AST_LIST_HEAD(, skinny_speeddial) speeddials;
1245         AST_LIST_HEAD(, skinny_addon) addons;
1246         struct ast_codec_pref prefs;
1247         struct ast_ha *ha;
1248         struct skinnysession *session;
1249         struct skinny_line *activeline;
1250         AST_LIST_ENTRY(skinny_device) list;
1251 };
1252
1253 static AST_LIST_HEAD_STATIC(devices, skinny_device);
1254
1255 struct skinnysession {
1256         pthread_t t;
1257         ast_mutex_t lock;
1258         struct sockaddr_in sin;
1259         int fd;
1260         char inbuf[SKINNY_MAX_PACKET];
1261         char outbuf[SKINNY_MAX_PACKET];
1262         struct skinny_device *device;
1263         AST_LIST_ENTRY(skinnysession) list;
1264 };
1265
1266 static AST_LIST_HEAD_STATIC(sessions, skinnysession);
1267
1268 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause);
1269 static int skinny_devicestate(void *data);
1270 static int skinny_call(struct ast_channel *ast, char *dest, int timeout);
1271 static int skinny_hangup(struct ast_channel *ast);
1272 static int skinny_answer(struct ast_channel *ast);
1273 static struct ast_frame *skinny_read(struct ast_channel *ast);
1274 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1275 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1276 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1277 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1278 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1279 static int handle_time_date_req_message(struct skinny_req *req, struct skinnysession *s);
1280
1281 static const struct ast_channel_tech skinny_tech = {
1282         .type = "Skinny",
1283         .description = tdesc,
1284         .capabilities = AST_FORMAT_AUDIO_MASK,
1285         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1286         .requester = skinny_request,
1287         .devicestate = skinny_devicestate,
1288         .call = skinny_call,
1289         .hangup = skinny_hangup,
1290         .answer = skinny_answer,
1291         .read = skinny_read,
1292         .write = skinny_write,
1293         .indicate = skinny_indicate,
1294         .fixup = skinny_fixup,
1295         .send_digit_begin = skinny_senddigit_begin,
1296         .send_digit_end = skinny_senddigit_end,
1297         .bridge = ast_rtp_bridge,  
1298 };
1299
1300 static int skinny_extensionstate_cb(char *context, char* exten, int state, void *data);
1301 static int skinny_transfer(struct skinny_subchannel *sub);
1302
1303 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1304 {
1305         struct skinny_device *d = s->device;
1306         struct skinny_addon *a;
1307         int i;
1308
1309         switch (d->type) {
1310                 case SKINNY_DEVICE_30SPPLUS:
1311                 case SKINNY_DEVICE_30VIP:
1312                         /* 13 rows, 2 columns */
1313                         for (i = 0; i < 4; i++)
1314                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1315                         (btn++)->buttonDefinition = BT_REDIAL;
1316                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1317                         (btn++)->buttonDefinition = BT_CALLPARK;
1318                         (btn++)->buttonDefinition = BT_FORWARDALL;
1319                         (btn++)->buttonDefinition = BT_CONFERENCE;
1320                         for (i = 0; i < 4; i++)
1321                                 (btn++)->buttonDefinition = BT_NONE;
1322                         for (i = 0; i < 13; i++)
1323                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1324                         
1325                         break;
1326                 case SKINNY_DEVICE_12SPPLUS:
1327                 case SKINNY_DEVICE_12SP:
1328                 case SKINNY_DEVICE_12:
1329                         /* 6 rows, 2 columns */
1330                         for (i = 0; i < 2; i++)
1331                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1332                         for (i = 0; i < 4; i++)
1333                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1334                         (btn++)->buttonDefinition = BT_HOLD;
1335                         (btn++)->buttonDefinition = BT_REDIAL;
1336                         (btn++)->buttonDefinition = BT_TRANSFER;
1337                         (btn++)->buttonDefinition = BT_FORWARDALL;
1338                         (btn++)->buttonDefinition = BT_CALLPARK;
1339                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1340                         break;
1341                 case SKINNY_DEVICE_7910:
1342                         (btn++)->buttonDefinition = BT_LINE;
1343                         (btn++)->buttonDefinition = BT_HOLD;
1344                         (btn++)->buttonDefinition = BT_TRANSFER;
1345                         (btn++)->buttonDefinition = BT_DISPLAY;
1346                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1347                         (btn++)->buttonDefinition = BT_CONFERENCE;
1348                         (btn++)->buttonDefinition = BT_FORWARDALL;
1349                         for (i = 0; i < 2; i++)
1350                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1351                         (btn++)->buttonDefinition = BT_REDIAL;
1352                         break;
1353                 case SKINNY_DEVICE_7960:
1354                 case SKINNY_DEVICE_7961:
1355                 case SKINNY_DEVICE_7961GE:
1356                 case SKINNY_DEVICE_7962:
1357                 case SKINNY_DEVICE_7965:
1358                         for (i = 0; i < 6; i++)
1359                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1360                         break;
1361                 case SKINNY_DEVICE_7940:
1362                 case SKINNY_DEVICE_7941:
1363                 case SKINNY_DEVICE_7941GE:
1364                 case SKINNY_DEVICE_7942:
1365                 case SKINNY_DEVICE_7945:
1366                         for (i = 0; i < 2; i++)
1367                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1368                         break;
1369                 case SKINNY_DEVICE_7935:
1370                 case SKINNY_DEVICE_7936:
1371                         for (i = 0; i < 2; i++)
1372                                 (btn++)->buttonDefinition = BT_LINE;
1373                         break;
1374                 case SKINNY_DEVICE_ATA186:
1375                         (btn++)->buttonDefinition = BT_LINE;
1376                         break;
1377                 case SKINNY_DEVICE_7970:
1378                 case SKINNY_DEVICE_7971:
1379                 case SKINNY_DEVICE_7975:
1380                 case SKINNY_DEVICE_CIPC:
1381                         for (i = 0; i < 8; i++)
1382                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1383                         break;
1384                 case SKINNY_DEVICE_7985:
1385                         /* XXX I have no idea what the buttons look like on these. */
1386                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1387                         break;
1388                 case SKINNY_DEVICE_7912:
1389                 case SKINNY_DEVICE_7911:
1390                 case SKINNY_DEVICE_7905:
1391                         (btn++)->buttonDefinition = BT_LINE;
1392                         (btn++)->buttonDefinition = BT_HOLD;
1393                         break;
1394                 case SKINNY_DEVICE_7920:
1395                         /* XXX I don't know if this is right. */
1396                         for (i = 0; i < 4; i++)
1397                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1398                         break;
1399                 case SKINNY_DEVICE_7921:
1400                         for (i = 0; i < 6; i++)
1401                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1402                         break;
1403                 case SKINNY_DEVICE_7902:
1404                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1405                         break;
1406                 case SKINNY_DEVICE_7906:
1407                         ast_log(LOG_WARNING, "Unsupported device type '%d (7906)' found.\n", d->type);
1408                         break;
1409                 case SKINNY_DEVICE_7931:
1410                         ast_log(LOG_WARNING, "Unsupported device type '%d (7931)' found.\n", d->type);
1411                         break;
1412                 case SKINNY_DEVICE_7937:
1413                         ast_log(LOG_WARNING, "Unsupported device type '%d (7937)' found.\n", d->type);
1414                         break;
1415                 case SKINNY_DEVICE_7914:
1416                         ast_log(LOG_WARNING, "Unsupported device type '%d (7914)' found.  Expansion module registered by itself?\n", d->type);
1417                         break;
1418                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1419                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1420                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1421                         break;
1422                 default:
1423                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1424                         break;
1425         }
1426
1427         AST_LIST_LOCK(&d->addons);
1428         AST_LIST_TRAVERSE(&d->addons, a, list) {
1429                 if (!strcasecmp(a->type, "7914")) {
1430                         for (i = 0; i < 14; i++)
1431                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1432                 } else {
1433                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1434                 }
1435         }
1436         AST_LIST_UNLOCK(&d->addons);
1437
1438         return btn;
1439 }
1440
1441 static struct skinny_req *req_alloc(size_t size, int response_message)
1442 {
1443         struct skinny_req *req;
1444
1445         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1446                 return NULL;
1447
1448         req->len = htolel(size+4);
1449         req->e = htolel(response_message);
1450
1451         return req;
1452 }
1453
1454 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1455 {
1456         struct skinny_line *l;
1457
1458         /*Dialing from on hook or on a 7920 uses instance 0 in requests
1459           but we need to start looking at instance 1 */
1460
1461         if (!instance)
1462                 instance = 1;
1463
1464         AST_LIST_TRAVERSE(&d->lines, l, list){
1465                 if (l->instance == instance)
1466                         break;
1467         }
1468
1469         if (!l) {
1470                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1471         }
1472         return l;
1473 }
1474
1475 static struct skinny_line *find_line_by_name(const char *dest)
1476 {
1477         struct skinny_line *l;
1478         struct skinny_line *tmpl = NULL;
1479         struct skinny_device *d;
1480         char line[256];
1481         char *at;
1482         char *device;
1483         int checkdevice = 0;
1484
1485         ast_copy_string(line, dest, sizeof(line));
1486         at = strchr(line, '@');
1487         if (at)
1488                 *at++ = '\0';
1489         device = at;
1490
1491         if (!ast_strlen_zero(device))
1492                 checkdevice = 1;
1493
1494         AST_LIST_LOCK(&devices);
1495         AST_LIST_TRAVERSE(&devices, d, list){
1496                 if (checkdevice && tmpl)
1497                         break;
1498                 else if (!checkdevice) {
1499                         /* This is a match, since we're checking for line on every device. */
1500                 } else if (!strcasecmp(d->name, device)) {
1501                         if (skinnydebug)
1502                                 ast_verb(2, "Found device: %s\n", d->name);
1503                 } else
1504                         continue;
1505
1506                 /* Found the device (or we don't care which device) */
1507                 AST_LIST_TRAVERSE(&d->lines, l, list){
1508                         /* Search for the right line */
1509                         if (!strcasecmp(l->name, line)) {
1510                                 if (tmpl) {
1511                                         ast_verb(2, "Ambiguous line name: %s\n", line);
1512                                         AST_LIST_UNLOCK(&devices);
1513                                         return NULL;
1514                                 } else
1515                                         tmpl = l;
1516                         }
1517                 }
1518         }
1519         AST_LIST_UNLOCK(&devices);
1520         return tmpl;
1521 }
1522
1523 /*!
1524  * implement the setvar config line
1525  */
1526 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
1527 {
1528         struct ast_variable *tmpvar = NULL;
1529         char *varname = ast_strdupa(buf), *varval = NULL;
1530
1531         if ((varval = strchr(varname,'='))) {
1532                 *varval++ = '\0';
1533                 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
1534                         tmpvar->next = list;
1535                         list = tmpvar;
1536                 }
1537         }
1538         return list;
1539 }
1540
1541 /* It's quicker/easier to find the subchannel when we know the instance number too */
1542 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
1543 {
1544         struct skinny_line *l = find_line_by_instance(d, instance);
1545         struct skinny_subchannel *sub;
1546
1547         if (!l) {
1548                 return NULL;
1549         }
1550
1551         /* 7920 phones set call reference to 0, so use the first
1552            sub-channel on the list.
1553            This MIGHT need more love to be right */
1554         if (!reference)
1555                 sub = AST_LIST_FIRST(&l->sub);
1556         else {
1557                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
1558                         if (sub->callid == reference)
1559                                 break;
1560                 }
1561         }
1562         if (!sub) {
1563                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
1564         }
1565         return sub;
1566 }
1567
1568 /* Find the subchannel when we only have the callid - this shouldn't happen often */
1569 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
1570 {
1571         struct skinny_line *l;
1572         struct skinny_subchannel *sub = NULL;
1573
1574         AST_LIST_TRAVERSE(&d->lines, l, list){
1575                 AST_LIST_TRAVERSE(&l->sub, sub, list){
1576                         if (sub->callid == reference)
1577                                 break;
1578                 }
1579                 if (sub)
1580                         break;
1581         }
1582
1583         if (!l) {
1584                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
1585         } else {
1586                 if (!sub) {
1587                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
1588                 }
1589         }
1590         return sub;
1591 }
1592
1593 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
1594 {
1595         struct skinny_speeddial *sd;
1596
1597         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1598                 if (sd->isHint == isHint && sd->instance == instance)
1599                         break;
1600         }
1601
1602         if (!sd) {
1603                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
1604         }
1605         return sd;
1606 }
1607
1608 static int codec_skinny2ast(enum skinny_codecs skinnycodec)
1609 {
1610         switch (skinnycodec) {
1611         case SKINNY_CODEC_ALAW:
1612                 return AST_FORMAT_ALAW;
1613         case SKINNY_CODEC_ULAW:
1614                 return AST_FORMAT_ULAW;
1615         case SKINNY_CODEC_G723_1:
1616                 return AST_FORMAT_G723_1;
1617         case SKINNY_CODEC_G729A:
1618                 return AST_FORMAT_G729A;
1619         case SKINNY_CODEC_G726_32:
1620                 return AST_FORMAT_G726_AAL2; /* XXX Is this right? */
1621         case SKINNY_CODEC_H261:
1622                 return AST_FORMAT_H261;
1623         case SKINNY_CODEC_H263:
1624                 return AST_FORMAT_H263;
1625         default:
1626                 return 0;
1627         }
1628 }
1629
1630 static int codec_ast2skinny(int astcodec)
1631 {
1632         switch (astcodec) {
1633         case AST_FORMAT_ALAW:
1634                 return SKINNY_CODEC_ALAW;
1635         case AST_FORMAT_ULAW:
1636                 return SKINNY_CODEC_ULAW;
1637         case AST_FORMAT_G723_1:
1638                 return SKINNY_CODEC_G723_1;
1639         case AST_FORMAT_G729A:
1640                 return SKINNY_CODEC_G729A;
1641         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
1642                 return SKINNY_CODEC_G726_32;
1643         case AST_FORMAT_H261:
1644                 return SKINNY_CODEC_H261;
1645         case AST_FORMAT_H263:
1646                 return SKINNY_CODEC_H263;
1647         default:
1648                 return 0;
1649         }
1650 }
1651
1652 static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
1653 {
1654         if (!l)
1655                 return 0;
1656
1657         if (!ast_strlen_zero(cfwd)) {
1658                 if (cfwdtype & SKINNY_CFWD_ALL) {
1659                         l->cfwdtype |= SKINNY_CFWD_ALL;
1660                         ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
1661                 }
1662                 if (cfwdtype & SKINNY_CFWD_BUSY) {
1663                         l->cfwdtype |= SKINNY_CFWD_BUSY;
1664                         ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
1665                 }
1666                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
1667                         l->cfwdtype |= SKINNY_CFWD_NOANSWER;
1668                         ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
1669                 }
1670         } else {
1671                 if (cfwdtype & SKINNY_CFWD_ALL) {
1672                         l->cfwdtype &= ~SKINNY_CFWD_ALL;
1673                         memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
1674                 }
1675                 if (cfwdtype & SKINNY_CFWD_BUSY) {
1676                         l->cfwdtype &= ~SKINNY_CFWD_BUSY;
1677                         memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
1678                 }
1679                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
1680                         l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
1681                         memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
1682                 }
1683         }
1684         return l->cfwdtype;
1685 }
1686
1687 static void cleanup_stale_contexts(char *new, char *old)
1688 {
1689         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
1690
1691         while ((oldcontext = strsep(&old, "&"))) {
1692                 stalecontext = '\0';
1693                 ast_copy_string(newlist, new, sizeof(newlist));
1694                 stringp = newlist;
1695                 while ((newcontext = strsep(&stringp, "&"))) {
1696                         if (strcmp(newcontext, oldcontext) == 0) {
1697                                 /* This is not the context you're looking for */
1698                                 stalecontext = '\0';
1699                                 break;
1700                         } else if (strcmp(newcontext, oldcontext)) {
1701                                 stalecontext = oldcontext;
1702                         }
1703                         
1704                 }
1705                 if (stalecontext)
1706                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
1707         }
1708 }
1709
1710 static void register_exten(struct skinny_line *l)
1711 {
1712         char multi[256];
1713         char *stringp, *ext, *context;
1714
1715         if (ast_strlen_zero(regcontext))
1716                 return;
1717
1718         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1719         stringp = multi;
1720         while ((ext = strsep(&stringp, "&"))) {
1721                 if ((context = strchr(ext, '@'))) {
1722                         *context++ = '\0'; /* split ext@context */
1723                         if (!ast_context_find(context)) {
1724                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1725                                 continue;
1726                         }
1727                 } else {
1728                         context = regcontext;
1729                 }
1730                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
1731                          ast_strdup(l->name), ast_free_ptr, "Skinny");
1732         }
1733 }
1734
1735 static void unregister_exten(struct skinny_line *l)
1736 {
1737         char multi[256];
1738         char *stringp, *ext, *context;
1739
1740         if (ast_strlen_zero(regcontext))
1741                 return;
1742
1743         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1744         stringp = multi;
1745         while ((ext = strsep(&stringp, "&"))) {
1746                 if ((context = strchr(ext, '@'))) {
1747                         *context++ = '\0'; /* split ext@context */
1748                         if (!ast_context_find(context)) {
1749                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1750                                 continue;
1751                         }
1752                 } else {
1753                         context = regcontext;
1754                 }
1755                 ast_context_remove_extension(context, ext, 1, NULL);
1756         }
1757 }
1758
1759 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
1760 {
1761         struct skinny_device *d;
1762         struct skinny_line *l;
1763         struct skinny_speeddial *sd;
1764         struct sockaddr_in sin;
1765         socklen_t slen;
1766
1767         AST_LIST_LOCK(&devices);
1768         AST_LIST_TRAVERSE(&devices, d, list){
1769                 if (!strcasecmp(req->data.reg.name, d->id)
1770                                 && ast_apply_ha(d->ha, &(s->sin))) {
1771                         s->device = d;
1772                         d->type = letohl(req->data.reg.type);
1773                         if (ast_strlen_zero(d->version_id)) {
1774                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
1775                         }
1776                         d->registered = 1;
1777                         d->session = s;
1778
1779                         slen = sizeof(sin);
1780                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
1781                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
1782                                 sin.sin_addr = __ourip;
1783                         }
1784                         d->ourip = sin.sin_addr;
1785
1786                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1787                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd);
1788                         }
1789                         AST_LIST_TRAVERSE(&d->lines, l, list) {
1790                                 register_exten(l);
1791                                 ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s@%s", l->name, d->name);
1792                         }
1793                         break;
1794                 }
1795         }
1796         AST_LIST_UNLOCK(&devices);
1797         if (!d) {
1798                 return 0;
1799         }
1800         return 1;
1801 }
1802
1803 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
1804 {
1805         struct skinny_device *d;
1806         struct skinny_line *l;
1807         struct skinny_speeddial *sd;
1808
1809         d = s->device;
1810
1811         if (d) {
1812                 d->session = NULL;
1813                 d->registered = 0;
1814
1815                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1816                         if (sd->stateid > -1)
1817                                 ast_extension_state_del(sd->stateid, NULL);
1818                 }
1819                 AST_LIST_TRAVERSE(&d->lines, l, list) {
1820                         unregister_exten(l);
1821                         ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "Skinny/%s@%s", l->name, d->name);
1822                 }
1823         }
1824
1825         return -1; /* main loop will destroy the session */
1826 }
1827
1828 static int transmit_response(struct skinny_device *d, struct skinny_req *req)
1829 {
1830         struct skinnysession *s = d->session;
1831         int res = 0;
1832
1833         if (!s) {
1834                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
1835                 return -1;
1836         }
1837
1838         ast_mutex_lock(&s->lock);
1839
1840         if (skinnydebug)
1841                 ast_log(LOG_VERBOSE, "writing packet type %04X (%d bytes) to socket %d\n", letohl(req->e), letohl(req->len)+8, s->fd);
1842
1843         if (letohl(req->len > SKINNY_MAX_PACKET) || letohl(req->len < 0)) {
1844                 ast_log(LOG_WARNING, "transmit_response: the length of the request is out of bounds\n");
1845                 ast_mutex_unlock(&s->lock);
1846                 return -1;
1847         }
1848
1849         memset(s->outbuf, 0, sizeof(s->outbuf));
1850         memcpy(s->outbuf, req, skinny_header_size);
1851         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
1852
1853         res = write(s->fd, s->outbuf, letohl(req->len)+8);
1854         
1855         if (res != letohl(req->len)+8) {
1856                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
1857                 if (res == -1) {
1858                         if (skinnydebug)
1859                                 ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
1860                         skinny_unregister(NULL, s);
1861                 }
1862                 
1863         }
1864         
1865         ast_free(req);
1866         ast_mutex_unlock(&s->lock);
1867         return 1;
1868 }
1869
1870 static void transmit_speaker_mode(struct skinny_device *d, int mode)
1871 {
1872         struct skinny_req *req;
1873
1874         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
1875                 return;
1876
1877         req->data.setspeaker.mode = htolel(mode);
1878         transmit_response(d, req);
1879 }
1880 /*
1881 static void transmit_microphone_mode(struct skinny_device *d, int mode)
1882 {
1883         struct skinny_req *req;
1884
1885         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
1886                 return;
1887
1888         req->data.setmicrophone.mode = htolel(mode);
1889         transmit_response(d, req);
1890 }
1891 */
1892
1893 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)
1894 {
1895         struct skinny_req *req;
1896
1897         /* We should not be able to get here without a device */
1898         if (!d)
1899                 return;
1900
1901         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
1902                 return;
1903
1904         if (skinnydebug)
1905                         ast_verb(1, "Setting Callinfo to %s(%s) from %s(%s) on %s(%d)\n", fromname, fromnum, toname, tonum, d->name, instance);
1906
1907         if (fromname) {
1908                 ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
1909         }
1910         if (fromnum) {
1911                 ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
1912         }
1913         if (toname) {
1914                 ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
1915         }
1916         if (tonum) {
1917                 ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
1918         }
1919         req->data.callinfo.instance = htolel(instance);
1920         req->data.callinfo.reference = htolel(callid);
1921         req->data.callinfo.type = htolel(calltype);
1922         transmit_response(d, req);
1923 }
1924
1925 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
1926 {
1927         struct skinny_req *req;
1928         struct skinny_line *l = sub->parent;
1929         struct ast_format_list fmt;
1930
1931         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
1932                 return;
1933
1934         fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
1935
1936         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
1937         req->data.openreceivechannel.partyId = htolel(sub->callid);
1938         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
1939         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(fmt.bits));
1940         req->data.openreceivechannel.echo = htolel(0);
1941         req->data.openreceivechannel.bitrate = htolel(0);
1942         transmit_response(d, req);
1943 }
1944
1945 static void transmit_tone(struct skinny_device *d, int tone, int instance, int reference)
1946 {
1947         struct skinny_req *req;
1948
1949         if (tone == SKINNY_NOTONE) {
1950                 /* This is bad, mmm'kay? */
1951                 return;
1952         }
1953
1954         if (tone > 0) {
1955                 if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
1956                         return;
1957                 req->data.starttone.tone = htolel(tone);
1958                 req->data.starttone.instance = htolel(instance);
1959                 req->data.starttone.reference = htolel(reference);
1960         } else {
1961                 if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
1962                         return;
1963                 req->data.stoptone.instance = htolel(instance);
1964                 req->data.stoptone.reference = htolel(reference);
1965         }
1966
1967         //Bad, tone is already set so this is redundant and a change to the if above
1968         //may lead to issues where we try to set a tone to a stop_tone_message
1969         //if (tone > 0) {
1970         //      req->data.starttone.tone = htolel(tone);
1971         //}
1972         transmit_response(d, req);
1973 }
1974
1975 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey)
1976 {
1977         struct skinny_req *req;
1978
1979         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
1980                 return;
1981
1982         req->data.selectsoftkey.instance = htolel(instance);
1983         req->data.selectsoftkey.reference = htolel(callid);
1984         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
1985         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
1986         transmit_response(d, req);
1987 }
1988
1989 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
1990 {
1991         struct skinny_req *req;
1992
1993         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
1994                 return;
1995
1996         req->data.setlamp.stimulus = htolel(stimulus);
1997         req->data.setlamp.stimulusInstance = htolel(instance);
1998         req->data.setlamp.deviceStimulus = htolel(indication);
1999         transmit_response(d, req);
2000 }
2001
2002 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2003 {
2004         struct skinny_req *req;
2005
2006         if (skinnydebug)
2007                 ast_verb(1, "Setting ringer mode to '%d'.\n", mode);
2008
2009         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2010                 return;
2011
2012         req->data.setringer.ringerMode = htolel(mode);
2013         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2014            Note: The phone will always show as ringing on the display.
2015
2016            1: phone will audibly ring over and over
2017            2: phone will audibly ring only once
2018            any other value, will NOT cause the phone to audibly ring
2019         */
2020         req->data.setringer.unknown1 = htolel(1);
2021         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2022            Perhaps a packet capture can shed some light on this. */
2023         req->data.setringer.unknown2 = htolel(1);
2024         transmit_response(d, req);
2025 }
2026
2027 static void transmit_displaymessage(struct skinny_device *d, const char *text, int instance, int reference)
2028 {
2029         struct skinny_req *req;
2030
2031         if (text == 0) {
2032                 if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
2033                         return;
2034
2035                 //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2036                 //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2037                 //req->data.clearpromptstatus.lineInstance = instance;
2038                 //req->data.clearpromptstatus.callReference = reference;
2039
2040                 if (skinnydebug)
2041                         ast_verb(1, "Clearing Display\n");
2042         } else {
2043                 if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2044                         return;
2045
2046                 ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2047                 if (skinnydebug)
2048                         ast_verb(1, "Displaying message '%s'\n", req->data.displaytext.text);
2049         }
2050
2051         transmit_response(d, req);
2052 }
2053
2054 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2055 {
2056         struct skinny_req *req;
2057
2058         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2059                 return;
2060
2061         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2062         req->data.displaynotify.displayTimeout = htolel(t);
2063
2064         if (skinnydebug)
2065                 ast_verb(1, "Displaying notify '%s'\n", text);
2066
2067         transmit_response(d, req);
2068 }
2069
2070 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
2071 {
2072         struct skinny_req *req;
2073
2074         if (text == 0) {
2075                 if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2076                         return;
2077
2078                 req->data.clearpromptstatus.lineInstance = htolel(instance);
2079                 req->data.clearpromptstatus.callReference = htolel(callid);
2080
2081                 if (skinnydebug)
2082                         ast_verb(1, "Clearing Prompt\n");
2083         } else {
2084                 if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2085                         return;
2086
2087                 ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2088                 req->data.displaypromptstatus.messageTimeout = htolel(t);
2089                 req->data.displaypromptstatus.lineInstance = htolel(instance);
2090                 req->data.displaypromptstatus.callReference = htolel(callid);
2091
2092                 if (skinnydebug)
2093                         ast_verb(1, "Displaying Prompt Status '%s'\n", text);
2094         }
2095
2096         transmit_response(d, req);
2097 }
2098
2099 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2100 {
2101         struct skinny_req *req;
2102
2103         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2104                 return;
2105
2106         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2107         req->data.dialednumber.lineInstance = htolel(instance);
2108         req->data.dialednumber.callReference = htolel(callid);
2109
2110         transmit_response(d, req);
2111 }
2112
2113 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2114 {
2115         struct skinny_req *req;
2116
2117         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2118                 return;
2119
2120         req->data.closereceivechannel.conferenceId = htolel(0);
2121         req->data.closereceivechannel.partyId = htolel(sub->callid);
2122         transmit_response(d, req);
2123 }
2124
2125 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2126 {
2127         struct skinny_req *req;
2128
2129         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2130                 return;
2131
2132         req->data.stopmedia.conferenceId = htolel(0);
2133         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2134         transmit_response(d, req);
2135 }
2136
2137 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
2138 {
2139         struct skinny_req *req;
2140
2141         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2142                 return;
2143
2144         req->data.activatecallplane.lineInstance = htolel(l->instance);
2145         transmit_response(d, req);
2146 }
2147
2148 static void transmit_callstateonly(struct skinny_device *d, struct skinny_subchannel *sub, int state)
2149 {
2150         struct skinny_req *req;
2151
2152         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2153                 return;
2154
2155         req->data.callstate.callState = htolel(state);
2156         req->data.callstate.lineInstance = htolel(sub->parent->instance);
2157         req->data.callstate.callReference = htolel(sub->callid);
2158         transmit_response(d, req);
2159 }
2160
2161 static void transmit_callstate(struct skinny_device *d, int instance, int state, unsigned callid)
2162 {
2163         struct skinny_req *req;
2164
2165         if (state == SKINNY_ONHOOK) {
2166                 if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2167                         return;
2168
2169                 req->data.closereceivechannel.conferenceId = htolel(callid);
2170                 req->data.closereceivechannel.partyId = htolel(callid);
2171                 transmit_response(d, req);
2172
2173                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2174                         return;
2175
2176                 req->data.stopmedia.conferenceId = htolel(callid);
2177                 req->data.stopmedia.passThruPartyId = htolel(callid);
2178                 transmit_response(d, req);
2179
2180                 transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
2181
2182                 transmit_displaypromptstatus(d, NULL, 0, instance, callid);
2183         }
2184
2185         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2186                 return;
2187
2188         req->data.callstate.callState = htolel(state);
2189         req->data.callstate.lineInstance = htolel(instance);
2190         req->data.callstate.callReference = htolel(callid);
2191         transmit_response(d, req);
2192
2193         if (state == SKINNY_ONHOOK) {
2194                 transmit_selectsoftkeys(d, 0, 0, KEYDEF_ONHOOK);
2195         }
2196
2197         if (state == SKINNY_OFFHOOK || state == SKINNY_ONHOOK) {
2198                 if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2199                         return;
2200
2201                 req->data.activatecallplane.lineInstance = htolel(instance);
2202                 transmit_response(d, req);
2203         }
2204 }
2205
2206
2207 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
2208 {
2209         struct skinny_req *req;
2210         int anyon = 0;
2211
2212         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
2213                 return;
2214
2215         if (l->cfwdtype & SKINNY_CFWD_ALL) {
2216                 if (!ast_strlen_zero(l->call_forward_all)) {
2217                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
2218                         req->data.forwardstat.fwdall = htolel(1);
2219                         anyon++;
2220                 } else {
2221                         req->data.forwardstat.fwdall = htolel(0);
2222                 }
2223         }
2224         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
2225                 if (!ast_strlen_zero(l->call_forward_busy)) {
2226                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
2227                         req->data.forwardstat.fwdbusy = htolel(1);
2228                         anyon++;
2229                 } else {
2230                         req->data.forwardstat.fwdbusy = htolel(0);
2231                 }
2232         }
2233         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
2234                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
2235                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
2236                         req->data.forwardstat.fwdnoanswer = htolel(1);
2237                         anyon++;
2238                 } else {
2239                         req->data.forwardstat.fwdnoanswer = htolel(0);
2240                 }
2241         }
2242         req->data.forwardstat.lineNumber = htolel(l->instance);
2243         if (anyon)
2244                 req->data.forwardstat.activeforward = htolel(7);
2245         else
2246                 req->data.forwardstat.activeforward = htolel(0);
2247
2248         transmit_response(d, req);
2249 }
2250
2251 static int skinny_extensionstate_cb(char *context, char *exten, int state, void *data)
2252 {
2253         struct skinny_speeddial *sd = data;
2254         struct skinny_device *d = sd->parent;
2255         char hint[AST_MAX_EXTENSION];
2256         int callstate = SKINNY_CALLREMOTEMULTILINE;
2257         int lamp = SKINNY_LAMP_OFF;
2258
2259         switch (state) {
2260         case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
2261         case AST_EXTENSION_REMOVED:     /* Extension is gone */
2262                 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify Device %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
2263                 sd->stateid = -1;
2264                 callstate = SKINNY_ONHOOK;
2265                 lamp = SKINNY_LAMP_OFF;
2266                 break;
2267         case AST_EXTENSION_RINGING:
2268         case AST_EXTENSION_UNAVAILABLE:
2269                 callstate = SKINNY_RINGIN;
2270                 lamp = SKINNY_LAMP_BLINK;
2271                 break;
2272         case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
2273         case AST_EXTENSION_INUSE:
2274                 callstate = SKINNY_CALLREMOTEMULTILINE;
2275                 lamp = SKINNY_LAMP_ON;
2276                 break;
2277         case AST_EXTENSION_ONHOLD:
2278                 callstate = SKINNY_HOLD;
2279                 lamp = SKINNY_LAMP_WINK;
2280                 break;
2281         case AST_EXTENSION_NOT_INUSE:
2282         default:
2283                 callstate = SKINNY_ONHOOK;
2284                 lamp = SKINNY_LAMP_OFF;
2285                 break;
2286         }
2287
2288         if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
2289                 /* If they are not registered, we will override notification and show no availability */
2290                 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
2291                         callstate = SKINNY_ONHOOK;
2292                         lamp = SKINNY_LAMP_FLASH;
2293                 }
2294         }
2295
2296         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, lamp);
2297         transmit_callstate(d, sd->instance, callstate, 0);
2298         sd->laststate = state;
2299
2300         return 0;
2301 }
2302
2303 static void mwi_event_cb(const struct ast_event *event, void *userdata)
2304 {
2305         /* This module does not handle MWI in an event-based manner.  However, it
2306          * subscribes to MWI for each mailbox that is configured so that the core
2307          * knows that we care about it.  Then, chan_skinny will get the MWI from the
2308          * event cache instead of checking the mailbox directly. */
2309 }
2310
2311 static int has_voicemail(struct skinny_line *l)
2312 {
2313         int new_msgs;
2314         struct ast_event *event;
2315         char *mbox, *context;
2316
2317         context = mbox = ast_strdupa(l->mailbox);
2318         strsep(&context, "@");
2319         if (ast_strlen_zero(context))
2320                 context = "default";
2321
2322         event = ast_event_get_cached(AST_EVENT_MWI,
2323                 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mbox,
2324                 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
2325                 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
2326                 AST_EVENT_IE_END);
2327
2328         if (event) {
2329                 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
2330                 ast_event_destroy(event);
2331         } else
2332                 new_msgs = ast_app_has_voicemail(l->mailbox, NULL);
2333
2334         return new_msgs;
2335 }
2336
2337 static void do_housekeeping(struct skinnysession *s)
2338 {
2339         int device_lamp = 0;
2340         struct skinny_device *d = s->device;
2341         struct skinny_line *l;
2342
2343         /* Update time on device */
2344         handle_time_date_req_message(NULL, s);
2345
2346         /* Set MWI on individual lines */
2347         AST_LIST_TRAVERSE(&d->lines, l, list) {
2348                 if (has_voicemail(l)) {
2349                         if (skinnydebug)
2350                                 ast_verb(1, "Checking for voicemail Skinny %s@%s\n", l->name, d->name);
2351                         if (skinnydebug)
2352                                 ast_verb(1, "Skinny %s@%s has voicemail!\n", l->name, d->name);
2353                         transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2354                         device_lamp++;
2355                 } else {
2356                         transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
2357                 }
2358         }
2359         /* If at least one line has VM, turn the device level lamp on */
2360         if (device_lamp)
2361                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_ON);
2362         else
2363                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
2364 }
2365
2366 /* I do not believe skinny can deal with video.
2367    Anyone know differently? */
2368 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
2369 static enum ast_rtp_get_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
2370 {
2371         struct skinny_subchannel *sub = NULL;
2372
2373         if (!(sub = c->tech_pvt) || !(sub->vrtp))
2374                 return AST_RTP_GET_FAILED;
2375
2376         *rtp = sub->vrtp;
2377
2378         return AST_RTP_TRY_NATIVE;
2379 }
2380
2381 static enum ast_rtp_get_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
2382 {
2383         struct skinny_subchannel *sub = NULL;
2384         struct skinny_line *l;
2385         enum ast_rtp_get_result res = AST_RTP_TRY_NATIVE;
2386
2387         if (skinnydebug)
2388                 ast_verb(1, "skinny_get_rtp_peer() Channel = %s\n", c->name);
2389
2390
2391         if (!(sub = c->tech_pvt))
2392                 return AST_RTP_GET_FAILED;
2393
2394         ast_mutex_lock(&sub->lock);
2395
2396         if (!(sub->rtp)){
2397                 ast_mutex_unlock(&sub->lock);
2398                 return AST_RTP_GET_FAILED;
2399         }
2400         
2401         *rtp = sub->rtp;
2402
2403         l = sub->parent;
2404
2405         if (!l->canreinvite || l->nat){
2406                 res = AST_RTP_TRY_PARTIAL;
2407                 if (skinnydebug)
2408                         ast_verb(1, "skinny_get_rtp_peer() Using AST_RTP_TRY_PARTIAL \n");
2409         }
2410
2411         ast_mutex_unlock(&sub->lock);
2412
2413         return res;
2414
2415 }
2416
2417 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)
2418 {
2419         struct skinny_subchannel *sub;
2420         struct skinny_line *l;
2421         struct skinny_device *d;
2422         struct skinnysession *s;
2423         struct ast_format_list fmt;
2424         struct sockaddr_in us;
2425         struct sockaddr_in them;
2426         struct skinny_req *req;
2427         
2428         sub = c->tech_pvt;
2429
2430         if (c->_state != AST_STATE_UP)
2431                 return 0;
2432
2433         if (!sub) {
2434                 return -1;
2435         }
2436
2437         l = sub->parent;
2438         d = l->parent;
2439         s = d->session;
2440
2441         if (rtp){
2442                 ast_rtp_get_peer(rtp, &them);
2443
2444                 /* Shutdown any early-media or previous media on re-invite */
2445                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2446                         return -1;
2447
2448                 req->data.stopmedia.conferenceId = htolel(sub->callid);
2449                 req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2450                 transmit_response(d, req);
2451
2452                 if (skinnydebug)
2453                         ast_verb(1, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
2454
2455                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message), START_MEDIA_TRANSMISSION_MESSAGE)))
2456                         return -1;
2457
2458                 fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
2459
2460                 if (skinnydebug)
2461                         ast_verb(1, "Setting payloadType to '%d' (%d ms)\n", fmt.bits, fmt.cur_ms);
2462
2463                 req->data.startmedia.conferenceId = htolel(sub->callid);
2464                 req->data.startmedia.passThruPartyId = htolel(sub->callid);
2465                 if (!(l->canreinvite) || (l->nat)){
2466                         ast_rtp_get_us(rtp, &us);
2467                         req->data.startmedia.remoteIp = htolel(d->ourip.s_addr);
2468                         req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
2469                 } else {
2470                         req->data.startmedia.remoteIp = htolel(them.sin_addr.s_addr);
2471                         req->data.startmedia.remotePort = htolel(ntohs(them.sin_port));
2472                 }
2473                 req->data.startmedia.packetSize = htolel(fmt.cur_ms);
2474                 req->data.startmedia.payloadType = htolel(codec_ast2skinny(fmt.bits));
2475                 req->data.startmedia.qualifier.precedence = htolel(127);
2476                 req->data.startmedia.qualifier.vad = htolel(0);
2477                 req->data.startmedia.qualifier.packets = htolel(0);
2478                 req->data.startmedia.qualifier.bitRate = htolel(0);
2479                 transmit_response(d, req);
2480
2481                 return 0;
2482         }
2483         /* Need a return here to break the bridge */
2484         return 0;
2485 }
2486
2487 static struct ast_rtp_protocol skinny_rtp = {
2488         .type = "Skinny",
2489         .get_rtp_info = skinny_get_rtp_peer,
2490         .get_vrtp_info = skinny_get_vrtp_peer,
2491         .set_rtp_peer = skinny_set_rtp_peer,
2492 };
2493
2494 static char *handle_skinny_set_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2495 {
2496         switch (cmd) {
2497         case CLI_INIT:
2498                 e->command = "skinny set debug [off]";
2499                 e->usage =
2500                         "Usage: skinny set debug [off]\n"
2501                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2502                 return NULL;
2503         case CLI_GENERATE:
2504                 return NULL;
2505         }
2506         
2507         if (a->argc < 3 || a->argc > 4)
2508                 return CLI_SHOWUSAGE;
2509
2510         if (a->argc == 3) {
2511                 skinnydebug = 1;
2512                 ast_cli(a->fd, "Skinny Debugging Enabled\n");
2513                 return CLI_SUCCESS;
2514         } else if (!strncasecmp(a->argv[3], "off", 3)) {
2515                 skinnydebug = 0;
2516                 ast_cli(a->fd, "Skinny Debugging Disabled\n");
2517                 return CLI_SUCCESS;
2518         } else {
2519                 return CLI_SHOWUSAGE;
2520         }
2521 }
2522
2523 static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2524 {
2525         switch (cmd) {
2526         case CLI_INIT:
2527                 e->command = "skinny set debug {on|off}";
2528                 e->usage =
2529                         "Usage: skinny set debug {on|off}\n"
2530                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2531                 return NULL;
2532         case CLI_GENERATE:
2533                 return NULL;
2534         }
2535         
2536         if (a->argc != e->args)
2537                 return CLI_SHOWUSAGE;
2538
2539         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
2540                 skinnydebug = 1;
2541                 ast_cli(a->fd, "Skinny Debugging Enabled\n");
2542                 return CLI_SUCCESS;
2543         } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
2544                 skinnydebug = 0;
2545                 ast_cli(a->fd, "Skinny Debugging Disabled\n");
2546                 return CLI_SUCCESS;
2547         } else {
2548                 return CLI_SHOWUSAGE;
2549         }
2550 }
2551
2552 static char *complete_skinny_devices(const char *word, int state)
2553 {
2554         struct skinny_device *d;
2555         char *result = NULL;
2556         int wordlen = strlen(word), which = 0;
2557
2558         AST_LIST_TRAVERSE(&devices, d, list) {
2559                 if (!strncasecmp(word, d->id, wordlen) && ++which > state)
2560                         result = ast_strdup(d->id);
2561         }
2562
2563         return result;
2564 }
2565
2566 static char *complete_skinny_show_device(const char *line, const char *word, int pos, int state)
2567 {
2568         return (pos == 3 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2569 }
2570
2571 static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
2572 {
2573         return (pos == 2 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2574 }
2575
2576 static char *complete_skinny_show_line(const char *line, const char *word, int pos, int state)
2577 {
2578         struct skinny_device *d;
2579         struct skinny_line *l;
2580         char *result = NULL;
2581         int wordlen = strlen(word), which = 0;
2582
2583         if (pos != 3)
2584                 return NULL;
2585         
2586         AST_LIST_TRAVERSE(&devices, d, list) {
2587                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2588                         if (!strncasecmp(word, l->name, wordlen) && ++which > state)
2589                                 result = ast_strdup(l->name);
2590                 }
2591         }
2592
2593         return result;
2594 }
2595
2596 static char *handle_skinny_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2597 {
2598         struct skinny_device *d;
2599         struct skinny_req *req;
2600
2601         switch (cmd) {
2602         case CLI_INIT:
2603                 e->command = "skinny reset";
2604                 e->usage =
2605                         "Usage: skinny reset <DeviceId|DeviceName|all> [restart]\n"
2606                         "       Causes a Skinny device to reset itself, optionally with a full restart\n";
2607                 return NULL;
2608         case CLI_GENERATE:
2609                 return complete_skinny_reset(a->line, a->word, a->pos, a->n);
2610         }
2611
2612         if (a->argc < 3 || a->argc > 4)
2613                 return CLI_SHOWUSAGE;
2614
2615         AST_LIST_LOCK(&devices);
2616         AST_LIST_TRAVERSE(&devices, d, list) {
2617                 int fullrestart = 0;
2618                 if (!strcasecmp(a->argv[2], d->id) || !strcasecmp(a->argv[2], d->name) || !strcasecmp(a->argv[2], "all")) {
2619                         if (!(d->session))
2620                                 continue;
2621
2622                         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
2623                                 continue;
2624
2625                         if (a->argc == 4 && !strcasecmp(a->argv[3], "restart"))
2626                                 fullrestart = 1;
2627
2628                         if (fullrestart)
2629                                 req->data.reset.resetType = 2;
2630                         else
2631                                 req->data.reset.resetType = 1;
2632
2633                         ast_verb(3, "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
2634                         transmit_response(d, req);
2635                 }
2636         }
2637         AST_LIST_UNLOCK(&devices);
2638         return CLI_SUCCESS;
2639 }
2640
2641 static char *device2str(int type)
2642 {
2643         char *tmp;
2644
2645         switch (type) {
2646         case SKINNY_DEVICE_NONE:
2647                 return "No Device";
2648         case SKINNY_DEVICE_30SPPLUS:
2649                 return "30SP Plus";
2650         case SKINNY_DEVICE_12SPPLUS:
2651                 return "12SP Plus";
2652         case SKINNY_DEVICE_12SP:
2653                 return "12SP";
2654         case SKINNY_DEVICE_12:
2655                 return "12";
2656         case SKINNY_DEVICE_30VIP:
2657                 return "30VIP";
2658         case SKINNY_DEVICE_7910:
2659                 return "7910";
2660         case SKINNY_DEVICE_7960:
2661                 return "7960";
2662         case SKINNY_DEVICE_7940:
2663                 return "7940";
2664         case SKINNY_DEVICE_7935:
2665                 return "7935";
2666         case SKINNY_DEVICE_ATA186:
2667                 return "ATA186";
2668         case SKINNY_DEVICE_7941:
2669                 return "7941";
2670         case SKINNY_DEVICE_7971:
2671                 return "7971";
2672         case SKINNY_DEVICE_7914:
2673                 return "7914";
2674         case SKINNY_DEVICE_7985:
2675                 return "7985";
2676         case SKINNY_DEVICE_7911:
2677                 return "7911";
2678         case SKINNY_DEVICE_7961GE:
2679                 return "7961GE";
2680         case SKINNY_DEVICE_7941GE:
2681                 return "7941GE";
2682         case SKINNY_DEVICE_7931:
2683                 return "7931";
2684         case SKINNY_DEVICE_7921:
2685                 return "7921";
2686         case SKINNY_DEVICE_7906:
2687                 return "7906";
2688         case SKINNY_DEVICE_7962:
2689                 return "7962";
2690         case SKINNY_DEVICE_7937:
2691                 return "7937";
2692         case SKINNY_DEVICE_7942:
2693                 return "7942";
2694         case SKINNY_DEVICE_7945:
2695                 return "7945";
2696         case SKINNY_DEVICE_7965:
2697                 return "7965";
2698         case SKINNY_DEVICE_7975:
2699                 return "7975";
2700         case SKINNY_DEVICE_7905:
2701                 return "7905";
2702         case SKINNY_DEVICE_7920:
2703                 return "7920";
2704         case SKINNY_DEVICE_7970:
2705                 return "7970";
2706         case SKINNY_DEVICE_7912:
2707                 return "7912";
2708         case SKINNY_DEVICE_7902:
2709                 return "7902";
2710         case SKINNY_DEVICE_CIPC:
2711                 return "IP Communicator";
2712         case SKINNY_DEVICE_7961:
2713                 return "7961";
2714         case SKINNY_DEVICE_7936:
2715                 return "7936";
2716         case SKINNY_DEVICE_SCCPGATEWAY_AN:
2717                 return "SCCPGATEWAY_AN";
2718         case SKINNY_DEVICE_SCCPGATEWAY_BRI:
2719                 return "SCCPGATEWAY_BRI";
2720         case SKINNY_DEVICE_UNKNOWN:
2721                 return "Unknown";
2722         default:
2723                 if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
2724                         return "Unknown";
2725                 snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
2726                 return tmp;
2727         }
2728 }
2729
2730 /*! \brief Print codec list from preference to CLI/manager */
2731 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
2732 {
2733         int x, codec;
2734
2735         for(x = 0; x < 32 ; x++) {
2736                 codec = ast_codec_pref_index(pref, x);
2737                 if (!codec)
2738                         break;
2739                 ast_cli(fd, "%s", ast_getformatname(codec));
2740                 ast_cli(fd, ":%d", pref->framing[x]);
2741                 if (x < 31 && ast_codec_pref_index(pref, x + 1))
2742                         ast_cli(fd, ",");
2743         }
2744         if (!x)
2745                 ast_cli(fd, "none");
2746 }
2747
2748 static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2749 {
2750         struct skinny_device *d;
2751         struct skinny_line *l;
2752
2753         switch (cmd) {
2754         case CLI_INIT:
2755                 e->command = "skinny show devices";
2756                 e->usage =
2757                         "Usage: skinny show devices\n"
2758                         "       Lists all devices known to the Skinny subsystem.\n";
2759                 return NULL;
2760         case CLI_GENERATE:
2761                 return NULL;
2762         }
2763
2764         if (a->argc != 3)
2765                 return CLI_SHOWUSAGE;
2766
2767         ast_cli(a->fd, "Name                 DeviceId         IP              Type            R NL\n");
2768         ast_cli(a->fd, "-------------------- ---------------- --------------- --------------- - --\n");
2769
2770         AST_LIST_LOCK(&devices); 
2771         AST_LIST_TRAVERSE(&devices, d, list) {
2772                 int numlines = 0;
2773                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2774                         numlines++;
2775                 }
2776                 
2777                 ast_cli(a->fd, "%-20s %-16s %-15s %-15s %c %2d\n",
2778                         d->name,
2779                         d->id,
2780                         d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
2781                         device2str(d->type),
2782                         d->registered?'Y':'N',
2783                         numlines);
2784         }
2785         AST_LIST_UNLOCK(&devices);
2786         return CLI_SUCCESS;
2787 }
2788
2789 /*! \brief Show device information */
2790 static char *handle_skinny_show_device(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2791 {
2792         struct skinny_device *d;
2793         struct skinny_line *l;
2794         struct skinny_speeddial *sd;
2795         struct skinny_addon *sa;
2796
2797         switch (cmd) {
2798         case CLI_INIT:
2799                 e->command = "skinny show device";
2800                 e->usage =
2801                         "Usage: skinny show device <DeviceId|DeviceName>\n"
2802                         "       Lists all deviceinformation of a specific device known to the Skinny subsystem.\n";
2803                 return NULL;
2804         case CLI_GENERATE:
2805                 return complete_skinny_show_device(a->line, a->word, a->pos, a->n);
2806         }
2807
2808         if (a->argc < 4)
2809                 return CLI_SHOWUSAGE;
2810
2811         AST_LIST_LOCK(&devices);
2812         AST_LIST_TRAVERSE(&devices, d, list) {
2813                 if (!strcasecmp(a->argv[3], d->id) || !strcasecmp(a->argv[3], d->name)) {
2814                         int numlines = 0, numaddons = 0, numspeeddials = 0;
2815
2816                         AST_LIST_TRAVERSE(&d->lines, l, list){
2817                                 numlines++;
2818                         }
2819
2820                         ast_cli(a->fd, "Name:        %s\n", d->name);
2821                         ast_cli(a->fd, "Id:          %s\n", d->id);
2822                         ast_cli(a->fd, "version:     %s\n", S_OR(d->version_id, "Unknown"));
2823                         ast_cli(a->fd, "Ip address:  %s\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
2824                         ast_cli(a->fd, "Port:        %d\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
2825                         ast_cli(a->fd, "Device Type: %s\n", device2str(d->type));
2826                         ast_cli(a->fd, "Registered:  %s\n", (d->registered ? "Yes" : "No"));
2827                         ast_cli(a->fd, "Lines:       %d\n", numlines);
2828                         AST_LIST_TRAVERSE(&d->lines, l, list) {
2829                                 ast_cli(a->fd, "  %s (%s)\n", l->name, l->label);
2830                         }
2831                         AST_LIST_TRAVERSE(&d->addons, sa, list) {
2832                                 numaddons++;
2833                         }       
2834                         ast_cli(a->fd, "Addons:      %d\n", numaddons);
2835                         AST_LIST_TRAVERSE(&d->addons, sa, list) {
2836                                 ast_cli(a->fd, "  %s\n", sa->type);
2837                         }
2838                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2839                                 numspeeddials++;
2840                         }
2841                         ast_cli(a->fd, "Speeddials:  %d\n", numspeeddials);
2842                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
2843                                 ast_cli(a->fd, "  %s (%s) ishint: %d\n", sd->exten, sd->label, sd->isHint);
2844                         }
2845                 }
2846         }
2847         AST_LIST_UNLOCK(&devices);
2848         return CLI_SUCCESS;
2849 }
2850
2851 static char *handle_skinny_show_lines(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2852 {
2853         struct skinny_device *d;
2854         struct skinny_line *l;
2855         struct skinny_subchannel *sub;
2856         int verbose = 0;
2857
2858         switch (cmd) {
2859         case CLI_INIT:
2860                 e->command = "skinny show lines [verbose]";
2861                 e->usage =
2862                         "Usage: skinny show lines\n"
2863                         "       Lists all lines known to the Skinny subsystem.\n"
2864                         "       If 'verbose' is specified, the output includes\n"
2865                         "       information about subs for each line.\n";
2866                 return NULL;
2867         case CLI_GENERATE:
2868                 return NULL;
2869         }
2870
2871
2872         if (a->argc == e->args) {
2873                 if (!strcasecmp(a->argv[e->args-1], "verbose")) {
2874                         verbose = 1;
2875                 } else {
2876                         return CLI_SHOWUSAGE;
2877                 }
2878         } else if (a->argc != e->args - 1) {
2879                 return CLI_SHOWUSAGE;
2880         }
2881         
2882         
2883         ast_cli(a->fd, "Device Name          Instance Name                 Label               \n");
2884         ast_cli(a->fd, "-------------------- -------- -------------------- --------------------\n");
2885         AST_LIST_LOCK(&devices);
2886         AST_LIST_TRAVERSE(&devices, d, list) {
2887                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2888                         ast_cli(a->fd, "%-20s %8d %-20s %-20s\n",
2889                                 d->name,
2890                                 l->instance,
2891                                 l->name,
2892                                 l->label);
2893                         if (verbose) {
2894                                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
2895                                         ast_cli(a->fd, "  %s> %s to %s\n",
2896                                                 (sub == l->activesub?"Active  ":"Inactive"),
2897                                                 sub->owner->name,
2898                                                 (ast_bridged_channel(sub->owner)?ast_bridged_channel(sub->owner)->name:"")
2899                                         );
2900                                 }
2901                         }
2902                 }
2903         }
2904         AST_LIST_UNLOCK(&devices);
2905         return CLI_SUCCESS;
2906 }
2907
2908 /*! \brief List line information. */
2909 static char *handle_skinny_show_line(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2910 {
2911         struct skinny_device *d;
2912         struct skinny_line *l;
2913         char codec_buf[512];
2914         char group_buf[256];
2915
2916         switch (cmd) {
2917         case CLI_INIT:
2918                 e->command = "skinny show line";
2919                 e->usage =
2920                         "Usage: skinny show line <Line> [ on <DeviceID|DeviceName> ]\n"
2921                         "       List all lineinformation of a specific line known to the Skinny subsystem.\n";
2922                 return NULL;
2923         case CLI_GENERATE:
2924                 return complete_skinny_show_line(a->line, a->word, a->pos, a->n);
2925         }
2926
2927         if (a->argc < 4)
2928                 return CLI_SHOWUSAGE;
2929         
2930         AST_LIST_LOCK(&devices);
2931
2932         /* Show all lines matching the one supplied */
2933         AST_LIST_TRAVERSE(&devices, d, list) {
2934                 if (a->argc == 6 && (strcasecmp(a->argv[5], d->id) && strcasecmp(a->argv[5], d->name)))
2935                         continue;
2936                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2937                         if (strcasecmp(a->argv[3], l->name))
2938                                 continue;
2939                         ast_cli(a->fd, "Line:             %s\n", l->name);
2940                         ast_cli(a->fd, "On Device:        %s\n", d->name);
2941                         ast_cli(a->fd, "Line Label:       %s\n", l->label);
2942                         ast_cli(a->fd, "Extension:        %s\n", S_OR(l->exten, "<not set>"));
2943                         ast_cli(a->fd, "Context:          %s\n", l->context);
2944                         ast_cli(a->fd, "CallGroup:        %s\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
2945                         ast_cli(a->fd, "PickupGroup:      %s\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
2946                         ast_cli(a->fd, "Language:         %s\n", S_OR(l->language, "<not set>"));
2947                         ast_cli(a->fd, "Accountcode:      %s\n", S_OR(l->accountcode, "<not set>"));
2948                         ast_cli(a->fd, "AmaFlag:          %s\n", ast_cdr_flags2str(l->amaflags));
2949                         ast_cli(a->fd, "CallerId Number:  %s\n", S_OR(l->cid_num, "<not set>"));
2950                         ast_cli(a->fd, "CallerId Name:    %s\n", S_OR(l->cid_name, "<not set>"));
2951                         ast_cli(a->fd, "Hide CallerId:    %s\n", (l->hidecallerid ? "Yes" : "No"));
2952                         ast_cli(a->fd, "CFwdAll:          %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
2953                         ast_cli(a->fd, "CFwdBusy:         %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
2954                         ast_cli(a->fd, "CFwdNoAnswer:     %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
2955                         ast_cli(a->fd, "VoicemailBox:     %s\n", S_OR(l->mailbox, "<not set>"));
2956                         ast_cli(a->fd, "VoicemailNumber:  %s\n", S_OR(l->vmexten, "<not set>"));
2957                         ast_cli(a->fd, "MWIblink:         %d\n", l->mwiblink);
2958                         ast_cli(a->fd, "Regextension:     %s\n", S_OR(l->regexten, "<not set>"));
2959                         ast_cli(a->fd, "Regcontext:       %s\n", S_OR(l->regcontext, "<not set>"));
2960                         ast_cli(a->fd, "MoHInterpret:     %s\n", S_OR(l->mohinterpret, "<not set>"));
2961                         ast_cli(a->fd, "MoHSuggest:       %s\n", S_OR(l->mohsuggest, "<not set>"));
2962                         ast_cli(a->fd, "Last dialed nr:   %s\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
2963                         ast_cli(a->fd, "Last CallerID:    %s\n", S_OR(l->lastcallerid, "<not set>"));
2964                         ast_cli(a->fd, "Transfer enabled: %s\n", (l->transfer ? "Yes" : "No"));
2965                         ast_cli(a->fd, "Callwaiting:      %s\n", (l->callwaiting ? "Yes" : "No"));
2966                         ast_cli(a->fd, "3Way Calling:     %s\n", (l->threewaycalling ? "Yes" : "No"));
2967                         ast_cli(a->fd, "Can forward:      %s\n", (l->cancallforward ? "Yes" : "No"));
2968                         ast_cli(a->fd, "Do Not Disturb:   %s\n", (l->dnd ? "Yes" : "No"));
2969                         ast_cli(a->fd, "NAT:              %s\n", (l->nat ? "Yes" : "No"));
2970                         ast_cli(a->fd, "immediate:        %s\n", (l->immediate ? "Yes" : "No"));
2971                         ast_cli(a->fd, "Group:            %d\n", l->group);
2972                         ast_cli(a->fd, "Codecs:           ");
2973                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->capability);
2974                         ast_cli(a->fd, "%s\n", codec_buf);
2975                         ast_cli(a->fd, "Codec Order:      (");
2976                         print_codec_to_cli(a->fd, &l->prefs);
2977                         ast_cli(a->fd, ")\n");
2978                         ast_cli(a->fd, "\n");
2979                 }
2980         }
2981         
2982         AST_LIST_UNLOCK(&devices);
2983         return CLI_SUCCESS;
2984 }
2985
2986 /*! \brief List global settings for the Skinny subsystem. */
2987 static char *handle_skinny_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2988 {
2989         switch (cmd) {
2990         case CLI_INIT:
2991                 e->command = "skinny show settings";
2992                 e->usage =
2993                         "Usage: skinny show settings\n"
2994                         "       Lists all global configuration settings of the Skinny subsystem.\n";
2995                 return NULL;
2996         case CLI_GENERATE:
2997                 return NULL;
2998         }       
2999
3000         if (a->argc != 3)
3001                 return CLI_SHOWUSAGE;
3002
3003         ast_cli(a->fd, "\nGlobal Settings:\n");
3004         ast_cli(a->fd, "  Skinny Port:            %d\n", ntohs(bindaddr.sin_port));
3005         ast_cli(a->fd, "  Bindaddress:            %s\n", ast_inet_ntoa(bindaddr.sin_addr));
3006         ast_cli(a->fd, "  KeepAlive:              %d\n", keep_alive);
3007         ast_cli(a->fd, "  Date Format:            %s\n", date_format);
3008         ast_cli(a->fd, "  Voice Mail Extension:   %s\n", S_OR(vmexten, "(not set)"));
3009         ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(regcontext, "(not set)"));
3010         ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", (ast_test_flag(&global_jbconf, AST_JB_ENABLED) ? "Yes" : "No"));
3011         ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", (ast_test_flag(&global_jbconf, AST_JB_FORCED) ? "Yes" : "No"));
3012         ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
3013         ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
3014         ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
3015         ast_cli(a->fd, "  Jitterbuffer log:       %s\n", (ast_test_flag(&global_jbconf, AST_JB_LOG) ? "Yes" : "No"));
3016
3017         return CLI_SUCCESS;
3018 }
3019
3020 static struct ast_cli_entry cli_skinny_set_debug_deprecated = AST_CLI_DEFINE(handle_skinny_set_debug_deprecated, "Enable/Disable Skinny debugging");
3021 static struct ast_cli_entry cli_skinny[] = {
3022         AST_CLI_DEFINE(handle_skinny_show_devices, "List defined Skinny devices"),
3023         AST_CLI_DEFINE(handle_skinny_show_device, "List Skinny device information"),
3024         AST_CLI_DEFINE(handle_skinny_show_lines, "List defined Skinny lines per device"),
3025         AST_CLI_DEFINE(handle_skinny_show_line, "List Skinny line information"),
3026         AST_CLI_DEFINE(handle_skinny_show_settings, "List global Skinny settings"),
3027         AST_CLI_DEFINE(handle_skinny_set_debug, "Enable/Disable Skinny debugging", .deprecate_cmd = &cli_skinny_set_debug_deprecated),
3028         AST_CLI_DEFINE(handle_skinny_reset, "Reset Skinny device(s)"),
3029 };
3030
3031 static struct skinny_device *build_device(const char *cat, struct ast_variable *v)
3032 {
3033         struct skinny_device *d;
3034         struct skinny_line *l;
3035         struct skinny_speeddial *sd;
3036         struct skinny_addon *a;
3037         char device_vmexten[AST_MAX_EXTENSION];
3038         struct ast_variable *chanvars = NULL;
3039         int lineInstance = 1;
3040         int speeddialInstance = 1;
3041         int y = 0;
3042
3043         if (!(d = ast_calloc(1, sizeof(*d)))) {
3044                 return NULL;
3045         } else {
3046                 ast_copy_string(d->name, cat, sizeof(d->name));
3047                 d->lastlineinstance = 1;
3048                 d->capability = default_capability;
3049                 d->prefs = default_prefs;
3050                 if (!ast_strlen_zero(vmexten))
3051                         ast_copy_string(device_vmexten, vmexten, sizeof(device_vmexten));
3052                 else
3053                         memset(device_vmexten, 0, sizeof(device_vmexten));
3054
3055                 d->earlyrtp = 1;
3056                 while(v) {
3057                         if (!strcasecmp(v->name, "host")) {
3058                                 if (ast_get_ip(&d->addr, v->value)) {
3059                                         ast_free(d);
3060                                         return NULL;
3061                                 }
3062                         } else if (!strcasecmp(v->name, "port")) {
3063                                 d->addr.sin_port = htons(atoi(v->value));
3064                         } else if (!strcasecmp(v->name, "device")) {
3065                                 ast_copy_string(d->id, v->value, sizeof(d->id));
3066                         } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
3067                                 d->ha = ast_append_ha(v->name, v->value, d->ha, NULL);
3068                         } else if (!strcasecmp(v->name, "vmexten")) {
3069                                 ast_copy_string(device_vmexten, v->value, sizeof(device_vmexten));
3070                         } else if (!strcasecmp(v->name, "context")) {
3071                                 ast_copy_string(global_context, v->value, sizeof(global_context));
3072                         } else if (!strcasecmp(v->name, "regexten")) {
3073                                 ast_copy_string(regexten, v->value, sizeof(regexten));
3074                         } else if (!strcasecmp(v->name, "allow")) {
3075                                 ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 1);
3076                         } else if (!strcasecmp(v->name, "disallow")) {
3077                                 ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 0);
3078                         } else if (!strcasecmp(v->name, "version")) {
3079                                 ast_copy_string(d->version_id, v->value, sizeof(d->version_id));
3080                         } else if (!strcasecmp(v->name, "canreinvite")) {
3081                                 canreinvite = ast_true(v->value);
3082                         } else if (!strcasecmp(v->name, "earlyrtp")) {
3083                                 d->earlyrtp = ast_true(v->value);
3084                         } else if (!strcasecmp(v->name, "nat")) {
3085                                 nat = ast_true(v->value);
3086                         } else if (!strcasecmp(v->name, "callerid")) {
3087                                 if (!strcasecmp(v->value, "asreceived")) {
3088                                         cid_num[0] = '\0';
3089                                         cid_name[0] = '\0';
3090                                 } else {
3091                                         ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
3092                                 }
3093                         } else if (!strcasecmp(v->name, "language")) {
3094                                 ast_copy_string(language, v->value, sizeof(language));
3095                         } else if (!strcasecmp(v->name, "accountcode")) {
3096                                 ast_copy_string(accountcode, v->value, sizeof(accountcode));
3097                         } else if (!strcasecmp(v->name, "amaflags")) {
3098                                 y = ast_cdr_amaflags2int(v->value);
3099                                 if (y < 0) {
3100                                         ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
3101                                 } else {
3102                                         amaflags = y;
3103                                 }
3104                         } else if (!strcasecmp(v->name, "mohinterpret") || !strcasecmp(v->name, "musiconhold")) {
3105                                 ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
3106                         } else if (!strcasecmp(v->name, "mohsuggest")) {
3107                                 ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
3108                         } else if (!strcasecmp(v->name, "callgroup")) {
3109                                 cur_callergroup = ast_get_group(v->value);
3110                         } else if (!strcasecmp(v->name, "pickupgroup")) {
3111                                 cur_pickupgroup = ast_get_group(v->value);
3112                         } else if (!strcasecmp(v->name, "immediate")) {
3113                                 immediate = ast_true(v->value);
3114                         } else if (!strcasecmp(v->name, "cancallforward")) {
3115                                 cancallforward = ast_true(v->value);
3116                         } else if (!strcasecmp(v->name, "mailbox")) {
3117                                 ast_copy_string(mailbox, v->value, sizeof(mailbox));
3118                         } else if (!strcasecmp(v->name, "hasvoicemail")) {
3119                                 if (ast_true(v->value) && ast_strlen_zero(mailbox)) {
3120                                         ast_copy_string(mailbox, cat, sizeof(mailbox));
3121                                 }
3122                         } else if (!strcasecmp(v->name, "callreturn")) {
3123                                 callreturn = ast_true(v->value);
3124                         } else if (!strcasecmp(v->name, "callwaiting")) {
3125                                 callwaiting = ast_true(v->value);
3126                         } else if (!strcasecmp(v->name, "transfer")) {
3127                                 transfer = ast_true(v->value);
3128                         } else if (!strcasecmp(v->name, "threewaycalling")) {
3129                                 threewaycalling = ast_true(v->value);
3130                         } else if (!strcasecmp(v->name, "mwiblink")) {
3131                                 mwiblink = ast_true(v->value);
3132                         } else if (!strcasecmp(v->name, "linelabel")) {
3133                                 ast_copy_string(linelabel, v->value, sizeof(linelabel));
3134                         } else if (!strcasecmp(v->name, "setvar")) {
3135                                 chanvars = add_var(v->value, chanvars);
3136                         } else if ( !strcasecmp(v->name, "parkinglot")) {
3137                                 ast_copy_string(parkinglot, v->value, sizeof(parkinglot));
3138                         } else if (!strcasecmp(v->name, "speeddial")) {
3139                                 if (!(sd = ast_calloc(1, sizeof(*sd)))) {
3140                                         return NULL;
3141                                 } else {
3142                                         char buf[256];
3143                                         char *stringp = buf, *exten, *context, *label;
3144
3145                                         ast_copy_string(buf, v->value, sizeof(buf));
3146                                         exten = strsep(&stringp, ",");
3147                                         if ((context = strchr(exten, '@'))) {
3148                                                 *context++ = '\0';
3149                                         }
3150                                         label = stringp;
3151                                         ast_mutex_init(&sd->lock);
3152                                         ast_copy_string(sd->exten, exten, sizeof(sd->exten));
3153                                         if (!ast_strlen_zero(context)) {
3154                                                 sd->isHint = 1;
3155                                                 sd->instance = lineInstance++;
3156                                                 ast_copy_string(sd->context, context, sizeof(sd->context));
3157                                         } else {
3158                                                 sd->isHint = 0;
3159                                                 sd->instance = speeddialInstance++;
3160                                                 sd->context[0] = '\0';
3161                                         }
3162                                         ast_copy_string(sd->label, S_OR(label, exten), sizeof(sd->label));
3163
3164                                         sd->parent = d;
3165
3166                                         AST_LIST_INSERT_HEAD(&d->speeddials, sd, list);
3167                                 }
3168                         } else if (!strcasecmp(v->name, "addon")) {
3169                                 if (!(a = ast_calloc(1, sizeof(*a)))) {
3170                                         return NULL;
3171                                 } else {
3172                                         ast_mutex_init(&a->lock);
3173                                         ast_copy_string(a->type, v->value, sizeof(a->type));
3174
3175                                         AST_LIST_INSERT_HEAD(&d->addons, a, list);
3176                                 }
3177                         } else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
3178                                 if (!(l = ast_calloc(1, sizeof(*l)))) {
3179                                         return NULL;
3180                                 } else {
3181                                         ast_mutex_init(&l->lock);
3182                                         ast_copy_string(l->name, v->value, sizeof(l->name));
3183
3184                                         /* XXX Should we check for uniqueness?? XXX */
3185                                         ast_copy_string(l->context, global_context, sizeof(l->context));
3186                                         ast_copy_string(l->cid_num, cid_num, sizeof(l->cid_num));
3187                                         ast_copy_string(l->cid_name, cid_name, sizeof(l->cid_name));
3188                                         ast_copy_string(l->label, linelabel, sizeof(l->label));
3189                                         ast_copy_string(l->parkinglot, parkinglot, sizeof(l->parkinglot));
3190                                         ast_copy_string(l->language, language, sizeof(l->language));
3191                                         ast_copy_string(l->mohinterpret, mohinterpret, sizeof(l->mohinterpret));
3192                                         ast_copy_string(l->mohsuggest, mohsuggest, sizeof(l->mohsuggest));
3193                                         ast_copy_string(l->regexten, regexten, sizeof(l->regexten));
3194                                         ast_copy_string(l->mailbox, mailbox, sizeof(l->mailbox));
3195                                         if (!ast_strlen_zero(mailbox)) {
3196                                                 char *cfg_mailbox, *cfg_context;
3197                                                 cfg_context = cfg_mailbox = ast_strdupa(l->mailbox);
3198                                                 ast_verb(3, "Setting mailbox '%s' on %s@%s\n", cfg_mailbox, d->name, l->name);
3199                                                 strsep(&cfg_context, "@");
3200                                                 if (ast_strlen_zero(cfg_context))
3201                                                          cfg_context = "default";
3202                                                 l->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, NULL,
3203                                                         AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, cfg_mailbox,
3204                                                         AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, cfg_context,
3205                                                         AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
3206                                                         AST_EVENT_IE_END);
3207                                         }
3208                                         ast_copy_string(l->vmexten, device_vmexten, sizeof(vmexten));
3209                                         l->chanvars = chanvars;
3210                                         l->msgstate = -1;
3211                                         l->capability = d->capability;
3212                                         l->prefs = d->prefs;
3213                                         l->parent = d;
3214                                         if (!strcasecmp(v->name, "trunk")) {
3215                                                 l->type = TYPE_TRUNK;
3216                                         } else {
3217                                                 l->type = TYPE_LINE;
3218                                         }
3219                                         l->immediate = immediate;
3220                                         l->callgroup = cur_callergroup;
3221                                         l->pickupgroup = cur_pickupgroup;
3222                                         l->callreturn = callreturn;
3223                                         l->cancallforward = cancallforward;
3224                                         l->getforward = 0;
3225                                         set_callforwards(l, NULL, 0);
3226                                         l->callwaiting = callwaiting;
3227                                         l->transfer = transfer;
3228                                         l->threewaycalling = threewaycalling;
3229                                         l->mwiblink = mwiblink;
3230                                         l->onhooktime = time(NULL);
3231                                         l->instance = lineInstance++;
3232                                         /* ASSUME we're onhook at this point */
3233                                         l->hookstate = SKINNY_ONHOOK;
3234                                         l->nat = nat;
3235                                         l->canreinvite = canreinvite;
3236
3237                                         if (!AST_LIST_FIRST(&d->lines)) {
3238                                                 d->activeline = l;
3239                                         }
3240                                         AST_LIST_INSERT_HEAD(&d->lines, l, list);
3241                                 }
3242                         } else {
3243                                 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
3244                         }
3245                         v = v->next;
3246                 }
3247
3248                 if (!AST_LIST_FIRST(&d->lines)) {
3249                         ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
3250                         return NULL;
3251                 }
3252                 if (/*d->addr.sin_addr.s_addr && */!ntohs(d->addr.sin_port)) {
3253                         d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
3254                 }
3255         }
3256         return d;
3257 }
3258
3259 static void start_rtp(struct skinny_subchannel *sub)
3260 {
3261         struct skinny_line *l = sub->parent;
3262         struct skinny_device *d = l->parent;
3263         int hasvideo = 0;
3264
3265         ast_mutex_lock(&sub->lock);
3266         /* Allocate the RTP */
3267         sub->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3268         if (hasvideo)
3269                 sub->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3270         
3271         if (sub->rtp && sub->owner) {
3272                 ast_channel_set_fd(sub->owner, 0, ast_rtp_fd(sub->rtp));
3273                 ast_channel_set_fd(sub->owner, 1, ast_rtcp_fd(sub->rtp));
3274         }
3275         if (hasvideo && sub->vrtp && sub->owner) {
3276                 ast_channel_set_fd(sub->owner, 2, ast_rtp_fd(sub->vrtp));
3277                 ast_channel_set_fd(sub->owner, 3, ast_rtcp_fd(sub->vrtp));
3278         }
3279         if (sub->rtp) {
3280                 ast_rtp_setqos(sub->rtp, qos.tos_audio, qos.cos_audio, "Skinny RTP");
3281                 ast_rtp_setnat(sub->rtp, l->nat);
3282         }
3283         if (sub->vrtp) {
3284                 ast_rtp_setqos(sub->vrtp, qos.tos_video, qos.cos_video, "Skinny VRTP");
3285                 ast_rtp_setnat(sub->vrtp, l->nat);
3286         }
3287         /* Set Frame packetization */
3288         if (sub->rtp)
3289                 ast_rtp_codec_setpref(sub->rtp, &l->prefs);
3290
3291         /* Create the RTP connection */
3292         transmit_connect(d, sub);
3293         ast_mutex_unlock(&sub->lock);
3294 }
3295
3296 static void *skinny_newcall(void *data)
3297 {
3298         struct ast_channel *c = data;
3299         struct skinny_subchannel *sub = c->tech_pvt;
3300         struct skinny_line *l = sub->parent;
3301         struct skinny_device *d = l->parent;
3302         int res = 0;
3303
3304         ast_copy_string(l->lastnumberdialed, c->exten, sizeof(l->lastnumberdialed));
3305         ast_set_callerid(c,
3306                 l->hidecallerid ? "" : l->cid_num,
3307                 l->hidecallerid ? "" : l->cid_name,
3308                 c->cid.cid_ani ? NULL : l->cid_num);
3309         ast_setstate(c, AST_STATE_RING);
3310         if (!sub->rtp) {
3311                 start_rtp(sub);
3312         }
3313         res = ast_pbx_run(c);
3314         if (res) {
3315                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
3316                 transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
3317         }
3318         return NULL;
3319 }
3320
3321 static void *skinny_ss(void *data)
3322 {
3323         struct ast_channel *c = data;
3324         struct skinny_subchannel *sub = c->tech_pvt;
3325         struct skinny_line *l = sub->parent;
3326         struct skinny_device *d = l->parent;
3327         int len = 0;
3328         int timeout = firstdigittimeout;
3329         int res = 0;
3330         int loop_pause = 100;
3331
3332         ast_verb(3, "Starting simple switch on '%s@%s'\n", l->name, d->name);
3333
3334         len = strlen(d->exten);
3335
3336         while (len < AST_MAX_EXTENSION-1) {
3337                 res = 1;  /* Assume that we will get a digit */
3338                 while (strlen(d->exten) == len){
3339                         ast_safe_sleep(c, loop_pause);
3340                         timeout -= loop_pause;
3341                         if ( (timeout -= loop_pause) <= 0){
3342                                  res = 0;
3343                                  break;
3344                         }
3345                 res = 1;
3346                 }
3347
3348                 timeout = 0;
3349                 len = strlen(d->exten);
3350
3351                 if (!ast_ignore_pattern(c->context, d->exten)) {
3352                         transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
3353                 }
3354                 if (ast_exists_extension(c, c->context, d->exten, 1, l->cid_num)) {
3355                         if (!res || !ast_matchmore_extension(c, c->context, d->exten, 1, l->cid_num)) {
3356                                 if (l->getforward) {
3357                                         /* Record this as the forwarding extension */
3358                                         set_callforwards(l, d->exten, l->getforward);
3359                                         ast_verb(3, "Setting call forward (%d) to '%s' on channel %s\n",
3360                                                         l->cfwdtype, d->exten, c->name);
3361                                         transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
3362                                         transmit_lamp_indication(d, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
3363                                         transmit_displaynotify(d, "CFwd enabled", 10);
3364                                         transmit_cfwdstate(d, l);
3365                                         ast_safe_sleep(c, 500);
3366                                         ast_indicate(c, -1);
3367                                         ast_safe_sleep(c, 1000);
3368                                         memset(d->exten, 0, sizeof(d->exten));
3369                                         len = 0;
3370                                         l->getforward = 0;
3371                                         if (sub->owner && sub->owner->_state != AST_STATE_UP) {
3372                                                 ast_indicate(c, -1);
3373                                                 ast_hangup(c);
3374                                         }
3375                                         return NULL;
3376                                 } else {
3377                                         ast_copy_string(c->exten, d->exten, sizeof(c->exten));
3378                                         ast_copy_string(l->lastnumberdialed, d->exten, sizeof(l->lastnumberdialed));
3379                                         memset(d->exten, 0, sizeof(d->exten));
3380                                         skinny_newcall(c);
3381                                         return NULL;
3382                                 }
3383                         } else {
3384                                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
3385                                    so just set the timeout to matchdigittimeout and wait some more */
3386                                 timeout = matchdigittimeout;
3387                         }
3388                 } else if (res == 0) {
3389                         ast_debug(1, "Not enough digits (%s) (and no ambiguous match)...\n", d->exten);
3390                         memset(d->exten, 0, sizeof(d->exten));
3391                         transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
3392                         if (sub->owner && sub->owner->_state != AST_STATE_UP) {
3393                                 ast_indicate(c, -1);
3394                                 ast_hangup(c);
3395                         }
3396                         return NULL;
3397                 } else if (!ast_canmatch_extension(c, c->context, d->exten, 1, c->cid.cid_num) &&
3398                            ((d->exten[0] != '*') || (!ast_strlen_zero(d->exten) > 2))) {
3399                         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);
3400                         memset(d->exten, 0, sizeof(d->exten));
3401                         transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
3402                         /* hang out for 3 seconds to let congestion play */
3403                         ast_safe_sleep(c, 3000);
3404                         break;
3405                 }
3406                 if (!timeout) {
3407                         timeout = gendigittimeout;
3408                 }
3409                 if (len && !ast_ignore_pattern(c->context, d->exten)) {
3410                         ast_indicate(c, -1);
3411                 }
3412         }
3413         if (c)
3414                 ast_hangup(c);
3415         memset(d->exten, 0, sizeof(d->exten));
3416         return NULL;
3417 }
3418
3419
3420
3421 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
3422 {
3423         int res = 0;
3424         int tone = 0;
3425         struct skinny_subchannel *sub = ast->tech_pvt;
3426         struct skinny_line *l = sub->parent;
3427         struct skinny_device *d = l->parent;
3428
3429         if (!d->registered) {
3430                 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
3431                 return -1;
3432         }
3433
3434         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
3435                 ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
3436                 return -1;
3437         }
3438
3439         if (skinnydebug)
3440                 ast_verb(3, "skinny_call(%s)\n", ast->name);
3441
3442         if (l->dnd) {
3443                 ast_queue_control(ast, AST_CONTROL_BUSY);
3444                 return -1;
3445         }
3446
3447         if (AST_LIST_NEXT(sub,list) && !l->callwaiting) {
3448                 ast_queue_control(ast, AST_CONTROL_BUSY);
3449                 return -1;
3450         }
3451         
3452         switch (l->hookstate) {
3453         case SKINNY_OFFHOOK:
3454                 tone = SKINNY_CALLWAITTONE;
3455                 break;
3456         case SKINNY_ONHOOK:
3457                 tone = SKINNY_ALERT;
3458                 l->activesub = sub;
3459                 break;
3460         default:
3461                 ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
3462                 break;
3463         }
3464
3465         transmit_callstateonly(d, sub, SKINNY_RINGIN);
3466         transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGIN);
3467         transmit_displaypromptstatus(d, "Ring-In", 0, l->instance, sub->callid);
3468         transmit_callinfo(d, ast->cid.cid_name, ast->cid.cid_num, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
3469         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3470         transmit_ringer_mode(d, SKINNY_RING_INSIDE);
3471
3472         ast_setstate(ast, AST_STATE_RINGING);
3473         ast_queue_control(ast, AST_CONTROL_RINGING);
3474         sub->outgoing = 1;
3475         return res;
3476 }
3477
3478 static int skinny_hangup(struct ast_channel *ast)
3479 {
3480         struct skinny_subchannel *sub = ast->tech_pvt;
3481         struct skinny_line *l;
3482         struct skinny_device *d;
3483         struct skinnysession *s;
3484
3485         if (!sub) {
3486                 ast_debug(1, "Asked to hangup channel not connected\n");
3487                 return 0;
3488         }
3489
3490         l = sub->parent;
3491         d = l->parent;
3492         s = d->session;
3493
3494         if (skinnydebug)
3495                 ast_verb(3,"Hanging up %s/%d\n",d->name,sub->callid);
3496
3497         AST_LIST_REMOVE(&l->sub, sub, list);
3498
3499         if (d->registered) {
3500                 /* Ignoring l->type, doesn't seem relevant and previous code 
3501                    assigned rather than tested, ie always true */
3502                 if (!AST_LIST_EMPTY(&l->sub)) {
3503                         if (sub->related) {
3504                                 sub->related->related = NULL;
3505
3506                         }
3507                         if (sub == l->activesub) {      /* we are killing the active sub, but there are other subs on the line*/
3508                                 ast_verb(4,"Killing active sub %d\n", sub->callid);
3509                                 if (sub->related) {
3510                                         l->activesub = sub->related;
3511                                 } else {
3512                                         if (AST_LIST_NEXT(sub, list)) {
3513                                                 l->activesub = AST_LIST_NEXT(sub, list);
3514                                         } else {
3515                                                 l->activesub = AST_LIST_FIRST(&l->sub);
3516                                         }
3517                                 }
3518                                 //transmit_callstate(d, l->instance, SKINNY_ONHOOK, sub->callid);
3519                                 transmit_activatecallplane(d, l);
3520                                 transmit_closereceivechannel(d, sub);
3521                                 transmit_stopmediatransmission(d, sub);
3522                                 transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3523                         } else {    /* we are killing a background sub on the line with other subs*/
3524                                 ast_verb(4,"Killing inactive sub %d\n", sub->callid);
3525                                 if (AST_LIST_NEXT(sub, list)) {
3526                                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3527                                 } else {
3528                                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3529                                 }
3530                         }
3531                 } else {                                                /* no more subs on line so make idle */
3532                         ast_verb(4,"Killing only sub %d\n", sub->callid);
3533                         l->hookstate = SKINNY_ONHOOK;
3534                         transmit_callstate(d, l->instance, SKINNY_ONHOOK, sub->callid);
3535                         l->activesub = NULL;
3536                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
3537                         if (sub->parent == d->activeline) {
3538                                 transmit_activatecallplane(d, l);
3539                                 transmit_closereceivechannel(d, sub);
3540                                 transmit_stopmediatransmission(d, sub);
3541                                 transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
3542                                 transmit_ringer_mode(d, SKINNY_RING_OFF);
3543                                 /* we should check to see if we can start the ringer if another line is ringing */
3544                         }
3545                 }
3546         }
3547         ast_mutex_lock(&sub->lock);
3548         sub->owner = NULL;
3549         ast->tech_pvt = NULL;
3550         sub->alreadygone = 0;
3551         sub->outgoing = 0;
3552         if (sub->rtp) {
3553                 ast_rtp_destroy(sub->rtp);
3554                 sub->rtp = NULL;
3555         }
3556         ast_mutex_unlock(&sub->lock);
3557         ast_free(sub);
3558         ast_module_unref(ast_module_info->self);
3559         return 0;
3560 }
3561
3562 static int skinny_answer(struct ast_channel *ast)
3563 {
3564         int res = 0;
3565         struct skinny_subchannel *sub = ast->tech_pvt;
3566         struct skinny_line *l = sub->parent;
3567         struct skinny_device *d = l->parent;
3568
3569         if (sub->blindxfer) {
3570                 if (skinnydebug)
3571                         ast_debug(1, "skinny_answer(%s) on %s@%s-%d with BlindXFER, transferring\n",
3572                                 ast->name, l->name, d->name, sub->callid);
3573                 ast_setstate(ast, AST_STATE_UP);
3574                 skinny_transfer(sub);
3575                 return 0;
3576         }
3577
3578         sub->cxmode = SKINNY_CX_SENDRECV;
3579         if (!sub->rtp) {
3580                 start_rtp(sub);
3581         }
3582         if (skinnydebug)
3583                 ast_verb(1, "skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, d->name, sub->callid);
3584         if (ast->_state != AST_STATE_UP) {
3585                 ast_setstate(ast, AST_STATE_UP);
3586         }
3587
3588         transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
3589         /* order matters here...
3590            for some reason, transmit_callinfo must be before transmit_callstate,
3591            or you won't get keypad messages in some situations. */
3592         transmit_callinfo(d, ast->cid.cid_name, ast->cid.cid_num, l->lastnumberdialed, l->lastnumberdialed, l->instance, sub->callid, 2);
3593         transmit_callstateonly(d, sub, SKINNY_CONNECTED);
3594         transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_CONNECTED);
3595         transmit_dialednumber(d, l->lastnumberdialed, l->instance, sub->callid);
3596         transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
3597         l->activesub = sub;
3598         return res;
3599 }
3600
3601 /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
3602 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
3603 {
3604         struct ast_channel *ast = sub->owner;
3605         struct ast_frame *f;
3606
3607         if (!sub->rtp) {
3608                 /* We have no RTP allocated for this channel */
3609                 return &ast_null_frame;
3610         }
3611
3612         switch(ast->fdno) {
3613         case 0:
3614                 f = ast_rtp_read(sub->rtp); /* RTP Audio */
3615                 break;
3616         case 1:
3617                 f = ast_rtcp_read(sub->rtp); /* RTCP Control Channel */
3618                 break;
3619         case 2:
3620                 f = ast_rtp_read(sub->vrtp); /* RTP Video */
3621                 break;
3622         case 3:
3623                 f = ast_rtcp_read(sub->vrtp); /* RTCP Control Channel for video */
3624                 break;
3625 #if 0
3626         case 5:
3627                 /* Not yet supported */
3628                 f = ast_udptl_read(sub->udptl); /* UDPTL for T.38 */
3629                 break;
3630 #endif
3631         default:
3632                 f = &ast_null_frame;
3633         }
3634
3635         if (ast) {
3636                 /* We already hold the channel lock */
3637                 if (f->frametype == AST_FRAME_VOICE) {
3638                         if (f->subclass != ast->nativeformats) {
3639                                 ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
3640                                 ast->nativeformats = f->subclass;
3641                                 ast_set_read_format(ast, ast->readformat);
3642                                 ast_set_write_format(ast, ast->writeformat);
3643                         }
3644                 }
3645         }
3646         return f;
3647 }
3648
3649 static struct ast_frame *skinny_read(struct ast_channel *ast)
3650 {
3651         struct ast_frame *fr;
3652         struct skinny_subchannel *sub = ast->tech_pvt;
3653         ast_mutex_lock(&sub->lock);
3654         fr = skinny_rtp_read(sub);
3655         ast_mutex_unlock(&sub->lock);
3656         return fr;
3657 }
3658
3659 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
3660 {
3661         struct skinny_subchannel *sub = ast->tech_pvt;
3662         int res = 0;
3663         if (frame->frametype != AST_FRAME_VOICE) {
3664                 if (frame->frametype == AST_FRAME_IMAGE) {
3665                         return 0;
3666                 } else {
3667                         ast_log(LOG_WARNING, "Can't send %d type frames with skinny_write\n", frame->frametype);
3668                         return 0;
3669                 }
3670         } else {
3671                 if (!(frame->subclass & ast->nativeformats)) {
3672                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
3673                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
3674                         return -1;
3675                 }
3676         }
3677         if (sub) {