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