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