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