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