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