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