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