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