e5d96811029479abb003322aaa5ce59633c1b339
[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 <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 #include <netinet/tcp.h>
40 #include <sys/ioctl.h>
41 #include <net/if.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <netdb.h>
45 #include <arpa/inet.h>
46 #include <sys/signal.h>
47 #include <signal.h>
48 #include <ctype.h>
49
50 #include "asterisk/lock.h"
51 #include "asterisk/channel.h"
52 #include "asterisk/config.h"
53 #include "asterisk/logger.h"
54 #include "asterisk/module.h"
55 #include "asterisk/pbx.h"
56 #include "asterisk/options.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/sched.h"
59 #include "asterisk/io.h"
60 #include "asterisk/rtp.h"
61 #include "asterisk/acl.h"
62 #include "asterisk/callerid.h"
63 #include "asterisk/cli.h"
64 #include "asterisk/say.h"
65 #include "asterisk/cdr.h"
66 #include "asterisk/astdb.h"
67 #include "asterisk/features.h"
68 #include "asterisk/app.h"
69 #include "asterisk/musiconhold.h"
70 #include "asterisk/utils.h"
71 #include "asterisk/dsp.h"
72 #include "asterisk/stringfields.h"
73 #include "asterisk/astobj.h"
74 #include "asterisk/abstract_jb.h"
75 #include "asterisk/threadstorage.h"
76
77 /*************************************
78  * Skinny/Asterisk Protocol Settings *
79  *************************************/
80 static const char tdesc[] = "Skinny Client Control Protocol (Skinny)";
81 static const char config[] = "skinny.conf";
82
83 /* Just about everybody seems to support ulaw, so make it a nice default */
84 static int default_capability = AST_FORMAT_ULAW;
85 static struct ast_codec_pref default_prefs;
86
87 #define DEFAULT_SKINNY_PORT     2000
88 #define DEFAULT_SKINNY_BACKLOG  2
89 #define SKINNY_MAX_PACKET       1000
90
91 static int keep_alive = 120;
92 static char date_format[6] = "D-M-Y";
93 static char version_id[16] = "P002F202";
94
95 #if __BYTE_ORDER == __LITTLE_ENDIAN
96 #define letohl(x) (x)
97 #define letohs(x) (x)
98 #define htolel(x) (x)
99 #define htoles(x) (x)
100 #else
101 #if defined(SOLARIS) || defined(__Darwin__) || defined(__NetBSD__)
102 #define __bswap_16(x) \
103         ((((x) & 0xff00) >> 8) | \
104          (((x) & 0x00ff) << 8))
105 #define __bswap_32(x) \
106         ((((x) & 0xff000000) >> 24) | \
107          (((x) & 0x00ff0000) >>  8) | \
108          (((x) & 0x0000ff00) <<  8) | \
109          (((x) & 0x000000ff) << 24))
110 #else
111 #include <bits/byteswap.h>
112 #endif
113 #define letohl(x) __bswap_32(x)
114 #define letohs(x) __bswap_16(x)
115 #define htolel(x) __bswap_32(x)
116 #define htoles(x) __bswap_16(x)
117 #endif
118
119 /*! Global jitterbuffer configuration - by default, jb is disabled */
120 static struct ast_jb_conf default_jbconf =
121 {
122         .flags = 0,
123         .max_size = -1,
124         .resync_threshold = -1,
125         .impl = ""
126 };
127 static struct ast_jb_conf global_jbconf;
128
129 AST_THREADSTORAGE(device2str_threadbuf, device2str_threadbuf_init);
130 #define DEVICE2STR_BUFSIZE   15
131
132 AST_THREADSTORAGE(control2str_threadbuf, control2str_threadbuf_init);
133 #define CONTROL2STR_BUFSIZE   100
134
135 /*********************
136  * Protocol Messages *
137  *********************/
138 /* message types */
139 #define KEEP_ALIVE_MESSAGE 0x0000
140 /* no additional struct */
141
142 #define REGISTER_MESSAGE 0x0001
143 struct register_message {
144         char name[16];
145         uint32_t userId;
146         uint32_t instance;
147         uint32_t ip;
148         uint32_t type;
149         uint32_t maxStreams;
150 };
151
152 #define IP_PORT_MESSAGE 0x0002
153
154 #define KEYPAD_BUTTON_MESSAGE 0x0003
155 struct keypad_button_message {
156         uint32_t button;
157         uint32_t lineInstance;
158         uint32_t callReference;
159 };
160
161 #define STIMULUS_MESSAGE 0x0005
162 struct stimulus_message {
163         uint32_t stimulus;
164         uint32_t stimulusInstance;
165         uint32_t unknown1;
166 };
167
168 #define OFFHOOK_MESSAGE 0x0006
169 struct offhook_message {
170         uint32_t unknown1;
171         uint32_t unknown2;
172 };
173
174 #define ONHOOK_MESSAGE 0x0007
175 struct onhook_message {
176         uint32_t unknown1;
177         uint32_t unknown2;
178 };
179
180 #define CAPABILITIES_RES_MESSAGE 0x0010
181 struct station_capabilities {
182         uint32_t codec;
183         uint32_t frames;
184         union {
185                 char res[8];
186                 uint64_t rate;
187         } payloads;
188 };
189
190 struct capabilities_res_message {
191         uint32_t count;
192         struct station_capabilities caps[18];
193 };
194
195 #define SPEED_DIAL_STAT_REQ_MESSAGE 0x000A
196 struct speed_dial_stat_req_message {
197         uint32_t speedDialNumber;
198 };
199
200 #define LINE_STATE_REQ_MESSAGE 0x000B
201 struct line_state_req_message {
202         uint32_t lineNumber;
203 };
204
205 #define TIME_DATE_REQ_MESSAGE 0x000D
206 #define BUTTON_TEMPLATE_REQ_MESSAGE 0x000E
207 #define VERSION_REQ_MESSAGE 0x000F
208 #define SERVER_REQUEST_MESSAGE 0x0012
209
210 #define ALARM_MESSAGE 0x0020
211 struct alarm_message {
212         uint32_t alarmSeverity;
213         char displayMessage[80];
214         uint32_t alarmParam1;
215         uint32_t alarmParam2;
216 };
217
218 #define OPEN_RECEIVE_CHANNEL_ACK_MESSAGE 0x0022
219 struct open_receive_channel_ack_message {
220         uint32_t status;
221         uint32_t ipAddr;
222         uint32_t port;
223         uint32_t passThruId;
224 };
225
226 #define SOFT_KEY_SET_REQ_MESSAGE 0x0025
227
228 #define SOFT_KEY_EVENT_MESSAGE 0x0026
229 struct soft_key_event_message {
230         uint32_t softKeyEvent;
231         uint32_t instance;
232         uint32_t reference;
233 };
234
235 #define UNREGISTER_MESSAGE 0x0027
236 #define SOFT_KEY_TEMPLATE_REQ_MESSAGE 0x0028
237 #define HEADSET_STATUS_MESSAGE 0x002B
238 #define REGISTER_AVAILABLE_LINES_MESSAGE 0x002D
239
240 #define REGISTER_ACK_MESSAGE 0x0081
241 struct register_ack_message {
242         uint32_t keepAlive;
243         char dateTemplate[6];
244         char res[2];
245         uint32_t secondaryKeepAlive;
246         char res2[4];
247 };
248
249 #define START_TONE_MESSAGE 0x0082
250 struct start_tone_message {
251         uint32_t tone;
252 };
253
254 #define STOP_TONE_MESSAGE 0x0083
255
256 #define SET_RINGER_MESSAGE 0x0085
257 struct set_ringer_message {
258         uint32_t ringerMode;
259         uint32_t unknown1; /* See notes in transmit_ringer_mode */
260         uint32_t unknown2;
261 };
262
263 #define SET_LAMP_MESSAGE 0x0086
264 struct set_lamp_message {
265         uint32_t stimulus;
266         uint32_t stimulusInstance;
267         uint32_t deviceStimulus;
268 };
269
270 #define SET_SPEAKER_MESSAGE 0x0088
271 struct set_speaker_message {
272         uint32_t mode;
273 };
274
275 /* XXX When do we need to use this? */
276 #define SET_MICROPHONE_MESSAGE 0x0089
277 struct set_microphone_message {
278         uint32_t mode;
279 };
280
281 #define START_MEDIA_TRANSMISSION_MESSAGE 0x008A
282 struct media_qualifier {
283         uint32_t precedence;
284         uint32_t vad;
285         uint32_t packets;
286         uint32_t bitRate;
287 };
288
289 struct start_media_transmission_message {
290         uint32_t conferenceId;
291         uint32_t passThruPartyId;
292         uint32_t remoteIp;
293         uint32_t remotePort;
294         uint32_t packetSize;
295         uint32_t payloadType;
296         struct media_qualifier qualifier;
297 };
298
299 #define STOP_MEDIA_TRANSMISSION_MESSAGE 0x008B
300 struct stop_media_transmission_message {
301         uint32_t conferenceId;
302         uint32_t passThruPartyId;
303 };
304
305 #define CALL_INFO_MESSAGE 0x008F
306 struct call_info_message {
307         char callingPartyName[40];
308         char callingParty[24];
309         char calledPartyName[40];
310         char calledParty[24];
311         uint32_t instance;
312         uint32_t reference;
313         uint32_t type;
314         char originalCalledPartyName[40];
315         char originalCalledParty[24];
316 };
317
318 #define SPEED_DIAL_STAT_RES_MESSAGE 0x0091
319 struct speed_dial_stat_res_message {
320         uint32_t speedDialNumber;
321         char speedDialDirNumber[24];
322         char speedDialDisplayName[40];
323 };
324
325 #define LINE_STAT_RES_MESSAGE 0x0092
326 struct line_stat_res_message {
327         uint32_t lineNumber;
328         char lineDirNumber[24];
329         char lineDisplayName[42];
330         uint32_t space;
331 };
332
333 #define DEFINETIMEDATE_MESSAGE 0x0094
334 struct definetimedate_message {
335         uint32_t year;  /* since 1900 */
336         uint32_t month;
337         uint32_t dayofweek;     /* monday = 1 */
338         uint32_t day;
339         uint32_t hour;
340         uint32_t minute;
341         uint32_t seconds;
342         uint32_t milliseconds;
343         uint32_t timestamp;
344 };
345
346 #define BUTTON_TEMPLATE_RES_MESSAGE 0x0097
347 struct button_definition {
348         uint8_t instanceNumber;
349         uint8_t buttonDefinition;
350 };
351
352 struct button_definition_template {
353         uint8_t buttonDefinition;
354         /* for now, anything between 0xB0 and 0xCF is custom */
355         /*int custom;*/
356 };
357
358 #define STIMULUS_REDIAL                 0x01
359 #define STIMULUS_SPEEDDIAL              0x02
360 #define STIMULUS_HOLD                   0x03
361 #define STIMULUS_TRANSFER               0x04
362 #define STIMULUS_FORWARDALL             0x05
363 #define STIMULUS_FORWARDBUSY            0x06
364 #define STIMULUS_FORWARDNOANSWER        0x07
365 #define STIMULUS_DISPLAY                0x08
366 #define STIMULUS_LINE                   0x09
367 #define STIMULUS_VOICEMAIL              0x0F
368 #define STIMULUS_AUTOANSWER             0x11
369 #define STIMULUS_CONFERENCE             0x7D
370 #define STIMULUS_CALLPARK               0x7E
371 #define STIMULUS_CALLPICKUP             0x7F
372 #define STIMULUS_NONE                   0xFF
373
374 /* Button types */
375 #define BT_REDIAL                       STIMULUS_REDIAL
376 #define BT_SPEEDDIAL                    STIMULUS_SPEEDDIAL
377 #define BT_HOLD                         STIMULUS_HOLD
378 #define BT_TRANSFER                     STIMULUS_TRANSFER
379 #define BT_FORWARDALL                   STIMULUS_FORWARDALL
380 #define BT_FORWARDBUSY                  STIMULUS_FORWARDBUSY
381 #define BT_FORWARDNOANSWER              STIMULUS_FORWARDNOANSWER
382 #define BT_DISPLAY                      STIMULUS_DISPLAY
383 #define BT_LINE                         STIMULUS_LINE
384 #define BT_VOICEMAIL                    STIMULUS_VOICEMAIL
385 #define BT_AUTOANSWER                   STIMULUS_AUTOANSWER
386 #define BT_CONFERENCE                   STIMULUS_CONFERENCE
387 #define BT_CALLPARK                     STIMULUS_CALLPARK
388 #define BT_CALLPICKUP                   STIMULUS_CALLPICKUP
389 #define BT_NONE                         0x00
390
391 /* Custom button types - add our own between 0xB0 and 0xCF.
392    This may need to be revised in the future,
393    if stimuluses are ever added in this range. */
394 #define BT_CUST_LINESPEEDDIAL           0xB0    /* line or speeddial */
395 #define BT_CUST_HINT                    0xB1    /* pipe dream */
396
397 struct button_template_res_message {
398         uint32_t buttonOffset;
399         uint32_t buttonCount;
400         uint32_t totalButtonCount;
401         struct button_definition definition[42];
402 };
403
404 #define VERSION_RES_MESSAGE 0x0098
405 struct version_res_message {
406         char version[16];
407 };
408
409 #define DISPLAYTEXT_MESSAGE 0x0099
410 struct displaytext_message {
411         char text[40];
412 };
413
414 #define CLEAR_DISPLAY_MESSAGE 0x009A
415 #define CAPABILITIES_REQ_MESSAGE 0x009B
416
417 #define REGISTER_REJ_MESSAGE 0x009D
418 struct register_rej_message {
419         char errMsg[33];
420 };
421
422 #define SERVER_RES_MESSAGE 0x009E
423 struct server_identifier {
424         char serverName[48];
425 };
426
427 struct server_res_message {
428         struct server_identifier server[5];
429         uint32_t serverListenPort[5];
430         uint32_t serverIpAddr[5];
431 };
432
433 #define RESET_MESSAGE 0x009F
434 struct reset_message {
435         uint32_t resetType;
436 };
437
438 #define KEEP_ALIVE_ACK_MESSAGE 0x0100
439
440 #define OPEN_RECEIVE_CHANNEL_MESSAGE 0x0105
441 struct open_receive_channel_message {
442         uint32_t conferenceId;
443         uint32_t partyId;
444         uint32_t packets;
445         uint32_t capability;
446         uint32_t echo;
447         uint32_t bitrate;
448 };
449
450 #define CLOSE_RECEIVE_CHANNEL_MESSAGE 0x0106
451 struct close_receive_channel_message {
452         uint32_t conferenceId;
453         uint32_t partyId;
454 };
455
456 #define SOFT_KEY_TEMPLATE_RES_MESSAGE 0x0108
457
458 struct soft_key_template_definition {
459         char softKeyLabel[16];
460         uint32_t softKeyEvent;
461 };
462
463 #define KEYDEF_ONHOOK                   0
464 #define KEYDEF_CONNECTED                1
465 #define KEYDEF_ONHOLD                   2
466 #define KEYDEF_RINGIN                   3
467 #define KEYDEF_OFFHOOK                  4
468 #define KEYDEF_CONNWITHTRANS            5
469 #define KEYDEF_DADFD                    6 /* Digits After Dialing First Digit */
470 #define KEYDEF_CONNWITHCONF             7
471 #define KEYDEF_RINGOUT                  8
472 #define KEYDEF_OFFHOOKWITHFEAT          9
473 #define KEYDEF_UNKNOWN                  10
474
475 #define SOFTKEY_NONE                    0x00
476 #define SOFTKEY_REDIAL                  0x01
477 #define SOFTKEY_NEWCALL                 0x02
478 #define SOFTKEY_HOLD                    0x03
479 #define SOFTKEY_TRNSFER                 0x04
480 #define SOFTKEY_CFWDALL                 0x05
481 #define SOFTKEY_CFWDBUSY                0x06
482 #define SOFTKEY_CFWDNOANSWER            0x07
483 #define SOFTKEY_BKSPC                   0x08
484 #define SOFTKEY_ENDCALL                 0x09
485 #define SOFTKEY_RESUME                  0x0A
486 #define SOFTKEY_ANSWER                  0x0B
487 #define SOFTKEY_INFO                    0x0C
488 #define SOFTKEY_CONFRN                  0x0D
489 #define SOFTKEY_PARK                    0x0E
490 #define SOFTKEY_JOIN                    0x0F
491 #define SOFTKEY_MEETME                  0x10
492 #define SOFTKEY_PICKUP                  0x11
493 #define SOFTKEY_GPICKUP                 0x12
494
495 struct soft_key_template_definition soft_key_template_default[] = {
496         { "Redial",             0x01 },
497         { "NewCall",            0x02 },
498         { "Hold",               0x03 },
499         { "Trnsfer",            0x04 },
500         { "CFwdAll",            0x05 },
501         { "CFwdBusy",           0x06 },
502         { "CFwdNoAnswer",       0x07 },
503         { "<<",                 0x08 },
504         { "EndCall",            0x09 },
505         { "Resume",             0x0A },
506         { "Answer",             0x0B },
507         { "Info",               0x0C },
508         { "Confrn",             0x0D },
509         { "Park",               0x0E },
510         { "Join",               0x0F },
511         { "MeetMe",             0x10 },
512         { "PickUp",             0x11 },
513         { "GPickUp",            0x12 },
514 };
515
516 struct soft_key_definitions {
517         const uint8_t mode;
518         const uint8_t *defaults;
519         const int count;
520 };
521
522 static const uint8_t soft_key_default_onhook[] = {
523         SOFTKEY_REDIAL,
524         SOFTKEY_CFWDALL,
525         SOFTKEY_CFWDBUSY,
526         SOFTKEY_GPICKUP,
527         SOFTKEY_CONFRN,
528 };
529
530 static const uint8_t soft_key_default_connected[] = {
531         SOFTKEY_HOLD,
532         SOFTKEY_ENDCALL,
533         SOFTKEY_TRNSFER,
534         SOFTKEY_PARK,
535         SOFTKEY_CFWDALL,
536         SOFTKEY_CFWDBUSY,
537 };
538
539 static const uint8_t soft_key_default_onhold[] = {
540         SOFTKEY_RESUME,
541         SOFTKEY_NEWCALL,
542         SOFTKEY_ENDCALL,
543         SOFTKEY_TRNSFER,
544 };
545
546 static const uint8_t soft_key_default_ringin[] = {
547         SOFTKEY_ANSWER,
548         SOFTKEY_ENDCALL,
549         SOFTKEY_TRNSFER,
550 };
551
552 static const uint8_t soft_key_default_offhook[] = {
553         SOFTKEY_REDIAL,
554         SOFTKEY_ENDCALL,
555         SOFTKEY_CFWDALL,
556         SOFTKEY_CFWDBUSY,
557         SOFTKEY_GPICKUP,
558 };
559
560 static const uint8_t soft_key_default_connwithtrans[] = {
561         SOFTKEY_HOLD,
562         SOFTKEY_ENDCALL,
563         SOFTKEY_TRNSFER,
564         SOFTKEY_PARK,
565         SOFTKEY_CFWDALL,
566         SOFTKEY_CFWDBUSY,
567 };
568
569 static const uint8_t soft_key_default_dadfd[] = {
570         SOFTKEY_BKSPC,
571         SOFTKEY_ENDCALL,
572 };
573
574 static const uint8_t soft_key_default_connwithconf[] = {
575         SOFTKEY_NONE,
576 };
577
578 static const uint8_t soft_key_default_ringout[] = {
579         SOFTKEY_ENDCALL,
580         SOFTKEY_TRNSFER,
581         SOFTKEY_CFWDALL,
582         SOFTKEY_CFWDBUSY,
583 };
584
585 static const uint8_t soft_key_default_offhookwithfeat[] = {
586         SOFTKEY_REDIAL,
587         SOFTKEY_ENDCALL,
588 };
589
590 static const uint8_t soft_key_default_unknown[] = {
591         SOFTKEY_NONE,
592 };
593
594 static const struct soft_key_definitions soft_key_default_definitions[] = {
595         {KEYDEF_ONHOOK, soft_key_default_onhook, sizeof(soft_key_default_onhook) / sizeof(uint8_t)},
596         {KEYDEF_CONNECTED, soft_key_default_connected, sizeof(soft_key_default_connected) / sizeof(uint8_t)},
597         {KEYDEF_ONHOLD, soft_key_default_onhold, sizeof(soft_key_default_onhold) / sizeof(uint8_t)},
598         {KEYDEF_RINGIN, soft_key_default_ringin, sizeof(soft_key_default_ringin) / sizeof(uint8_t)},
599         {KEYDEF_OFFHOOK, soft_key_default_offhook, sizeof(soft_key_default_offhook) / sizeof(uint8_t)},
600         {KEYDEF_CONNWITHTRANS, soft_key_default_connwithtrans, sizeof(soft_key_default_connwithtrans) / sizeof(uint8_t)},
601         {KEYDEF_DADFD, soft_key_default_dadfd, sizeof(soft_key_default_dadfd) / sizeof(uint8_t)},
602         {KEYDEF_CONNWITHCONF, soft_key_default_connwithconf, sizeof(soft_key_default_connwithconf) / sizeof(uint8_t)},
603         {KEYDEF_RINGOUT, soft_key_default_ringout, sizeof(soft_key_default_ringout) / sizeof(uint8_t)},
604         {KEYDEF_OFFHOOKWITHFEAT, soft_key_default_offhookwithfeat, sizeof(soft_key_default_offhookwithfeat) / sizeof(uint8_t)},
605         {KEYDEF_UNKNOWN, soft_key_default_unknown, sizeof(soft_key_default_unknown) / sizeof(uint8_t)}
606 };
607
608 struct soft_key_template_res_message {
609         uint32_t softKeyOffset;
610         uint32_t softKeyCount;
611         uint32_t totalSoftKeyCount;
612         struct soft_key_template_definition softKeyTemplateDefinition[32];
613 };
614
615 #define SOFT_KEY_SET_RES_MESSAGE 0x0109
616
617 struct soft_key_set_definition {
618         uint8_t softKeyTemplateIndex[16];
619         uint16_t softKeyInfoIndex[16];
620 };
621
622 struct soft_key_set_res_message {
623         uint32_t softKeySetOffset;
624         uint32_t softKeySetCount;
625         uint32_t totalSoftKeySetCount;
626         struct soft_key_set_definition softKeySetDefinition[16];
627         uint32_t res;
628 };
629
630 #define SELECT_SOFT_KEYS_MESSAGE 0x0110
631 struct select_soft_keys_message {
632         uint32_t instance;
633         uint32_t reference;
634         uint32_t softKeySetIndex;
635         uint32_t validKeyMask;
636 };
637
638 #define CALL_STATE_MESSAGE 0x0111
639 struct call_state_message {
640         uint32_t callState;
641         uint32_t lineInstance;
642         uint32_t callReference;
643 };
644
645 #define DISPLAY_PROMPT_STATUS_MESSAGE 0x0112
646 struct display_prompt_status_message {
647         uint32_t messageTimeout;
648         char promptMessage[32];
649         uint32_t lineInstance;
650         uint32_t callReference;
651 };
652
653 #define DISPLAY_NOTIFY_MESSAGE 0x0114
654 struct display_notify_message {
655         uint32_t displayTimeout;
656         char displayMessage[100];
657 };
658
659 #define ACTIVATE_CALL_PLANE_MESSAGE 0x0116
660 struct activate_call_plane_message {
661         uint32_t lineInstance;
662 };
663
664 #define DIALED_NUMBER_MESSAGE 0x011D
665 struct dialed_number_message {
666         char dialedNumber[24];
667         uint32_t lineInstance;
668         uint32_t callReference;
669 };
670
671 union skinny_data {
672         struct alarm_message alarm;
673         struct speed_dial_stat_req_message speeddialreq;
674         struct register_message reg;
675         struct register_ack_message regack;
676         struct register_rej_message regrej;
677         struct capabilities_res_message caps;
678         struct version_res_message version;
679         struct button_template_res_message buttontemplate;
680         struct displaytext_message displaytext;
681         struct display_prompt_status_message displaypromptstatus;
682         struct definetimedate_message definetimedate;
683         struct start_tone_message starttone;
684         struct speed_dial_stat_res_message speeddial;
685         struct line_state_req_message line;
686         struct line_stat_res_message linestat;
687         struct soft_key_set_res_message softkeysets;
688         struct soft_key_template_res_message softkeytemplate;
689         struct server_res_message serverres;
690         struct reset_message reset;
691         struct set_lamp_message setlamp;
692         struct set_ringer_message setringer;
693         struct call_state_message callstate;
694         struct keypad_button_message keypad;
695         struct select_soft_keys_message selectsoftkey;
696         struct activate_call_plane_message activatecallplane;
697         struct stimulus_message stimulus;
698         struct offhook_message offhook;
699         struct onhook_message onhook;
700         struct set_speaker_message setspeaker;
701         struct set_microphone_message setmicrophone;
702         struct call_info_message callinfo;
703         struct start_media_transmission_message startmedia;
704         struct stop_media_transmission_message stopmedia;
705         struct open_receive_channel_message openreceivechannel;
706         struct open_receive_channel_ack_message openreceivechannelack;
707         struct close_receive_channel_message closereceivechannel;
708         struct display_notify_message displaynotify;
709         struct dialed_number_message dialednumber;
710         struct soft_key_event_message softkeyeventmessage;
711 };
712
713 /* packet composition */
714 struct skinny_req {
715         int len;
716         int res;
717         int e;
718         union skinny_data data;
719 };
720
721 /* XXX This is the combined size of the variables above.  (len, res, e)
722    If more are added, this MUST change.
723    (sizeof(skinny_req) - sizeof(skinny_data)) DOES NOT WORK on all systems (amd64?). */
724 int skinny_header_size = 12;
725
726 /*****************************
727  * Asterisk specific globals *
728  *****************************/
729
730 static int skinnydebug = 0;
731
732 /* a hostname, portnumber, socket and such is usefull for VoIP protocols */
733 static struct sockaddr_in bindaddr;
734 static char ourhost[256];
735 static int ourport;
736 static struct in_addr __ourip;
737 struct ast_hostent ahp;
738 struct hostent *hp;
739 static int skinnysock = -1;
740 static pthread_t tcp_thread;
741 static pthread_t accept_t;
742 static char context[AST_MAX_CONTEXT] = "default";
743 static char language[MAX_LANGUAGE] = "";
744 static char mohinterpret[MAX_MUSICCLASS] = "default";
745 static char mohsuggest[MAX_MUSICCLASS] = "";
746 static char cid_num[AST_MAX_EXTENSION] = "";
747 static char cid_name[AST_MAX_EXTENSION] = "";
748 static char linelabel[AST_MAX_EXTENSION] ="";
749 static int nat = 0;
750 static ast_group_t cur_callergroup = 0;
751 static ast_group_t cur_pickupgroup = 0;
752 static int immediate = 0;
753 static int callwaiting = 0;
754 static int callreturn = 0;
755 static int threewaycalling = 0;
756 static int mwiblink = 0;
757 /* This is for flashhook transfers */
758 static int transfer = 0;
759 static int cancallforward = 0;
760 /* static int busycount = 3;*/
761 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
762 static char mailbox[AST_MAX_EXTENSION];
763 static int amaflags = 0;
764 static int callnums = 1;
765
766 #define SKINNY_DEVICE_UNKNOWN           -1
767 #define SKINNY_DEVICE_NONE              0
768 #define SKINNY_DEVICE_30SPPLUS          1
769 #define SKINNY_DEVICE_12SPPLUS          2
770 #define SKINNY_DEVICE_12SP              3
771 #define SKINNY_DEVICE_12                4
772 #define SKINNY_DEVICE_30VIP             5
773 #define SKINNY_DEVICE_7910              6
774 #define SKINNY_DEVICE_7960              7
775 #define SKINNY_DEVICE_7940              8
776 #define SKINNY_DEVICE_7935              9
777 #define SKINNY_DEVICE_ATA186            12      /* Cisco ATA-186 */
778 #define SKINNY_DEVICE_7941              115
779 #define SKINNY_DEVICE_7971              119
780 #define SKINNY_DEVICE_7985              302
781 #define SKINNY_DEVICE_7911              307
782 #define SKINNY_DEVICE_7961GE            308
783 #define SKINNY_DEVICE_7941GE            309
784 #define SKINNY_DEVICE_7905              20000
785 #define SKINNY_DEVICE_7920              30002
786 #define SKINNY_DEVICE_7970              30006
787 #define SKINNY_DEVICE_7912              30007
788 #define SKINNY_DEVICE_7902              30008
789 #define SKINNY_DEVICE_CIPC              30016   /* Cisco IP Communicator */
790 #define SKINNY_DEVICE_7961              30018
791 #define SKINNY_DEVICE_7936              30019
792 #define SKINNY_DEVICE_SCCPGATEWAY_AN    30027   /* ??? */
793 #define SKINNY_DEVICE_SCCPGATEWAY_BRI   30028   /* ??? */
794
795 #define SKINNY_SPEAKERON 1
796 #define SKINNY_SPEAKEROFF 2
797
798 #define SKINNY_MICON 1
799 #define SKINNY_MICOFF 2
800
801 #define SKINNY_OFFHOOK 1
802 #define SKINNY_ONHOOK 2
803 #define SKINNY_RINGOUT 3
804 #define SKINNY_RINGIN 4
805 #define SKINNY_CONNECTED 5
806 #define SKINNY_BUSY 6
807 #define SKINNY_CONGESTION 7
808 #define SKINNY_HOLD 8
809 #define SKINNY_CALLWAIT 9
810 #define SKINNY_TRANSFER 10
811 #define SKINNY_PARK 11
812 #define SKINNY_PROGRESS 12
813 #define SKINNY_INVALID 14
814
815 #define SKINNY_SILENCE          0x00
816 #define SKINNY_DIALTONE         0x21
817 #define SKINNY_BUSYTONE         0x23
818 #define SKINNY_ALERT            0x24
819 #define SKINNY_REORDER          0x25
820 #define SKINNY_CALLWAITTONE     0x2D
821 #define SKINNY_NOTONE           0x7F
822
823 #define SKINNY_LAMP_OFF 1
824 #define SKINNY_LAMP_ON 2
825 #define SKINNY_LAMP_WINK 3
826 #define SKINNY_LAMP_FLASH 4
827 #define SKINNY_LAMP_BLINK 5
828
829 #define SKINNY_RING_OFF 1
830 #define SKINNY_RING_INSIDE 2
831 #define SKINNY_RING_OUTSIDE 3
832 #define SKINNY_RING_FEATURE 4
833
834 #define TYPE_TRUNK 1
835 #define TYPE_LINE 2
836
837 /* Skinny rtp stream modes. Do we really need this? */
838 #define SKINNY_CX_SENDONLY      0
839 #define SKINNY_CX_RECVONLY      1
840 #define SKINNY_CX_SENDRECV      2
841 #define SKINNY_CX_CONF          3
842 #define SKINNY_CX_CONFERENCE    3
843 #define SKINNY_CX_MUTE          4
844 #define SKINNY_CX_INACTIVE      4
845
846 #if 0
847 static char *skinny_cxmodes[] = {
848         "sendonly",
849         "recvonly",
850         "sendrecv",
851         "confrnce",
852         "inactive"
853 };
854 #endif
855
856 /* driver scheduler */
857 static struct sched_context *sched;
858 static struct io_context *io;
859
860 /* usage count and locking */
861 static int usecnt = 0;
862 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
863
864 /* Protect the monitoring thread, so only one process can kill or start it, and not
865    when it's doing something critical. */
866 AST_MUTEX_DEFINE_STATIC(monlock);
867 /* Protect the network socket */
868 AST_MUTEX_DEFINE_STATIC(netlock);
869 /* Protect the session list */
870 AST_MUTEX_DEFINE_STATIC(sessionlock);
871 /* Protect the device list */
872 AST_MUTEX_DEFINE_STATIC(devicelock);
873 #if 0
874 /* Protect the paging device list */
875 AST_MUTEX_DEFINE_STATIC(pagingdevicelock);
876 #endif
877
878 /* This is the thread for the monitor which checks for input on the channels
879    which are not currently in use. */
880 static pthread_t monitor_thread = AST_PTHREADT_NULL;
881
882 /* Wait up to 16 seconds for first digit */
883 static int firstdigittimeout = 16000;
884
885 /* How long to wait for following digits */
886 static int gendigittimeout = 8000;
887
888 /* How long to wait for an extra digit, if there is an ambiguous match */
889 static int matchdigittimeout = 3000;
890
891 struct skinny_subchannel {
892         ast_mutex_t lock;
893         struct ast_channel *owner;
894         struct ast_rtp *rtp;
895         struct ast_rtp *vrtp;
896         unsigned int callid;
897         /* time_t lastouttime; */                       /* Unused */
898         int progress;
899         int ringing;
900         int onhold;
901         /* int lastout; */                              /* Unused */
902         int cxmode;
903         int nat;
904         int outgoing;
905         int alreadygone;
906
907         struct skinny_subchannel *next;
908         struct skinny_line *parent;
909 };
910
911 struct skinny_line {
912         ast_mutex_t lock;
913         char name[80];
914         char label[42];                                 /* Label that shows next to the line buttons */
915         char accountcode[AST_MAX_ACCOUNT_CODE];
916         char exten[AST_MAX_EXTENSION];                  /* Extension where to start */
917         char context[AST_MAX_CONTEXT];
918         char language[MAX_LANGUAGE];
919         char cid_num[AST_MAX_EXTENSION];                /* Caller*ID */
920         char cid_name[AST_MAX_EXTENSION];               /* Caller*ID */
921         char lastcallerid[AST_MAX_EXTENSION];           /* Last Caller*ID */
922         char call_forward[AST_MAX_EXTENSION];
923         char mailbox[AST_MAX_EXTENSION];
924         char mohinterpret[MAX_MUSICCLASS];
925         char mohsuggest[MAX_MUSICCLASS];
926         char lastnumberdialed[AST_MAX_EXTENSION];       /* Last number that was dialed - used for redial */
927         int curtone;                                    /* Current tone being played */
928         ast_group_t callgroup;
929         ast_group_t pickupgroup;
930         int callwaiting;
931         int transfer;
932         int threewaycalling;
933         int mwiblink;
934         int cancallforward;
935         int callreturn;
936         int dnd; /* How does this affect callwait?  Do we just deny a skinny_request if we're dnd? */
937         int hascallerid;
938         int hidecallerid;
939         int amaflags;
940         int type;
941         int instance;
942         int group;
943         int needdestroy;
944         int capability;
945         int nonCodecCapability;
946         int onhooktime;
947         int msgstate;                                   /* voicemail message state */
948         int immediate;
949         int hookstate;
950         int nat;
951
952         struct ast_codec_pref prefs;
953         struct skinny_subchannel *sub;
954         struct skinny_line *next;
955         struct skinny_device *parent;
956 };
957
958 struct skinny_speeddial {
959         ast_mutex_t lock;
960         char label[42];
961         char exten[AST_MAX_EXTENSION];
962         int instance;
963
964         struct skinny_speeddial *next;
965         struct skinny_device *parent;
966 };
967
968 struct skinny_addon {
969         ast_mutex_t lock;
970         char type[10];
971
972         struct skinny_addon *next;
973         struct skinny_device *parent;
974 };
975
976 static struct skinny_device {
977         /* A device containing one or more lines */
978         char name[80];
979         char id[16];
980         char version_id[16];
981         int type;
982         int registered;
983         int lastlineinstance;
984         int lastcallreference;
985         int capability;
986         struct sockaddr_in addr;
987         struct in_addr ourip;
988         struct skinny_line *lines;
989         struct skinny_speeddial *speeddials;
990         struct skinny_addon *addons;
991         struct ast_codec_pref prefs;
992         struct ast_ha *ha;
993         struct skinnysession *session;
994         struct skinny_device *next;
995 } *devices = NULL;
996
997 struct skinny_paging_device {
998         char name[80];
999         char id[16];
1000         struct skinny_device ** devices;
1001         struct skinny_paging_device *next;
1002 };
1003
1004 static struct skinnysession {
1005         pthread_t t;
1006         ast_mutex_t lock;
1007         struct sockaddr_in sin;
1008         int fd;
1009         char inbuf[SKINNY_MAX_PACKET];
1010         char outbuf[SKINNY_MAX_PACKET];
1011         struct skinny_device *device;
1012         struct skinnysession *next;
1013 } *sessions = NULL;
1014
1015 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause);
1016 static int skinny_call(struct ast_channel *ast, char *dest, int timeout);
1017 static int skinny_hangup(struct ast_channel *ast);
1018 static int skinny_answer(struct ast_channel *ast);
1019 static struct ast_frame *skinny_read(struct ast_channel *ast);
1020 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
1021 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
1022 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1023 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
1024 static int skinny_senddigit_end(struct ast_channel *ast, char digit);
1025
1026 static const struct ast_channel_tech skinny_tech = {
1027         .type = "Skinny",
1028         .description = tdesc,
1029         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
1030         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1031         .requester = skinny_request,
1032         .call = skinny_call,
1033         .hangup = skinny_hangup,
1034         .answer = skinny_answer,
1035         .read = skinny_read,
1036         .write = skinny_write,
1037         .indicate = skinny_indicate,
1038         .fixup = skinny_fixup,
1039         .send_digit_begin = skinny_senddigit_begin,
1040         .send_digit_end = skinny_senddigit_end,
1041 /*      .bridge = ast_rtp_bridge, */
1042 };
1043
1044 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
1045 {
1046         struct skinny_device *d = s->device;
1047         struct skinny_addon *a = d->addons;
1048         int i;
1049
1050         switch (d->type) {
1051                 case SKINNY_DEVICE_30SPPLUS:
1052                 case SKINNY_DEVICE_30VIP:
1053                         /* 13 rows, 2 columns */
1054                         for (i = 0; i < 4; i++)
1055                                 (btn++)->buttonDefinition = BT_LINE;
1056                         (btn++)->buttonDefinition = BT_REDIAL;
1057                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1058                         (btn++)->buttonDefinition = BT_CALLPARK;
1059                         (btn++)->buttonDefinition = BT_FORWARDALL;
1060                         (btn++)->buttonDefinition = BT_CONFERENCE;
1061                         for (i = 0; i < 4; i++)
1062                                 (btn++)->buttonDefinition = BT_NONE;
1063                         for (i = 0; i < 13; i++)
1064                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1065                         
1066                         break;
1067                 case SKINNY_DEVICE_12SPPLUS:
1068                 case SKINNY_DEVICE_12SP:
1069                 case SKINNY_DEVICE_12:
1070                         /* 6 rows, 2 columns */
1071                         for (i = 0; i < 2; i++)
1072                                 (btn++)->buttonDefinition = BT_LINE;
1073                         (btn++)->buttonDefinition = BT_REDIAL;
1074                         for (i = 0; i < 3; i++)
1075                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1076                         (btn++)->buttonDefinition = BT_HOLD;
1077                         (btn++)->buttonDefinition = BT_TRANSFER;
1078                         (btn++)->buttonDefinition = BT_FORWARDALL;
1079                         (btn++)->buttonDefinition = BT_CALLPARK;
1080                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1081                         (btn++)->buttonDefinition = BT_CONFERENCE;
1082                         break;
1083                 case SKINNY_DEVICE_7910:
1084                         (btn++)->buttonDefinition = BT_LINE;
1085                         (btn++)->buttonDefinition = BT_HOLD;
1086                         (btn++)->buttonDefinition = BT_TRANSFER;
1087                         (btn++)->buttonDefinition = BT_DISPLAY;
1088                         (btn++)->buttonDefinition = BT_VOICEMAIL;
1089                         (btn++)->buttonDefinition = BT_CONFERENCE;
1090                         (btn++)->buttonDefinition = BT_FORWARDALL;
1091                         for (i = 0; i < 2; i++)
1092                                 (btn++)->buttonDefinition = BT_SPEEDDIAL;
1093                         (btn++)->buttonDefinition = BT_REDIAL;
1094                         break;
1095                 case SKINNY_DEVICE_7960:
1096                 case SKINNY_DEVICE_7961:
1097                 case SKINNY_DEVICE_7961GE:
1098                         for (i = 0; i < 6; i++)
1099                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1100                         break;
1101                 case SKINNY_DEVICE_7940:
1102                 case SKINNY_DEVICE_7941:
1103                 case SKINNY_DEVICE_7941GE:
1104                         for (i = 0; i < 2; i++)
1105                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1106                         break;
1107                 case SKINNY_DEVICE_7935:
1108                 case SKINNY_DEVICE_7936:
1109                         for (i = 0; i < 2; i++)
1110                                 (btn++)->buttonDefinition = BT_LINE;
1111                         break;
1112                 case SKINNY_DEVICE_ATA186:
1113                         (btn++)->buttonDefinition = BT_LINE;
1114                         break;
1115                 case SKINNY_DEVICE_7970:
1116                 case SKINNY_DEVICE_7971:
1117                 case SKINNY_DEVICE_CIPC:
1118                         for (i = 0; i < 8; i++)
1119                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1120                         break;
1121                 case SKINNY_DEVICE_7985:
1122                         /* XXX I have no idea what the buttons look like on these. */
1123                         ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
1124                         break;
1125                 case SKINNY_DEVICE_7912:
1126                 case SKINNY_DEVICE_7911:
1127                 case SKINNY_DEVICE_7905:
1128                         (btn++)->buttonDefinition = BT_LINE;
1129                         (btn++)->buttonDefinition = BT_HOLD;
1130                         break;
1131                 case SKINNY_DEVICE_7920:
1132                         /* XXX I don't know if this is right. */
1133                         for (i = 0; i < 4; i++)
1134                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1135                         break;
1136                 case SKINNY_DEVICE_7902:
1137                         ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
1138                         break;
1139                 case SKINNY_DEVICE_SCCPGATEWAY_AN:
1140                 case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1141                         ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
1142                         break;
1143                 default:
1144                         ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
1145                         break;
1146         }
1147
1148         for (a = d->addons; a; a = a->next) {
1149                 if (!strcasecmp(a->type, "7914")) {
1150                         for (i = 0; i < 14; i++)
1151                                 (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
1152                 } else {
1153                         ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
1154                 }
1155         }
1156
1157         return btn;
1158 }
1159
1160 static struct skinny_req *req_alloc(size_t size, int response_message)
1161 {
1162         struct skinny_req *req;
1163
1164         if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
1165                 return NULL;
1166
1167         req->len = htolel(size+4);
1168         req->e = htolel(response_message);
1169
1170         return req;
1171 }
1172
1173 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
1174 {
1175         struct skinny_line *l;
1176
1177         for (l = d->lines; l; l = l->next) {
1178                 if (l->instance == instance)
1179                         break;
1180         }
1181
1182         if (!l) {
1183                 ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
1184         }
1185         return l;
1186 }
1187
1188 static struct skinny_line *find_line_by_name(const char *dest)
1189 {
1190         struct skinny_line *l;
1191         struct skinny_device *d;
1192         char line[256];
1193         char *at;
1194         char *device;
1195
1196         ast_copy_string(line, dest, sizeof(line));
1197         at = strchr(line, '@');
1198         if (!at) {
1199                 ast_log(LOG_NOTICE, "Device '%s' has no @ (at) sign!\n", dest);
1200                 return NULL;
1201         }
1202         *at++ = '\0';
1203         device = at;
1204         ast_mutex_lock(&devicelock);
1205         for (d = devices; d; d = d->next) {
1206                 if (!strcasecmp(d->name, device)) {
1207                         if (skinnydebug)
1208                                 ast_verbose("Found device: %s\n", d->name);
1209                         /* Found the device */
1210                         for (l = d->lines; l; l = l->next) {
1211                                 /* Search for the right line */
1212                                 if (!strcasecmp(l->name, line)) {
1213                                         ast_mutex_unlock(&devicelock);
1214                                         return l;
1215                                 }
1216                         }
1217                 }
1218         }
1219         /* Device not found */
1220         ast_mutex_unlock(&devicelock);
1221         return NULL;
1222 }
1223
1224 /* It's quicker/easier to find the subchannel when we know the instance number too */
1225 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
1226 {
1227         struct skinny_line *l = find_line_by_instance(d, instance);
1228         struct skinny_subchannel *sub;
1229
1230         if (!l) {
1231                 return NULL;
1232         }
1233
1234         for (sub = l->sub; sub; sub = sub->next) {
1235                 if (sub->callid == reference)
1236                         break;
1237         }
1238
1239         if (!sub) {
1240                 ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
1241         }
1242         return sub;
1243 }
1244
1245 /* Find the subchannel when we only have the callid - this shouldn't happen often */
1246 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
1247 {
1248         struct skinny_line *l;
1249         struct skinny_subchannel *sub = NULL;
1250
1251         for (l = d->lines; l; l = l->next) {
1252                 for (sub = l->sub; sub; sub = sub->next) {
1253                         if (sub->callid == reference)
1254                                 break;
1255                 }
1256                 if (sub)
1257                         break;
1258         }
1259
1260         if (!l) {
1261                 ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
1262         } else {
1263                 if (!sub) {
1264                         ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
1265                 }
1266         }
1267         return sub;
1268 }
1269
1270 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance)
1271 {
1272         struct skinny_speeddial *sd;
1273
1274         for (sd = d->speeddials; sd; sd = sd->next) {
1275                 if (sd->instance == instance)
1276                         break;
1277         }
1278
1279         if (!sd) {
1280                 ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
1281         }
1282         return sd;
1283 }
1284
1285 static int transmit_response(struct skinnysession *s, struct skinny_req *req)
1286 {
1287         int res = 0;
1288         ast_mutex_lock(&s->lock);
1289
1290 #if 0
1291         if (skinnydebug)
1292                 ast_verbose("writing packet type %04X (%d bytes) to socket %d\n", letohl(req->e), letohl(req->len)+8, s->fd);
1293 #endif
1294
1295         memset(s->outbuf,0,sizeof(s->outbuf));
1296         memcpy(s->outbuf, req, skinny_header_size);
1297         memcpy(s->outbuf+skinny_header_size, &req->data, sizeof(union skinny_data));
1298
1299         res = write(s->fd, s->outbuf, letohl(req->len)+8);
1300         if (res != letohl(req->len)+8) {
1301                 ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
1302         }
1303         ast_mutex_unlock(&s->lock);
1304         return 1;
1305 }
1306
1307 /* XXX Do this right */
1308 static int convert_cap(int capability)
1309 {
1310         return 4; /* ulaw (this is not the same as asterisk's '4' */
1311
1312 }
1313
1314 static void transmit_speaker_mode(struct skinnysession *s, int mode)
1315 {
1316         struct skinny_req *req;
1317
1318         if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
1319                 return;
1320
1321         req->data.setspeaker.mode = htolel(mode);
1322         transmit_response(s, req);
1323 }
1324 /*
1325 static void transmit_microphone_mode(struct skinnysession *s, int mode)
1326 {
1327         struct skinny_req *req;
1328
1329         if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
1330                 return;
1331
1332         req->data.setmicrophone.mode = htolel(mode);
1333         transmit_response(s, req);
1334 }
1335 */
1336 static void transmit_callstate(struct skinnysession *s, int instance, int state, unsigned callid)
1337 {
1338         struct skinny_req *req;
1339
1340         if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
1341                 return;
1342
1343         if (state == SKINNY_ONHOOK) {
1344                 transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
1345         }
1346         req->data.callstate.callState = htolel(state);
1347         req->data.callstate.lineInstance = htolel(instance);
1348         req->data.callstate.callReference = htolel(callid);
1349         transmit_response(s, req);
1350         if (state == SKINNY_OFFHOOK) {
1351                 if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
1352                         return;
1353
1354                 req->data.activatecallplane.lineInstance = htolel(instance);
1355                 transmit_response(s, req);
1356         } else if (state == SKINNY_ONHOOK) {
1357                 if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
1358                         return;
1359
1360                 req->data.activatecallplane.lineInstance = htolel(instance);
1361                 transmit_response(s, req);
1362
1363                 if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
1364                         return;
1365
1366                 req->data.closereceivechannel.conferenceId = 0;
1367                 req->data.closereceivechannel.partyId = htolel(callid);
1368                 transmit_response(s, req);
1369
1370                 if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
1371                         return;
1372
1373                 req->data.stopmedia.conferenceId = 0;
1374                 req->data.stopmedia.passThruPartyId = htolel(callid);
1375                 transmit_response(s, req);
1376         }
1377 }
1378
1379 static void transmit_callinfo(struct skinnysession *s, const char *fromname, const char *fromnum, const char *toname, const char *tonum, int instance, int callid, int calltype)
1380 {
1381         struct skinny_req *req;
1382
1383         if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
1384                 return;
1385
1386         if (fromname) {
1387                 ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
1388         }
1389         if (fromnum) {
1390                 ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
1391         }
1392         if (toname) {
1393                 ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
1394         }
1395         if (tonum) {
1396                 ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
1397         }
1398         req->data.callinfo.instance = htolel(instance);
1399         req->data.callinfo.reference = htolel(callid);
1400         req->data.callinfo.type = htolel(calltype);
1401         transmit_response(s, req);
1402 }
1403
1404 static void transmit_connect(struct skinnysession *s, struct skinny_subchannel *sub)
1405 {
1406         struct skinny_req *req;
1407         struct skinny_line *l = sub->parent;
1408
1409         if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
1410                 return;
1411
1412         req->data.openreceivechannel.conferenceId = htolel(0);
1413         req->data.openreceivechannel.partyId = htolel(sub->callid);
1414         req->data.openreceivechannel.packets = htolel(l->prefs.framing[0]);
1415         req->data.openreceivechannel.capability = htolel(convert_cap(l->capability));
1416         req->data.openreceivechannel.echo = htolel(0);
1417         req->data.openreceivechannel.bitrate = htolel(0);
1418         transmit_response(s, req);
1419 }
1420
1421 static void transmit_tone(struct skinnysession *s, int tone)
1422 {
1423         struct skinny_req *req;
1424
1425         if (tone == SKINNY_NOTONE) {
1426                 /* This is bad, mmm'kay? */
1427                 return;
1428         }
1429
1430         if (tone > 0) {
1431                 if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
1432                         return;
1433         } else {
1434                 if (!(req = req_alloc(0, STOP_TONE_MESSAGE)))
1435                         return;
1436         }
1437
1438         if (tone > 0) {
1439                 req->data.starttone.tone = htolel(tone);
1440         }
1441         transmit_response(s, req);
1442 }
1443
1444 static void transmit_selectsoftkeys(struct skinnysession *s, int instance, int callid, int softkey)
1445 {
1446         struct skinny_req *req;
1447
1448         if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
1449                 return;
1450
1451         req->data.selectsoftkey.instance = htolel(instance);
1452         req->data.selectsoftkey.reference = htolel(callid);
1453         req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
1454         req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
1455         transmit_response(s, req);
1456 }
1457
1458 static void transmit_lamp_indication(struct skinnysession *s, int stimulus, int instance, int indication)
1459 {
1460         struct skinny_req *req;
1461
1462         if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
1463                 return;
1464
1465         req->data.setlamp.stimulus = htolel(stimulus);
1466         req->data.setlamp.stimulusInstance = htolel(instance);
1467         req->data.setlamp.deviceStimulus = htolel(indication);
1468         transmit_response(s, req);
1469 }
1470
1471 static void transmit_ringer_mode(struct skinnysession *s, int mode)
1472 {
1473         struct skinny_req *req;
1474
1475         if (skinnydebug)
1476                 ast_verbose("Setting ringer mode to '%d'.\n", mode);
1477
1478         if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
1479                 return;
1480
1481         req->data.setringer.ringerMode = htolel(mode);
1482         /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
1483            Note: The phone will always show as ringing on the display.
1484
1485            1: phone will audibly ring over and over
1486            2: phone will audibly ring only once
1487            any other value, will NOT cause the phone to audibly ring
1488         */
1489         req->data.setringer.unknown1 = htolel(1);
1490         /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
1491            Perhaps a packet capture can shed some light on this. */
1492         req->data.setringer.unknown2 = htolel(1);
1493         transmit_response(s, req);
1494 }
1495
1496 static void transmit_displaymessage(struct skinnysession *s, const char *text)
1497 {
1498         struct skinny_req *req;
1499
1500         if (text == 0) {
1501                 if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
1502                         return;
1503
1504                 if (skinnydebug)
1505                         ast_verbose("Clearing Display\n");
1506         } else {
1507                 if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
1508                         return;
1509
1510                 ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
1511                 if (skinnydebug)
1512                         ast_verbose("Displaying message '%s'\n", req->data.displaytext.text);
1513         }
1514
1515         transmit_response(s, req);
1516 }
1517
1518 static void transmit_displaynotify(struct skinnysession *s, const char *text, int t)
1519 {
1520         struct skinny_req *req;
1521
1522         if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
1523                 return;
1524
1525         ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
1526         req->data.displaynotify.displayTimeout = htolel(t);
1527
1528         if (skinnydebug)
1529                 ast_verbose("Displaying notify '%s'\n", text);
1530
1531         transmit_response(s, req);
1532 }
1533
1534 static void transmit_displaypromptstatus(struct skinnysession *s, const char *text, int t, int instance, int callid)
1535 {
1536         struct skinny_req *req;
1537
1538         if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
1539                 return;
1540
1541         ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
1542         req->data.displaypromptstatus.messageTimeout = htolel(t);
1543         req->data.displaypromptstatus.lineInstance = htolel(instance);
1544         req->data.displaypromptstatus.callReference = htolel(callid);
1545
1546         if (skinnydebug)
1547                 ast_verbose("Displaying Prompt Status '%s'\n", text);
1548
1549         transmit_response(s, req);
1550 }
1551
1552 static void transmit_dialednumber(struct skinnysession *s, const char *text, int instance, int callid)
1553 {
1554         struct skinny_req *req;
1555
1556         if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
1557                 return;
1558
1559         ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
1560         req->data.dialednumber.lineInstance = htolel(instance);
1561         req->data.dialednumber.callReference = htolel(callid);
1562
1563         transmit_response(s, req);
1564 }
1565
1566 /*
1567 static int has_voicemail(struct skinny_line *l)
1568 {
1569         return ast_app_has_voicemail(l->mailbox, NULL);
1570 }
1571 */
1572
1573 static void do_housekeeping(struct skinnysession *s)
1574 {
1575 /*
1576         int new;
1577         int old;
1578         struct skinny_device *d = s->device;
1579         struct skinny_line *l;
1580 */
1581
1582         transmit_displaymessage(s, NULL);
1583
1584 /*
1585         for (l = d->lines; l; l = l->next) {
1586                 if (has_voicemail(l)) {
1587                         if (skinnydebug)
1588                                 ast_verbose("Checking for voicemail Skinny %s@%s\n", l->name, d->name);
1589                         ast_app_inboxcount(l->mailbox, &new, &old);
1590                         if (skinnydebug)
1591                                 ast_verbose("Skinny %s@%s has voicemail!\n", l->name, d->name);
1592                         transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
1593                 } else {
1594                         transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
1595                 }
1596         }
1597 */
1598 }
1599
1600 /* I do not believe skinny can deal with video.
1601    Anyone know differently? */
1602 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
1603 static enum ast_rtp_get_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
1604 {
1605         struct skinny_subchannel *sub = NULL;
1606
1607         if (!(sub = c->tech_pvt) || !(sub->vrtp))
1608                 return AST_RTP_GET_FAILED;
1609
1610         *rtp = sub->vrtp;
1611
1612         return AST_RTP_TRY_NATIVE;
1613 }
1614
1615 static enum ast_rtp_get_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
1616 {
1617         struct skinny_subchannel *sub = NULL;
1618
1619         if (!(sub = c->tech_pvt) || !(sub->rtp))
1620                 return AST_RTP_GET_FAILED;
1621
1622         *rtp = sub->rtp;
1623
1624         return AST_RTP_TRY_NATIVE;
1625 }
1626
1627 static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
1628 {
1629         struct skinny_subchannel *sub;
1630         sub = c->tech_pvt;
1631         if (sub) {
1632                 /* transmit_modify_with_sdp(sub, rtp); @@FIXME@@ if needed */
1633                 return 0;
1634         }
1635         return -1;
1636 }
1637
1638 static struct ast_rtp_protocol skinny_rtp = {
1639         .type = "Skinny",
1640         .get_rtp_info = skinny_get_rtp_peer,
1641         .get_vrtp_info = skinny_get_vrtp_peer,
1642         .set_rtp_peer = skinny_set_rtp_peer,
1643 };
1644
1645 static int skinny_do_debug(int fd, int argc, char *argv[])
1646 {
1647         if (argc != 2) {
1648                 return RESULT_SHOWUSAGE;
1649         }
1650         skinnydebug = 1;
1651         ast_cli(fd, "Skinny Debugging Enabled\n");
1652         return RESULT_SUCCESS;
1653 }
1654
1655 static int skinny_no_debug(int fd, int argc, char *argv[])
1656 {
1657         if (argc != 2) {
1658                 return RESULT_SHOWUSAGE;
1659         }
1660         skinnydebug = 0;
1661         ast_cli(fd, "Skinny Debugging Disabled\n");
1662         return RESULT_SUCCESS;
1663 }
1664
1665 static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
1666 {
1667         struct skinny_device *d;
1668
1669         char *result = NULL;
1670         int wordlen = strlen(word);
1671         int which = 0;
1672
1673         if (pos == 2) {
1674                 for (d = devices; d && !result; d = d->next) {
1675                         if (!strncasecmp(word, d->id, wordlen) && ++which > state)
1676                                 result = ast_strdup(d->id);
1677                 }
1678         }
1679
1680         return result;
1681 }
1682
1683 static int skinny_reset_device(int fd, int argc, char *argv[])
1684 {
1685         struct skinny_device *d;
1686         struct skinny_req *req;
1687
1688         if (argc < 3 || argc > 4) {
1689                 return RESULT_SHOWUSAGE;
1690         }
1691         ast_mutex_lock(&devicelock);
1692
1693         for (d = devices; d; d = d->next) {
1694                 int fullrestart = 0;
1695                 if (!strcasecmp(argv[2], d->id) || !strcasecmp(argv[2], "all")) {
1696                         if (!(d->session))
1697                                 continue;
1698
1699                         if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
1700                                 continue;
1701
1702                         if (argc == 4 && !strcasecmp(argv[3], "restart"))
1703                                 fullrestart = 1;
1704
1705                         if (fullrestart)
1706                                 req->data.reset.resetType = 2;
1707                         else
1708                                 req->data.reset.resetType = 1;
1709
1710                         if (option_verbose > 2)
1711                                 ast_verbose(VERBOSE_PREFIX_3 "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
1712                         transmit_response(d->session, req);
1713                 }
1714         }
1715         ast_mutex_unlock(&devicelock);
1716         return RESULT_SUCCESS;
1717 }
1718
1719 static char *device2str(int type)
1720 {
1721         char *tmp;
1722
1723         switch (type) {
1724         case SKINNY_DEVICE_NONE:
1725                 return "No Device";
1726         case SKINNY_DEVICE_30SPPLUS:
1727                 return "30SP Plus";
1728         case SKINNY_DEVICE_12SPPLUS:
1729                 return "12SP Plus";
1730         case SKINNY_DEVICE_12SP:
1731                 return "12SP";
1732         case SKINNY_DEVICE_12:
1733                 return "12";
1734         case SKINNY_DEVICE_30VIP:
1735                 return "30VIP";
1736         case SKINNY_DEVICE_7910:
1737                 return "7910";
1738         case SKINNY_DEVICE_7960:
1739                 return "7960";
1740         case SKINNY_DEVICE_7940:
1741                 return "7940";
1742         case SKINNY_DEVICE_7935:
1743                 return "7935";
1744         case SKINNY_DEVICE_ATA186:
1745                 return "ATA186";
1746         case SKINNY_DEVICE_7941:
1747                 return "7941";
1748         case SKINNY_DEVICE_7971:
1749                 return "7971";
1750         case SKINNY_DEVICE_7985:
1751                 return "7985";
1752         case SKINNY_DEVICE_7911:
1753                 return "7911";
1754         case SKINNY_DEVICE_7961GE:
1755                 return "7961GE";
1756         case SKINNY_DEVICE_7941GE:
1757                 return "7941GE";
1758         case SKINNY_DEVICE_7905:
1759                 return "7905";
1760         case SKINNY_DEVICE_7920:
1761                 return "7920";
1762         case SKINNY_DEVICE_7970:
1763                 return "7970";
1764         case SKINNY_DEVICE_7912:
1765                 return "7912";
1766         case SKINNY_DEVICE_7902:
1767                 return "7902";
1768         case SKINNY_DEVICE_CIPC:
1769                 return "IP Communicator";
1770         case SKINNY_DEVICE_7961:
1771                 return "7961";
1772         case SKINNY_DEVICE_7936:
1773                 return "7936";
1774         case SKINNY_DEVICE_SCCPGATEWAY_AN:
1775                 return "SCCPGATEWAY_AN";
1776         case SKINNY_DEVICE_SCCPGATEWAY_BRI:
1777                 return "SCCPGATEWAY_BRI";
1778         case SKINNY_DEVICE_UNKNOWN:
1779                 return "Unknown";
1780         default:
1781                 if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
1782                         return "Unknown";
1783                 snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
1784                 return tmp;
1785         }
1786 }
1787
1788 static int skinny_show_devices(int fd, int argc, char *argv[])
1789 {
1790         struct skinny_device *d;
1791         struct skinny_line *l;
1792         int numlines = 0;
1793
1794         if (argc != 3) {
1795                 return RESULT_SHOWUSAGE;
1796         }
1797         ast_mutex_lock(&devicelock);
1798
1799         ast_cli(fd, "Name                 DeviceId         IP              Type            R NL\n");
1800         ast_cli(fd, "-------------------- ---------------- --------------- --------------- - --\n");
1801         for (d = devices; d; d = d->next) {
1802                 numlines = 0;
1803                 for (l = d->lines; l; l = l->next) {
1804                         numlines++;
1805                 }
1806
1807                 ast_cli(fd, "%-20s %-16s %-15s %-15s %c %2d\n",
1808                                 d->name,
1809                                 d->id,
1810                                 d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
1811                                 device2str(d->type),
1812                                 d->registered?'Y':'N',
1813                                 numlines);
1814         }
1815         ast_mutex_unlock(&devicelock);
1816         return RESULT_SUCCESS;
1817 }
1818
1819 static int skinny_show_lines(int fd, int argc, char *argv[])
1820 {
1821         struct skinny_device *d;
1822         struct skinny_line *l;
1823
1824         if (argc != 3) {
1825                 return RESULT_SHOWUSAGE;
1826         }
1827         ast_mutex_lock(&devicelock);
1828
1829         ast_cli(fd, "Device Name          Instance Name                 Label               \n");
1830         ast_cli(fd, "-------------------- -------- -------------------- --------------------\n");
1831         for (d = devices; d; d = d->next) {
1832                 for (l = d->lines; l; l = l->next) {
1833                         ast_cli(fd, "%-20s %8d %-20s %-20s\n",
1834                                 d->name,
1835                                 l->instance,
1836                                 l->name,
1837                                 l->label);
1838                 }
1839         }
1840
1841         ast_mutex_unlock(&devicelock);
1842         return RESULT_SUCCESS;
1843 }
1844
1845 static char show_devices_usage[] =
1846 "Usage: skinny list devices\n"
1847 "       Lists all devices known to the Skinny subsystem.\n";
1848
1849 static char show_lines_usage[] =
1850 "Usage: skinny list lines\n"
1851 "       Lists all lines known to the Skinny subsystem.\n";
1852
1853 static char debug_usage[] =
1854 "Usage: skinny debug\n"
1855 "       Enables dumping of Skinny packets for debugging purposes\n";
1856
1857 static char no_debug_usage[] =
1858 "Usage: skinny nodebug\n"
1859 "       Disables dumping of Skinny packets for debugging purposes\n";
1860
1861 static char reset_usage[] =
1862 "Usage: skinny reset <DeviceId|all> [restart]\n"
1863 "       Causes a Skinny device to reset itself, optionally with a full restart\n";
1864
1865 static struct ast_cli_entry cli_skinny[] = {
1866         { { "skinny", "list", "devices", NULL },
1867         skinny_show_devices, "List defined Skinny devices",
1868         show_devices_usage },
1869
1870         { { "skinny", "list", "lines", NULL },
1871         skinny_show_lines, "List defined Skinny lines per device",
1872         show_lines_usage },
1873
1874         { { "skinny", "debug", NULL },
1875         skinny_do_debug, "Enable Skinny debugging",
1876         debug_usage },
1877
1878         { { "skinny", "nodebug", NULL },
1879         skinny_no_debug, "Disable Skinny debugging",
1880         no_debug_usage },
1881
1882         { { "skinny", "reset", NULL },
1883         skinny_reset_device, "Reset Skinny device(s)",
1884         reset_usage, complete_skinny_reset },
1885 };
1886
1887 #if 0
1888 static struct skinny_paging_device *build_paging_device(const char *cat, struct ast_variable *v)
1889 {
1890         return NULL;
1891 }
1892 #endif
1893
1894 static struct skinny_device *build_device(const char *cat, struct ast_variable *v)
1895 {
1896         struct skinny_device *d;
1897         struct skinny_line *l;
1898         struct skinny_speeddial *sd;
1899         struct skinny_addon *a;
1900         int lineInstance = 1;
1901         int speeddialInstance = 1;
1902         int y = 0;
1903
1904         if (!(d = ast_calloc(1, sizeof(struct skinny_device)))) {
1905                 return NULL;
1906         } else {
1907                 ast_copy_string(d->name, cat, sizeof(d->name));
1908                 d->lastlineinstance = 1;
1909                 d->capability = default_capability;
1910                 d->prefs = default_prefs;
1911                 while(v) {
1912                         if (!strcasecmp(v->name, "host")) {
1913                                 if (ast_get_ip(&d->addr, v->value)) {
1914                                         free(d);
1915                                         return NULL;
1916                                 }
1917                         } else if (!strcasecmp(v->name, "port")) {
1918                                 d->addr.sin_port = htons(atoi(v->value));
1919                         } else if (!strcasecmp(v->name, "device")) {
1920                                 ast_copy_string(d->id, v->value, sizeof(d->id));
1921                         } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
1922                                 d->ha = ast_append_ha(v->name, v->value, d->ha);
1923                         } else if (!strcasecmp(v->name, "context")) {
1924                                 ast_copy_string(context, v->value, sizeof(context));
1925                         } else if (!strcasecmp(v->name, "allow")) {
1926                                 ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 1);
1927                         } else if (!strcasecmp(v->name, "disallow")) {
1928                                 ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 0);
1929                         } else if (!strcasecmp(v->name, "version")) {
1930                                 ast_copy_string(d->version_id, v->value, sizeof(d->version_id));
1931                         } else if (!strcasecmp(v->name, "nat")) {
1932                                 nat = ast_true(v->value);
1933                         } else if (!strcasecmp(v->name, "callerid")) {
1934                                 if (!strcasecmp(v->value, "asreceived")) {
1935                                         cid_num[0] = '\0';
1936                                         cid_name[0] = '\0';
1937                                 } else {
1938                                         ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
1939                                 }
1940                         } else if (!strcasecmp(v->name, "language")) {
1941                                 ast_copy_string(language, v->value, sizeof(language));
1942                         } else if (!strcasecmp(v->name, "accountcode")) {
1943                                 ast_copy_string(accountcode, v->value, sizeof(accountcode));
1944                         } else if (!strcasecmp(v->name, "amaflags")) {
1945                                 y = ast_cdr_amaflags2int(v->value);
1946                                 if (y < 0) {
1947                                         ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
1948                                 } else {
1949                                         amaflags = y;
1950                                 }
1951                         } else if (!strcasecmp(v->name, "mohinterpret") || !strcasecmp(v->name, "musiconhold")) {
1952                                 ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
1953                         } else if (!strcasecmp(v->name, "mohsuggest")) {
1954                                 ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
1955                         } else if (!strcasecmp(v->name, "callgroup")) {
1956                                 cur_callergroup = ast_get_group(v->value);
1957                         } else if (!strcasecmp(v->name, "pickupgroup")) {
1958                                 cur_pickupgroup = ast_get_group(v->value);
1959                         } else if (!strcasecmp(v->name, "immediate")) {
1960                                 immediate = ast_true(v->value);
1961                         } else if (!strcasecmp(v->name, "cancallforward")) {
1962                                 cancallforward = ast_true(v->value);
1963                         } else if (!strcasecmp(v->name, "mailbox")) {
1964                                 ast_copy_string(mailbox, v->value, sizeof(mailbox));
1965                         } else if (!strcasecmp(v->name, "callreturn")) {
1966                                 callreturn = ast_true(v->value);
1967                         } else if (!strcasecmp(v->name, "callwaiting")) {
1968                                 callwaiting = ast_true(v->value);
1969                         } else if (!strcasecmp(v->name, "transfer")) {
1970                                 transfer = ast_true(v->value);
1971                         } else if (!strcasecmp(v->name, "threewaycalling")) {
1972                                 threewaycalling = ast_true(v->value);
1973                         } else if (!strcasecmp(v->name, "mwiblink")) {
1974                                 mwiblink = ast_true(v->value);
1975                         } else if (!strcasecmp(v->name, "linelabel")) {
1976                                 ast_copy_string(linelabel, v->value, sizeof(linelabel));
1977                         } else if (!strcasecmp(v->name, "speeddial")) {
1978                                 if (!(sd = ast_calloc(1, sizeof(struct skinny_speeddial)))) {
1979                                         return NULL;
1980                                 } else {
1981                                         char *stringp, *exten, *label;
1982                                         stringp = v->value;
1983                                         exten = strsep(&stringp, ",");
1984                                         label = strsep(&stringp, ",");
1985                                         ast_mutex_init(&sd->lock);
1986                                         ast_copy_string(sd->exten, exten, sizeof(sd->exten));
1987                                         if (label)
1988                                                 ast_copy_string(sd->label, label, sizeof(sd->label));
1989                                         else
1990                                                 ast_copy_string(sd->label, exten, sizeof(sd->label));
1991                                         sd->instance = speeddialInstance++;
1992
1993                                         sd->next = d->speeddials;
1994                                         d->speeddials = sd;
1995                                 }
1996                         } else if (!strcasecmp(v->name, "addon")) {
1997                                 if (!(a = ast_calloc(1, sizeof(struct skinny_addon)))) {
1998                                         return NULL;
1999                                 } else {
2000                                         ast_mutex_init(&a->lock);
2001                                         ast_copy_string(a->type, v->value, sizeof(a->type));
2002
2003                                         a->next = d->addons;
2004                                         d->addons = a;
2005                                 }
2006                         } else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
2007                                 if (!(l = ast_calloc(1, sizeof(struct skinny_line)))) {
2008                                         return NULL;
2009                                 } else {
2010                                         ast_mutex_init(&l->lock);
2011                                         ast_copy_string(l->name, v->value, sizeof(l->name));
2012
2013                                         /* XXX Should we check for uniqueness?? XXX */
2014                                         ast_copy_string(l->context, context, sizeof(l->context));
2015                                         ast_copy_string(l->cid_num, cid_num, sizeof(l->cid_num));
2016                                         ast_copy_string(l->cid_name, cid_name, sizeof(l->cid_name));
2017                                         ast_copy_string(l->label, linelabel, sizeof(l->label));
2018                                         ast_copy_string(l->language, language, sizeof(l->language));
2019                                         ast_copy_string(l->mohinterpret, mohinterpret, sizeof(l->mohinterpret));
2020                                         ast_copy_string(l->mohsuggest, mohsuggest, sizeof(l->mohsuggest));
2021                                         ast_copy_string(l->mailbox, mailbox, sizeof(l->mailbox));
2022                                         ast_copy_string(l->mailbox, mailbox, sizeof(l->mailbox));
2023                                         if (!ast_strlen_zero(mailbox)) {
2024                                                 if (option_verbose > 2)
2025                                                         ast_verbose(VERBOSE_PREFIX_3 "Setting mailbox '%s' on %s@%s\n", mailbox, d->name, l->name);
2026                                         }
2027                                         l->msgstate = -1;
2028                                         l->capability = d->capability;
2029                                         l->prefs = d->prefs;
2030                                         l->parent = d;
2031                                         if (!strcasecmp(v->name, "trunk")) {
2032                                                 l->type = TYPE_TRUNK;
2033                                         } else {
2034                                                 l->type = TYPE_LINE;
2035                                         }
2036                                         l->immediate = immediate;
2037                                         l->callgroup = cur_callergroup;
2038                                         l->pickupgroup = cur_pickupgroup;
2039                                         l->callreturn = callreturn;
2040                                         l->cancallforward = cancallforward;
2041                                         l->callwaiting = callwaiting;
2042                                         l->transfer = transfer;
2043                                         l->threewaycalling = threewaycalling;
2044                                         l->mwiblink = mwiblink;
2045                                         l->onhooktime = time(NULL);
2046                                         l->instance = lineInstance++;
2047                                         /* ASSUME we're onhook at this point */
2048                                         l->hookstate = SKINNY_ONHOOK;
2049                                         l->nat = nat;
2050
2051                                         l->next = d->lines;
2052                                         d->lines = l;
2053                                 }
2054                         } else {
2055                                 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
2056                         }
2057                         v = v->next;
2058                 }
2059
2060                 if (!d->lines) {
2061                         ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
2062                         return NULL;
2063                 }
2064                 if (/*d->addr.sin_addr.s_addr && */!ntohs(d->addr.sin_port)) {
2065                         d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
2066                 }
2067 #if 0
2068                 /* I don't think we need this anymore at all, since d->ourip is set in skinny_register now */
2069                 if (d->addr.sin_addr.s_addr) {
2070                         /* XXX See note above, in 'host' option. */
2071                         if (ast_ouraddrfor(&d->addr.sin_addr, &d->ourip)) {
2072                                 d->ourip = __ourip;
2073                         }
2074                 } else {
2075                         d->ourip = __ourip;
2076                 }
2077 #endif
2078         }
2079         return d;
2080 }
2081
2082 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
2083 {
2084         struct skinny_device *d;
2085         struct sockaddr_in sin;
2086         socklen_t slen;
2087
2088         ast_mutex_lock(&devicelock);
2089         for (d = devices; d; d = d->next) {
2090                 if (!strcasecmp(req->data.reg.name, d->id)
2091                                 && ast_apply_ha(d->ha, &(s->sin))) {
2092                         s->device = d;
2093                         d->type = letohl(req->data.reg.type);
2094                         if (ast_strlen_zero(d->version_id)) {
2095                                 ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
2096                         }
2097                         d->registered = 1;
2098                         d->session = s;
2099
2100                         slen = sizeof(sin);
2101                         if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
2102                                 ast_log(LOG_WARNING, "Cannot get socket name\n");
2103                                 sin.sin_addr = __ourip;
2104                         }
2105                         d->ourip = sin.sin_addr;
2106                         break;
2107                 }
2108         }
2109         ast_mutex_unlock(&devicelock);
2110         if (!d) {
2111                 return 0;
2112         }
2113         return 1;
2114 }
2115
2116 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
2117 {
2118         struct skinny_device *d;
2119
2120         d = s->device;
2121
2122         if (d) {
2123                 d->session = NULL;
2124                 d->registered = 0;
2125         }
2126
2127         return -1; /* main loop will destroy the session */
2128 }
2129
2130 static void start_rtp(struct skinny_subchannel *sub)
2131 {
2132         struct skinny_line *l = sub->parent;
2133         struct skinny_device *d = l->parent;
2134         int hasvideo = 0;
2135
2136         ast_mutex_lock(&sub->lock);
2137         /* Allocate the RTP */
2138         sub->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2139         if (hasvideo)
2140                 sub->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2141         
2142         if (sub->rtp && sub->owner) {
2143                 sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
2144                 sub->owner->fds[1] = ast_rtcp_fd(sub->rtp);
2145         }
2146         if (hasvideo && sub->vrtp && sub->owner) {
2147                 sub->owner->fds[2] = ast_rtp_fd(sub->vrtp);
2148                 sub->owner->fds[3] = ast_rtcp_fd(sub->vrtp);
2149         }
2150         if (sub->rtp) {
2151                 ast_rtp_setnat(sub->rtp, l->nat);
2152         }
2153         if (sub->vrtp) {
2154                 ast_rtp_setnat(sub->vrtp, l->nat);
2155         }
2156         /* Set Frame packetization */
2157         if (sub->rtp)
2158                 ast_rtp_codec_setpref(sub->rtp, &l->prefs);
2159
2160         /* Create the RTP connection */
2161         transmit_connect(d->session, sub);
2162         ast_mutex_unlock(&sub->lock);
2163 }
2164
2165 static void *skinny_newcall(void *data)
2166 {
2167         struct ast_channel *c = data;
2168         struct skinny_subchannel *sub = c->tech_pvt;
2169         struct skinny_line *l = sub->parent;
2170         struct skinny_device *d = l->parent;
2171         struct skinnysession *s = d->session;
2172         int res = 0;
2173
2174         ast_copy_string(l->lastnumberdialed, c->exten, sizeof(l->lastnumberdialed));
2175         ast_set_callerid(c,
2176                 l->hidecallerid ? "" : l->cid_num,
2177                 l->hidecallerid ? "" : l->cid_name,
2178                 c->cid.cid_ani ? NULL : l->cid_num);
2179         ast_setstate(c, AST_STATE_RING);
2180         res = ast_pbx_run(c);
2181         if (res) {
2182                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2183                 transmit_tone(s, SKINNY_REORDER);
2184         }
2185         return NULL;
2186 }
2187
2188 static void *skinny_ss(void *data)
2189 {
2190         struct ast_channel *c = data;
2191         struct skinny_subchannel *sub = c->tech_pvt;
2192         struct skinny_line *l = sub->parent;
2193         struct skinny_device *d = l->parent;
2194         struct skinnysession *s = d->session;
2195         char exten[AST_MAX_EXTENSION] = "";
2196         int len = 0;
2197         int timeout = firstdigittimeout;
2198         int res;
2199         int getforward=0;
2200
2201         if (option_verbose > 2)
2202                 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s@%s'\n", l->name, d->name);
2203
2204         while (len < AST_MAX_EXTENSION-1) {
2205                 res = ast_waitfordigit(c, timeout);
2206                 timeout = 0;
2207                 if (res < 0) {
2208                         if (skinnydebug)
2209                                 ast_verbose("Skinny(%s@%s): waitfordigit returned < 0\n", l->name, d->name);
2210                         ast_indicate(c, -1);
2211                         ast_hangup(c);
2212                         return NULL;
2213                 } else if (res) {
2214                         exten[len++]=res;
2215                         exten[len] = '\0';
2216                 }
2217                 if (!ast_ignore_pattern(c->context, exten)) {
2218                         transmit_tone(s, SKINNY_SILENCE);
2219                 }
2220                 if (ast_exists_extension(c, c->context, exten, 1, l->cid_num)) {
2221                         if (!res || !ast_matchmore_extension(c, c->context, exten, 1, l->cid_num)) {
2222                                 if (getforward) {
2223                                         /* Record this as the forwarding extension */
2224                                         ast_copy_string(l->call_forward, exten, sizeof(l->call_forward));
2225                                         if (option_verbose > 2)
2226                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n",
2227                                                         l->call_forward, c->name);
2228                                         transmit_tone(s, SKINNY_DIALTONE);
2229                                         if (res) {
2230                                                 break;
2231                                         }
2232                                         ast_safe_sleep(c, 500);
2233                                         ast_indicate(c, -1);
2234                                         ast_safe_sleep(c, 1000);
2235                                         memset(exten, 0, sizeof(exten));
2236                                         transmit_tone(s, SKINNY_DIALTONE);
2237                                         len = 0;
2238                                         getforward = 0;
2239                                 } else {
2240                                         ast_copy_string(c->exten, exten, sizeof(c->exten));
2241                                         ast_copy_string(l->lastnumberdialed, exten, sizeof(l->lastnumberdialed));
2242                                         skinny_newcall(c);
2243                                         return NULL;
2244                                 }
2245                         } else {
2246                                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
2247                                    so just set the timeout to matchdigittimeout and wait some more */
2248                                 timeout = matchdigittimeout;
2249                         }
2250                 } else if (res == 0) {
2251                         ast_log(LOG_DEBUG, "Not enough digits (and no ambiguous match)...\n");
2252                         transmit_tone(s, SKINNY_REORDER);
2253                         ast_hangup(c);
2254                         return NULL;
2255                 } else if (!ast_canmatch_extension(c, c->context, exten, 1, c->cid.cid_num) &&
2256                            ((exten[0] != '*') || (!ast_strlen_zero(exten) > 2))) {
2257                         ast_log(LOG_WARNING, "Can't match [%s] from '%s' in context %s\n", exten, c->cid.cid_num ? c->cid.cid_num : "<Unknown Caller>", c->context);
2258                         transmit_tone(s, SKINNY_REORDER);
2259                         /* hang out for 3 seconds to let congestion play */
2260                         ast_safe_sleep(c, 3000);
2261                         break;
2262                 }
2263                 if (!timeout) {
2264                         timeout = gendigittimeout;
2265                 }
2266                 if (len && !ast_ignore_pattern(c->context, exten)) {
2267                         ast_indicate(c, -1);
2268                 }
2269         }
2270         ast_hangup(c);
2271         return NULL;
2272 }
2273
2274
2275
2276 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
2277 {
2278         int res = 0;
2279         int tone = 0;
2280         struct skinny_subchannel *sub = ast->tech_pvt;
2281         struct skinny_line *l = sub->parent;
2282         struct skinny_device *d = l->parent;
2283         struct skinnysession *s = d->session;
2284
2285         if (!d->registered) {
2286                 ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
2287                 return -1;
2288         }
2289
2290         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2291                 ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
2292                 return -1;
2293         }
2294
2295         if (skinnydebug)
2296                 ast_verbose(VERBOSE_PREFIX_3 "skinny_call(%s)\n", ast->name);
2297
2298         if (l->dnd) {
2299                 ast_queue_control(ast, AST_CONTROL_BUSY);
2300                 return -1;
2301         }
2302
2303         switch (l->hookstate) {
2304         case SKINNY_OFFHOOK:
2305                 tone = SKINNY_CALLWAITTONE;
2306                 break;
2307         case SKINNY_ONHOOK:
2308                 tone = SKINNY_ALERT;
2309                 break;
2310         default:
2311                 ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
2312                 break;
2313         }
2314
2315         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
2316         transmit_ringer_mode(s, SKINNY_RING_INSIDE);
2317
2318         transmit_tone(s, tone);
2319         transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
2320         transmit_callstate(s, l->instance, SKINNY_RINGIN, sub->callid);
2321         transmit_displaypromptstatus(s, "Ring-In", 0, l->instance, sub->callid);
2322         transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGIN);
2323
2324         ast_setstate(ast, AST_STATE_RINGING);
2325         ast_queue_control(ast, AST_CONTROL_RINGING);
2326         sub->outgoing = 1;
2327         return res;
2328 }
2329
2330 static int skinny_hangup(struct ast_channel *ast)
2331 {
2332         struct skinny_subchannel *sub = ast->tech_pvt;
2333         struct skinny_line *l;
2334         struct skinny_device *d;
2335         struct skinnysession *s;
2336
2337         if (!sub) {
2338                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
2339                 return 0;
2340         }
2341         l = sub->parent;
2342         d = l->parent;
2343         s = d->session;
2344         if (skinnydebug)
2345                 ast_verbose("skinny_hangup(%s) on %s@%s\n", ast->name, l->name, d->name);
2346
2347         if (d->registered) {
2348                 if ((l->type = TYPE_LINE) && (l->hookstate == SKINNY_OFFHOOK)) {
2349                         l->hookstate = SKINNY_ONHOOK;
2350                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2351                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2352                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
2353                 } else if ((l->type = TYPE_LINE) && (l->hookstate == SKINNY_ONHOOK)) {
2354                         transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
2355                         transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
2356                         transmit_ringer_mode(s, SKINNY_RING_OFF);
2357                         transmit_tone(s, SKINNY_SILENCE);
2358                         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
2359                         do_housekeeping(s);
2360                 }
2361         }
2362         ast_mutex_lock(&sub->lock);
2363         sub->owner = NULL;
2364         ast->tech_pvt = NULL;
2365         sub->alreadygone = 0;
2366         sub->outgoing = 0;
2367         if (sub->rtp) {
2368                 ast_rtp_destroy(sub->rtp);
2369                 sub->rtp = NULL;
2370         }
2371         ast_mutex_unlock(&sub->lock);
2372         return 0;
2373 }
2374
2375 static int skinny_answer(struct ast_channel *ast)
2376 {
2377         int res = 0;
2378         struct skinny_subchannel *sub = ast->tech_pvt;
2379         struct skinny_line *l = sub->parent;
2380         struct skinny_device *d = l->parent;
2381         struct skinnysession *s = d->session;
2382
2383         sub->cxmode = SKINNY_CX_SENDRECV;
2384         if (!sub->rtp) {
2385                 start_rtp(sub);
2386         }
2387         if (skinnydebug)
2388                 ast_verbose("skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, d->name, sub->callid);
2389         if (ast->_state != AST_STATE_UP) {
2390                 ast_setstate(ast, AST_STATE_UP);
2391         }
2392
2393         transmit_tone(s, SKINNY_SILENCE);
2394         /* order matters here...
2395            for some reason, transmit_callinfo must be before transmit_callstate,
2396            or you won't get keypad messages in some situations. */
2397         transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2);
2398         transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
2399         transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
2400         return res;
2401 }
2402
2403 /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
2404 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
2405 {
2406         struct ast_channel *ast = sub->owner;
2407         struct ast_frame *f;
2408
2409         if (!sub->rtp) {
2410                 /* We have no RTP allocated for this channel */
2411                 return &ast_null_frame;
2412         }
2413
2414         switch(ast->fdno) {
2415         case 0:
2416                 f = ast_rtp_read(sub->rtp);     /* RTP Audio */
2417                 break;
2418         case 1:
2419                 f = ast_rtcp_read(sub->rtp);    /* RTCP Control Channel */
2420                 break;
2421         case 2:
2422                 f = ast_rtp_read(sub->vrtp);    /* RTP Video */
2423                 break;
2424         case 3:
2425                 f = ast_rtcp_read(sub->vrtp);   /* RTCP Control Channel for video */
2426                 break;
2427 #if 0
2428         case 5:
2429                 /* Not yet supported */
2430                 f = ast_udptl_read(sub->udptl); /* UDPTL for T.38 */
2431                 break;
2432 #endif
2433         default:
2434                 f = &ast_null_frame;
2435         }
2436
2437         if (ast) {
2438                 /* We already hold the channel lock */
2439                 if (f->frametype == AST_FRAME_VOICE) {
2440                         if (f->subclass != ast->nativeformats) {
2441                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2442                                 ast->nativeformats = f->subclass;
2443                                 ast_set_read_format(ast, ast->readformat);
2444                                 ast_set_write_format(ast, ast->writeformat);
2445                         }
2446                 }
2447         }
2448         return f;
2449 }
2450
2451 static struct ast_frame *skinny_read(struct ast_channel *ast)
2452 {
2453         struct ast_frame *fr;
2454         struct skinny_subchannel *sub = ast->tech_pvt;
2455         ast_mutex_lock(&sub->lock);
2456         fr = skinny_rtp_read(sub);
2457         ast_mutex_unlock(&sub->lock);
2458         return fr;
2459 }
2460
2461 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
2462 {
2463         struct skinny_subchannel *sub = ast->tech_pvt;
2464         int res = 0;
2465         if (frame->frametype != AST_FRAME_VOICE) {
2466                 if (frame->frametype == AST_FRAME_IMAGE) {
2467                         return 0;
2468                 } else {
2469                         ast_log(LOG_WARNING, "Can't send %d type frames with skinny_write\n", frame->frametype);
2470                         return 0;
2471                 }
2472         } else {
2473                 if (!(frame->subclass & ast->nativeformats)) {
2474                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2475                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2476                         return -1;
2477                 }
2478         }
2479         if (sub) {
2480                 ast_mutex_lock(&sub->lock);
2481                 if (sub->rtp) {
2482                         res = ast_rtp_write(sub->rtp, frame);
2483                 }
2484                 ast_mutex_unlock(&sub->lock);
2485         }
2486         return res;
2487 }
2488
2489 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2490 {
2491         struct skinny_subchannel *sub = newchan->tech_pvt;
2492         ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", oldchan->name, newchan->name);
2493         if (sub->owner != oldchan) {
2494                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
2495                 return -1;
2496         }
2497         sub->owner = newchan;
2498         return 0;
2499 }
2500
2501 static int skinny_senddigit_begin(struct ast_channel *ast, char digit)
2502 {
2503         return -1; /* Start inband indications */
2504 }
2505
2506 static int skinny_senddigit_end(struct ast_channel *ast, char digit)
2507 {
2508 #if 0
2509         struct skinny_subchannel *sub = ast->tech_pvt;
2510         struct skinny_line *l = sub->parent;
2511         struct skinny_device *d = l->parent;
2512         int tmp;
2513         /* not right */
2514         sprintf(tmp, "%d", digit);
2515         transmit_tone(d->session, digit);
2516 #endif
2517         return -1; /* Stop inband indications */
2518 }
2519
2520 static char *control2str(int ind) {
2521         char *tmp;
2522
2523         switch (ind) {
2524         case AST_CONTROL_HANGUP:
2525                 return "Other end has hungup";
2526         case AST_CONTROL_RING:
2527                 return "Local ring";
2528         case AST_CONTROL_RINGING:
2529                 return "Remote end is ringing";
2530         case AST_CONTROL_ANSWER:
2531                 return "Remote end has answered";
2532         case AST_CONTROL_BUSY:
2533                 return "Remote end is busy";
2534         case AST_CONTROL_TAKEOFFHOOK:
2535                 return "Make it go off hook";
2536         case AST_CONTROL_OFFHOOK:
2537                 return "Line is off hook";
2538         case AST_CONTROL_CONGESTION:
2539                 return "Congestion (circuits busy)";
2540         case AST_CONTROL_FLASH:
2541                 return "Flash hook";
2542         case AST_CONTROL_WINK:
2543                 return "Wink";
2544         case AST_CONTROL_OPTION:
2545                 return "Set a low-level option";
2546         case AST_CONTROL_RADIO_KEY:
2547                 return "Key Radio";
2548         case AST_CONTROL_RADIO_UNKEY:
2549                 return "Un-Key Radio";
2550         case AST_CONTROL_PROGRESS:
2551                 return "Remote end is making Progress";
2552         case AST_CONTROL_PROCEEDING:
2553                 return "Remote end is proceeding";
2554         case AST_CONTROL_HOLD:
2555                 return "Hold";
2556         case AST_CONTROL_UNHOLD:
2557                 return "Unhold";
2558         case -1:
2559                 return "Stop tone";
2560         default:
2561                 if (!(tmp = ast_threadstorage_get(&control2str_threadbuf, CONTROL2STR_BUFSIZE)))
2562                         return "Unknown";
2563                 snprintf(tmp, CONTROL2STR_BUFSIZE, "UNKNOWN-%d", ind);
2564                 return tmp;
2565         }
2566 }
2567
2568
2569 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
2570 {
2571         struct skinny_subchannel *sub = ast->tech_pvt;
2572         struct skinny_line *l = sub->parent;
2573         struct skinny_device *d = l->parent;
2574         struct skinnysession *s = d->session;
2575
2576         if (skinnydebug)
2577                 ast_verbose(VERBOSE_PREFIX_3 "Asked to indicate '%s' condition on channel %s\n", control2str(ind), ast->name);
2578         switch(ind) {
2579         case AST_CONTROL_RINGING:
2580                 if (ast->_state != AST_STATE_UP) {
2581                         if (!sub->progress) {
2582                                 transmit_tone(s, SKINNY_ALERT);
2583                                 transmit_callstate(s, l->instance, SKINNY_RINGOUT, sub->callid);
2584                                 transmit_dialednumber(s, ast->exten, l->instance, sub->callid);
2585                                 transmit_displaypromptstatus(s, "Ring Out", 0, l->instance, sub->callid);
2586                                 transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2587                                 sub->ringing = 1;
2588                                 break;
2589                         }
2590                 }
2591                 return -1;
2592         case AST_CONTROL_BUSY:
2593                 if (ast->_state != AST_STATE_UP) {
2594                         transmit_tone(s, SKINNY_BUSYTONE);
2595                         transmit_callstate(s, l->instance, SKINNY_BUSY, sub->callid);
2596                         sub->alreadygone = 1;
2597                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2598                         break;
2599                 }
2600                 return -1;
2601         case AST_CONTROL_CONGESTION:
2602                 if (ast->_state != AST_STATE_UP) {
2603                         transmit_tone(s, SKINNY_REORDER);
2604                         transmit_callstate(s, l->instance, SKINNY_CONGESTION, sub->callid);
2605                         sub->alreadygone = 1;
2606                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2607                         break;
2608                 }
2609                 return -1;
2610         case AST_CONTROL_PROGRESS:
2611                 if ((ast->_state != AST_STATE_UP) && !sub->progress && !sub->outgoing) {
2612                         transmit_tone(s, SKINNY_ALERT);
2613                         transmit_callstate(s, l->instance, SKINNY_PROGRESS, sub->callid);
2614                         transmit_displaypromptstatus(s, "Call Progress", 0, l->instance, sub->callid);
2615                         transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, ast->exten, ast->exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
2616                         sub->progress = 1;
2617                         break;
2618                 }
2619                 return -1;
2620         case -1:
2621                 transmit_tone(s, SKINNY_SILENCE);
2622                 break;
2623         case AST_CONTROL_HOLD:
2624                 ast_moh_start(ast, data, l->mohinterpret);
2625                 break;
2626         case AST_CONTROL_UNHOLD:
2627                 ast_moh_stop(ast);
2628                 break;
2629         case AST_CONTROL_PROCEEDING:
2630                 break;
2631         default:
2632                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
2633                 return -1;
2634         }
2635         return 0;
2636 }
2637
2638 static struct ast_channel *skinny_new(struct skinny_line *l, int state)
2639 {
2640         struct ast_channel *tmp;
2641         struct skinny_subchannel *sub;
2642         struct skinny_device *d = l->parent;
2643         int fmt;
2644
2645         tmp = ast_channel_alloc(1);
2646         if (!tmp) {
2647                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2648                 return NULL;
2649         } else {
2650                 sub = ast_calloc(1, sizeof(struct skinny_subchannel));
2651                 if (!sub) {
2652                         ast_log(LOG_WARNING, "Unable to allocate Skinny subchannel\n");
2653                         return NULL;
2654                 } else {
2655                         ast_mutex_init(&sub->lock);
2656
2657                         sub->owner = tmp;
2658                         sub->callid = callnums++;
2659                         d->lastlineinstance = l->instance;
2660                         d->lastcallreference = sub->callid;
2661                         sub->cxmode = SKINNY_CX_INACTIVE;
2662                         sub->nat = l->nat;
2663                         sub->parent = l;
2664                         sub->onhold = 0;
2665
2666                         sub->next = l->sub;
2667                         l->sub = sub;
2668                 }
2669                 tmp->tech = &skinny_tech;
2670                 tmp->tech_pvt = sub;
2671                 tmp->nativeformats = l->capability;
2672                 if (!tmp->nativeformats)
2673                         tmp->nativeformats = default_capability;
2674                 fmt = ast_best_codec(tmp->nativeformats);
2675                 if (skinnydebug)
2676                         ast_verbose("skinny_new: tmp->nativeformats=%d fmt=%d\n", tmp->nativeformats, fmt);
2677                 ast_string_field_build(tmp, name, "Skinny/%s@%s-%d", l->name, d->name, sub->callid);
2678                 if (sub->rtp) {
2679                         tmp->fds[0] = ast_rtp_fd(sub->rtp);
2680                 }
2681                 ast_setstate(tmp, state);
2682                 if (state == AST_STATE_RING) {
2683                         tmp->rings = 1;
2684                 }
2685                 tmp->writeformat = fmt;
2686                 tmp->rawwriteformat = fmt;
2687                 tmp->readformat = fmt;
2688                 tmp->rawreadformat = fmt;
2689                 if (!ast_strlen_zero(l->language))
2690                         ast_string_field_set(tmp, language, l->language);
2691                 if (!ast_strlen_zero(l->accountcode))
2692                         ast_string_field_set(tmp, accountcode, l->accountcode);
2693                 if (l->amaflags)
2694                         tmp->amaflags = l->amaflags;
2695
2696                 ast_mutex_lock(&usecnt_lock);
2697                 usecnt++;
2698                 ast_mutex_unlock(&usecnt_lock);
2699                 ast_update_use_count();
2700                 tmp->callgroup = l->callgroup;
2701                 tmp->pickupgroup = l->pickupgroup;
2702                 ast_string_field_set(tmp, call_forward, l->call_forward);
2703                 ast_copy_string(tmp->context, l->context, sizeof(tmp->context));
2704                 ast_copy_string(tmp->exten, l->exten, sizeof(tmp->exten));
2705
2706                 /* Don't use ast_set_callerid() here because it will
2707                  * generate a NewCallerID event before the NewChannel event */
2708                 tmp->cid.cid_num = ast_strdup(l->cid_num);
2709                 tmp->cid.cid_ani = ast_strdup(l->cid_num);
2710                 tmp->cid.cid_name = ast_strdup(l->cid_name);
2711
2712                 tmp->priority = 1;
2713                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2714
2715                 if (sub->rtp)
2716                         ast_jb_configure(tmp, &global_jbconf);
2717
2718                 if (state != AST_STATE_DOWN) {
2719                         if (ast_pbx_start(tmp)) {
2720                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2721                                 ast_hangup(tmp);
2722                                 tmp = NULL;
2723                         }
2724                 }
2725         }
2726         return tmp;
2727 }
2728
2729 static int skinny_hold(struct skinny_subchannel *sub)
2730 {
2731         struct skinny_line *l = sub->parent;
2732         struct skinny_device *d = l->parent;
2733         struct skinnysession *s = d->session;
2734         struct skinny_req *req;
2735
2736         /* Channel needs to be put on hold */
2737         if (skinnydebug)
2738                 ast_verbose("Putting on Hold(%d)\n", l->instance);
2739
2740         ast_queue_control_data(sub->owner, AST_CONTROL_HOLD,
2741                 S_OR(l->mohsuggest, NULL),
2742                 !ast_strlen_zero(l->mohsuggest) ? strlen(l->mohsuggest) + 1 : 0);
2743
2744         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2745                 return 0;
2746
2747         req->data.activatecallplane.lineInstance = htolel(l->instance);
2748         transmit_response(s, req);
2749
2750         if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
2751                 return 0;
2752
2753         req->data.closereceivechannel.conferenceId = htolel(0);
2754         req->data.closereceivechannel.partyId = htolel(sub->callid);
2755         transmit_response(s, req);
2756
2757         if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
2758                 return 0;
2759
2760         req->data.stopmedia.conferenceId = htolel(0);
2761         req->data.stopmedia.passThruPartyId = htolel(sub->callid);
2762         transmit_response(s, req);
2763
2764         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
2765         sub->onhold = 1;
2766         return 1;
2767 }
2768
2769 static int skinny_unhold(struct skinny_subchannel *sub)
2770 {
2771         struct skinny_line *l = sub->parent;
2772         struct skinny_device *d = l->parent;
2773         struct skinnysession *s = d->session;
2774         struct skinny_req *req;
2775
2776         /* Channel is on hold, so we will unhold */
2777         if (skinnydebug)
2778                 ast_verbose("Taking off Hold(%d)\n", l->instance);
2779
2780         ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
2781
2782         if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
2783                 return 0;
2784
2785         req->data.activatecallplane.lineInstance = htolel(l->instance);
2786         transmit_response(s, req);
2787
2788         transmit_connect(s, sub);
2789         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
2790         sub->onhold = 0;
2791         return 1;
2792 }
2793
2794 static int handle_keep_alive_message(struct skinny_req *req, struct skinnysession *s)
2795 {
2796         if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
2797                 return -1;
2798
2799         transmit_response(s, req);
2800         do_housekeeping(s);
2801         return 1;
2802 }
2803
2804 static int handle_register_message(struct skinny_req *req, struct skinnysession *s)
2805 {
2806         char name[16];
2807         int res;
2808
2809         memcpy(&name, req->data.reg.name, sizeof(name));
2810
2811         res = skinny_register(req, s);
2812         if (!res) {
2813                 ast_log(LOG_ERROR, "Rejecting Device %s: Device not found\n", name);
2814                 if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
2815                         return -1;
2816
2817                 snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
2818                 transmit_response(s, req);
2819                 return 0;
2820         }
2821         if (option_verbose > 2)
2822                 ast_verbose(VERBOSE_PREFIX_3 "Device '%s' successfully registered\n", name);
2823
2824         if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
2825                 return -1;
2826
2827         req->data.regack.res[0] = '0';
2828         req->data.regack.res[1] = '\0';
2829         req->data.regack.keepAlive = htolel(keep_alive);
2830         ast_copy_string(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate));
2831         req->data.regack.res2[0] = '0';
2832         req->data.regack.res2[1] = '\0';
2833         req->data.regack.secondaryKeepAlive = htolel(keep_alive);
2834         transmit_response(s, req);
2835         if (skinnydebug)
2836                 ast_verbose("Requesting capabilities\n");
2837
2838         if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
2839                 return -1;
2840
2841         transmit_response(s, req);
2842
2843         return res;
2844 }
2845
2846 static int handle_ip_port_message(struct skinny_req *req, struct skinnysession *s)
2847 {
2848         /* no response necessary */
2849         return 1;
2850 }
2851
2852 static int handle_keypad_button_message(struct skinny_req *req, struct skinnysession *s)
2853 {
2854         struct skinny_subchannel *sub = NULL;
2855         struct skinny_line *l;
2856         struct skinny_device *d = s->device;
2857         struct ast_frame f = { 0, };
2858         char dgt;
2859         int digit;
2860         int lineInstance;
2861         int callReference;
2862
2863         digit = letohl(req->data.keypad.button);
2864         lineInstance = letohl(req->data.keypad.lineInstance);
2865         callReference = letohl(req->data.keypad.callReference);
2866
2867         if (digit == 14) {
2868                 dgt = '*';
2869         } else if (digit == 15) {
2870                 dgt = '#';
2871         } else if (digit >= 0 && digit <= 9) {
2872                 dgt = '0' + digit;
2873         } else {
2874                 /* digit=10-13 (A,B,C,D ?), or
2875                  * digit is bad value
2876                  *
2877                  * probably should not end up here, but set
2878                  * value for backward compatibility, and log
2879                  * a warning.
2880                  */
2881                 dgt = '0' + digit;
2882                 ast_log(LOG_WARNING, "Unsupported digit %d\n", digit);
2883         }
2884
2885         f.subclass = dgt;
2886
2887         f.src = "skinny";
2888
2889         if (lineInstance && callReference)
2890                 sub = find_subchannel_by_instance_reference(d, lineInstance, callReference);
2891         else
2892                 sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
2893
2894         if (!sub)
2895                 return 0;
2896
2897         l = sub->parent;
2898         if (sub->owner) {
2899                 if (sub->owner->_state == 0) {
2900                         f.frametype = AST_FRAME_DTMF_BEGIN;
2901                         ast_queue_frame(sub->owner, &f);
2902                 }
2903                 /* XXX MUST queue this frame to all lines in threeway call if threeway call is active */
2904                 f.frametype = AST_FRAME_DTMF_END;
2905                 ast_queue_frame(sub->owner, &f);
2906                 /* XXX This seriously needs to be fixed */
2907                 if (sub->next && sub->next->owner) {
2908                         if (sub->owner->_state == 0) {
2909                                 f.frametype = AST_FRAME_DTMF_BEGIN;
2910                                 ast_queue_frame(sub->next->owner, &f);
2911                         }
2912                         f.frametype = AST_FRAME_DTMF_END;
2913                         ast_queue_frame(sub->next->owner, &f);
2914                 }
2915         } else {
2916                 if (skinnydebug)
2917                         ast_verbose("No owner: %s\n", l->name);
2918         }
2919         return 1;
2920 }
2921
2922 static int handle_stimulus_message(struct skinny_req *req, struct skinnysession *s)
2923 {
2924         struct skinny_device *d = s->device;
2925         struct skinny_line *l;
2926         struct skinny_subchannel *sub;
2927         /*struct skinny_speeddial *sd;*/
2928         struct ast_channel *c;
2929         pthread_t t;
2930         int event;
2931         int instance;
2932         int unknown1;
2933         /*int res = 0;*/
2934
2935         event = letohl(req->data.stimulus.stimulus);
2936         instance = letohl(req->data.stimulus.stimulusInstance);
2937         unknown1 = letohl(req->data.stimulus.unknown1); /* No clue.. */
2938         if (skinnydebug)
2939                 ast_verbose("unknown1 in handle_stimulus_message is '%d'\n", unknown1);
2940
2941         sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
2942
2943         if (!sub) {
2944                 l = find_line_by_instance(d, d->lastlineinstance);
2945                 if (!l) {
2946                         return 0;
2947                 }
2948         } else {
2949                 l = sub->parent;
2950         }
2951
2952         switch(event) {
2953         case STIMULUS_REDIAL:
2954                 if (skinnydebug)
2955                         ast_verbose("Received Stimulus: Redial(%d)\n", instance);
2956
2957 #if 0
2958                 c = skinny_new(l, AST_STATE_DOWN);
2959                 if(!c) {
2960                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
2961                 } else {
2962                         sub = c->tech_pvt;
2963                         transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
2964                         if (skinnydebug)
2965                                 ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
2966                         transmit_displaymessage(s, NULL); /* clear display */
2967                         transmit_tone(s, SKINNY_DIALTONE);
2968
2969                         if (ast_strlen_zero(l->lastnumberdialed)) {
2970                                 ast_log(LOG_WARNING, "Attempted redial, but no previously dialed number found.\n");
2971                                 return 0;
2972                         }
2973                         if (!ast_ignore_pattern(c->context, l->lastnumberdialed)) {
2974                                 transmit_tone(s, SKINNY_SILENCE);
2975                         }
2976                         ast_copy_string(c->exten, l->lastnumberdialed, sizeof(c->exten));
2977                         if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
2978                                 ast_log(LOG_WARNING, "Unable to create new call thread: %s\n", strerror(errno));
2979                                 ast_hangup(c);
2980                         }
2981                 }
2982 #endif
2983                 break;
2984         case STIMULUS_SPEEDDIAL:
2985                 if (skinnydebug)
2986                         ast_verbose("Received Stimulus: SpeedDial(%d)\n", instance);
2987
2988 #if 0
2989                 if (!(sd = find_speeddial_by_instance(d, instance))) {
2990                         return 0;
2991                 }
2992
2993                 c = skinny_new(l, AST_STATE_DOWN);
2994                 if(c) {
2995                         sub = c->tech_pvt;
2996                         l = sub->parent;
2997                         transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
2998                         if (skinnydebug)
2999                                 ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
3000                         transmit_displaymessage(s, NULL); /* clear display */
3001                         transmit_tone(s, SKINNY_DIALTONE);
3002
3003                         if (!ast_ignore_pattern(c->context, sd->exten)) {
3004                                 transmit_tone(s, SKINNY_SILENCE);
3005                         }
3006                         if (ast_exists_extension(c, c->context, sd->exten, 1, l->cid_num)) {
3007                                 if (!ast_matchmore_extension(c, c->context, sd->exten, 1, l->cid_num)) {
3008                                         ast_copy_string(c->exten, sd->exten, sizeof(c->exten));
3009                                         ast_copy_string(l->lastnumberdialed, sd->exten, sizeof(l->lastnumberdialed));
3010                                         skinny_newcall(c);
3011                                         break;
3012                                 }
3013                         }
3014                 } else {
3015                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
3016                 }
3017 #endif
3018                 break;
3019         case STIMULUS_HOLD:
3020                 if (skinnydebug)
3021                         ast_verbose("Received Stimulus: Hold(%d)\n", instance);
3022
3023                 if (sub->onhold) {
3024                         skinny_unhold(sub);
3025                 } else {
3026                         skinny_hold(sub);
3027                 }
3028                 break;
3029         case STIMULUS_TRANSFER:
3030                 if (skinnydebug)
3031                         ast_verbose("Received Stimulus: Transfer(%d)\n", instance);
3032                 transmit_tone(s, SKINNY_DIALTONE);
3033                 /* XXX figure out how to transfer */
3034                 break;
3035         case STIMULUS_CONFERENCE:
3036                 if (skinnydebug)
3037                         ast_verbose("Received Stimulus: Conference(%d)\n", instance);
3038                 transmit_tone(s, SKINNY_DIALTONE);
3039                 /* XXX determine the best way to pull off a conference.  Meetme? */
3040                 break;
3041         case STIMULUS_VOICEMAIL:
3042                 if (skinnydebug)
3043                         ast_verbose("Received Stimulus: Voicemail(%d)\n", instance);
3044                 /* XXX Find and dial voicemail extension */
3045                 break;
3046         case STIMULUS_CALLPARK:
3047                 if (skinnydebug)
3048                         ast_verbose("Received Stimulus: Park Call(%d)\n", instance);
3049                 /* XXX Park the call */
3050                 break;
3051         case STIMULUS_FORWARDALL:
3052                 if (skinnydebug)
3053                         ast_verbose("Received Stimulus: Forward All(%d)\n", instance);
3054                 /* Why is DND under FORWARDALL? */
3055                 /* Because it's the same thing. */
3056
3057                 /* Do not disturb */
3058                 transmit_tone(s, SKINNY_DIALTONE);
3059                 if (l->dnd != 0){
3060                         if (option_verbose > 2)
3061                                 ast_verbose(VERBOSE_PREFIX_3 "Disabling DND on %s@%s\n", l->name, d->name);
3062                         l->dnd = 0;
3063                         transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
3064                         transmit_displaynotify(s, "DnD disabled", 10);
3065                 } else {
3066                         if (option_verbose > 2)
3067                                 ast_verbose(VERBOSE_PREFIX_3 "Enabling DND on %s@%s\n", l->name, d->name);
3068                         l->dnd = 1;
3069                         transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_OFF);
3070                         transmit_displaynotify(s, "DnD enabled", 10);
3071                 }
3072                 break;
3073         case STIMULUS_FORWARDBUSY:
3074                 if (skinnydebug)
3075                         ast_verbose("Received Stimulus: Forward Busy (%d)\n", instance);
3076                 break;
3077         case STIMULUS_FORWARDNOANSWER:
3078                 if (skinnydebug)
3079                         ast_verbose("Received Stimulus: Forward No Answer (%d)\n", instance);
3080                 break;
3081         case STIMULUS_DISPLAY:
3082                 /* Not sure what this is */
3083                 if (skinnydebug)
3084                         ast_verbose("Received Stimulus: Display(%d)\n", instance);
3085                 break;
3086         case STIMULUS_LINE:
3087                 if (skinnydebug)
3088                         ast_verbose("Received Stimulus: Line(%d)\n", instance);
3089
3090                 l = find_line_by_instance(s->device, instance);
3091
3092                 if (!l) {
3093                         return 0;
3094                 }
3095
3096                 /* turn the speaker on */
3097                 transmit_speaker_mode(s, SKINNY_SPEAKERON);
3098                 transmit_ringer_mode(s, SKINNY_RING_OFF);
3099                 transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3100
3101                 l->hookstate = SKINNY_OFFHOOK;
3102
3103                 if (sub && sub->outgoing) {
3104                         /* We're answering a ringing call */
3105                         ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
3106                         transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3107                         transmit_tone(s, SKINNY_SILENCE);
3108                         transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
3109                         transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
3110                         transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
3111                         start_rtp(sub);
3112                         ast_setstate(sub->owner, AST_STATE_UP);
3113                 } else {
3114                         if (sub && sub->owner) {
3115                                 ast_log(LOG_DEBUG, "Current subchannel [%s] already has owner\n", sub->owner->name);
3116                         } else {
3117                                 c = skinny_new(l, AST_STATE_DOWN);
3118                                 if(c) {
3119                                         sub = c->tech_pvt;
3120                                         transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3121                                         if (skinnydebug)
3122                                                 ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
3123                                         transmit_displaymessage(s, NULL); /* clear display */
3124                                         transmit_tone(s, SKINNY_DIALTONE);
3125                                         transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
3126
3127                                         /* start the switch thread */
3128                                         if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
3129                                                 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
3130                                                 ast_hangup(c);
3131                                         }
3132                                 } else {
3133                                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
3134                                 }
3135                         }
3136                 }
3137                 break;
3138         default:
3139                 if (skinnydebug)
3140                         ast_verbose("RECEIVED UNKNOWN STIMULUS:  %d(%d)\n", event, instance);
3141                 break;
3142         }
3143         return 1;
3144 }
3145
3146 static int handle_offhook_message(struct skinny_req *req, struct skinnysession *s)
3147 {
3148         struct skinny_device *d = s->device;
3149         struct skinny_line *l;
3150         struct skinny_subchannel *sub;
3151         struct ast_channel *c;
3152         pthread_t t;
3153         int unknown1;
3154         int unknown2;
3155
3156         unknown1 = letohl(req->data.offhook.unknown1);
3157         unknown2 = letohl(req->data.offhook.unknown2);
3158
3159         sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
3160
3161         if (!sub) {
3162                 l = find_line_by_instance(d, d->lastlineinstance);
3163                 if (!l) {
3164                         return 0;
3165                 }
3166         } else {
3167                 l = sub->parent;
3168         }
3169
3170         if (sub && sub->onhold) {
3171                 transmit_ringer_mode(s, SKINNY_RING_OFF);
3172                 l->hookstate = SKINNY_OFFHOOK;
3173                 return 1;
3174         }
3175
3176         transmit_ringer_mode(s, SKINNY_RING_OFF);
3177         transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
3178         l->hookstate = SKINNY_OFFHOOK;
3179
3180         if (sub && sub->outgoing) {
3181                 /* We're answering a ringing call */
3182                 ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
3183                 transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3184                 transmit_tone(s, SKINNY_SILENCE);
3185                 transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
3186                 transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
3187                 start_rtp(sub);
3188                 ast_setstate(sub->owner, AST_STATE_UP);
3189         } else {
3190                 if (sub && sub->owner) {
3191                         ast_log(LOG_DEBUG, "Current sub [%s] already has owner\n", sub->owner->name);
3192                 } else {
3193                         c = skinny_new(l, AST_STATE_DOWN);
3194                         if(c) {
3195                                 sub = c->tech_pvt;
3196                                 transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
3197                                 if (skinnydebug)
3198                                         ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
3199                                 transmit_displaymessage(s, NULL); /* clear display */
3200                                 transmit_tone(s, SKINNY_DIALTONE);
3201                                 transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
3202
3203                                 /* start the switch thread */
3204                                 if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
3205                                         ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
3206                                         ast_hangup(c);
3207                                 }
3208                         } else {
3209                                 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
3210                         }
3211                 }
3212         }
3213         return 1;
3214 }
3215
3216 static int handle_onhook_message(struct skinny_req *req, struct skinnysession *s)
3217 {
3218         struct skinny_device *d = s->device;
3219         struct skinny_line *l;
3220         struct skinny_subchannel *sub;
3221         int unknown1;
3222         int unknown2;
3223
3224         unknown1 = letohl(req->data.onhook.unknown1);
3225         unknown2 = letohl(req->data.onhook.unknown2);
3226
3227         sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
3228
3229         if (!sub) {
3230                 return 0;
3231         }
3232         l = sub->parent;
3233
3234         if (sub->onhold) {
3235                 l->hookstate = SKINNY_ONHOOK;
3236                 return 0;
3237         }
3238
3239         if (l->hookstate == SKINNY_ONHOOK) {
3240                 /* Something else already put us back on hook */
3241                 return 0;
3242         }
3243         sub->cxmode = SKINNY_CX_RECVONLY;
3244         l->hookstate = SKINNY_ONHOOK;
3245         transmit_callstate(s, l->instance, l->hookstate, sub->callid);
3246         if (skinnydebug)
3247                 ast_verbose("Skinny %s@%s went on hook\n", l->name, d->name);
3248         if (l->transfer && (sub->owner && sub->next && sub->next->owner) && ((!sub->outgoing) || (sub->next && !sub->next->outgoing))) {
3249                 /* We're allowed to transfer, we have two active calls and
3250                    we made at least one of the calls.  Let's try and transfer */
3251
3252 #if 0
3253                 if ((res = attempt_transfer(p)) < 0) {
3254                         if (sub->next && sub->next->owner) {
3255                                 sub->next->alreadygone = 1;
3256                                 ast_queue_hangup(sub->next->owner,1);
3257                         }
3258                 } else if (res) {
3259                         ast_log(LOG_WARNING, "Transfer attempt failed\n");
3260                         return 0;
3261                 }
3262 #endif
3263         } else {
3264                 /* Hangup the current call */
3265                 /* If there is another active call, skinny_hangup will ring the phone with the other call */
3266                 if (sub->owner) {
3267                         sub->alreadygone = 1;
3268                         ast_queue_hangup(sub->owner);
3269                 } else {
3270                         ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n",
3271                                 l->name, d->name, sub->callid);
3272                 }
3273         }
3274         if ((l->hookstate == SKINNY_ONHOOK) && (sub->next && !sub->next->rtp)) {
3275                 do_housekeeping(s);
3276         }
3277         return 1;
3278 }
3279
3280 static int handle_capabilities_res_message(struct skinny_req *req, struct skinnysession *s)
3281 {
3282         /* XXX process the capabilites */
3283         return 1;
3284 }
3285
3286 static int handle_speed_dial_stat_req_message(struct skinny_req *req, struct skinnysession *s)
3287 {
3288         struct skinny_device *d = s->device;
3289         struct skinny_speeddial *sd;
3290         int instance;
3291
3292         instance = letohl(req->data.speeddialreq.speedDialNumber);
3293
3294         sd = find_speeddial_by_instance(d, instance);
3295
3296         if (!sd) {
3297                 return 0;
3298         }
3299
3300         if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
3301                 return -1;
3302
3303         req->data.speeddialreq.speedDialNumber = htolel(instance);
3304         snprintf(req->data.speeddial.speedDialDirNumber, sizeof(req->data.speeddial.speedDialDirNumber), sd->exten);
3305         snprintf(req->data.speeddial.speedDialDisplayName, sizeof(req->data.speeddial.speedDialDisplayName), sd->label);
3306
3307         transmit_response(s, req);
3308         return 1;
3309 }
3310
3311 static int handle_line_state_req_message(struct skinny_req *req, struct skinnysession *s)
3312 {
3313         struct skinny_device *d = s->device;
3314         struct skinny_line *l;
3315         int instance;
3316
3317         instance = letohl(req->data.line.lineNumber);
3318
3319         ast_mutex_lock(&devicelock);
3320
3321         l = find_line_by_instance(d, instance);
3322
3323         if (!l) {
3324                 return 0;
3325         }
3326
3327         ast_mutex_unlock(&devicelock);
3328
3329         if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
3330                 return -1;
3331
3332         req->data.linestat.lineNumber = letohl(instance);
3333         memcpy(req->data.linestat.lineDirNumber, l->name,
3334                         sizeof(req->data.linestat.lineDirNumber));
3335         memcpy(req->data.linestat.lineDisplayName, l->label,
3336                         sizeof(req->data.linestat.lineDisplayName));
3337         transmit_response(s,req);
3338         return 1;
3339 }
3340
3341 static int handle_time_date_req_message(struct skinny_req *req, struct skinnysession *s)
3342 {
3343         time_t timer;
3344         struct tm *cmtime;
3345
3346         if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
3347                 return -1;
3348
3349         timer = time(NULL);
3350         cmtime = localtime(&timer);
3351         req->data.definetimedate.year = htolel(cmtime->tm_year+1900);
3352         req->data.definetimedate.month = htolel(cmtime->tm_mon+1);
3353         req->data.definetimedate.dayofweek = htolel(cmtime->tm_wday);
3354         req->data.definetimedate.day = htolel(cmtime->tm_mday);
3355         req->data.definetimedate.hour = htolel(cmtime->tm_hour);
3356         req->data.definetimedate.minute = htolel(cmtime->tm_min);
3357         req->data.definetimedate.seconds = htolel(cmtime->tm_sec);
3358         transmit_response(s, req);
3359         return 1;
3360 }
3361
3362 static int handle_button_template_req_message(struct skinny_req *req, struct skinnysession *s)
3363 {
3364         struct skinny_device *d = s->device;
3365         struct skinny_line *l;
3366         int i;
3367
3368         struct skinny_speeddial *sd;
3369         struct button_definition_template btn[42];
3370         int lineInstance = 1;
3371         int speeddialInstance = 1;
3372         int buttonCount = 0;
3373
3374         if (!(req = req_alloc(sizeof(struct button_template_res_message), BUTTON_TEMPLATE_RES_MESSAGE)))
3375                 return -1;
3376
3377         memset(&btn, 0, sizeof(btn));
3378
3379         get_button_template(s, btn);
3380
3381         for (i=0; i<42; i++) {
3382                 int btnSet = 0;
3383                 switch (btn[i].buttonDefinition) {
3384                         case BT_CUST_LINESPEEDDIAL:
3385                                 /* assume failure */
3386                                 req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
3387                                 req->data.buttontemplate.definition[i].instanceNumber = htolel(0);
3388
3389                                 for (l = d->lines; l; l = l->next) {
3390                                         if (l->instance == lineInstance) {
3391                                                 ast_verbose("Adding button: %d, %d\n", BT_LINE, lineInstance);
3392                                                 req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
3393                                                 req->data.buttontemplate.definition[i].instanceNumber = htolel(lineInstance);
3394                                                 lineInstance++;
3395                                                 buttonCount++;
3396                                                 btnSet = 1;
3397                                                 break;
3398                                         }
3399                                 }
3400
3401                                 if (!btnSet) {
3402                                         for (sd = d->speeddials; sd; sd = sd->next) {
3403                                                 if (sd->instance == speeddialInstance) {
3404                                                         ast_verbose("Adding button: %d, %d\n", BT_SPEEDDIAL, speeddialInstance);
3405                                                         req->data.buttontemplate.definition[i].buttonDefinition = BT_SPEEDDIAL;
3406                                                         req->data.buttontemplate.definition[i].instanceNumber = htolel(speeddialInstance);
3407                                                         speeddialInstance++;
3408                                                         buttonCount++;
3409                                                         btnSet = 1;
3410                                                         break;
3411                                                 }
3412                                         }
3413                                 }
3414                                 break;
3415                         case BT_LINE:
3416                                 req->data.buttontemplate.definition[i].buttonDefinition = htolel(BT_NONE);
3417                                 req->data.buttontemplate.definition[i].instanceNumber = htolel(0);
3418
3419                                 for (l = d->lines; l; l = l->next) {
3420                                         if (l->instance == lineInstance) {
3421                                                 ast_verbose("Adding button: %d, %d\n", BT_LINE, lineInstance);
3422                                                 req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
3423                                                 req->data.buttontemplate.definition[i].instanceNumber = htolel(lineInstance);
3424                                                 lineInstance++;
3425                                                 buttonCount++;
3426                                                 btnSet = 1;
3427                                                 break;
3428                                         }
3429                                 }
3430                                 break;
3431                         case BT_SPEEDDIAL:
3432                                 req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
3433                                 req->data.buttontemplate.definition[i].instanceNumber = 0;
3434
3435                                 for (sd = d->speeddials; sd; sd = sd->next) {
3436                                         if (sd->instance == speeddialInstance) {
3437                                                 ast_verbose("Adding button: %d, %d\n", BT_SPEEDDIAL, speeddialInstance);
3438                                                 req->data.buttontemplate.definition[i].buttonDefinition = BT_SPEEDDIAL;
3439                                                 req->data.buttontemplate.definition[i].instanceNumber = htolel(speeddialInstance);
3440                                                 speeddialInstance++;
3441                                                 buttonCount++;
3442                                                 btnSet = 1;
3443                                                 break;
3444                                         }
3445                                 }
3446                                 break;
3447                         case BT_CUST_HINT:
3448                                 break;
3449                         case BT_NONE:
3450                                 break;
3451                         default:
3452                                 ast_verbose("Adding button: %d, %d\n", btn[i].buttonDefinition, 0);
3453                                 req->data.buttontemplate.definition[i].buttonDefinition = htolel(btn[i].buttonDefinition);
3454                                 req->data.buttontemplate.definition[i].instanceNumber = htolel(0);
3455                                 buttonCount++;
3456                                 btnSet = 1;
3457                                 break;
3458                 }
3459         }
3460
3461         req->data.buttontemplate.buttonOffset = htolel(0);
3462         req->data.buttontemplate.buttonCount = htolel(buttonCount);
3463         req->data.buttontemplate.totalButtonCount = htolel(buttonCount);
3464
3465         if (skinnydebug)
3466                 ast_verbose("Sending %d template to %s\n",
3467                                         d->type,
3468                                         d->name);
3469         transmit_response(s, req);
3470         return 1;
3471 }
3472
3473 static int handle_version_req_message(struct skinny_req *req, struct skinnysession *s)
3474 {
3475         struct skinny_device *d = s->device;
3476         if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
3477                 return -1;
3478
3479         snprintf(req->data.version.version, sizeof(req->data.version.version), d->version_id);
3480         transmit_response(s, req);
3481         return 1;
3482 }
3483
3484 static int handle_server_request_message(struct skinny_req *req, struct skinnysession *s)
3485 {
3486         struct skinny_device *d = s->device;
3487         if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
3488                 return -1;
3489
3490         memcpy(req->data.serverres.server[0].serverName, ourhost,
3491                         sizeof(req->data.serverres.server[0].serverName));
3492         req->data.serverres.serverListenPort[0] = htolel(ourport);
3493         req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
3494         transmit_response(s, req);
3495         return 1;
3496 }
3497
3498 static int handle_alarm_message(struct skinny_req *req, struct skinnysession *s)
3499 {
3500         /* no response necessary */
3501         if (skinnydebug)
3502                 ast_verbose("Received Alarm Message: %s\n", req->data.alarm.displayMessage);
3503
3504         return 1;
3505 }
3506
3507 static int handle_open_receive_channel_ack_message(struct skinny_req *req, struct skinnysession *s)
3508 {
3509         struct skinny_device *d = s->device;
3510         struct skinny_line *l;
3511         struct skinny_subchannel *sub;
3512         struct sockaddr_in sin;
3513         struct sockaddr_in us;
3514         uint32_t addr;
3515         int port;
3516         int status;
3517         int passthruid;
3518
3519         status = letohl(req->data.openreceivechannelack.status);
3520         if (status) {
3521                 ast_log(LOG_ERROR, "Open Receive Channel Failure\n");
3522                 return 0;
3523         }
3524         addr = letohl(req->data.openreceivechannelack.ipAddr);
3525         port = letohl(req->data.openreceivechannelack.port);
3526         passthruid = letohl(req->data.openreceivechannelack.passThruId);
3527
3528         sin.sin_family = AF_INET;
3529         sin.sin_addr.s_addr = addr;
3530         sin.sin_port = htons(port);
3531
3532         sub = find_subchannel_by_reference(d, passthruid);
3533
3534         if (!sub)
3535                 return 0;
3536
3537         l = sub->parent;
3538
3539         if (sub->rtp) {
3540                 ast_rtp_set_peer(sub->rtp, &sin);
3541                 ast_rtp_get_us(sub->rtp, &us);
3542         } else {
3543                 ast_log(LOG_ERROR, "No RTP structure, this is very bad\n");
3544                 return 0;
3545         }
3546
3547         if (skinnydebug) {
3548                 ast_verbose("ipaddr = %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
3549                 ast_verbose("ourip = %s:%d\n", ast_inet_ntoa(d->ourip), ntohs(us.sin_port));
3550         }
3551
3552         if (!(req = req_alloc(sizeof(struct start_media_transmission_message), START_MEDIA_TRANSMISSION_MESSAGE)))
3553                 return -1;
3554
3555         req->data.startmedia.conferenceId = htolel(0);
3556         req->data.startmedia.passThruPartyId = htolel(sub->callid);
3557         req->data.startmedia.remoteIp = htolel(d->ourip.s_addr);
3558         req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
3559         req->data.startmedia.packetSize = htolel(l->prefs.framing[0]);
3560         req->data.startmedia.payloadType = htolel(convert_cap(l->capability));
3561         req->data.startmedia.qualifier.precedence = htolel(127);
3562         req->data.startmedia.qualifier.vad = htolel(0);
3563         req->data.startmedia.qualifier.packets = htolel(0);
3564         req->data.startmedia.qualifier.bitRate = htolel(0);
3565         transmit_response(s, req);
3566
3567         return 1;
3568 }
3569
3570 static int handle_soft_key_set_req_message(struct skinny_req *req, struct skinnysession *s)
3571 {
3572         int i;
3573         int x;
3574         int y;
3575         const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
3576
3577         if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
3578                 return -1;
3579
3580         req->data.softkeysets.softKeySetOffset = htolel(0);
3581         req->data.softkeysets.softKeySetCount = htolel(11);
3582         req->data.softkeysets.totalSoftKeySetCount = htolel(11);
3583         for (x = 0; x < sizeof(soft_key_default_definitions) / sizeof(struct soft_key_definitions); x++) {
3584                 const uint8_t *defaults = softkeymode->defaults;
3585                 /* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
3586                    This will have to do for now. */
3587                 for (y = 0; y < softkeymode->count; y++) {
3588                         for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
3589                                 if (defaults[y] == i+1) {
3590                                         req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = htolel(i+1);
3591                                 }
3592                         }
3593                 }
3594                 softkeymode++;
3595         }
3596         transmit_response(s,req);
3597         transmit_selectsoftkeys(s, 0, 0, KEYDEF_ONHOOK);
3598         return 1;
3599 }
3600
3601 static int handle_soft_key_event_message(struct skinny_req *req, struct skinnysession *s)
3602 {
3603         struct skinny_device *d = s->device;
3604         struct skinny_line *l;
3605         struct skinny_subchannel *sub = NULL;
3606         struct ast_channel *c;
3607         pthread_t t;
3608         int event;
3609         int instance;
3610         int reference;
3611
3612         event = letohl(req->data.softkeyeventmessage.softKeyEvent);
3613         instance = letohl(req->data.softkeyeventmessage.instance);
3614         reference = letohl(req->data.softkeyeventmessage.reference);
3615
3616         if (instance) {
3617                 l = find_line_by_instance(d, instance);
3618                 if (reference) {
3619                         sub = find_subchannel_by_instance_reference(d, instance, reference);
3620                 } else {
3621                         sub = find_subchannel_by_instance_reference(d, instance, d->lastcallreference);
3622                 }
3623         } else {
3624                 l = find_line_by_instance(d, d->lastlineinstance);
3625         }
3626
3627         if (!l) {
3628                 if (skinnydebug)
3629                         ast_verbose("Received Softkey Event: %d(%d)\n", event, instance);
3630                 return 0;
3631         }
3632
3633         switch(event) {
3634         case SOFTKEY_NONE:
3635                 if (skinnydebug)
3636                         ast_verbose("Received Softkey Event: None(%d)\n", instance);
3637                 break;
3638         case SOFTKEY_REDIAL:
3639                 if (skinnydebug)
3640                         ast_verbose("Received Softkey Event: Redial(%d)\n", instance);
3641
3642 #if 0
3643                 if (!sub || !sub->owner) {
3644                         c = skinny_new(l, AST_STATE_DOWN);
3645                 } else {
3646                         c = sub->owner;
3647                 }
3648
3649                 if(!c) {
3650                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->