dont segfault when a MWI event occurs on a line without a registered device
[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         int newmsgs;
1196 };
1197
1198 struct skinny_line_options{
1199         SKINNY_LINE_OPTIONS
1200 } default_line_struct = {
1201         .callwaiting = 1,
1202         .transfer = 1,
1203         .mwiblink = 0,
1204         .dnd = 0,
1205         .hidecallerid = 0,
1206         .amaflags = 0,
1207         .instance = 0,
1208         .canreinvite = 0,
1209         .nat = 0,
1210         .confcapability = AST_FORMAT_ULAW | AST_FORMAT_ALAW,
1211         .capability = 0,
1212         .getforward = 0,
1213         .needdestroy = 0,
1214         .hookstate = SKINNY_ONHOOK,
1215 };
1216 struct skinny_line_options *default_line = &default_line_struct;
1217
1218 static AST_LIST_HEAD_STATIC(lines, skinny_line);
1219
1220 struct skinny_speeddial {
1221         ast_mutex_t lock;
1222         char label[42];
1223         char context[AST_MAX_CONTEXT];
1224         char exten[AST_MAX_EXTENSION];
1225         int instance;
1226         int stateid;
1227         int laststate;
1228         int isHint;
1229
1230         AST_LIST_ENTRY(skinny_speeddial) list;
1231         struct skinny_device *parent;
1232 };
1233
1234 struct skinny_addon {
1235         ast_mutex_t lock;
1236         char type[10];
1237         AST_LIST_ENTRY(skinny_addon) list;
1238         struct skinny_device *parent;
1239 };
1240
1241 #define SKINNY_DEVICE_OPTIONS                                   \
1242         char name[80];                                          \
1243         char id[16];                                            \
1244         char version_id[16];                                    \
1245         char exten[AST_MAX_EXTENSION];                          \
1246         char vmexten[AST_MAX_EXTENSION];                        \
1247         int type;                                               \
1248         int registered;                                         \
1249         int lastlineinstance;                                   \
1250         int lastcallreference;                                  \
1251         int confcapability;                                     \
1252         struct ast_codec_pref confprefs;                        \
1253         int capability;                                         \
1254         int earlyrtp;                                           \
1255         int transfer;                                           \
1256         int callwaiting;                                        \
1257         int mwiblink;                                           \
1258         int dnd;
1259
1260 struct skinny_device {
1261         SKINNY_DEVICE_OPTIONS
1262         struct type *first;
1263         struct type *last;
1264         ast_mutex_t lock;
1265         struct sockaddr_in addr;
1266         struct in_addr ourip;
1267         struct ast_ha *ha;
1268         struct skinnysession *session;
1269         struct skinny_line *activeline;
1270         AST_LIST_HEAD(, skinny_line) lines;
1271         AST_LIST_HEAD(, skinny_speeddial) speeddials;
1272         AST_LIST_HEAD(, skinny_addon) addons;
1273         AST_LIST_ENTRY(skinny_device) list;
1274 };
1275
1276 struct skinny_device_options{
1277         SKINNY_DEVICE_OPTIONS
1278 } default_device_struct = {
1279         .transfer = 1,
1280         .earlyrtp = 1,
1281         .callwaiting = 1,
1282         .mwiblink = 0,
1283         .dnd = 0,
1284         .confcapability = AST_FORMAT_ULAW | AST_FORMAT_ALAW,
1285         .capability = 0,
1286 };
1287 struct skinny_device_options *default_device = &default_device_struct;
1288         
1289 static AST_LIST_HEAD_STATIC(devices, skinny_device);
1290
1291 /*static struct ast_jb_conf default_jbconf =
1292 {
1293         .flags = 0,
1294         .max_size = -1,
1295         .resync_threshold = -1,
1296         .impl = ""
1297 };
1298 static struct ast_jb_conf global_jbconf;*/
1299
1300 struct skinnysession {
1301         pthread_t t;
1302         ast_mutex_t lock;
1303         struct sockaddr_in sin;
1304         int fd;
1305         char inbuf[SKINNY_MAX_PACKET];
1306         char outbuf[SKINNY_MAX_PACKET];
1307         struct skinny_device *device;
1308         AST_LIST_ENTRY(skinnysession) list;
1309 };
1310
1311 static AST_LIST_HEAD_STATIC(sessions, skinnysession);
1312
1313 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause);
1314 static int skinny_devicestate(void *data);
1315 static int skinny_call(struct ast_channel *ast, char *dest, int timeout);
1316 static int skinny_hangup(struct ast_channel *ast);
1317 static int skinny_answer(struct ast_channel *ast);
1318 static struct ast_frame *skinny_read(struct ast_channel *ast);
1319 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1320 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1321 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1322 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1323 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1324 static int handle_time_date_req_message(struct skinny_req *req, struct skinnysession *s);
1325 static void mwi_event_cb(const struct ast_event *event, void *userdata);
1326
1327 static const struct ast_channel_tech skinny_tech = {
1328         .type = "Skinny",
1329         .description = tdesc,
1330         .capabilities = AST_FORMAT_AUDIO_MASK,
1331         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1332         .requester = skinny_request,
1333         .devicestate = skinny_devicestate,
1334         .call = skinny_call,
1335         .hangup = skinny_hangup,
1336         .answer = skinny_answer,
1337         .read = skinny_read,
1338         .write = skinny_write,
1339         .indicate = skinny_indicate,
1340         .fixup = skinny_fixup,
1341         .send_digit_begin = skinny_senddigit_begin,
1342         .send_digit_end = skinny_senddigit_end,
1343         .bridge = ast_rtp_bridge,  
1344 };
1345
1346 static int skinny_extensionstate_cb(char *context, char* exten, int state, void *data);
1347 static int skinny_transfer(struct skinny_subchannel *sub);
1348
1349 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1350 {
1351         struct skinny_device *d = s->device;
1352         struct skinny_addon *a;
1353         int i;
1354
1355         switch (d->type) {
1356                 case SKINNY_DEVICE_30SPPLUS:
1357                 case SKINNY_DEVICE_30VIP:
1358                         /* 13 rows, 2 columns */
1359                         for (i = 0; i < 4; i++)
1360                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1361                         (btn++)->buttonDefinition = BT_REDIAL;
1362                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1363                         (btn++)->buttonDefinition = BT_CALLPARK;
1364                         (btn++)->buttonDefinition = BT_FORWARDALL;
1365                         (btn++)->buttonDefinition = BT_CONFERENCE;
1366                         for (i = 0; i < 4; i++)
1367                                 (btn++)->buttonDefinition = BT_NONE;
1368                         for (i = 0; i < 13; i++)
1369                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1370                         
1371                         break;
1372                 case SKINNY_DEVICE_12SPPLUS:
1373                 case SKINNY_DEVICE_12SP:
1374                 case SKINNY_DEVICE_12:
1375                         /* 6 rows, 2 columns */
1376                         for (i = 0; i < 2; i++)
1377                                 (btn++)->buttonDefinition = BT_CUST_LINE;
1378                         for (i = 0; i < 4; i++)
1379                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1380                         (btn++)->buttonDefinition = BT_HOLD;
1381                         (btn++)->buttonDefinition = BT_REDIAL;
1382                         (btn++)->buttonDefinition = BT_TRANSFER;
1383                         (btn++)->buttonDefinition = BT_FORWARDALL;
1384                         (btn++)->buttonDefinition = BT_CALLPARK;
1385                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1386                         break;
1387                 case SKINNY_DEVICE_7910:
1388                         (btn++)->buttonDefinition = BT_LINE;
1389                         (btn++)->buttonDefinition = BT_HOLD;
1390                         (btn++)->buttonDefinition = BT_TRANSFER;
1391                         (btn++)->buttonDefinition = BT_DISPLAY;
1392                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1393                         (btn++)->buttonDefinition = BT_CONFERENCE;
1394                         (btn++)->buttonDefinition = BT_FORWARDALL;
1395                         for (i = 0; i < 2; i++)
1396                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1397                         (btn++)->buttonDefinition = BT_REDIAL;
1398                         break;
1399                 case SKINNY_DEVICE_7960:
1400                 case SKINNY_DEVICE_7961:
1401                 case SKINNY_DEVICE_7961GE:
1402                 case SKINNY_DEVICE_7962:
1403                 case SKINNY_DEVICE_7965:
1404                         for (i = 0; i < 6; i++)
1405                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1406                         break;
1407                 case SKINNY_DEVICE_7940:
1408                 case SKINNY_DEVICE_7941:
1409                 case SKINNY_DEVICE_7941GE:
1410                 case SKINNY_DEVICE_7942:
1411                 case SKINNY_DEVICE_7945:
1412                         for (i = 0; i < 2; i++)
1413                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1414                         break;
1415                 case SKINNY_DEVICE_7935:
1416                 case SKINNY_DEVICE_7936:
1417                         for (i = 0; i < 2; i++)
1418                                 (btn++)->buttonDefinition = BT_LINE;
1419                         break;
1420                 case SKINNY_DEVICE_ATA186:
1421                         (btn++)->buttonDefinition = BT_LINE;
1422                         break;
1423                 case SKINNY_DEVICE_7970:
1424                 case SKINNY_DEVICE_7971:
1425                 case SKINNY_DEVICE_7975:
1426                 case SKINNY_DEVICE_CIPC:
1427                         for (i = 0; i < 8; i++)
1428                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1429                         break;
1430                 case SKINNY_DEVICE_7985:
1431                         /* XXX I have no idea what the buttons look like on these. */
1432                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1433                         break;
1434                 case SKINNY_DEVICE_7912:
1435                 case SKINNY_DEVICE_7911:
1436                 case SKINNY_DEVICE_7905:
1437                         (btn++)->buttonDefinition = BT_LINE;
1438                         (btn++)->buttonDefinition = BT_HOLD;
1439                         break;
1440                 case SKINNY_DEVICE_7920:
1441                         /* XXX I don't know if this is right. */
1442                         for (i = 0; i < 4; i++)
1443                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1444                         break;
1445                 case SKINNY_DEVICE_7921:
1446                         for (i = 0; i < 6; i++)
1447                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1448                         break;
1449                 case SKINNY_DEVICE_7902:
1450                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1451                         break;
1452                 case SKINNY_DEVICE_7906:
1453                         ast_log(LOG_WARNING, "Unsupported device type '%d (7906)' found.\n", d->type);
1454                         break;
1455                 case SKINNY_DEVICE_7931:
1456                         ast_log(LOG_WARNING, "Unsupported device type '%d (7931)' found.\n", d->type);
1457                         break;
1458                 case SKINNY_DEVICE_7937:
1459                         ast_log(LOG_WARNING, "Unsupported device type '%d (7937)' found.\n", d->type);
1460                         break;
1461                 case SKINNY_DEVICE_7914:
1462                         ast_log(LOG_WARNING, "Unsupported device type '%d (7914)' found.  Expansion module registered by itself?\n", d->type);
1463                         break;
1464                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1465                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1466                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1467                         break;
1468                 default:
1469                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1470                         break;
1471         }
1472
1473         AST_LIST_LOCK(&d->addons);
1474         AST_LIST_TRAVERSE(&d->addons, a, list) {
1475                 if (!strcasecmp(a->type, "7914")) {
1476                         for (i = 0; i < 14; i++)
1477                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1478                 } else {
1479                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1480                 }
1481         }
1482         AST_LIST_UNLOCK(&d->addons);
1483
1484         return btn;
1485 }
1486
1487 static struct skinny_req *req_alloc(size_t size, int response_message)
1488 {
1489         struct skinny_req *req;
1490
1491         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1492                 return NULL;
1493
1494         req->len = htolel(size+4);
1495         req->e = htolel(response_message);
1496
1497         return req;
1498 }
1499
1500 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1501 {
1502         struct skinny_line *l;
1503
1504         /*Dialing from on hook or on a 7920 uses instance 0 in requests
1505           but we need to start looking at instance 1 */
1506
1507         if (!instance)
1508                 instance = 1;
1509
1510         AST_LIST_TRAVERSE(&d->lines, l, list){
1511                 if (l->instance == instance)
1512                         break;
1513         }
1514
1515         if (!l) {
1516                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1517         }
1518         return l;
1519 }
1520
1521 static struct skinny_line *find_line_by_name(const char *dest)
1522 {
1523         struct skinny_line *l;
1524         struct skinny_line *tmpl = NULL;
1525         struct skinny_device *d;
1526         char line[256];
1527         char *at;
1528         char *device;
1529         int checkdevice = 0;
1530
1531         ast_copy_string(line, dest, sizeof(line));
1532         at = strchr(line, '@');
1533         if (at)
1534                 *at++ = '\0';
1535         device = at;
1536
1537         if (!ast_strlen_zero(device))
1538                 checkdevice = 1;
1539
1540         AST_LIST_LOCK(&devices);
1541         AST_LIST_TRAVERSE(&devices, d, list){
1542                 if (checkdevice && tmpl)
1543                         break;
1544                 else if (!checkdevice) {
1545                         /* This is a match, since we're checking for line on every device. */
1546                 } else if (!strcasecmp(d->name, device)) {
1547                         if (skinnydebug)
1548                                 ast_verb(2, "Found device: %s\n", d->name);
1549                 } else
1550                         continue;
1551
1552                 /* Found the device (or we don't care which device) */
1553                 AST_LIST_TRAVERSE(&d->lines, l, list){
1554                         /* Search for the right line */
1555                         if (!strcasecmp(l->name, line)) {
1556                                 if (tmpl) {
1557                                         ast_verb(2, "Ambiguous line name: %s\n", line);
1558                                         AST_LIST_UNLOCK(&devices);
1559                                         return NULL;
1560                                 } else
1561                                         tmpl = l;
1562                         }
1563                 }
1564         }
1565         AST_LIST_UNLOCK(&devices);
1566         return tmpl;
1567 }
1568
1569 /*!
1570  * implement the setvar config line
1571  */
1572 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
1573 {
1574         struct ast_variable *tmpvar = NULL;
1575         char *varname = ast_strdupa(buf), *varval = NULL;
1576
1577         if ((varval = strchr(varname,'='))) {
1578                 *varval++ = '\0';
1579                 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
1580                         tmpvar->next = list;
1581                         list = tmpvar;
1582                 }
1583         }
1584         return list;
1585 }
1586
1587 /* It's quicker/easier to find the subchannel when we know the instance number too */
1588 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
1589 {
1590         struct skinny_line *l = find_line_by_instance(d, instance);
1591         struct skinny_subchannel *sub;
1592
1593         if (!l) {
1594                 return NULL;
1595         }
1596
1597         /* 7920 phones set call reference to 0, so use the first
1598            sub-channel on the list.
1599            This MIGHT need more love to be right */
1600         if (!reference)
1601                 sub = AST_LIST_FIRST(&l->sub);
1602         else {
1603                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
1604                         if (sub->callid == reference)
1605                                 break;
1606                 }
1607         }
1608         if (!sub) {
1609                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
1610         }
1611         return sub;
1612 }
1613
1614 /* Find the subchannel when we only have the callid - this shouldn't happen often */
1615 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
1616 {
1617         struct skinny_line *l;
1618         struct skinny_subchannel *sub = NULL;
1619
1620         AST_LIST_TRAVERSE(&d->lines, l, list){
1621                 AST_LIST_TRAVERSE(&l->sub, sub, list){
1622                         if (sub->callid == reference)
1623                                 break;
1624                 }
1625                 if (sub)
1626                         break;
1627         }
1628
1629         if (!l) {
1630                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
1631         } else {
1632                 if (!sub) {
1633                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
1634                 }
1635         }
1636         return sub;
1637 }
1638
1639 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance, int isHint)
1640 {
1641         struct skinny_speeddial *sd;
1642
1643         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1644                 if (sd->isHint == isHint && sd->instance == instance)
1645                         break;
1646         }
1647
1648         if (!sd) {
1649                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
1650         }
1651         return sd;
1652 }
1653
1654 static int codec_skinny2ast(enum skinny_codecs skinnycodec)
1655 {
1656         switch (skinnycodec) {
1657         case SKINNY_CODEC_ALAW:
1658                 return AST_FORMAT_ALAW;
1659         case SKINNY_CODEC_ULAW:
1660                 return AST_FORMAT_ULAW;
1661         case SKINNY_CODEC_G723_1:
1662                 return AST_FORMAT_G723_1;
1663         case SKINNY_CODEC_G729A:
1664                 return AST_FORMAT_G729A;
1665         case SKINNY_CODEC_G726_32:
1666                 return AST_FORMAT_G726_AAL2; /* XXX Is this right? */
1667         case SKINNY_CODEC_H261:
1668                 return AST_FORMAT_H261;
1669         case SKINNY_CODEC_H263:
1670                 return AST_FORMAT_H263;
1671         default:
1672                 return 0;
1673         }
1674 }
1675
1676 static int codec_ast2skinny(int astcodec)
1677 {
1678         switch (astcodec) {
1679         case AST_FORMAT_ALAW:
1680                 return SKINNY_CODEC_ALAW;
1681         case AST_FORMAT_ULAW:
1682                 return SKINNY_CODEC_ULAW;
1683         case AST_FORMAT_G723_1:
1684                 return SKINNY_CODEC_G723_1;
1685         case AST_FORMAT_G729A:
1686                 return SKINNY_CODEC_G729A;
1687         case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
1688                 return SKINNY_CODEC_G726_32;
1689         case AST_FORMAT_H261:
1690                 return SKINNY_CODEC_H261;
1691         case AST_FORMAT_H263:
1692                 return SKINNY_CODEC_H263;
1693         default:
1694                 return 0;
1695         }
1696 }
1697
1698 static int set_callforwards(struct skinny_line *l, const char *cfwd, int cfwdtype)
1699 {
1700         if (!l)
1701                 return 0;
1702
1703         if (!ast_strlen_zero(cfwd)) {
1704                 if (cfwdtype & SKINNY_CFWD_ALL) {
1705                         l->cfwdtype |= SKINNY_CFWD_ALL;
1706                         ast_copy_string(l->call_forward_all, cfwd, sizeof(l->call_forward_all));
1707                 }
1708                 if (cfwdtype & SKINNY_CFWD_BUSY) {
1709                         l->cfwdtype |= SKINNY_CFWD_BUSY;
1710                         ast_copy_string(l->call_forward_busy, cfwd, sizeof(l->call_forward_busy));
1711                 }
1712                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
1713                         l->cfwdtype |= SKINNY_CFWD_NOANSWER;
1714                         ast_copy_string(l->call_forward_noanswer, cfwd, sizeof(l->call_forward_noanswer));
1715                 }
1716         } else {
1717                 if (cfwdtype & SKINNY_CFWD_ALL) {
1718                         l->cfwdtype &= ~SKINNY_CFWD_ALL;
1719                         memset(l->call_forward_all, 0, sizeof(l->call_forward_all));
1720                 }
1721                 if (cfwdtype & SKINNY_CFWD_BUSY) {
1722                         l->cfwdtype &= ~SKINNY_CFWD_BUSY;
1723                         memset(l->call_forward_busy, 0, sizeof(l->call_forward_busy));
1724                 }
1725                 if (cfwdtype & SKINNY_CFWD_NOANSWER) {
1726                         l->cfwdtype &= ~SKINNY_CFWD_NOANSWER;
1727                         memset(l->call_forward_noanswer, 0, sizeof(l->call_forward_noanswer));
1728                 }
1729         }
1730         return l->cfwdtype;
1731 }
1732
1733 static void cleanup_stale_contexts(char *new, char *old)
1734 {
1735         char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
1736
1737         while ((oldcontext = strsep(&old, "&"))) {
1738                 stalecontext = '\0';
1739                 ast_copy_string(newlist, new, sizeof(newlist));
1740                 stringp = newlist;
1741                 while ((newcontext = strsep(&stringp, "&"))) {
1742                         if (strcmp(newcontext, oldcontext) == 0) {
1743                                 /* This is not the context you're looking for */
1744                                 stalecontext = '\0';
1745                                 break;
1746                         } else if (strcmp(newcontext, oldcontext)) {
1747                                 stalecontext = oldcontext;
1748                         }
1749                         
1750                 }
1751                 if (stalecontext)
1752                         ast_context_destroy(ast_context_find(stalecontext), "Skinny");
1753         }
1754 }
1755
1756 static void register_exten(struct skinny_line *l)
1757 {
1758         char multi[256];
1759         char *stringp, *ext, *context;
1760
1761         if (ast_strlen_zero(regcontext))
1762                 return;
1763
1764         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1765         stringp = multi;
1766         while ((ext = strsep(&stringp, "&"))) {
1767                 if ((context = strchr(ext, '@'))) {
1768                         *context++ = '\0'; /* split ext@context */
1769                         if (!ast_context_find(context)) {
1770                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1771                                 continue;
1772                         }
1773                 } else {
1774                         context = regcontext;
1775                 }
1776                 ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
1777                          ast_strdup(l->name), ast_free_ptr, "Skinny");
1778         }
1779 }
1780
1781 static void unregister_exten(struct skinny_line *l)
1782 {
1783         char multi[256];
1784         char *stringp, *ext, *context;
1785
1786         if (ast_strlen_zero(regcontext))
1787                 return;
1788
1789         ast_copy_string(multi, S_OR(l->regexten, l->name), sizeof(multi));
1790         stringp = multi;
1791         while ((ext = strsep(&stringp, "&"))) {
1792                 if ((context = strchr(ext, '@'))) {
1793                         *context++ = '\0'; /* split ext@context */
1794                         if (!ast_context_find(context)) {
1795                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in skinny.conf!\n", context);
1796                                 continue;
1797                         }
1798                 } else {
1799                         context = regcontext;
1800                 }
1801                 ast_context_remove_extension(context, ext, 1, NULL);
1802         }
1803 }
1804
1805 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
1806 {
1807         struct skinny_device *d;
1808         struct skinny_line *l;
1809         struct skinny_speeddial *sd;
1810         struct sockaddr_in sin;
1811         socklen_t slen;
1812         int instance;
1813
1814         AST_LIST_LOCK(&devices);
1815         AST_LIST_TRAVERSE(&devices, d, list){
1816                 if (!strcasecmp(req->data.reg.name, d->id)
1817                                 && ast_apply_ha(d->ha, &(s->sin))) {
1818                         s->device = d;
1819                         d->type = letohl(req->data.reg.type);
1820                         if (ast_strlen_zero(d->version_id)) {
1821                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
1822                         }
1823                         d->registered = 1;
1824                         d->session = s;
1825
1826                         slen = sizeof(sin);
1827                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
1828                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
1829                                 sin.sin_addr = __ourip;
1830                         }
1831                         d->ourip = sin.sin_addr;
1832
1833                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1834                                 sd->stateid = ast_extension_state_add(sd->context, sd->exten, skinny_extensionstate_cb, sd);
1835                         }
1836                         instance = 0;
1837                         AST_LIST_TRAVERSE(&d->lines, l, list) {
1838                                 instance++;
1839                         }
1840                         AST_LIST_TRAVERSE(&d->lines, l, list) {
1841                                 /* FIXME: All sorts of issues will occur if this line is already connected to a device */
1842                                 if (l->device) {
1843                                         ast_verb(1, "Line %s already connected to %s. Not connecting to %s.\n", l->name, l->device->name, d->name);
1844                                 } else {
1845                                         l->device = d;
1846                                         l->capability = l->confcapability & d->capability;
1847                                         l->prefs = l->confprefs;
1848                                         if (!l->prefs.order[0]) {
1849                                                 l->prefs = d->confprefs;
1850                                         }
1851                                         /* l->capability = d->capability;
1852                                         l->prefs = d->prefs; */
1853                                         l->instance = instance;
1854                                         l->newmsgs = ast_app_has_voicemail(l->mailbox, NULL);
1855                                         set_callforwards(l, NULL, 0);
1856                                         register_exten(l);
1857                                         /* initialize MWI on line and device */
1858                                         mwi_event_cb(0, l);
1859                                         ast_devstate_changed(AST_DEVICE_NOT_INUSE, "Skinny/%s@%s", l->name, d->name);
1860                                 }
1861                                 --instance;
1862                         }
1863                         break;
1864                 }
1865         }
1866         AST_LIST_UNLOCK(&devices);
1867         if (!d) {
1868                 return 0;
1869         }
1870         return 1;
1871 }
1872
1873 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
1874 {
1875         struct skinny_device *d;
1876         struct skinny_line *l;
1877         struct skinny_speeddial *sd;
1878
1879         d = s->device;
1880
1881         if (d) {
1882                 d->session = NULL;
1883                 d->registered = 0;
1884
1885                 AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
1886                         if (sd->stateid > -1)
1887                                 ast_extension_state_del(sd->stateid, NULL);
1888                 }
1889                 AST_LIST_TRAVERSE(&d->lines, l, list) {
1890                         if (l->device == d) {
1891                                 l->device = NULL;
1892                                 l->capability = 0;
1893                                 ast_parse_allow_disallow(&l->prefs, &l->capability, "all", 0);                  
1894                                 l->instance = 0;
1895                                 unregister_exten(l);
1896                                 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "Skinny/%s@%s", l->name, d->name);
1897                         }
1898                 }
1899         }
1900
1901         return -1; /* main loop will destroy the session */
1902 }
1903
1904 #ifdef SKINNY_DEVMODE
1905 static char *message2str(int type)
1906 {
1907         char *tmp;
1908
1909         switch (type) {
1910         case KEEP_ALIVE_MESSAGE:
1911                 return "KEEP_ALIVE_MESSAGE";
1912         case REGISTER_MESSAGE:
1913                 return "REGISTER_MESSAGE";
1914         case IP_PORT_MESSAGE:
1915                 return "IP_PORT_MESSAGE";
1916         case KEYPAD_BUTTON_MESSAGE:
1917                 return "KEYPAD_BUTTON_MESSAGE";
1918         case ENBLOC_CALL_MESSAGE:
1919                 return "ENBLOC_CALL_MESSAGE";
1920         case STIMULUS_MESSAGE:
1921                 return "STIMULUS_MESSAGE";
1922         case OFFHOOK_MESSAGE:
1923                 return "OFFHOOK_MESSAGE";
1924         case ONHOOK_MESSAGE:
1925                 return "ONHOOK_MESSAGE";
1926         case CAPABILITIES_RES_MESSAGE:
1927                 return "CAPABILITIES_RES_MESSAGE";
1928         case SPEED_DIAL_STAT_REQ_MESSAGE:
1929                 return "SPEED_DIAL_STAT_REQ_MESSAGE";
1930         case LINE_STATE_REQ_MESSAGE:
1931                 return "LINE_STATE_REQ_MESSAGE";
1932         case TIME_DATE_REQ_MESSAGE:
1933                 return "TIME_DATE_REQ_MESSAGE";
1934         case BUTTON_TEMPLATE_REQ_MESSAGE:
1935                 return "BUTTON_TEMPLATE_REQ_MESSAGE";
1936         case VERSION_REQ_MESSAGE:
1937                 return "VERSION_REQ_MESSAGE";
1938         case SERVER_REQUEST_MESSAGE:
1939                 return "SERVER_REQUEST_MESSAGE";
1940         case ALARM_MESSAGE:
1941                 return "ALARM_MESSAGE";
1942         case OPEN_RECEIVE_CHANNEL_ACK_MESSAGE:
1943                 return "OPEN_RECEIVE_CHANNEL_ACK_MESSAGE";
1944         case SOFT_KEY_SET_REQ_MESSAGE:
1945                 return "SOFT_KEY_SET_REQ_MESSAGE";
1946         case SOFT_KEY_EVENT_MESSAGE:
1947                 return "SOFT_KEY_EVENT_MESSAGE";
1948         case UNREGISTER_MESSAGE:
1949                 return "UNREGISTER_MESSAGE";
1950         case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
1951                 return "SOFT_KEY_TEMPLATE_REQ_MESSAGE";
1952         case HEADSET_STATUS_MESSAGE:
1953                 return "HEADSET_STATUS_MESSAGE";
1954         case REGISTER_AVAILABLE_LINES_MESSAGE:
1955                 return "REGISTER_AVAILABLE_LINES_MESSAGE";
1956         case REGISTER_ACK_MESSAGE:
1957                 return "REGISTER_ACK_MESSAGE";
1958         case START_TONE_MESSAGE:
1959                 return "START_TONE_MESSAGE";
1960         case STOP_TONE_MESSAGE:
1961                 return "STOP_TONE_MESSAGE";
1962         case SET_RINGER_MESSAGE:
1963                 return "SET_RINGER_MESSAGE";
1964         case SET_LAMP_MESSAGE:
1965                 return "SET_LAMP_MESSAGE";
1966         case SET_SPEAKER_MESSAGE:
1967                 return "SET_SPEAKER_MESSAGE";
1968         case SET_MICROPHONE_MESSAGE:
1969                 return "SET_MICROPHONE_MESSAGE";
1970         case START_MEDIA_TRANSMISSION_MESSAGE:
1971                 return "START_MEDIA_TRANSMISSION_MESSAGE";
1972         case STOP_MEDIA_TRANSMISSION_MESSAGE:
1973                 return "STOP_MEDIA_TRANSMISSION_MESSAGE";
1974         case CALL_INFO_MESSAGE:
1975                 return "CALL_INFO_MESSAGE";
1976         case FORWARD_STAT_MESSAGE:
1977                 return "FORWARD_STAT_MESSAGE";
1978         case SPEED_DIAL_STAT_RES_MESSAGE:
1979                 return "SPEED_DIAL_STAT_RES_MESSAGE";
1980         case LINE_STAT_RES_MESSAGE:
1981                 return "LINE_STAT_RES_MESSAGE";
1982         case DEFINETIMEDATE_MESSAGE:
1983                 return "DEFINETIMEDATE_MESSAGE";
1984         case BUTTON_TEMPLATE_RES_MESSAGE:
1985                 return "BUTTON_TEMPLATE_RES_MESSAGE";
1986         case VERSION_RES_MESSAGE:
1987                 return "VERSION_RES_MESSAGE";
1988         case DISPLAYTEXT_MESSAGE:
1989                 return "DISPLAYTEXT_MESSAGE";
1990         case CLEAR_NOTIFY_MESSAGE:
1991                 return "CLEAR_NOTIFY_MESSAGE";
1992         case CLEAR_DISPLAY_MESSAGE:
1993                 return "CLEAR_DISPLAY_MESSAGE";
1994         case CAPABILITIES_REQ_MESSAGE:
1995                 return "CAPABILITIES_REQ_MESSAGE";
1996         case REGISTER_REJ_MESSAGE:
1997                 return "REGISTER_REJ_MESSAGE";
1998         case SERVER_RES_MESSAGE:
1999                 return "SERVER_RES_MESSAGE";
2000         case RESET_MESSAGE:
2001                 return "RESET_MESSAGE";
2002         case KEEP_ALIVE_ACK_MESSAGE:
2003                 return "KEEP_ALIVE_ACK_MESSAGE";
2004         case OPEN_RECEIVE_CHANNEL_MESSAGE:
2005                 return "OPEN_RECEIVE_CHANNEL_MESSAGE";
2006         case CLOSE_RECEIVE_CHANNEL_MESSAGE:
2007                 return "CLOSE_RECEIVE_CHANNEL_MESSAGE";
2008         case SOFT_KEY_TEMPLATE_RES_MESSAGE:
2009                 return "SOFT_KEY_TEMPLATE_RES_MESSAGE";
2010         case SOFT_KEY_SET_RES_MESSAGE:
2011                 return "SOFT_KEY_SET_RES_MESSAGE";
2012         case SELECT_SOFT_KEYS_MESSAGE:
2013                 return "SELECT_SOFT_KEYS_MESSAGE";
2014         case CALL_STATE_MESSAGE:
2015                 return "CALL_STATE_MESSAGE";
2016         case DISPLAY_PROMPT_STATUS_MESSAGE:
2017                 return "DISPLAY_PROMPT_STATUS_MESSAGE";
2018         case CLEAR_PROMPT_MESSAGE:
2019                 return "CLEAR_PROMPT_MESSAGE";
2020         case DISPLAY_NOTIFY_MESSAGE:
2021                 return "DISPLAY_NOTIFY_MESSAGE";
2022         case ACTIVATE_CALL_PLANE_MESSAGE:
2023                 return "ACTIVATE_CALL_PLANE_MESSAGE";
2024         case DIALED_NUMBER_MESSAGE:
2025                 return "DIALED_NUMBER_MESSAGE";
2026         default:
2027                 if (!(tmp = ast_threadstorage_get(&message2str_threadbuf, MESSAGE2STR_BUFSIZE)))
2028                         return "Unknown";
2029                 snprintf(tmp, MESSAGE2STR_BUFSIZE, "UNKNOWN_MESSAGE-%d", type);
2030                 return tmp;
2031         }
2032 }
2033 #endif
2034
2035 static int transmit_response(struct skinny_device *d, struct skinny_req *req)
2036 {
2037         struct skinnysession *s = d->session;
2038         int res = 0;
2039
2040         if (!s) {
2041                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2042                 return -1;
2043         }
2044
2045         ast_mutex_lock(&s->lock);
2046
2047         SKINNY_DEVONLY(if (skinnydebug>1) ast_verb(4, "Transmitting %s to %s\n", message2str(req->e), d->name);)
2048
2049         if (letohl(req->len > SKINNY_MAX_PACKET) || letohl(req->len < 0)) {
2050                 ast_log(LOG_WARNING, "transmit_response: the length of the request is out of bounds\n");
2051                 ast_mutex_unlock(&s->lock);
2052                 return -1;
2053         }
2054
2055         memset(s->outbuf, 0, sizeof(s->outbuf));
2056         memcpy(s->outbuf, req, skinny_header_size);
2057         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2058
2059         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2060         
2061         if (res != letohl(req->len)+8) {
2062                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2063                 if (res == -1) {
2064                         if (skinnydebug)
2065                                 ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2066                         skinny_unregister(NULL, s);
2067                 }
2068                 
2069         }
2070         
2071         ast_free(req);
2072         ast_mutex_unlock(&s->lock);
2073         return 1;
2074 }
2075
2076 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2077 {
2078         struct skinny_req *req;
2079
2080         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2081                 return;
2082
2083         req->data.setspeaker.mode = htolel(mode);
2084         transmit_response(d, req);
2085 }
2086 /*
2087 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2088 {
2089         struct skinny_req *req;
2090
2091         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2092                 return;
2093
2094         req->data.setmicrophone.mode = htolel(mode);
2095         transmit_response(d, req);
2096 }
2097 */
2098
2099 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)
2100 {
2101         struct skinny_req *req;
2102
2103         /* We should not be able to get here without a device */
2104         if (!d)
2105                 return;
2106
2107         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2108                 return;
2109
2110         if (skinnydebug)
2111                         ast_verb(1, "Setting Callinfo to %s(%s) from %s(%s) on %s(%d)\n", fromname, fromnum, toname, tonum, d->name, instance);
2112
2113         if (fromname) {
2114                 ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2115         }
2116         if (fromnum) {
2117                 ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2118         }
2119         if (toname) {
2120                 ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2121         }
2122         if (tonum) {
2123                 ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2124         }
2125         req->data.callinfo.instance = htolel(instance);
2126         req->data.callinfo.reference = htolel(callid);
2127         req->data.callinfo.type = htolel(calltype);
2128         transmit_response(d, req);
2129 }
2130
2131 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2132 {
2133         struct skinny_req *req;
2134         struct skinny_line *l = sub->parent;
2135         struct ast_format_list fmt;
2136
2137         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2138                 return;
2139
2140         fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
2141
2142         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2143         req->data.openreceivechannel.partyId = htolel(sub->callid);
2144         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2145         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(fmt.bits));
2146         req->data.openreceivechannel.echo = htolel(0);
2147         req->data.openreceivechannel.bitrate = htolel(0);
2148         transmit_response(d, req);
2149 }
2150
2151 static void transmit_tone(struct skinny_device *d, int tone, int instance, int reference)
2152 {
2153         struct skinny_req *req;
2154
2155         if (tone == SKINNY_NOTONE) {
2156                 /* This is bad, mmm'kay? */
2157                 return;
2158         }
2159
2160         if (tone > 0) {
2161                 if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2162                         return;
2163                 req->data.starttone.tone = htolel(tone);
2164                 req->data.starttone.instance = htolel(instance);
2165                 req->data.starttone.reference = htolel(reference);
2166         } else {
2167                 if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2168                         return;
2169                 req->data.stoptone.instance = htolel(instance);
2170                 req->data.stoptone.reference = htolel(reference);
2171         }
2172
2173         //Bad, tone is already set so this is redundant and a change to the if above
2174         //may lead to issues where we try to set a tone to a stop_tone_message
2175         //if (tone > 0) {
2176         //      req->data.starttone.tone = htolel(tone);
2177         //}
2178         transmit_response(d, req);
2179 }
2180
2181 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey)
2182 {
2183         struct skinny_req *req;
2184
2185         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2186                 return;
2187
2188         req->data.selectsoftkey.instance = htolel(instance);
2189         req->data.selectsoftkey.reference = htolel(callid);
2190         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2191         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
2192         transmit_response(d, req);
2193 }
2194
2195 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2196 {
2197         struct skinny_req *req;
2198
2199         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2200                 return;
2201
2202         req->data.setlamp.stimulus = htolel(stimulus);
2203         req->data.setlamp.stimulusInstance = htolel(instance);
2204         req->data.setlamp.deviceStimulus = htolel(indication);
2205         transmit_response(d, req);
2206 }
2207
2208 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2209 {
2210         struct skinny_req *req;
2211
2212         if (skinnydebug)
2213                 ast_verb(1, "Setting ringer mode to '%d'.\n", mode);
2214
2215         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2216                 return;
2217
2218         req->data.setringer.ringerMode = htolel(mode);
2219         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2220            Note: The phone will always show as ringing on the display.
2221
2222            1: phone will audibly ring over and over
2223            2: phone will audibly ring only once
2224            any other value, will NOT cause the phone to audibly ring
2225         */
2226         req->data.setringer.unknown1 = htolel(1);
2227         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2228            Perhaps a packet capture can shed some light on this. */
2229         req->data.setringer.unknown2 = htolel(1);
2230         transmit_response(d, req);
2231 }
2232
2233 static void transmit_displaymessage(struct skinny_device *d, const char *text, int instance, int reference)
2234 {
2235         struct skinny_req *req;
2236
2237         if (text == 0) {
2238                 if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
2239                         return;
2240
2241                 //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2242                 //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2243                 //req->data.clearpromptstatus.lineInstance = instance;
2244                 //req->data.clearpromptstatus.callReference = reference;
2245
2246                 /* send datetime message. We have to do it here because it will clear the display on the phone if we do it elsewhere */
2247                 handle_time_date_req_message(NULL, d->session);
2248
2249                 if (skinnydebug)
2250                         ast_verb(1, "Clearing Display\n");
2251         } else {
2252                 if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2253                         return;
2254
2255                 ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2256                 if (skinnydebug)
2257                         ast_verb(1, "Displaying message '%s'\n", req->data.displaytext.text);
2258         }
2259
2260         transmit_response(d, req);
2261 }
2262
2263 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2264 {
2265         struct skinny_req *req;
2266
2267         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2268                 return;
2269
2270         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2271         req->data.displaynotify.displayTimeout = htolel(t);
2272
2273         if (skinnydebug)
2274                 ast_verb(1, "Displaying notify '%s'\n", text);
2275
2276         transmit_response(d, req);
2277 }
2278
2279 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
2280 {
2281         struct skinny_req *req;
2282
2283         if (text == 0) {
2284                 if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2285                         return;
2286
2287                 req->data.clearpromptstatus.lineInstance = htolel(instance);
2288                 req->data.clearpromptstatus.callReference = htolel(callid);
2289
2290                 if (skinnydebug)
2291                         ast_verb(1, "Clearing Prompt\n");
2292         } else {
2293                 if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2294                         return;
2295
2296                 ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2297                 req->data.displaypromptstatus.messageTimeout = htolel(t);
2298                 req->data.displaypromptstatus.lineInstance = htolel(instance);
2299                 req->data.displaypromptstatus.callReference = htolel(callid);
2300
2301                 if (skinnydebug)
2302                         ast_verb(1, "Displaying Prompt Status '%s'\n", text);
2303         }
2304
2305         transmit_response(d, req);
2306 }
2307
2308 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2309 {
2310         struct skinny_req *req;
2311
2312         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2313                 return;
2314
2315         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2316         req->data.dialednumber.lineInstance = htolel(instance);
2317         req->data.dialednumber.callReference = htolel(callid);
2318
2319         transmit_response(d, req);
2320 }
2321
2322 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2323 {
2324         struct skinny_req *req;
2325
2326         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2327                 return;
2328
2329         req->data.closereceivechannel.conferenceId = htolel(0);
2330         req->data.closereceivechannel.partyId = htolel(sub->callid);
2331         transmit_response(d, req);
2332 }
2333
2334 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2335 {
2336         struct skinny_req *req;
2337
2338         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2339                 return;
2340
2341         req->data.stopmedia.conferenceId = htolel(0);
2342         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2343         transmit_response(d, req);
2344 }
2345
2346 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
2347 {
2348         struct skinny_req *req;
2349
2350         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2351                 return;
2352
2353         req->data.activatecallplane.lineInstance = htolel(l->instance);
2354         transmit_response(d, req);
2355 }
2356
2357 static void transmit_callstateonly(struct skinny_device *d, struct skinny_subchannel *sub, int state)
2358 {
2359         struct skinny_req *req;
2360
2361         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2362                 return;
2363
2364         req->data.callstate.callState = htolel(state);
2365         req->data.callstate.lineInstance = htolel(sub->parent->instance);
2366         req->data.callstate.callReference = htolel(sub->callid);
2367         transmit_response(d, req);
2368 }
2369
2370 static void transmit_callstate(struct skinny_device *d, int instance, int state, unsigned callid)
2371 {
2372         struct skinny_req *req;
2373
2374         if (state == SKINNY_ONHOOK) {
2375                 if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2376                         return;
2377
2378                 req->data.closereceivechannel.conferenceId = htolel(callid);
2379                 req->data.closereceivechannel.partyId = htolel(callid);
2380                 transmit_response(d, req);
2381
2382                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2383                         return;
2384
2385                 req->data.stopmedia.conferenceId = htolel(callid);
2386                 req->data.stopmedia.passThruPartyId = htolel(callid);
2387                 transmit_response(d, req);
2388
2389                 transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
2390
2391                 transmit_displaypromptstatus(d, NULL, 0, instance, callid);
2392         }
2393
2394         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2395                 return;
2396
2397         req->data.callstate.callState = htolel(state);
2398         req->data.callstate.lineInstance = htolel(instance);
2399         req->data.callstate.callReference = htolel(callid);
2400         transmit_response(d, req);
2401
2402         if (state == SKINNY_ONHOOK) {
2403                 transmit_selectsoftkeys(d, 0, 0, KEYDEF_ONHOOK);
2404         }
2405
2406         if (state == SKINNY_OFFHOOK || state == SKINNY_ONHOOK) {
2407                 if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2408                         return;
2409
2410                 req->data.activatecallplane.lineInstance = htolel(instance);
2411                 transmit_response(d, req);
2412         }
2413 }
2414
2415
2416 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
2417 {
2418         struct skinny_req *req;
2419         int anyon = 0;
2420
2421         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
2422                 return;
2423
2424         if (l->cfwdtype & SKINNY_CFWD_ALL) {
2425                 if (!ast_strlen_zero(l->call_forward_all)) {
2426                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
2427                         req->data.forwardstat.fwdall = htolel(1);
2428                         anyon++;
2429                 } else {
2430                         req->data.forwardstat.fwdall = htolel(0);
2431                 }
2432         }
2433         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
2434                 if (!ast_strlen_zero(l->call_forward_busy)) {
2435                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
2436                         req->data.forwardstat.fwdbusy = htolel(1);
2437                         anyon++;
2438                 } else {
2439                         req->data.forwardstat.fwdbusy = htolel(0);
2440                 }
2441         }
2442         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
2443                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
2444                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
2445                         req->data.forwardstat.fwdnoanswer = htolel(1);
2446                         anyon++;
2447                 } else {
2448                         req->data.forwardstat.fwdnoanswer = htolel(0);
2449                 }
2450         }
2451         req->data.forwardstat.lineNumber = htolel(l->instance);
2452         if (anyon)
2453                 req->data.forwardstat.activeforward = htolel(7);
2454         else
2455                 req->data.forwardstat.activeforward = htolel(0);
2456
2457         transmit_response(d, req);
2458 }
2459
2460 static int skinny_extensionstate_cb(char *context, char *exten, int state, void *data)
2461 {
2462         struct skinny_speeddial *sd = data;
2463         struct skinny_device *d = sd->parent;
2464         char hint[AST_MAX_EXTENSION];
2465         int callstate = SKINNY_CALLREMOTEMULTILINE;
2466         int lamp = SKINNY_LAMP_OFF;
2467
2468         switch (state) {
2469         case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
2470         case AST_EXTENSION_REMOVED:     /* Extension is gone */
2471                 ast_verb(2, "Extension state: Watcher for hint %s %s. Notify Device %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
2472                 sd->stateid = -1;
2473                 callstate = SKINNY_ONHOOK;
2474                 lamp = SKINNY_LAMP_OFF;
2475                 break;
2476         case AST_EXTENSION_RINGING:
2477         case AST_EXTENSION_UNAVAILABLE:
2478                 callstate = SKINNY_RINGIN;
2479                 lamp = SKINNY_LAMP_BLINK;
2480                 break;
2481         case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
2482         case AST_EXTENSION_INUSE:
2483                 callstate = SKINNY_CALLREMOTEMULTILINE;
2484                 lamp = SKINNY_LAMP_ON;
2485                 break;
2486         case AST_EXTENSION_ONHOLD:
2487                 callstate = SKINNY_HOLD;
2488                 lamp = SKINNY_LAMP_WINK;
2489                 break;
2490         case AST_EXTENSION_NOT_INUSE:
2491         default:
2492                 callstate = SKINNY_ONHOOK;
2493                 lamp = SKINNY_LAMP_OFF;
2494                 break;
2495         }
2496
2497         if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
2498                 /* If they are not registered, we will override notification and show no availability */
2499                 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
2500                         callstate = SKINNY_ONHOOK;
2501                         lamp = SKINNY_LAMP_FLASH;
2502                 }
2503         }
2504
2505         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, lamp);
2506         transmit_callstate(d, sd->instance, callstate, 0);
2507         sd->laststate = state;
2508
2509         return 0;
2510 }
2511
2512 static void mwi_event_cb(const struct ast_event *event, void *userdata)
2513 {
2514         struct skinny_line *l = userdata;
2515         struct skinny_device *d = l->device;
2516         if (d) {
2517                 struct skinnysession *s = d->session;
2518                 struct skinny_line *l2;
2519                 int new_msgs = 0;
2520                 int dev_msgs = 0;
2521
2522                 if (s) {
2523                         if (event) {
2524                                 l->newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
2525                         }
2526
2527                         if (l->newmsgs) {
2528                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2529                         } else {
2530                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
2531                         }
2532
2533                         /* find out wether the device lamp should be on or off */
2534                         AST_LIST_TRAVERSE(&d->lines, l2, list) {
2535                                 if (l2->newmsgs) {
2536                                         dev_msgs++;
2537                                 }
2538                         }
2539
2540                         if (dev_msgs) {
2541                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2542                         } else {
2543                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
2544                         }
2545                         ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", new_msgs);
2546                 }
2547         }
2548 }
2549
2550 /* I do not believe skinny can deal with video.
2551    Anyone know differently? */
2552 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
2553 static enum ast_rtp_get_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
2554 {
2555         struct skinny_subchannel *sub = NULL;
2556
2557         if (!(sub = c->tech_pvt) || !(sub->vrtp))
2558                 return AST_RTP_GET_FAILED;
2559
2560         *rtp = sub->vrtp;
2561
2562         return AST_RTP_TRY_NATIVE;
2563 }
2564
2565 static enum ast_rtp_get_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
2566 {
2567         struct skinny_subchannel *sub = NULL;
2568         struct skinny_line *l;
2569         enum ast_rtp_get_result res = AST_RTP_TRY_NATIVE;
2570
2571         if (skinnydebug)
2572                 ast_verb(1, "skinny_get_rtp_peer() Channel = %s\n", c->name);
2573
2574
2575         if (!(sub = c->tech_pvt))
2576                 return AST_RTP_GET_FAILED;
2577
2578         ast_mutex_lock(&sub->lock);
2579
2580         if (!(sub->rtp)){
2581                 ast_mutex_unlock(&sub->lock);
2582                 return AST_RTP_GET_FAILED;
2583         }
2584         
2585         *rtp = sub->rtp;
2586
2587         l = sub->parent;
2588
2589         if (!l->canreinvite || l->nat){
2590                 res = AST_RTP_TRY_PARTIAL;
2591                 if (skinnydebug)
2592                         ast_verb(1, "skinny_get_rtp_peer() Using AST_RTP_TRY_PARTIAL \n");
2593         }
2594
2595         ast_mutex_unlock(&sub->lock);
2596
2597         return res;
2598
2599 }
2600
2601 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)
2602 {
2603         struct skinny_subchannel *sub;
2604         struct skinny_line *l;
2605         struct skinny_device *d;
2606         struct skinnysession *s;
2607         struct ast_format_list fmt;
2608         struct sockaddr_in us;
2609         struct sockaddr_in them;
2610         struct skinny_req *req;
2611         
2612         sub = c->tech_pvt;
2613
2614         if (c->_state != AST_STATE_UP)
2615                 return 0;
2616
2617         if (!sub) {
2618                 return -1;
2619         }
2620
2621         l = sub->parent;
2622         d = l->device;
2623         s = d->session;
2624
2625         if (rtp){
2626                 ast_rtp_get_peer(rtp, &them);
2627
2628                 /* Shutdown any early-media or previous media on re-invite */
2629                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2630                         return -1;
2631
2632                 req->data.stopmedia.conferenceId = htolel(sub->callid);
2633                 req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2634                 transmit_response(d, req);
2635
2636                 if (skinnydebug)
2637                         ast_verb(1, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
2638
2639                 if (!(req = req_alloc(sizeof(struct start_media_transmission_message), START_MEDIA_TRANSMISSION_MESSAGE)))
2640                         return -1;
2641
2642                 fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
2643
2644                 if (skinnydebug)
2645                         ast_verb(1, "Setting payloadType to '%d' (%d ms)\n", fmt.bits, fmt.cur_ms);
2646
2647                 req->data.startmedia.conferenceId = htolel(sub->callid);
2648                 req->data.startmedia.passThruPartyId = htolel(sub->callid);
2649                 if (!(l->canreinvite) || (l->nat)){
2650                         ast_rtp_get_us(rtp, &us);
2651                         req->data.startmedia.remoteIp = htolel(d->ourip.s_addr);
2652                         req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
2653                 } else {
2654                         req->data.startmedia.remoteIp = htolel(them.sin_addr.s_addr);
2655                         req->data.startmedia.remotePort = htolel(ntohs(them.sin_port));
2656                 }
2657                 req->data.startmedia.packetSize = htolel(fmt.cur_ms);
2658                 req->data.startmedia.payloadType = htolel(codec_ast2skinny(fmt.bits));
2659                 req->data.startmedia.qualifier.precedence = htolel(127);
2660                 req->data.startmedia.qualifier.vad = htolel(0);
2661                 req->data.startmedia.qualifier.packets = htolel(0);
2662                 req->data.startmedia.qualifier.bitRate = htolel(0);
2663                 transmit_response(d, req);
2664
2665                 return 0;
2666         }
2667         /* Need a return here to break the bridge */
2668         return 0;
2669 }
2670
2671 static struct ast_rtp_protocol skinny_rtp = {
2672         .type = "Skinny",
2673         .get_rtp_info = skinny_get_rtp_peer,
2674         .get_vrtp_info = skinny_get_vrtp_peer,
2675         .set_rtp_peer = skinny_set_rtp_peer,
2676 };
2677
2678 static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2679 {
2680         switch (cmd) {
2681         case CLI_INIT:
2682 #ifdef SKINNY_DEVMODE
2683                 e->command = "skinny set debug {off|on|packet}";
2684                 e->usage =
2685                         "Usage: skinny set debug {off|on|packet}\n"
2686                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2687 #else
2688                 e->command = "skinny set debug {off|on}";
2689                 e->usage =
2690                         "Usage: skinny set debug {off|on}\n"
2691                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2692 #endif
2693                 return NULL;
2694         case CLI_GENERATE:
2695                 return NULL;
2696         }
2697         
2698         if (a->argc != e->args)
2699                 return CLI_SHOWUSAGE;
2700
2701         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
2702                 skinnydebug = 1;
2703                 ast_cli(a->fd, "Skinny Debugging Enabled\n");
2704                 return CLI_SUCCESS;
2705         } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
2706                 skinnydebug = 0;
2707                 ast_cli(a->fd, "Skinny Debugging Disabled\n");
2708                 return CLI_SUCCESS;
2709 #ifdef SKINNY_DEVMODE
2710         } else if (!strncasecmp(a->argv[e->args - 1], "packet", 6)) {
2711                 skinnydebug = 2;
2712                 ast_cli(a->fd, "Skinny Debugging Enabled including Packets\n");
2713                 return CLI_SUCCESS;
2714 #endif
2715         } else {
2716                 return CLI_SHOWUSAGE;
2717         }
2718 }
2719
2720 static char *complete_skinny_devices(const char *word, int state)
2721 {
2722         struct skinny_device *d;
2723         char *result = NULL;
2724         int wordlen = strlen(word), which = 0;
2725
2726         AST_LIST_TRAVERSE(&devices, d, list) {
2727                 if (!strncasecmp(word, d->id, wordlen) && ++which > state)
2728                         result = ast_strdup(d->id);
2729         }
2730
2731         return result;
2732 }
2733
2734 static char *complete_skinny_show_device(const char *line, const char *word, int pos, int state)
2735 {
2736         return (pos == 3 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2737 }
2738
2739 static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
2740 {
2741         return (pos == 2 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2742 }
2743
2744 static char *complete_skinny_show_line(const char *line, const char *word, int pos, int state)
2745 {
2746         struct skinny_device *d;
2747         struct skinny_line *l;
2748         char *result = NULL;
2749         int wordlen = strlen(word), which = 0;
2750
2751         if (pos != 3)
2752                 return NULL;
2753         
2754         AST_LIST_TRAVERSE(&devices, d, list) {
2755                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2756                         if (!strncasecmp(word, l->name, wordlen) && ++which > state)
2757                                 result = ast_strdup(l->name);
2758                 }
2759         }
2760
2761         return result;
2762 }
2763
2764 static char *handle_skinny_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2765 {
2766         struct skinny_device *d;
2767         struct skinny_req *req;
2768
2769         switch (cmd) {
2770         case CLI_INIT:
2771                 e->command = "skinny reset";
2772                 e->usage =
2773                         "Usage: skinny reset <DeviceId|DeviceName|all> [restart]\n"
2774                         "       Causes a Skinny device to reset itself, optionally with a full restart\n";
2775                 return NULL;
2776         case CLI_GENERATE:
2777                 return complete_skinny_reset(a->line, a->word, a->pos, a->n);
2778         }
2779
2780         if (a->argc < 3 || a->argc > 4)
2781                 return CLI_SHOWUSAGE;
2782
2783         AST_LIST_LOCK(&devices);
2784         AST_LIST_TRAVERSE(&devices, d, list) {
2785                 int fullrestart = 0;
2786                 if (!strcasecmp(a->argv[2], d->id) || !strcasecmp(a->argv[2], d->name) || !strcasecmp(a->argv[2], "all")) {
2787                         if (!(d->session))
2788                                 continue;
2789
2790                         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
2791                                 continue;
2792
2793                         if (a->argc == 4 && !strcasecmp(a->argv[3], "restart"))
2794                                 fullrestart = 1;
2795
2796                         if (fullrestart)
2797                                 req->data.reset.resetType = 2;
2798                         else
2799                                 req->data.reset.resetType = 1;
2800
2801                         ast_verb(3, "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
2802                         transmit_response(d, req);
2803                 }
2804         }
2805         AST_LIST_UNLOCK(&devices);
2806         return CLI_SUCCESS;
2807 }
2808
2809 static char *device2str(int type)
2810 {
2811         char *tmp;
2812
2813         switch (type) {
2814         case SKINNY_DEVICE_NONE:
2815                 return "No Device";
2816         case SKINNY_DEVICE_30SPPLUS:
2817                 return "30SP Plus";
2818         case SKINNY_DEVICE_12SPPLUS:
2819                 return "12SP Plus";
2820         case SKINNY_DEVICE_12SP:
2821                 return "12SP";
2822         case SKINNY_DEVICE_12:
2823                 return "12";
2824         case SKINNY_DEVICE_30VIP:
2825                 return "30VIP";
2826         case SKINNY_DEVICE_7910:
2827                 return "7910";
2828         case SKINNY_DEVICE_7960:
2829                 return "7960";
2830         case SKINNY_DEVICE_7940:
2831                 return "7940";
2832         case SKINNY_DEVICE_7935:
2833                 return "7935";
2834         case SKINNY_DEVICE_ATA186:
2835                 return "ATA186";
2836         case SKINNY_DEVICE_7941:
2837                 return "7941";
2838         case SKINNY_DEVICE_7971:
2839                 return "7971";
2840         case SKINNY_DEVICE_7914:
2841                 return "7914";
2842         case SKINNY_DEVICE_7985:
2843                 return "7985";
2844         case SKINNY_DEVICE_7911:
2845                 return "7911";
2846         case SKINNY_DEVICE_7961GE:
2847                 return "7961GE";
2848         case SKINNY_DEVICE_7941GE:
2849                 return "7941GE";
2850         case SKINNY_DEVICE_7931:
2851                 return "7931";
2852         case SKINNY_DEVICE_7921:
2853                 return "7921";
2854         case SKINNY_DEVICE_7906:
2855                 return "7906";
2856         case SKINNY_DEVICE_7962:
2857                 return "7962";
2858         case SKINNY_DEVICE_7937:
2859                 return "7937";
2860         case SKINNY_DEVICE_7942:
2861                 return "7942";
2862         case SKINNY_DEVICE_7945:
2863                 return "7945";
2864         case SKINNY_DEVICE_7965:
2865                 return "7965";
2866         case SKINNY_DEVICE_7975:
2867                 return "7975";
2868         case SKINNY_DEVICE_7905:
2869                 return "7905";
2870         case SKINNY_DEVICE_7920:
2871                 return "7920";
2872         case SKINNY_DEVICE_7970:
2873                 return "7970";
2874         case SKINNY_DEVICE_7912:
2875                 return "7912";
2876         case SKINNY_DEVICE_7902:
2877                 return "7902";
2878         case SKINNY_DEVICE_CIPC:
2879                 return "IP Communicator";
2880         case SKINNY_DEVICE_7961:
2881                 return "7961";
2882         case SKINNY_DEVICE_7936:
2883                 return "7936";
2884         case SKINNY_DEVICE_SCCPGATEWAY_AN:
2885                 return "SCCPGATEWAY_AN";
2886         case SKINNY_DEVICE_SCCPGATEWAY_BRI:
2887                 return "SCCPGATEWAY_BRI";
2888         case SKINNY_DEVICE_UNKNOWN:
2889                 return "Unknown";
2890         default:
2891                 if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
2892                         return "Unknown";
2893                 snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
2894                 return tmp;
2895         }
2896 }
2897
2898 /*! \brief Print codec list from preference to CLI/manager */
2899 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
2900 {
2901         int x, codec;
2902
2903         for(x = 0; x < 32 ; x++) {
2904                 codec = ast_codec_pref_index(pref, x);
2905                 if (!codec)
2906                         break;
2907                 ast_cli(fd, "%s", ast_getformatname(codec));
2908                 ast_cli(fd, ":%d", pref->framing[x]);
2909                 if (x < 31 && ast_codec_pref_index(pref, x + 1))
2910                         ast_cli(fd, ",");
2911         }
2912         if (!x)
2913                 ast_cli(fd, "none");
2914 }
2915
2916 static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2917 {
2918         struct skinny_device *d;
2919         struct skinny_line *l;
2920
2921         switch (cmd) {
2922         case CLI_INIT:
2923                 e->command = "skinny show devices";
2924                 e->usage =
2925                         "Usage: skinny show devices\n"
2926                         "       Lists all devices known to the Skinny subsystem.\n";
2927                 return NULL;
2928         case CLI_GENERATE:
2929                 return NULL;
2930         }
2931
2932         if (a->argc != 3)
2933                 return CLI_SHOWUSAGE;
2934
2935         ast_cli(a->fd, "Name                 DeviceId         IP              Type            R NL\n");
2936         ast_cli(a->fd, "-------------------- ---------------- --------------- --------------- - --\n");
2937
2938         AST_LIST_LOCK(&devices); 
2939         AST_LIST_TRAVERSE(&devices, d, list) {
2940                 int numlines = 0;
2941                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2942                         numlines++;
2943                 }
2944                 
2945                 ast_cli(a->fd, "%-20s %-16s %-15s %-15s %c %2d\n",
2946                         d->name,
2947                         d->id,
2948                         d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
2949                         device2str(d->type),
2950                         d->registered?'Y':'N',
2951                         numlines);
2952         }
2953         AST_LIST_UNLOCK(&devices);
2954         return CLI_SUCCESS;
2955 }
2956
2957 /*! \brief Show device information */
2958 static char *handle_skinny_show_device(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2959 {
2960         struct skinny_device *d;
2961         struct skinny_line *l;
2962         struct skinny_speeddial *sd;
2963         struct skinny_addon *sa;
2964         char codec_buf[512];
2965
2966         switch (cmd) {
2967         case CLI_INIT:
2968                 e->command = "skinny show device";
2969                 e->usage =
2970                         "Usage: skinny show device <DeviceId|DeviceName>\n"
2971                         "       Lists all deviceinformation of a specific device known to the Skinny subsystem.\n";
2972                 return NULL;
2973         case CLI_GENERATE:
2974                 return complete_skinny_show_device(a->line, a->word, a->pos, a->n);
2975         }
2976
2977         if (a->argc < 4)
2978                 return CLI_SHOWUSAGE;
2979
2980         AST_LIST_LOCK(&devices);
2981         AST_LIST_TRAVERSE(&devices, d, list) {
2982                 if (!strcasecmp(a->argv[3], d->id) || !strcasecmp(a->argv[3], d->name)) {
2983                         int numlines = 0, numaddons = 0, numspeeddials = 0;
2984
2985                         AST_LIST_TRAVERSE(&d->lines, l, list){
2986                                 numlines++;
2987                         }
2988
2989                         ast_cli(a->fd, "Name:        %s\n", d->name);
2990                         ast_cli(a->fd, "Id:          %s\n", d->id);
2991                         ast_cli(a->fd, "version:     %s\n", S_OR(d->version_id, "Unknown"));
2992                         ast_cli(a->fd, "Ip address:  %s\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
2993                         ast_cli(a->fd, "Port:        %d\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
2994                         ast_cli(a->fd, "Device Type: %s\n", device2str(d->type));
2995                         ast_cli(a->fd, "Conf Codecs:");
2996                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->confcapability);
2997                         ast_cli(a->fd, "%s\n", codec_buf);
2998                         ast_cli(a->fd, "Neg Codecs: ");
2999                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, d->capability);
3000                         ast_cli(a->fd, "%s\n", codec_buf);
3001                         ast_cli(a->fd, "Registered:  %s\n", (d->registered ? "Yes" : "No"));
3002                         ast_cli(a->fd, "Lines:       %d\n", numlines);
3003                         AST_LIST_TRAVERSE(&d->lines, l, list) {
3004                                 ast_cli(a->fd, "  %s (%s)\n", l->name, l->label);
3005                         }
3006                         AST_LIST_TRAVERSE(&d->addons, sa, list) {
3007                                 numaddons++;
3008                         }       
3009                         ast_cli(a->fd, "Addons:      %d\n", numaddons);
3010                         AST_LIST_TRAVERSE(&d->addons, sa, list) {
3011                                 ast_cli(a->fd, "  %s\n", sa->type);
3012                         }
3013                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3014                                 numspeeddials++;
3015                         }
3016                         ast_cli(a->fd, "Speeddials:  %d\n", numspeeddials);
3017                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3018                                 ast_cli(a->fd, "  %s (%s) ishint: %d\n", sd->exten, sd->label, sd->isHint);
3019                         }
3020                 }
3021         }
3022         AST_LIST_UNLOCK(&devices);
3023         return CLI_SUCCESS;
3024 }
3025
3026 static char *handle_skinny_show_lines(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3027 {
3028         struct skinny_line *l;
3029         struct skinny_subchannel *sub;
3030         int verbose = 0;
3031
3032         switch (cmd) {
3033         case CLI_INIT:
3034                 e->command = "skinny show lines [verbose]";
3035                 e->usage =
3036                         "Usage: skinny show lines\n"
3037                         "       Lists all lines known to the Skinny subsystem.\n"
3038                         "       If 'verbose' is specified, the output includes\n"
3039                         "       information about subs for each line.\n";
3040                 return NULL;
3041         case CLI_GENERATE:
3042                 return NULL;
3043         }
3044
3045
3046         if (a->argc == e->args) {
3047                 if (!strcasecmp(a->argv[e->args-1], "verbose")) {
3048                         verbose = 1;
3049                 } else {
3050                         return CLI_SHOWUSAGE;
3051                 }
3052         } else if (a->argc != e->args - 1) {
3053                 return CLI_SHOWUSAGE;
3054         }
3055         
3056         
3057         ast_cli(a->fd, "Name                 Device Name          Instance Label               \n");
3058         ast_cli(a->fd, "-------------------- -------------------- -------- --------------------\n");
3059         AST_LIST_LOCK(&lines);
3060         AST_LIST_TRAVERSE(&lines, l, all) {
3061                 ast_cli(a->fd, "%-20s %-20s %8d %-20s\n",
3062                         l->name,
3063                         (l->device ? l->device->name : "Not connected"),
3064                         l->instance,
3065                         l->label);
3066                         if (verbose) {
3067                         AST_LIST_TRAVERSE(&l->sub, sub, list) {
3068                                 ast_cli(a->fd, "  %s> %s to %s\n",
3069                                         (sub == l->activesub?"Active  ":"Inactive"),
3070                                         sub->owner->name,
3071                                         (ast_bridged_channel(sub->owner)?ast_bridged_channel(sub->owner)->name:"")
3072                                 );
3073                         }
3074                 }
3075         }
3076         AST_LIST_UNLOCK(&lines);
3077         return CLI_SUCCESS;
3078 }
3079
3080 /*! \brief List line information. */
3081 static char *handle_skinny_show_line(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3082 {
3083         struct skinny_device *d;
3084         struct skinny_line *l;
3085         char codec_buf[512];
3086         char group_buf[256];
3087
3088         switch (cmd) {
3089         case CLI_INIT:
3090                 e->command = "skinny show line";
3091                 e->usage =
3092                         "Usage: skinny show line <Line> [ on <DeviceID|DeviceName> ]\n"
3093                         "       List all lineinformation of a specific line known to the Skinny subsystem.\n";
3094                 return NULL;
3095         case CLI_GENERATE:
3096                 return complete_skinny_show_line(a->line, a->word, a->pos, a->n);
3097         }
3098
3099         if (a->argc < 4)
3100                 return CLI_SHOWUSAGE;
3101         
3102         AST_LIST_LOCK(&devices);
3103
3104         /* Show all lines matching the one supplied */
3105         AST_LIST_TRAVERSE(&devices, d, list) {
3106                 if (a->argc == 6 && (strcasecmp(a->argv[5], d->id) && strcasecmp(a->argv[5], d->name)))
3107                         continue;
3108                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3109                         if (strcasecmp(a->argv[3], l->name))
3110                                 continue;
3111                         ast_cli(a->fd, "Line:             %s\n", l->name);
3112                         ast_cli(a->fd, "On Device:        %s\n", d->name);
3113                         ast_cli(a->fd, "Line Label:       %s\n", l->label);
3114                         ast_cli(a->fd, "Extension:        %s\n", S_OR(l->exten, "<not set>"));
3115                         ast_cli(a->fd, "Context:          %s\n", l->context);
3116                         ast_cli(a->fd, "CallGroup:        %s\n", ast_print_group(group_buf, sizeof(group_buf), l->callgroup));
3117                         ast_cli(a->fd, "PickupGroup:      %s\n", ast_print_group(group_buf, sizeof(group_buf), l->pickupgroup));
3118                         ast_cli(a->fd, "Language:         %s\n", S_OR(l->language, "<not set>"));
3119                         ast_cli(a->fd, "Accountcode:      %s\n", S_OR(l->accountcode, "<not set>"));
3120                         ast_cli(a->fd, "AmaFlag:          %s\n", ast_cdr_flags2str(l->amaflags));
3121                         ast_cli(a->fd, "CallerId Number:  %s\n", S_OR(l->cid_num, "<not set>"));
3122                         ast_cli(a->fd, "CallerId Name:    %s\n", S_OR(l->cid_name, "<not set>"));
3123                         ast_cli(a->fd, "Hide CallerId:    %s\n", (l->hidecallerid ? "Yes" : "No"));
3124                         ast_cli(a->fd, "CFwdAll:          %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_ALL), l->call_forward_all, "<not set>"));
3125                         ast_cli(a->fd, "CFwdBusy:         %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_BUSY), l->call_forward_busy, "<not set>"));
3126                         ast_cli(a->fd, "CFwdNoAnswer:     %s\n", S_COR((l->cfwdtype & SKINNY_CFWD_NOANSWER), l->call_forward_noanswer, "<not set>"));
3127                         ast_cli(a->fd, "VoicemailBox:     %s\n", S_OR(l->mailbox, "<not set>"));
3128                         ast_cli(a->fd, "VoicemailNumber:  %s\n", S_OR(l->vmexten, "<not set>"));
3129                         ast_cli(a->fd, "MWIblink:         %d\n", l->mwiblink);
3130                         ast_cli(a->fd, "Regextension:     %s\n", S_OR(l->regexten, "<not set>"));
3131                         ast_cli(a->fd, "Regcontext:       %s\n", S_OR(l->regcontext, "<not set>"));
3132                         ast_cli(a->fd, "MoHInterpret:     %s\n", S_OR(l->mohinterpret, "<not set>"));
3133                         ast_cli(a->fd, "MoHSuggest:       %s\n", S_OR(l->mohsuggest, "<not set>"));
3134                         ast_cli(a->fd, "Last dialed nr:   %s\n", S_OR(l->lastnumberdialed, "<no calls made yet>"));
3135                         ast_cli(a->fd, "Last CallerID:    %s\n", S_OR(l->lastcallerid, "<not set>"));
3136                         ast_cli(a->fd, "Transfer enabled: %s\n", (l->transfer ? "Yes" : "No"));
3137                         ast_cli(a->fd, "Callwaiting:      %s\n", (l->callwaiting ? "Yes" : "No"));
3138                         ast_cli(a->fd, "3Way Calling:     %s\n", (l->threewaycalling ? "Yes" : "No"));
3139                         ast_cli(a->fd, "Can forward:      %s\n", (l->cancallforward ? "Yes" : "No"));
3140                         ast_cli(a->fd, "Do Not Disturb:   %s\n", (l->dnd ? "Yes" : "No"));
3141                         ast_cli(a->fd, "NAT:              %s\n", (l->nat ? "Yes" : "No"));
3142                         ast_cli(a->fd, "immediate:        %s\n", (l->immediate ? "Yes" : "No"));
3143                         ast_cli(a->fd, "Group:            %d\n", l->group);
3144                         ast_cli(a->fd, "Conf Codecs:      ");
3145                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->confcapability);
3146                         ast_cli(a->fd, "%s\n", codec_buf);
3147                         ast_cli(a->fd, "Neg Codecs:       ");
3148                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf) - 1, l->capability);
3149                         ast_cli(a->fd, "%s\n", codec_buf);
3150                         ast_cli(a->fd, "Codec Order:      (");
3151                         print_codec_to_cli(a->fd, &l->prefs);
3152                         ast_cli(a->fd, ")\n");
3153                         ast_cli(a->fd, "\n");
3154                 }
3155         }
3156         
3157         AST_LIST_UNLOCK(&devices);
3158         return CLI_SUCCESS;
3159 }
3160
3161 /*! \brief List global settings for the Skinny subsystem. */
3162 static char *handle_skinny_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3163 {
3164         switch (cmd) {
3165         case CLI_INIT:
3166                 e->command = "skinny show settings";
3167                 e->usage =
3168                         "Usage: skinny show settings\n"
3169                         "       Lists all global configuration settings of the Skinny subsystem.\n";
3170                 return NULL;
3171         case CLI_GENERATE:
3172                 return NULL;
3173         }       
3174
3175         if (a->argc != 3)
3176                 return CLI_SHOWUSAGE;
3177
3178         ast_cli(a->fd, "\nGlobal Settings:\n");
3179         ast_cli(a->fd, "  Skinny Port:            %d\n", ntohs(bindaddr.sin_port));
3180         ast_cli(a->fd, "  Bindaddress:            %s\n", ast_inet_ntoa(bindaddr.sin_addr));
3181         ast_cli(a->fd, "  KeepAlive:              %d\n", keep_alive);
3182         ast_cli(a->fd, "  Date Format:            %s\n", date_format);
3183         ast_cli(a->fd, "  Voice Mail Extension:   %s\n", S_OR(global_vmexten, "(not set)"));
3184         ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(regcontext, "(not set)"));
3185         ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", (ast_test_flag(&global_jbconf, AST_JB_ENABLED) ? "Yes" : "No"));
3186         ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", (ast_test_flag(&global_jbconf, AST_JB_FORCED) ? "Yes" : "No"));
3187         ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
3188         ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
3189         ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
3190         ast_cli(a->fd, "  Jitterbuffer log:       %s\n", (ast_test_flag(&global_jbconf, AST_JB_LOG) ? "Yes" : "No"));
3191
3192         return CLI_SUCCESS;
3193 }
3194
3195 static struct ast_cli_entry cli_skinny[] = {
3196         AST_CLI_DEFINE(handle_skinny_show_devices, "List defined Skinny devices"),
3197         AST_CLI_DEFINE(handle_skinny_show_device, "List Skinny device information"),
3198         AST_CLI_DEFINE(handle_skinny_show_lines, "List defined Skinny lines per device"),
3199         AST_CLI_DEFINE(handle_skinny_show_line, "List Skinny line information"),
3200         AST_CLI_DEFINE(handle_skinny_show_settings, "List global Skinny settings"),
3201         AST_CLI_DEFINE(handle_skinny_set_debug, "Enable/Disable Skinny debugging"),
3202         AST_CLI_DEFINE(handle_skinny_reset, "Reset Skinny device(s)"),
3203 };
3204
3205 static void start_rtp(struct skinny_subchannel *sub)
3206 {
3207         struct skinny_line *l = sub->parent;
3208         struct skinny_device *d = l->device;
3209         int hasvideo = 0;
3210
3211         ast_mutex_lock(&sub->lock);
3212         /* Allocate the RTP */
3213         sub->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3214         if (hasvideo)
3215                 sub->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3216         
3217         if (sub->rtp && sub->owner) {
3218                 ast_channel_set_fd(sub->owner, 0, ast_rtp_fd(sub->rtp));
3219                 ast_channel_set_fd(sub->owner, 1, ast_rtcp_fd(sub->rtp));
3220         }
3221         if (hasvideo && sub->vrtp && sub->owner) {
3222                 ast_channel_set_fd(sub->owner, 2, ast_rtp_fd(sub->vrtp));
3223                 ast_channel_set_fd(sub->owner, 3, ast_rtcp_fd(sub->vrtp));
3224         }
3225         if (sub->rtp) {
3226                 ast_rtp_setqos(sub->rtp, qos.tos_audio, qos.cos_audio, "Skinny RTP");
3227                 ast_rtp_setnat(sub->rtp, l->nat);
3228         }
3229         if (sub->vrtp) {
3230                 ast_rtp_setqos(sub->vrtp, qos.tos_video, qos.cos_video, "Skinny VRTP");
3231                 ast_rtp_setnat(sub->vrtp, l->nat);
3232         }
3233         /* Set Frame packetization */
3234         if (sub->rtp)
3235                 ast_rtp_codec_setpref(sub->rtp, &l->prefs);
3236
3237         /* Create the RTP connection */
3238         transmit_connect(d, sub);
3239         ast_mutex_unlock(&sub->lock);
3240 }
3241
3242 static void *skinny_newcall(void *data)
3243 {
3244         struct ast_channel *c = data;
3245         struct skinny_subchannel *sub = c->tech_pvt;
3246         struct skinny_line *l = sub->parent;
3247         struct skinny_device *d = l->device;
3248         int res = 0;
3249
3250         ast_copy_string(l->lastnumberdialed, c->exten, sizeof(l->lastnumberdialed));
3251         ast_set_callerid(c,
3252                 l->hidecallerid ? "" : l->cid_num,
3253                 l->hidecallerid ? "" : l->cid_name,
3254                 c->cid.cid_ani ? NULL : l->cid_num);
3255         ast_setstate(c, AST_STATE_RING);
3256         if (!sub->rtp) {
3257                 start_rtp(sub);
3258         }
3259         res = ast_pbx_run(c);
3260         if (res) {
3261                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
3262                 transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
3263         }
3264         return NULL;
3265 }
3266
3267 static void *skinny_ss(void *data)
3268 {
3269         struct ast_channel *c = data;
3270         struct skinny_subchannel *sub = c->tech_pvt;
3271         struct skinny_line *l = sub->parent;
3272         struct skinny_device *d = l->device;
3273         int len = 0;
3274         int timeout = firstdigittimeout;
3275         int res = 0;
3276         int loop_pause = 100;
3277
3278         ast_verb(3, "Starting simple switch on '%s@%s'\n", l->name, d->name);
3279
3280         len = strlen(d->exten);
3281
3282         while (len < AST_MAX_EXTENSION-1) {
3283                 res = 1;  /* Assume that we will get a digit */
3284                 while (strlen(d->exten) == len){
3285                         ast_safe_sleep(c, loop_pause);
3286                         timeout -= loop_pause;
3287                         if ( (timeout -= loop_pause) <= 0){
3288                                  res = 0;
3289                                  break;
3290                         }
3291                 res = 1;
3292                 }
3293
3294                 timeout = 0;
3295                 len = strlen(d->exten);
3296
3297                 if (!ast_ignore_pattern(c->context, d->exten)) {
3298                         transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
3299                 }
3300                 if (ast_exists_extension(c, c->context, d->exten, 1, l->cid_num)) {
3301                         if (!res || !ast_matchmore_extension(c, c->context, d->exten, 1, l->cid_num)) {
3302                                 if (l->getforward) {
3303                                         /* Record this as the forwarding extension */
3304                                         set_callforwards(l, d->exten, l->getforward);
3305                                         ast_verb(3, "Setting call forward (%d) to '%s' on channel %s\n",
3306                                                         l->cfwdtype, d->exten, c->name);
3307                                         transmit_tone(d, SKINNY_DIALTONE, l->instance, sub->callid);
3308                                         transmit_lamp_indication(d, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
3309                                         transmit_displaynotify(d, "CFwd enabled", 10);
3310                                         transmit_cfwdstate(d, l);
3311                                         ast_safe_sleep(c, 500);
3312                                         ast_indicate(c, -1);
3313                                         ast_safe_sleep(c, 1000);
3314                                         memset(d->exten, 0, sizeof(d->exten));
3315                                         len = 0;
3316                                         l->getforward = 0;
3317                                         if (sub->owner && sub->owner->_state != AST_STATE_UP) {
3318                                                 ast_indicate(c, -1);
3319                                                 ast_hangup(c);
3320                                         }
3321                                         return NULL;
3322                                 } else {
3323                                         ast_copy_string(c->exten, d->exten, sizeof(c->exten));
3324                                         ast_copy_string(l->lastnumberdialed, d->exten, sizeof(l->lastnumberdialed));
3325                                         memset(d->exten, 0, sizeof(d->exten));
3326                                         skinny_newcall(c);
3327                                         return NULL;
3328                                 }
3329                         } else {
3330                                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
3331                                    so just set the timeout to matchdigittimeout and wait some more */
3332                                 timeout = matchdigittimeout;
3333                         }
3334                 } else if (res == 0) {
3335                         ast_debug(1, "Not enough digits (%s) (and no ambiguous match)...\n", d->exten);
3336                         memset(d->exten, 0, sizeof(d->exten));
3337                         if (l->hookstate == SKINNY_OFFHOOK) {
3338                                 transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
3339                         }
3340                         if (sub->owner && sub->owner->_state != AST_STATE_UP) {
3341                                 ast_indicate(c, -1);
3342                                 ast_hangup(c);
3343                         }
3344                         return NULL;
3345                 } else if (!ast_canmatch_extension(c, c->context, d->exten, 1, c->cid.cid_num) &&
3346                            ((d->exten[0] != '*') || (!ast_strlen_zero(d->exten) > 2))) {
3347                         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);
3348                         memset(d->exten, 0, sizeof(d->exten));
3349                         if (l->hookstate == SKINNY_OFFHOOK) {
3350                                 transmit_tone(d, SKINNY_REORDER, l->instance, sub->callid);
3351                                 /* hang out for 3 seconds to let congestion play */
3352                                 ast_safe_sleep(c, 3000);
3353                         }
3354                         break;
3355                 }
3356                 if (!timeout) {
3357                         timeout = gendigittimeout;
3358                 }
3359                 if (len && !ast_ignore_pattern(c->context, d->exten)) {
3360                         ast_indicate(c, -1);
3361                 }
3362         }
3363         if (c)
3364                 ast_hangup(c);
3365         memset(d->exten, 0, sizeof(d->exten));
3366         return NULL;
3367 }
3368
3369
3370
3371 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
3372 {
3373         int res = 0;
3374         int tone = 0;
3375         struct skinny_subchannel *sub = ast->tech_pvt;
3376         struct skinny_line *l = sub->parent;
3377         struct skinny_device *d = l->device;
3378
3379         if (!d->registered) {
3380                 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
3381                 return -1;
3382         }
3383
3384         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
3385                 ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
3386                 return -1;
3387         }
3388
3389         if (skinnydebug)
3390                 ast_verb(3, "skinny_call(%s)\n", ast->name);
3391
3392         if (l->dnd) {
3393                 ast_queue_control(ast, AST_CONTROL_BUSY);
3394                 return -1;
3395         }
3396
3397         if (AST_LIST_NEXT(sub,list) && !l->callwaiting) {
3398                 ast_queue_control(ast, AST_CONTROL_BUSY);
3399                 return -1;
3400         }
3401         
3402         switch (l->hookstate) {
3403         case SKINNY_OFFHOOK:
3404                 tone = SKINNY_CALLWAITTONE;
3405                 break;
3406         case SKINNY_ONHOOK:
3407                 tone = SKINNY_ALERT;
3408                 l->activesub = sub;
3409                 break;
3410         default:
3411                 ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
3412                 break;
3413         }
3414
3415         transmit_callstateonly(d, sub, SKINNY_RINGIN);
3416         transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_RINGIN);
3417         transmit_displaypromptstatus(d, "Ring-In", 0, l->instance, sub->callid);
3418         transmit_callinfo(d, ast->cid.cid_name, ast->cid.cid_num, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
3419         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3420         transmit_ringer_mode(d, SKINNY_RING_INSIDE);
3421
3422         ast_setstate(ast, AST_STATE_RINGING);
3423         ast_queue_control(ast, AST_CONTROL_RINGING);
3424         sub->outgoing = 1;
3425         return res;
3426 }
3427
3428 static int skinny_hangup(struct ast_channel *ast)
3429 {
3430         struct skinny_subchannel *sub = ast->tech_pvt;
3431         struct skinny_line *l;
3432         struct skinny_device *d;
3433         struct skinnysession *s;
3434
3435         if (!sub) {
3436                 ast_debug(1, "Asked to hangup channel not connected\n");
3437                 return 0;
3438         }
3439
3440         l = sub->parent;
3441         d = l->device;
3442         s = d->session;
3443
3444         if (skinnydebug)
3445                 ast_verb(3,"Hanging up %s/%d\n",d->name,sub->callid);
3446
3447         AST_LIST_REMOVE(&l->sub, sub, list);
3448
3449         if (d->registered) {
3450                 /* Ignoring l->type, doesn't seem relevant and previous code 
3451                    assigned rather than tested, ie always true */
3452                 if (!AST_LIST_EMPTY(&l->sub)) {
3453                         if (sub->related) {
3454                                 sub->related->related = NULL;
3455
3456                         }
3457                         if (sub == l->activesub) {      /* we are killing the active sub, but there are other subs on the line*/
3458                                 ast_verb(4,"Killing active sub %d\n", sub->callid);
3459                                 if (sub->related) {
3460                                         l->activesub = sub->related;
3461                                 } else {
3462                                         if (AST_LIST_NEXT(sub, list)) {
3463                                                 l->activesub = AST_LIST_NEXT(sub, list);
3464                                         } else {
3465                                                 l->activesub = AST_LIST_FIRST(&l->sub);
3466                                         }
3467                                 }
3468                                 //transmit_callstate(d, l->instance, SKINNY_ONHOOK, sub->callid);
3469                                 transmit_activatecallplane(d, l);
3470                                 transmit_closereceivechannel(d, sub);
3471                                 transmit_stopmediatransmission(d, sub);
3472                                 transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3473                                 transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
3474                         } else {    /* we are killing a background sub on the line with other subs*/
3475                                 ast_verb(4,"Killing inactive sub %d\n", sub->callid);
3476                                 if (AST_LIST_NEXT(sub, list)) {
3477                                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
3478                                 } else {
3479                                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3480                                 }
3481                         }
3482                 } else {                                                /* no more subs on line so make idle */
3483                         ast_verb(4,"Killing only sub %d\n", sub->callid);
3484                         l->hookstate = SKINNY_ONHOOK;
3485                         transmit_callstate(d, l->instance, SKINNY_ONHOOK, sub->callid);
3486                         l->activesub = NULL;
3487                         transmit_lamp_indication(d, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
3488                         if (sub->parent == d->activeline) {
3489                                 transmit_activatecallplane(d, l);
3490                                 transmit_closereceivechannel(d, sub);
3491                                 transmit_stopmediatransmission(d, sub);
3492                                 transmit_speaker_mode(d, SKINNY_SPEAKEROFF);
3493                                 transmit_ringer_mode(d, SKINNY_RING_OFF);
3494                                 transmit_displaymessage(d, NULL, l->instance, sub->callid); /* clear display */
3495                                 transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
3496                                 /* we should check to see if we can start the ringer if another line is ringing */
3497                         }
3498                 }
3499         }
3500         ast_mutex_lock(&sub->lock);
3501         sub->owner = NULL;
3502         ast->tech_pvt = NULL;
3503         sub->alreadygone = 0;
3504         sub->outgoing = 0;
3505         if (sub->rtp) {
3506                 ast_rtp_destroy(sub->rtp);
3507                 sub->rtp = NULL;
3508         }
3509         ast_mutex_unlock(&sub->lock);
3510         ast_free(sub);
3511         ast_module_unref(ast_module_info->self);
3512         return 0;
3513 }
3514
3515 static int skinny_answer(struct ast_channel *ast)
3516 {
3517         int res = 0;
3518         struct skinny_subchannel *sub = ast->tech_pvt;
3519         struct skinny_line *l = sub->parent;
3520         struct skinny_device *d = l->device;
3521
3522         if (sub->blindxfer) {
3523                 if (skinnydebug)
3524                         ast_debug(1, "skinny_answer(%s) on %s@%s-%d with BlindXFER, transferring\n",
3525                                 ast->name, l->name, d->name, sub->callid);
3526                 ast_setstate(ast, AST_STATE_UP);
3527                 skinny_transfer(sub);
3528                 return 0;
3529         }
3530
3531         sub->cxmode = SKINNY_CX_SENDRECV;
3532         if (!sub->rtp) {
3533                 start_rtp(sub);
3534         }
3535         if (skinnydebug)
3536                 ast_verb(1, "skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, d->name, sub->callid);
3537         if (ast->_state != AST_STATE_UP) {
3538                 ast_setstate(ast, AST_STATE_UP);
3539         }
3540
3541         transmit_tone(d, SKINNY_SILENCE, l->instance, sub->callid);
3542         /* order matters here...
3543            for some reason, transmit_callinfo must be before transmit_callstate,
3544            or you won't get keypad messages in some situations. */
3545         transmit_callinfo(d, ast->cid.cid_name, ast->cid.cid_num, l->lastnumberdialed, l->lastnumberdialed, l->instance, sub->callid, 2);
3546         transmit_callstateonly(d, sub, SKINNY_CONNECTED);
3547         transmit_selectsoftkeys(d, l->instance, sub->callid, KEYDEF_CONNECTED);
3548         transmit_dialednumber(d, l->lastnumberdialed, l->instance, sub->callid);
3549         transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
3550         l->activesub = sub;
3551         return res;
3552 }
3553
3554 /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
3555 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
3556 {
3557         struct ast_channel *ast = sub->owner;
3558         struct ast_frame *f;
3559
3560         if (!sub->rtp) {
3561                 /* We have no RTP allocated for this channel */
3562                 return &ast_null_frame;
3563         }
3564
3565         switch(ast->fdno) {
3566         case 0:
3567                 f = ast_rtp_read(sub->rtp); /* RTP Audio */
3568                 break;
3569         case 1:
3570                 f = ast_rtcp_read(sub->rtp); /* RTCP Control Channel */
3571                 break;
3572         case 2:
3573                 f = ast_rtp_read(sub->vrtp); /* RTP Video */
3574                 break;
3575         case 3:
3576                 f = ast_rtcp_read(sub->vrtp); /* RTCP Control Channel for video */
3577                 break;
3578 #if 0
3579         case 5:
3580                 /* Not yet supported */
3581                 f = ast_udptl_read(sub->udptl); /* UDPTL for T.38 */
3582                 break;
3583 #endif
3584         default:
3585                 f = &ast_null_frame;
3586         }
3587
3588         if (ast) {
3589                 /* We already hold the channel lock */
3590                 if (f->frametype == AST_FRAME_VOICE) {
3591                         if (f->subclass != ast->nativeformats) {
3592                                 ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
3593                                 ast->nativeformats = f->subclass;
3594                                 ast_set_read_format(ast, ast->readformat);
3595                                 ast_set_write_format(ast, ast->writeformat);
3596                         }
3597                 }
3598         }
3599         return f;
3600 }
3601
3602 static struct ast_frame *skinny_read(struct ast_channel *ast)
3603 {
3604         struct ast_frame *fr;
3605         struct skinny_subchannel *sub = ast->tech_pvt;
3606         ast_mutex_lock(&sub->lock);
3607         fr = skinny_rtp_read(sub);
3608         ast_mutex_unlock(&sub->lock);
3609         return fr;
3610 }
3611
3612 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
3613 {
3614         struct skinny_subchannel *sub = ast->tech_pvt;
3615         int res = 0;
3616         if (frame->frametype != AST_FRAME_VOICE) {
3617                 if (frame->frametype == AST_FRAME_IMAGE) {
3618                         return 0;
3619                 } else {
3620                         ast_log(LOG_WARNING, "Can't send %d type frames with skinny_write\n", frame->frametype);
3621                         return 0;
3622                 }
3623         } else {
3624                 if (!(frame->subclass & ast->nativeformats)) {
3625                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
3626                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
3627                         return -1;
3628                 }
3629         }
3630         if (sub) {
3631                 ast_mutex_lock(&sub->lock);
3632                 if (sub->rtp) {
3633                         res = ast_rtp_write(sub->rtp, frame);
3634                 }
3635                 ast_mutex_unlock(&sub->lock);
3636         }
3637         return res;
3638 }
3639
3640 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3641 {
3642         struct skinny_subchannel *sub = newchan->tech_pvt;
3643         ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", oldchan->name, newchan->name);
3644         if (sub->owner != oldchan) {
3645                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
3646                 return -1;
3647         }
3648         sub->owner = newchan;
3649         return 0;
3650 }
3651
3652 static int skinny_senddigit_begin(struct ast_channel *ast, char digit)
3653 {
3654         return -1; /* Start inband indications */
3655 }
3656
3657 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
3658 {
3659 #if 0
3660         struct skinny_subchannel *sub = ast->tech_pvt;
3661         struct skinny_line *l = sub->parent;
3662         struct skinny_device *d = l->device;
3663         int tmp;
3664         /* not right */
3665         sprintf(tmp, "%d", digit);
3666         transmit_tone(d, digit, l->instance, sub->callid);
3667 #endif
3668         return -1; /* Stop inband indications */
3669 }
3670
3671 static int get_devicestate(struct skinny_line *l)
3672 {
3673         struct skinny_subchannel *sub;
3674         int res = AST_DEVICE_UNKNOWN;
3675
3676         if (!l)
3677                 res = AST_DEVICE_INVALID;
3678         else if (!l->device)
3679                 res = AST_DEVICE_UNAVAILABLE;
3680         else if (l->dnd)
3681                 res = AST_DEVICE_BUSY;
3682         else {
3683                 if (l->hookstate == SKINNY_ONHOOK) {
3684                         res = AST_DEVICE_NOT_INUSE;
3685                 } else {
3686                         res = AST_DEVICE_INUSE;
3687                 }
3688
3689                 AST_LIST_TRAVERSE(&l->sub, sub, list) {
3690                         if (sub->onhold) {
3691                                 res = AST_DEVICE_ONHOLD;
3692                                 break;
3693                         }
3694                 }
3695         }
3696
3697         return res;
3698 }
3699
3700 static char *control2str(int ind) {
3701         char *tmp;
3702
3703         switch (ind) {
3704         case AST_CONTROL_HANGUP:
3705                 return "Other end has hungup";
3706         case AST_CONTROL_RING:
3707                 return "Local ring";
3708         case AST_CONTROL_RINGING:
3709                 return "Remote end is ringing";
3710         case AST_CONTROL_ANSWER:
3711                 return "Remote end has answered";