4edbc4ab973641e96316d192e11f43fb63397c16
[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(struct skinny_device *d, struct skinny_req *req)
2105 {
2106         struct skinnysession *s = d->session;
2107         int res = 0;
2108
2109         if (!s) {
2110                 ast_log(LOG_WARNING, "Asked to transmit to a non-existent session!\n");
2111                 return -1;
2112         }
2113
2114         ast_mutex_lock(&s->lock);
2115
2116         SKINNY_DEVONLY(if (skinnydebug>1) ast_verb(4, "Transmitting %s to %s\n", message2str(req->e), d->name);)
2117
2118         if ((letohl(req->len) > SKINNY_MAX_PACKET) || (letohl(req->len) < 0)) {
2119                 ast_log(LOG_WARNING, "transmit_response: the length of the request (%d) is out of bounds (%d)\n", letohl(req->len), SKINNY_MAX_PACKET);
2120                 ast_mutex_unlock(&s->lock);
2121                 return -1;
2122         }
2123
2124         memset(s->outbuf, 0, sizeof(s->outbuf));
2125         memcpy(s->outbuf, req, skinny_header_size);
2126         memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
2127
2128         res = write(s->fd, s->outbuf, letohl(req->len)+8);
2129         
2130         if (res != letohl(req->len)+8) {
2131                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
2132                 if (res == -1) {
2133                         if (skinnydebug)
2134                                 ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
2135                         skinny_unregister(NULL, s);
2136                 }
2137                 
2138         }
2139         
2140         ast_free(req);
2141         ast_mutex_unlock(&s->lock);
2142         return 1;
2143 }
2144
2145 static void transmit_speaker_mode(struct skinny_device *d, int mode)
2146 {
2147         struct skinny_req *req;
2148
2149         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
2150                 return;
2151
2152         req->data.setspeaker.mode = htolel(mode);
2153         transmit_response(d, req);
2154 }
2155 /*
2156 static void transmit_microphone_mode(struct skinny_device *d, int mode)
2157 {
2158         struct skinny_req *req;
2159
2160         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
2161                 return;
2162
2163         req->data.setmicrophone.mode = htolel(mode);
2164         transmit_response(d, req);
2165 }
2166 */
2167
2168 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)
2169 {
2170         struct skinny_req *req;
2171
2172         /* We should not be able to get here without a device */
2173         if (!d)
2174                 return;
2175
2176         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
2177                 return;
2178
2179         if (skinnydebug)
2180                         ast_verb(1, "Setting Callinfo to %s(%s) from %s(%s) on %s(%d)\n", fromname, fromnum, toname, tonum, d->name, instance);
2181
2182         if (fromname) {
2183                 ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
2184         }
2185         if (fromnum) {
2186                 ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
2187         }
2188         if (toname) {
2189                 ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
2190         }
2191         if (tonum) {
2192                 ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
2193         }
2194         req->data.callinfo.instance = htolel(instance);
2195         req->data.callinfo.reference = htolel(callid);
2196         req->data.callinfo.type = htolel(calltype);
2197         transmit_response(d, req);
2198 }
2199
2200 static void transmit_connect(struct skinny_device *d, struct skinny_subchannel *sub)
2201 {
2202         struct skinny_req *req;
2203         struct skinny_line *l = sub->parent;
2204         struct ast_format_list fmt;
2205
2206         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
2207                 return;
2208
2209         fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
2210
2211         req->data.openreceivechannel.conferenceId = htolel(sub->callid);
2212         req->data.openreceivechannel.partyId = htolel(sub->callid);
2213         req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
2214         req->data.openreceivechannel.capability = htolel(codec_ast2skinny(fmt.bits));
2215         req->data.openreceivechannel.echo = htolel(0);
2216         req->data.openreceivechannel.bitrate = htolel(0);
2217         transmit_response(d, req);
2218 }
2219
2220 static void transmit_start_tone(struct skinny_device *d, int tone, int instance, int reference)
2221 {
2222         struct skinny_req *req;
2223         if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
2224                 return;
2225         req->data.starttone.tone = htolel(tone);
2226         req->data.starttone.instance = htolel(instance);
2227         req->data.starttone.reference = htolel(reference);
2228         transmit_response(d, req);
2229 }
2230
2231 static void transmit_stop_tone(struct skinny_device *d, int instance, int reference)
2232 {
2233         struct skinny_req *req;
2234         if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
2235                 return;
2236         req->data.stoptone.instance = htolel(instance);
2237         req->data.stoptone.reference = htolel(reference);
2238         transmit_response(d, req);
2239 }
2240
2241 static void transmit_selectsoftkeys(struct skinny_device *d, int instance, int callid, int softkey)
2242 {
2243         struct skinny_req *req;
2244
2245         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
2246                 return;
2247
2248         req->data.selectsoftkey.instance = htolel(instance);
2249         req->data.selectsoftkey.reference = htolel(callid);
2250         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
2251         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
2252         transmit_response(d, req);
2253 }
2254
2255 static void transmit_lamp_indication(struct skinny_device *d, int stimulus, int instance, int indication)
2256 {
2257         struct skinny_req *req;
2258
2259         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
2260                 return;
2261
2262         req->data.setlamp.stimulus = htolel(stimulus);
2263         req->data.setlamp.stimulusInstance = htolel(instance);
2264         req->data.setlamp.deviceStimulus = htolel(indication);
2265         transmit_response(d, req);
2266 }
2267
2268 static void transmit_ringer_mode(struct skinny_device *d, int mode)
2269 {
2270         struct skinny_req *req;
2271
2272         if (skinnydebug)
2273                 ast_verb(1, "Setting ringer mode to '%d'.\n", mode);
2274
2275         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
2276                 return;
2277
2278         req->data.setringer.ringerMode = htolel(mode);
2279         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
2280            Note: The phone will always show as ringing on the display.
2281
2282            1: phone will audibly ring over and over
2283            2: phone will audibly ring only once
2284            any other value, will NOT cause the phone to audibly ring
2285         */
2286         req->data.setringer.unknown1 = htolel(1);
2287         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
2288            Perhaps a packet capture can shed some light on this. */
2289         req->data.setringer.unknown2 = htolel(1);
2290         transmit_response(d, req);
2291 }
2292
2293 static void transmit_clear_display_message(struct skinny_device *d, int instance, int reference)
2294 {
2295         struct skinny_req *req;
2296         if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
2297                 return;
2298
2299         //what do we want hear CLEAR_DISPLAY_MESSAGE or CLEAR_PROMPT_STATUS???
2300         //if we are clearing the display, it appears there is no instance and refernece info (size 0)
2301         //req->data.clearpromptstatus.lineInstance = instance;
2302         //req->data.clearpromptstatus.callReference = reference;
2303
2304         if (skinnydebug)
2305                 ast_verb(1, "Clearing Display\n");
2306         transmit_response(d, req);
2307 }
2308
2309 /* This function is not currently used, but will be (wedhorn)*/
2310 /* static void transmit_display_message(struct skinny_device *d, const char *text, int instance, int reference)
2311 {
2312         struct skinny_req *req;
2313
2314         if (text == 0) {
2315                 ast_verb(1, "Bug, Asked to display empty message\n");
2316                 return;
2317         }
2318
2319         if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
2320                 return;
2321
2322         ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
2323         if (skinnydebug)
2324                 ast_verb(1, "Displaying message '%s'\n", req->data.displaytext.text);
2325         transmit_response(d, req);
2326 } */
2327
2328 static void transmit_displaynotify(struct skinny_device *d, const char *text, int t)
2329 {
2330         struct skinny_req *req;
2331
2332         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
2333                 return;
2334
2335         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
2336         req->data.displaynotify.displayTimeout = htolel(t);
2337
2338         if (skinnydebug)
2339                 ast_verb(1, "Displaying notify '%s'\n", text);
2340
2341         transmit_response(d, req);
2342 }
2343
2344 static void transmit_displaypromptstatus(struct skinny_device *d, const char *text, int t, int instance, int callid)
2345 {
2346         struct skinny_req *req;
2347
2348         if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
2349                 return;
2350
2351         ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
2352         req->data.displaypromptstatus.messageTimeout = htolel(t);
2353         req->data.displaypromptstatus.lineInstance = htolel(instance);
2354         req->data.displaypromptstatus.callReference = htolel(callid);
2355
2356         if (skinnydebug)
2357                 ast_verb(1, "Displaying Prompt Status '%s'\n", text);
2358
2359         transmit_response(d, req);
2360 }
2361
2362 static void transmit_clearpromptmessage(struct skinny_device *d, int instance, int callid)
2363 {
2364         struct skinny_req *req;
2365
2366         if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
2367                 return;
2368
2369         req->data.clearpromptstatus.lineInstance = htolel(instance);
2370         req->data.clearpromptstatus.callReference = htolel(callid);
2371
2372         if (skinnydebug)
2373                 ast_verb(1, "Clearing Prompt\n");
2374
2375         transmit_response(d, req);
2376 }
2377
2378 static void transmit_dialednumber(struct skinny_device *d, const char *text, int instance, int callid)
2379 {
2380         struct skinny_req *req;
2381
2382         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
2383                 return;
2384
2385         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
2386         req->data.dialednumber.lineInstance = htolel(instance);
2387         req->data.dialednumber.callReference = htolel(callid);
2388
2389         transmit_response(d, req);
2390 }
2391
2392 static void transmit_closereceivechannel(struct skinny_device *d, struct skinny_subchannel *sub)
2393 {
2394         struct skinny_req *req;
2395
2396         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2397                 return;
2398
2399         req->data.closereceivechannel.conferenceId = htolel(0);
2400         req->data.closereceivechannel.partyId = htolel(sub->callid);
2401         transmit_response(d, req);
2402 }
2403
2404 static void transmit_stopmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub)
2405 {
2406         struct skinny_req *req;
2407
2408         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2409                 return;
2410
2411         req->data.stopmedia.conferenceId = htolel(0);
2412         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2413         transmit_response(d, req);
2414 }
2415
2416 static void transmit_startmediatransmission(struct skinny_device *d, struct skinny_subchannel *sub, struct sockaddr_in dest, struct ast_format_list fmt)
2417 {
2418         struct skinny_req *req;
2419
2420         if (!(req = req_alloc(sizeof(struct start_media_transmission_message), START_MEDIA_TRANSMISSION_MESSAGE)))
2421                 return;
2422
2423         req->data.startmedia.conferenceId = htolel(sub->callid);
2424         req->data.startmedia.passThruPartyId = htolel(sub->callid);
2425         req->data.startmedia.remoteIp = dest.sin_addr.s_addr;
2426         req->data.startmedia.remotePort = htolel(ntohs(dest.sin_port));
2427         req->data.startmedia.packetSize = htolel(fmt.cur_ms);
2428         req->data.startmedia.payloadType = htolel(codec_ast2skinny(fmt.bits));
2429         req->data.startmedia.qualifier.precedence = htolel(127);
2430         req->data.startmedia.qualifier.vad = htolel(0);
2431         req->data.startmedia.qualifier.packets = htolel(0);
2432         req->data.startmedia.qualifier.bitRate = htolel(0);
2433         transmit_response(d, req);
2434 }
2435
2436 static void transmit_activatecallplane(struct skinny_device *d, struct skinny_line *l)
2437 {
2438         struct skinny_req *req;
2439
2440         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2441                 return;
2442
2443         req->data.activatecallplane.lineInstance = htolel(l->instance);
2444         transmit_response(d, req);
2445 }
2446
2447 static void transmit_callstate(struct skinny_device *d, int buttonInstance, unsigned callid, int state)
2448 {
2449         struct skinny_req *req;
2450
2451         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
2452                 return;
2453
2454         req->data.callstate.callState = htolel(state);
2455         req->data.callstate.lineInstance = htolel(buttonInstance);
2456         req->data.callstate.callReference = htolel(callid);
2457         transmit_response(d, req);
2458 }
2459
2460 static void transmit_cfwdstate(struct skinny_device *d, struct skinny_line *l)
2461 {
2462         struct skinny_req *req;
2463         int anyon = 0;
2464
2465         if (!(req = req_alloc(sizeof(struct forward_stat_message), FORWARD_STAT_MESSAGE)))
2466                 return;
2467
2468         if (l->cfwdtype & SKINNY_CFWD_ALL) {
2469                 if (!ast_strlen_zero(l->call_forward_all)) {
2470                         ast_copy_string(req->data.forwardstat.fwdallnum, l->call_forward_all, sizeof(req->data.forwardstat.fwdallnum));
2471                         req->data.forwardstat.fwdall = htolel(1);
2472                         anyon++;
2473                 } else {
2474                         req->data.forwardstat.fwdall = htolel(0);
2475                 }
2476         }
2477         if (l->cfwdtype & SKINNY_CFWD_BUSY) {
2478                 if (!ast_strlen_zero(l->call_forward_busy)) {
2479                         ast_copy_string(req->data.forwardstat.fwdbusynum, l->call_forward_busy, sizeof(req->data.forwardstat.fwdbusynum));
2480                         req->data.forwardstat.fwdbusy = htolel(1);
2481                         anyon++;
2482                 } else {
2483                         req->data.forwardstat.fwdbusy = htolel(0);
2484                 }
2485         }
2486         if (l->cfwdtype & SKINNY_CFWD_NOANSWER) {
2487                 if (!ast_strlen_zero(l->call_forward_noanswer)) {
2488                         ast_copy_string(req->data.forwardstat.fwdnoanswernum, l->call_forward_noanswer, sizeof(req->data.forwardstat.fwdnoanswernum));
2489                         req->data.forwardstat.fwdnoanswer = htolel(1);
2490                         anyon++;
2491                 } else {
2492                         req->data.forwardstat.fwdnoanswer = htolel(0);
2493                 }
2494         }
2495         req->data.forwardstat.lineNumber = htolel(l->instance);
2496         if (anyon)
2497                 req->data.forwardstat.activeforward = htolel(7);
2498         else
2499                 req->data.forwardstat.activeforward = htolel(0);
2500
2501         transmit_response(d, req);
2502 }
2503
2504 static void transmit_speeddialstatres(struct skinny_device *d, struct skinny_speeddial *sd)
2505 {
2506         struct skinny_req *req;
2507
2508         if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
2509                 return;
2510
2511         req->data.speeddialreq.speedDialNumber = htolel(sd->instance);
2512         ast_copy_string(req->data.speeddial.speedDialDirNumber, sd->exten, sizeof(req->data.speeddial.speedDialDirNumber));
2513         ast_copy_string(req->data.speeddial.speedDialDisplayName, sd->label, sizeof(req->data.speeddial.speedDialDisplayName));
2514
2515         transmit_response(d, req);
2516 }
2517
2518 static void transmit_linestatres(struct skinny_device *d, struct skinny_line *l)
2519 {
2520         struct skinny_req *req;
2521
2522         if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
2523                 return;
2524
2525         req->data.linestat.lineNumber = letohl(l->instance);
2526         memcpy(req->data.linestat.lineDirNumber, l->name, sizeof(req->data.linestat.lineDirNumber));
2527         memcpy(req->data.linestat.lineDisplayName, l->label, sizeof(req->data.linestat.lineDisplayName));
2528         transmit_response(d, req);
2529 }
2530
2531 static void transmit_definetimedate(struct skinny_device *d)
2532 {
2533         struct skinny_req *req;
2534         struct timeval now = ast_tvnow();
2535         struct ast_tm cmtime;
2536
2537         if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
2538                 return;
2539
2540         ast_localtime(&now, &cmtime, NULL);
2541         req->data.definetimedate.year = htolel(cmtime.tm_year+1900);
2542         req->data.definetimedate.month = htolel(cmtime.tm_mon+1);
2543         req->data.definetimedate.dayofweek = htolel(cmtime.tm_wday);
2544         req->data.definetimedate.day = htolel(cmtime.tm_mday);
2545         req->data.definetimedate.hour = htolel(cmtime.tm_hour);
2546         req->data.definetimedate.minute = htolel(cmtime.tm_min);
2547         req->data.definetimedate.seconds = htolel(cmtime.tm_sec);
2548         req->data.definetimedate.milliseconds = htolel(cmtime.tm_usec / 1000);
2549         req->data.definetimedate.timestamp = htolel(now.tv_sec);
2550         transmit_response(d, req);
2551 }
2552
2553 static void transmit_versionres(struct skinny_device *d)
2554 {
2555         struct skinny_req *req;
2556         if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
2557                 return;
2558
2559         ast_copy_string(req->data.version.version, d->version_id, sizeof(req->data.version.version));
2560         transmit_response(d, req);
2561 }
2562
2563 static void transmit_serverres(struct skinny_device *d)
2564 {
2565         struct skinny_req *req;
2566         if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
2567                 return;
2568
2569         memcpy(req->data.serverres.server[0].serverName, ourhost,
2570                         sizeof(req->data.serverres.server[0].serverName));
2571         req->data.serverres.serverListenPort[0] = htolel(ourport);
2572         req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
2573         transmit_response(d, req);
2574 }
2575
2576 static void transmit_softkeysetres(struct skinny_device *d)
2577 {
2578         struct skinny_req *req;
2579         int i;
2580         int x;
2581         int y;
2582         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
2583
2584         if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
2585                 return;
2586
2587         req->data.softkeysets.softKeySetOffset = htolel(0);
2588         req->data.softkeysets.softKeySetCount = htolel(11);
2589         req->data.softkeysets.totalSoftKeySetCount = htolel(11);
2590         for (x = 0; x < sizeof(soft_key_default_definitions) / sizeof(struct soft_key_definitions); x++) {
2591                 const uint8_t *defaults = softkeymode->defaults;
2592                 /* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
2593                    This will have to do for now. */
2594                 for (y = 0; y < softkeymode->count; y++) {
2595                         for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
2596                                 if (defaults[y] == i+1) {
2597                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = (i+1);
2598                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyInfoIndex[y] = htoles(i+301);
2599                                         if (skinnydebug)        
2600                                                 ast_verbose("softKeySetDefinition : softKeyTemplateIndex: %d softKeyInfoIndex: %d\n", i+1, i+301);
2601                                 }
2602                         }
2603                 }
2604                 softkeymode++;
2605         }
2606         transmit_response(d, req);
2607 }
2608
2609 static void transmit_softkeytemplateres(struct skinny_device *d)
2610 {
2611         struct skinny_req *req;
2612         if (!(req = req_alloc(sizeof(struct soft_key_template_res_message), SOFT_KEY_TEMPLATE_RES_MESSAGE)))
2613                 return;
2614
2615         req->data.softkeytemplate.softKeyOffset = htolel(0);
2616         req->data.softkeytemplate.softKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
2617         req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
2618         memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
2619                 soft_key_template_default,
2620                 sizeof(soft_key_template_default));
2621         transmit_response(d, req);
2622 }
2623
2624
2625 static int skinny_extensionstate_cb(char *context, char *exten, int state, void *data)
2626 {
2627         struct skinny_speeddial *sd = data;
2628         struct skinny_device *d = sd->parent;
2629         char hint[AST_MAX_EXTENSION];
2630
2631         if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, sd->context, sd->exten)) {
2632                 /* If they are not registered, we will override notification and show no availability */
2633                 if (ast_device_state(hint) == AST_DEVICE_UNAVAILABLE) {
2634                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_FLASH);
2635                         transmit_callstate(d, sd->instance, SKINNY_ONHOOK, 0);
2636                 }
2637         } else {
2638                 switch (state) {
2639                 case AST_EXTENSION_DEACTIVATED: /* Retry after a while */
2640                 case AST_EXTENSION_REMOVED:     /* Extension is gone */
2641                         ast_verb(2, "Extension state: Watcher for hint %s %s. Notify Device %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", d->name);
2642                         sd->stateid = -1;
2643                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
2644                         transmit_callstate(d, sd->instance, SKINNY_ONHOOK, 0);
2645                         break;
2646                 case AST_EXTENSION_RINGING:
2647                 case AST_EXTENSION_UNAVAILABLE:
2648                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_BLINK);
2649                         transmit_callstate(d, sd->instance, SKINNY_RINGIN, 0);
2650                         break;
2651                 case AST_EXTENSION_BUSY: /* callstate = SKINNY_BUSY wasn't wanting to work - I'll settle for this */
2652                 case AST_EXTENSION_INUSE:
2653                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_ON);
2654                         transmit_callstate(d, sd->instance, SKINNY_CALLREMOTEMULTILINE, 0);
2655                         break;
2656                 case AST_EXTENSION_ONHOLD:
2657                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_WINK);
2658                         transmit_callstate(d, sd->instance, SKINNY_HOLD, 0);
2659                         break;
2660                 case AST_EXTENSION_NOT_INUSE:
2661                 default:
2662                         transmit_lamp_indication(d, STIMULUS_LINE, sd->instance, SKINNY_LAMP_OFF);
2663                         transmit_callstate(d, sd->instance, SKINNY_ONHOOK, 0);
2664                         break;
2665                 }
2666         }
2667
2668         sd->laststate = state;
2669
2670         return 0;
2671 }
2672
2673 static void update_connectedline(struct skinny_subchannel *sub, const void *data, size_t datalen)
2674 {
2675         struct ast_channel *c = sub->owner;
2676         struct skinny_line *l = sub->parent;
2677         struct skinny_device *d = l->device;
2678
2679         if (!c->caller.id.number.valid
2680                 || ast_strlen_zero(c->caller.id.number.str)
2681                 || !c->connected.id.number.valid
2682                 || ast_strlen_zero(c->connected.id.number.str))
2683                 return;
2684
2685         if (sub->owner->_state == AST_STATE_UP) {
2686                 transmit_callstate(d, l->instance, sub->callid, SKINNY_CONNECTED);
2687                 transmit_displaypromptstatus(d, "Connected", 0, l->instance, sub->callid);
2688                 if (sub->outgoing)
2689                         transmit_callinfo(d,
2690                                 S_COR(c->connected.id.name.valid, c->connected.id.name.str, ""),
2691                                 c->connected.id.number.str,
2692                                 l->cid_name, l->cid_num, l->instance, sub->callid, 1);
2693                 else
2694                         transmit_callinfo(d, l->cid_name, l->cid_num,
2695                                 S_COR(c->connected.id.name.valid, c->connected.id.name.str, ""),
2696                                 c->connected.id.number.str,
2697                                 l->instance, sub->callid, 2);
2698         } else {
2699                 if (sub->outgoing) {
2700                         transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGIN);
2701                         transmit_displaypromptstatus(d, "Ring-In", 0, l->instance, sub->callid);
2702                         transmit_callinfo(d,
2703                                 S_COR(c->connected.id.name.valid, c->connected.id.name.str, ""),
2704                                 c->connected.id.number.str,
2705                                 l->cid_name, l->cid_num, l->instance, sub->callid, 1);
2706                 } else {
2707                         if (!sub->ringing) {
2708                                 transmit_callstate(d, l->instance, sub->callid, SKINNY_RINGOUT);
2709                                 transmit_displaypromptstatus(d, "Ring-Out", 0, l->instance, sub->callid);
2710                                 sub->ringing = 1;
2711                         } else {
2712                                 transmit_callstate(d, l->instance, sub->callid, SKINNY_PROGRESS);
2713                                 transmit_displaypromptstatus(d, "Call Progress", 0, l->instance, sub->callid);
2714                                 sub->progress = 1;
2715                         }
2716
2717                         transmit_callinfo(d, l->cid_name, l->cid_num,
2718                                 S_COR(c->connected.id.name.valid, c->connected.id.name.str, ""),
2719                                 c->connected.id.number.str,
2720                                 l->instance, sub->callid, 2);
2721                 }
2722         }
2723 }
2724
2725 static void mwi_event_cb(const struct ast_event *event, void *userdata)
2726 {
2727         struct skinny_line *l = userdata;
2728         struct skinny_device *d = l->device;
2729         if (d) {
2730                 struct skinnysession *s = d->session;
2731                 struct skinny_line *l2;
2732                 int new_msgs = 0;
2733                 int dev_msgs = 0;
2734
2735                 if (s) {
2736                         if (event) {
2737                                 l->newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
2738                         }
2739
2740                         if (l->newmsgs) {
2741                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2742                         } else {
2743                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
2744                         }
2745
2746                         /* find out wether the device lamp should be on or off */
2747                         AST_LIST_TRAVERSE(&d->lines, l2, list) {
2748                                 if (l2->newmsgs) {
2749                                         dev_msgs++;
2750                                 }
2751                         }
2752
2753                         if (dev_msgs) {
2754                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, d->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
2755                         } else {
2756                                 transmit_lamp_indication(d, STIMULUS_VOICEMAIL, 0, SKINNY_LAMP_OFF);
2757                         }
2758                         ast_verb(3, "Skinny mwi_event_cb found %d new messages\n", new_msgs);
2759                 }
2760         }
2761 }
2762
2763 /* I do not believe skinny can deal with video.
2764    Anyone know differently? */
2765 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
2766 static enum ast_rtp_glue_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
2767 {
2768         struct skinny_subchannel *sub = NULL;
2769
2770         if (!(sub = c->tech_pvt) || !(sub->vrtp))
2771                 return AST_RTP_GLUE_RESULT_FORBID;
2772
2773         ao2_ref(sub->vrtp, +1);
2774         *instance = sub->vrtp;
2775
2776         return AST_RTP_GLUE_RESULT_REMOTE;
2777 }
2778
2779 static enum ast_rtp_glue_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp_instance **instance)
2780 {
2781         struct skinny_subchannel *sub = NULL;
2782         struct skinny_line *l;
2783         enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_REMOTE;
2784
2785         if (skinnydebug)
2786                 ast_verb(1, "skinny_get_rtp_peer() Channel = %s\n", c->name);
2787
2788
2789         if (!(sub = c->tech_pvt))
2790                 return AST_RTP_GLUE_RESULT_FORBID;
2791
2792         ast_mutex_lock(&sub->lock);
2793
2794         if (!(sub->rtp)){
2795                 ast_mutex_unlock(&sub->lock);
2796                 return AST_RTP_GLUE_RESULT_FORBID;
2797         }
2798
2799         ao2_ref(sub->rtp, +1);
2800         *instance = sub->rtp;
2801
2802         l = sub->parent;
2803
2804         if (!l->directmedia || l->nat){
2805                 res = AST_RTP_GLUE_RESULT_LOCAL;
2806                 if (skinnydebug)
2807                         ast_verb(1, "skinny_get_rtp_peer() Using AST_RTP_GLUE_RESULT_LOCAL \n");
2808         }
2809
2810         ast_mutex_unlock(&sub->lock);
2811
2812         return res;
2813
2814 }
2815
2816 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)
2817 {
2818         struct skinny_subchannel *sub;
2819         struct skinny_line *l;
2820         struct skinny_device *d;
2821         struct ast_format_list fmt;
2822         struct sockaddr_in us = { 0, };
2823         struct sockaddr_in them = { 0, };
2824         struct ast_sockaddr them_tmp;
2825         struct ast_sockaddr us_tmp;
2826         
2827         sub = c->tech_pvt;
2828
2829         if (c->_state != AST_STATE_UP)
2830                 return 0;
2831
2832         if (!sub) {
2833                 return -1;
2834         }
2835
2836         l = sub->parent;
2837         d = l->device;
2838
2839         if (rtp){
2840                 ast_rtp_instance_get_remote_address(rtp, &them_tmp);
2841                 ast_sockaddr_to_sin(&them_tmp, &them);
2842
2843                 /* Shutdown any early-media or previous media on re-invite */
2844                 transmit_stopmediatransmission(d, sub);
2845                 
2846                 if (skinnydebug)
2847                         ast_verb(1, "Peerip = %s:%d\n", ast_inet_ntoa(them.sin_addr), ntohs(them.sin_port));
2848
2849                 fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
2850
2851                 if (skinnydebug)
2852                         ast_verb(1, "Setting payloadType to '%s' (%d ms)\n", ast_getformatname(fmt.bits), fmt.cur_ms);
2853
2854                 if (!(l->directmedia) || (l->nat)){
2855                         ast_rtp_instance_get_local_address(rtp, &us_tmp);
2856                         ast_sockaddr_to_sin(&us_tmp, &us);
2857                         us.sin_addr.s_addr = us.sin_addr.s_addr ? us.sin_addr.s_addr : d->ourip.s_addr;
2858                         transmit_startmediatransmission(d, sub, us, fmt);
2859                 } else {
2860                         transmit_startmediatransmission(d, sub, them, fmt);
2861                 }
2862
2863                 return 0;
2864         }
2865         /* Need a return here to break the bridge */
2866         return 0;
2867 }
2868
2869 static struct ast_rtp_glue skinny_rtp_glue = {
2870         .type = "Skinny",
2871         .get_rtp_info = skinny_get_rtp_peer,
2872         .get_vrtp_info = skinny_get_vrtp_peer,
2873         .update_peer = skinny_set_rtp_peer,
2874 };
2875
2876 static char *handle_skinny_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2877 {
2878         switch (cmd) {
2879         case CLI_INIT:
2880 #ifdef SKINNY_DEVMODE
2881                 e->command = "skinny set debug {off|on|packet}";
2882                 e->usage =
2883                         "Usage: skinny set debug {off|on|packet}\n"
2884                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2885 #else
2886                 e->command = "skinny set debug {off|on}";
2887                 e->usage =
2888                         "Usage: skinny set debug {off|on}\n"
2889                         "       Enables/Disables dumping of Skinny packets for debugging purposes\n";
2890 #endif
2891                 return NULL;
2892         case CLI_GENERATE:
2893                 return NULL;
2894         }
2895         
2896         if (a->argc != e->args)
2897                 return CLI_SHOWUSAGE;
2898
2899         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
2900                 skinnydebug = 1;
2901                 ast_cli(a->fd, "Skinny Debugging Enabled\n");
2902                 return CLI_SUCCESS;
2903         } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
2904                 skinnydebug = 0;
2905                 ast_cli(a->fd, "Skinny Debugging Disabled\n");
2906                 return CLI_SUCCESS;
2907 #ifdef SKINNY_DEVMODE
2908         } else if (!strncasecmp(a->argv[e->args - 1], "packet", 6)) {
2909                 skinnydebug = 2;
2910                 ast_cli(a->fd, "Skinny Debugging Enabled including Packets\n");
2911                 return CLI_SUCCESS;
2912 #endif
2913         } else {
2914                 return CLI_SHOWUSAGE;
2915         }
2916 }
2917
2918 static char *handle_skinny_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2919 {
2920         switch (cmd) {
2921         case CLI_INIT:
2922                 e->command = "skinny reload";
2923                 e->usage =
2924                         "Usage: skinny reload\n"
2925                         "       Reloads the chan_skinny configuration\n";
2926                 return NULL;
2927         case CLI_GENERATE:
2928                 return NULL;
2929         }
2930         
2931         if (a->argc != e->args)
2932                 return CLI_SHOWUSAGE;
2933
2934         skinny_reload();
2935         return CLI_SUCCESS;
2936
2937 }
2938
2939 static char *complete_skinny_devices(const char *word, int state)
2940 {
2941         struct skinny_device *d;
2942         char *result = NULL;
2943         int wordlen = strlen(word), which = 0;
2944
2945         AST_LIST_TRAVERSE(&devices, d, list) {
2946                 if (!strncasecmp(word, d->id, wordlen) && ++which > state)
2947                         result = ast_strdup(d->id);
2948         }
2949
2950         return result;
2951 }
2952
2953 static char *complete_skinny_show_device(const char *line, const char *word, int pos, int state)
2954 {
2955         return (pos == 3 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2956 }
2957
2958 static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
2959 {
2960         return (pos == 2 ? ast_strdup(complete_skinny_devices(word, state)) : NULL);
2961 }
2962
2963 static char *complete_skinny_show_line(const char *line, const char *word, int pos, int state)
2964 {
2965         struct skinny_device *d;
2966         struct skinny_line *l;
2967         char *result = NULL;
2968         int wordlen = strlen(word), which = 0;
2969
2970         if (pos != 3)
2971                 return NULL;
2972         
2973         AST_LIST_TRAVERSE(&devices, d, list) {
2974                 AST_LIST_TRAVERSE(&d->lines, l, list) {
2975                         if (!strncasecmp(word, l->name, wordlen) && ++which > state)
2976                                 result = ast_strdup(l->name);
2977                 }
2978         }
2979
2980         return result;
2981 }
2982
2983 static char *handle_skinny_reset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2984 {
2985         struct skinny_device *d;
2986         struct skinny_req *req;
2987
2988         switch (cmd) {
2989         case CLI_INIT:
2990                 e->command = "skinny reset";
2991                 e->usage =
2992                         "Usage: skinny reset <DeviceId|DeviceName|all> [restart]\n"
2993                         "       Causes a Skinny device to reset itself, optionally with a full restart\n";
2994                 return NULL;
2995         case CLI_GENERATE:
2996                 return complete_skinny_reset(a->line, a->word, a->pos, a->n);
2997         }
2998
2999         if (a->argc < 3 || a->argc > 4)
3000                 return CLI_SHOWUSAGE;
3001
3002         AST_LIST_LOCK(&devices);
3003         AST_LIST_TRAVERSE(&devices, d, list) {
3004                 int fullrestart = 0;
3005                 if (!strcasecmp(a->argv[2], d->id) || !strcasecmp(a->argv[2], d->name) || !strcasecmp(a->argv[2], "all")) {
3006                         if (!(d->session))
3007                                 continue;
3008
3009                         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
3010                                 continue;
3011
3012                         if (a->argc == 4 && !strcasecmp(a->argv[3], "restart"))
3013                                 fullrestart = 1;
3014
3015                         if (fullrestart)
3016                                 req->data.reset.resetType = 2;
3017                         else
3018                                 req->data.reset.resetType = 1;
3019
3020                         ast_verb(3, "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
3021                         transmit_response(d, req);
3022                 }
3023         }
3024         AST_LIST_UNLOCK(&devices);
3025         return CLI_SUCCESS;
3026 }
3027
3028 static char *device2str(int type)
3029 {
3030         char *tmp;
3031
3032         switch (type) {
3033         case SKINNY_DEVICE_NONE:
3034                 return "No Device";
3035         case SKINNY_DEVICE_30SPPLUS:
3036                 return "30SP Plus";
3037         case SKINNY_DEVICE_12SPPLUS:
3038                 return "12SP Plus";
3039         case SKINNY_DEVICE_12SP:
3040                 return "12SP";
3041         case SKINNY_DEVICE_12:
3042                 return "12";
3043         case SKINNY_DEVICE_30VIP:
3044                 return "30VIP";
3045         case SKINNY_DEVICE_7910:
3046                 return "7910";
3047         case SKINNY_DEVICE_7960:
3048                 return "7960";
3049         case SKINNY_DEVICE_7940:
3050                 return "7940";
3051         case SKINNY_DEVICE_7935:
3052                 return "7935";
3053         case SKINNY_DEVICE_ATA186:
3054                 return "ATA186";
3055         case SKINNY_DEVICE_7941:
3056                 return "7941";
3057         case SKINNY_DEVICE_7971:
3058                 return "7971";
3059         case SKINNY_DEVICE_7914:
3060                 return "7914";
3061         case SKINNY_DEVICE_7985:
3062                 return "7985";
3063         case SKINNY_DEVICE_7911:
3064                 return "7911";
3065         case SKINNY_DEVICE_7961GE:
3066                 return "7961GE";
3067         case SKINNY_DEVICE_7941GE:
3068                 return "7941GE";
3069         case SKINNY_DEVICE_7931:
3070                 return "7931";
3071         case SKINNY_DEVICE_7921:
3072                 return "7921";
3073         case SKINNY_DEVICE_7906:
3074                 return "7906";
3075         case SKINNY_DEVICE_7962:
3076                 return "7962";
3077         case SKINNY_DEVICE_7937:
3078                 return "7937";
3079         case SKINNY_DEVICE_7942:
3080                 return "7942";
3081         case SKINNY_DEVICE_7945:
3082                 return "7945";
3083         case SKINNY_DEVICE_7965:
3084                 return "7965";
3085         case SKINNY_DEVICE_7975:
3086                 return "7975";
3087         case SKINNY_DEVICE_7905:
3088                 return "7905";
3089         case SKINNY_DEVICE_7920:
3090                 return "7920";
3091         case SKINNY_DEVICE_7970:
3092                 return "7970";
3093         case SKINNY_DEVICE_7912:
3094                 return "7912";
3095         case SKINNY_DEVICE_7902:
3096                 return "7902";
3097         case SKINNY_DEVICE_CIPC:
3098                 return "IP Communicator";
3099         case SKINNY_DEVICE_7961:
3100                 return "7961";
3101         case SKINNY_DEVICE_7936:
3102                 return "7936";
3103         case SKINNY_DEVICE_SCCPGATEWAY_AN:
3104                 return "SCCPGATEWAY_AN";
3105         case SKINNY_DEVICE_SCCPGATEWAY_BRI:
3106                 return "SCCPGATEWAY_BRI";
3107         case SKINNY_DEVICE_UNKNOWN:
3108                 return "Unknown";
3109         default:
3110                 if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
3111                         return "Unknown";
3112                 snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
3113                 return tmp;
3114         }
3115 }
3116
3117 /*! \brief Print codec list from preference to CLI/manager */
3118 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
3119 {
3120         int x, codec;
3121
3122         for(x = 0; x < 32 ; x++) {
3123                 codec = ast_codec_pref_index(pref, x);
3124                 if (!codec)
3125                         break;
3126                 ast_cli(fd, "%s", ast_getformatname(codec));
3127                 ast_cli(fd, ":%d", pref->framing[x]);
3128                 if (x < 31 && ast_codec_pref_index(pref, x + 1))
3129                         ast_cli(fd, ",");
3130         }
3131         if (!x)
3132                 ast_cli(fd, "none");
3133 }
3134
3135 static char *_skinny_show_devices(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
3136 {
3137         struct skinny_device *d;
3138         struct skinny_line *l;
3139         const char *id;
3140         char idtext[256] = "";
3141         int total_devices = 0;
3142
3143         if (s) {        /* Manager - get ActionID */
3144                 id = astman_get_header(m, "ActionID");
3145                 if (!ast_strlen_zero(id))
3146                         snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3147         }
3148
3149         switch (argc) {
3150         case 3:
3151                 break;
3152         default:
3153                 return CLI_SHOWUSAGE;
3154         }
3155
3156         if (!s) {
3157                 ast_cli(fd, "Name                 DeviceId         IP              Type            R NL\n");
3158                 ast_cli(fd, "-------------------- ---------------- --------------- --------------- - --\n");
3159         }
3160
3161         AST_LIST_LOCK(&devices);
3162         AST_LIST_TRAVERSE(&devices, d, list) {
3163                 int numlines = 0;
3164                 total_devices++;
3165                 AST_LIST_TRAVERSE(&d->lines, l, list) {
3166                         numlines++;
3167                 }
3168                 if (!s) {
3169                         ast_cli(fd, "%-20s %-16s %-15s %-15s %c %2d\n",
3170                                 d->name,
3171                                 d->id,
3172                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
3173                                 device2str(d->type),
3174                                 d->registered?'Y':'N',
3175                                 numlines);
3176                 } else {
3177                         astman_append(s,
3178                                 "Event: DeviceEntry\r\n%s"
3179                                 "Channeltype: SKINNY\r\n"
3180                                 "ObjectName: %s\r\n"
3181                                 "ChannelObjectType: device\r\n"
3182                                 "DeviceId: %s\r\n"
3183                                 "IPaddress: %s\r\n"
3184                                 "Type: %s\r\n"
3185                                 "Devicestatus: %s\r\n"
3186                                 "NumberOfLines: %d\r\n",
3187                                 idtext,
3188                                 d->name,
3189                                 d->id,
3190                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"-none-",
3191                                 device2str(d->type),
3192                                 d->registered?"registered":"unregistered",
3193                                 numlines);
3194                 }
3195         }
3196         AST_LIST_UNLOCK(&devices);
3197
3198         if (total)
3199                 *total = total_devices;
3200         
3201         return CLI_SUCCESS;
3202 }
3203
3204 /*! \brief  Show SKINNY devices in the manager API */
3205 /*    Inspired from chan_sip */
3206 static int manager_skinny_show_devices(struct mansession *s, const struct message *m)
3207 {
3208         const char *id = astman_get_header(m, "ActionID");
3209         const char *a[] = {"skinny", "show", "devices"};
3210         char idtext[256] = "";
3211         int total = 0;
3212
3213         if (!ast_strlen_zero(id))
3214                 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
3215
3216         astman_send_listack(s, m, "Device status list will follow", "start");
3217         /* List the devices in separate manager events */
3218         _skinny_show_devices(-1, &total, s, m, 3, a);
3219         /* Send final confirmation */
3220         astman_append(s,
3221         "Event: DevicelistComplete\r\n"
3222         "EventList: Complete\r\n"
3223         "ListItems: %d\r\n"
3224         "%s"
3225         "\r\n", total, idtext);
3226         return 0;
3227 }
3228
3229 static char *handle_skinny_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3230 {
3231
3232         switch (cmd) {
3233         case CLI_INIT:
3234                 e->command = "skinny show devices";
3235                 e->usage =
3236                         "Usage: skinny show devices\n"
3237                         "       Lists all devices known to the Skinny subsystem.\n";
3238                 return NULL;
3239         case CLI_GENERATE:
3240                 return NULL;
3241         }
3242
3243         return _skinny_show_devices(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
3244 }
3245
3246 static char *_skinny_show_device(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
3247 {
3248         struct skinny_device *d;
3249         struct skinny_line *l;
3250         struct skinny_speeddial *sd;
3251         struct skinny_addon *sa;
3252         char codec_buf[512];
3253
3254         if (argc < 4) {
3255                 return CLI_SHOWUSAGE;
3256         }
3257
3258         AST_LIST_LOCK(&devices);
3259         AST_LIST_TRAVERSE(&devices, d, list) {
3260                 if (!strcasecmp(argv[3], d->id) || !strcasecmp(argv[3], d->name)) {
3261                         int numlines = 0, numaddons = 0, numspeeddials = 0;
3262
3263                         AST_LIST_TRAVERSE(&d->lines, l, list){
3264                                 numlines++;
3265                         }
3266
3267                         AST_LIST_TRAVERSE(&d->addons, sa, list) {
3268                                 numaddons++;
3269                         }
3270
3271                         AST_LIST_TRAVERSE(&d->speeddials, sd, list) {
3272                                 numspeeddials++;
3273                         }
3274
3275                         if (type == 0) { /* CLI */
3276                                 ast_cli(fd, "Name:        %s\n", d->name);
3277                                 ast_cli(fd, "Id:          %s\n", d->id);
3278                                 ast_cli(fd, "version:     %s\n", S_OR(d->version_id, "Unknown"));
3279                                 ast_cli(fd, "Ip address:  %s\n", (d->session ? ast_inet_ntoa(d->session->sin.sin_addr) : "Unknown"));
3280                                 ast_cli(fd, "Port:        %d\n", (d->session ? ntohs(d->session->sin.sin_port) : 0));
3281                                 ast_cli(fd, "Device Type: %s\n", device2str(d->type));