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