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