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