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