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