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