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