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