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