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