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