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