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