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