Wed Aug 15 01:24:19 2007

Asterisk developer's documentation


chan_skinny.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2005, Digium, Inc.
00005  *
00006  * chan_skinny was developed by Jeremy McNamara & Florian Overkamp
00007  * chan_skinny was heavily modified/fixed by North Antara
00008  *
00009  * See http://www.asterisk.org for more information about
00010  * the Asterisk project. Please do not directly contact
00011  * any of the maintainers of this project for assistance;
00012  * the project provides a web site, mailing lists and IRC
00013  * channels for your use.
00014  *
00015  * This program is free software, distributed under the terms of
00016  * the GNU General Public License Version 2. See the LICENSE file
00017  * at the top of the source tree.
00018  */
00019 
00020 /*! \file
00021  *
00022  * \brief Implementation of the Skinny protocol
00023  *
00024  * \author Jeremy McNamara & Florian Overkamp & North Antara
00025  * \ingroup channel_drivers
00026  */
00027 
00028 
00029 #include "asterisk.h"
00030 
00031 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 78375 $")
00032 
00033 #include <stdio.h>
00034 #include <stdlib.h>
00035 #include <string.h>
00036 #include <unistd.h>
00037 #include <sys/socket.h>
00038 #include <netinet/in.h>
00039 #include <netinet/tcp.h>
00040 #include <sys/ioctl.h>
00041 #include <net/if.h>
00042 #include <errno.h>
00043 #include <fcntl.h>
00044 #include <netdb.h>
00045 #include <arpa/inet.h>
00046 #include <sys/signal.h>
00047 #include <signal.h>
00048 #include <ctype.h>
00049 
00050 #include "asterisk/lock.h"
00051 #include "asterisk/channel.h"
00052 #include "asterisk/config.h"
00053 #include "asterisk/logger.h"
00054 #include "asterisk/module.h"
00055 #include "asterisk/pbx.h"
00056 #include "asterisk/options.h"
00057 #include "asterisk/lock.h"
00058 #include "asterisk/sched.h"
00059 #include "asterisk/io.h"
00060 #include "asterisk/rtp.h"
00061 #include "asterisk/acl.h"
00062 #include "asterisk/callerid.h"
00063 #include "asterisk/cli.h"
00064 #include "asterisk/say.h"
00065 #include "asterisk/cdr.h"
00066 #include "asterisk/astdb.h"
00067 #include "asterisk/features.h"
00068 #include "asterisk/app.h"
00069 #include "asterisk/musiconhold.h"
00070 #include "asterisk/utils.h"
00071 #include "asterisk/dsp.h"
00072 #include "asterisk/stringfields.h"
00073 #include "asterisk/astobj.h"
00074 #include "asterisk/abstract_jb.h"
00075 #include "asterisk/threadstorage.h"
00076 
00077 /*************************************
00078  * Skinny/Asterisk Protocol Settings *
00079  *************************************/
00080 static const char tdesc[] = "Skinny Client Control Protocol (Skinny)";
00081 static const char config[] = "skinny.conf";
00082 
00083 static int default_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW;
00084 static struct ast_codec_pref default_prefs;
00085 
00086 enum skinny_codecs {
00087    SKINNY_CODEC_ALAW = 2,
00088    SKINNY_CODEC_ULAW = 4,
00089    SKINNY_CODEC_G723_1 = 9,
00090    SKINNY_CODEC_G729A = 12,
00091    SKINNY_CODEC_G726_32 = 82, /* XXX Which packing order does this translate to? */
00092    SKINNY_CODEC_H261 = 100,
00093    SKINNY_CODEC_H263 = 101
00094 };
00095 
00096 #define DEFAULT_SKINNY_PORT   2000
00097 #define DEFAULT_SKINNY_BACKLOG   2
00098 #define SKINNY_MAX_PACKET  1000
00099 
00100 static int keep_alive = 120;
00101 static char date_format[6] = "D-M-Y";
00102 static char version_id[16] = "P002F202";
00103 
00104 #if __BYTE_ORDER == __LITTLE_ENDIAN
00105 #define letohl(x) (x)
00106 #define letohs(x) (x)
00107 #define htolel(x) (x)
00108 #define htoles(x) (x)
00109 #else
00110 #if defined(SOLARIS) || defined(__Darwin__) || defined(__NetBSD__) || defined(__OpenBSD__)
00111 #define __bswap_16(x) \
00112    ((((x) & 0xff00) >> 8) | \
00113     (((x) & 0x00ff) << 8))
00114 #define __bswap_32(x) \
00115    ((((x) & 0xff000000) >> 24) | \
00116     (((x) & 0x00ff0000) >>  8) | \
00117     (((x) & 0x0000ff00) <<  8) | \
00118     (((x) & 0x000000ff) << 24))
00119 #else
00120 #include <bits/byteswap.h>
00121 #endif
00122 #define letohl(x) __bswap_32(x)
00123 #define letohs(x) __bswap_16(x)
00124 #define htolel(x) __bswap_32(x)
00125 #define htoles(x) __bswap_16(x)
00126 #endif
00127 
00128 /*! Global jitterbuffer configuration - by default, jb is disabled */
00129 static struct ast_jb_conf default_jbconf =
00130 {
00131    .flags = 0,
00132    .max_size = -1,
00133    .resync_threshold = -1,
00134    .impl = ""
00135 };
00136 static struct ast_jb_conf global_jbconf;
00137 
00138 AST_THREADSTORAGE(device2str_threadbuf, device2str_threadbuf_init);
00139 #define DEVICE2STR_BUFSIZE   15
00140 
00141 AST_THREADSTORAGE(control2str_threadbuf, control2str_threadbuf_init);
00142 #define CONTROL2STR_BUFSIZE   100
00143 
00144 /*********************
00145  * Protocol Messages *
00146  *********************/
00147 /* message types */
00148 #define KEEP_ALIVE_MESSAGE 0x0000
00149 /* no additional struct */
00150 
00151 #define REGISTER_MESSAGE 0x0001
00152 struct register_message {
00153    char name[16];
00154    uint32_t userId;
00155    uint32_t instance;
00156    uint32_t ip;
00157    uint32_t type;
00158    uint32_t maxStreams;
00159 };
00160 
00161 #define IP_PORT_MESSAGE 0x0002
00162 
00163 #define KEYPAD_BUTTON_MESSAGE 0x0003
00164 struct keypad_button_message {
00165    uint32_t button;
00166    uint32_t lineInstance;
00167    uint32_t callReference;
00168 };
00169 
00170 
00171 #define ENBLOC_CALL_MESSAGE 0x0004
00172 struct enbloc_call_message {
00173        char calledParty[24];
00174 };
00175 
00176 #define STIMULUS_MESSAGE 0x0005
00177 struct stimulus_message {
00178    uint32_t stimulus;
00179    uint32_t stimulusInstance;
00180    uint32_t callreference;
00181 };
00182 
00183 #define OFFHOOK_MESSAGE 0x0006
00184 struct offhook_message {
00185    uint32_t unknown1;
00186    uint32_t unknown2;
00187 };
00188 
00189 #define ONHOOK_MESSAGE 0x0007
00190 struct onhook_message {
00191    uint32_t unknown1;
00192    uint32_t unknown2;
00193 };
00194 
00195 #define CAPABILITIES_RES_MESSAGE 0x0010
00196 struct station_capabilities {
00197    uint32_t codec;
00198    uint32_t frames;
00199    union {
00200       char res[8];
00201       uint32_t rate;
00202    } payloads;
00203 };
00204 
00205 #define SKINNY_MAX_CAPABILITIES 18
00206 
00207 struct capabilities_res_message {
00208    uint32_t count;
00209    struct station_capabilities caps[SKINNY_MAX_CAPABILITIES];
00210 };
00211 
00212 #define SPEED_DIAL_STAT_REQ_MESSAGE 0x000A
00213 struct speed_dial_stat_req_message {
00214    uint32_t speedDialNumber;
00215 };
00216 
00217 #define LINE_STATE_REQ_MESSAGE 0x000B
00218 struct line_state_req_message {
00219    uint32_t lineNumber;
00220 };
00221 
00222 #define TIME_DATE_REQ_MESSAGE 0x000D
00223 #define BUTTON_TEMPLATE_REQ_MESSAGE 0x000E
00224 #define VERSION_REQ_MESSAGE 0x000F
00225 #define SERVER_REQUEST_MESSAGE 0x0012
00226 
00227 #define ALARM_MESSAGE 0x0020
00228 struct alarm_message {
00229    uint32_t alarmSeverity;
00230    char displayMessage[80];
00231    uint32_t alarmParam1;
00232    uint32_t alarmParam2;
00233 };
00234 
00235 #define OPEN_RECEIVE_CHANNEL_ACK_MESSAGE 0x0022
00236 struct open_receive_channel_ack_message {
00237    uint32_t status;
00238    uint32_t ipAddr;
00239    uint32_t port;
00240    uint32_t passThruId;
00241 };
00242 
00243 #define SOFT_KEY_SET_REQ_MESSAGE 0x0025
00244 
00245 #define SOFT_KEY_EVENT_MESSAGE 0x0026
00246 struct soft_key_event_message {
00247    uint32_t softKeyEvent;
00248    uint32_t instance;
00249    uint32_t callreference;
00250 };
00251 
00252 #define UNREGISTER_MESSAGE 0x0027
00253 #define SOFT_KEY_TEMPLATE_REQ_MESSAGE 0x0028
00254 #define HEADSET_STATUS_MESSAGE 0x002B
00255 #define REGISTER_AVAILABLE_LINES_MESSAGE 0x002D
00256 
00257 #define REGISTER_ACK_MESSAGE 0x0081
00258 struct register_ack_message {
00259    uint32_t keepAlive;
00260    char dateTemplate[6];
00261    char res[2];
00262    uint32_t secondaryKeepAlive;
00263    char res2[4];
00264 };
00265 
00266 #define START_TONE_MESSAGE 0x0082
00267 struct start_tone_message {
00268    uint32_t tone;
00269    uint32_t space;
00270    uint32_t instance;
00271    uint32_t reference;
00272 };
00273 
00274 #define STOP_TONE_MESSAGE 0x0083
00275 struct stop_tone_message {
00276    uint32_t instance;
00277    uint32_t reference;
00278 };
00279 
00280 #define SET_RINGER_MESSAGE 0x0085
00281 struct set_ringer_message {
00282    uint32_t ringerMode;
00283    uint32_t unknown1; /* See notes in transmit_ringer_mode */
00284    uint32_t unknown2;
00285    uint32_t space[2];
00286 };
00287 
00288 #define SET_LAMP_MESSAGE 0x0086
00289 struct set_lamp_message {
00290    uint32_t stimulus;
00291    uint32_t stimulusInstance;
00292    uint32_t deviceStimulus;
00293 };
00294 
00295 #define SET_SPEAKER_MESSAGE 0x0088
00296 struct set_speaker_message {
00297    uint32_t mode;
00298 };
00299 
00300 /* XXX When do we need to use this? */
00301 #define SET_MICROPHONE_MESSAGE 0x0089
00302 struct set_microphone_message {
00303    uint32_t mode;
00304 };
00305 
00306 #define START_MEDIA_TRANSMISSION_MESSAGE 0x008A
00307 struct media_qualifier {
00308    uint32_t precedence;
00309    uint32_t vad;
00310    uint16_t packets;
00311    uint32_t bitRate;
00312 };
00313 
00314 struct start_media_transmission_message {
00315    uint32_t conferenceId;
00316    uint32_t passThruPartyId;
00317    uint32_t remoteIp;
00318    uint32_t remotePort;
00319    uint32_t packetSize;
00320    uint32_t payloadType;
00321    struct media_qualifier qualifier;
00322    uint32_t space[16];
00323 };
00324 
00325 #define STOP_MEDIA_TRANSMISSION_MESSAGE 0x008B
00326 struct stop_media_transmission_message {
00327    uint32_t conferenceId;
00328    uint32_t passThruPartyId;
00329    uint32_t space[3];
00330 };
00331 
00332 #define CALL_INFO_MESSAGE 0x008F
00333 struct call_info_message {
00334    char callingPartyName[40];
00335    char callingParty[24];
00336    char calledPartyName[40];
00337    char calledParty[24];
00338    uint32_t instance;
00339    uint32_t reference;
00340    uint32_t type;
00341    char originalCalledPartyName[40];
00342    char originalCalledParty[24];
00343    char lastRedirectingPartyName[40];
00344    char lastRedirectingParty[24];
00345    uint32_t originalCalledPartyRedirectReason;
00346    uint32_t lastRedirectingReason;
00347    char callingPartyVoiceMailbox[24];
00348    char calledPartyVoiceMailbox[24];
00349    char originalCalledPartyVoiceMailbox[24];
00350    char lastRedirectingVoiceMailbox[24];
00351    uint32_t space[3];
00352 };
00353 
00354 #define SPEED_DIAL_STAT_RES_MESSAGE 0x0091
00355 struct speed_dial_stat_res_message {
00356    uint32_t speedDialNumber;
00357    char speedDialDirNumber[24];
00358    char speedDialDisplayName[40];
00359 };
00360 
00361 #define LINE_STAT_RES_MESSAGE 0x0092
00362 struct line_stat_res_message {
00363    uint32_t lineNumber;
00364    char lineDirNumber[24];
00365    char lineDisplayName[24];
00366    uint32_t space[15];
00367 };
00368 
00369 #define DEFINETIMEDATE_MESSAGE 0x0094
00370 struct definetimedate_message {
00371    uint32_t year; /* since 1900 */
00372    uint32_t month;
00373    uint32_t dayofweek;  /* monday = 1 */
00374    uint32_t day;
00375    uint32_t hour;
00376    uint32_t minute;
00377    uint32_t seconds;
00378    uint32_t milliseconds;
00379    uint32_t timestamp;
00380 };
00381 
00382 #define BUTTON_TEMPLATE_RES_MESSAGE 0x0097
00383 struct button_definition {
00384    uint8_t instanceNumber;
00385    uint8_t buttonDefinition;
00386 };
00387 
00388 struct button_definition_template {
00389    uint8_t buttonDefinition;
00390    /* for now, anything between 0xB0 and 0xCF is custom */
00391    /*int custom;*/
00392 };
00393 
00394 #define STIMULUS_REDIAL       0x01
00395 #define STIMULUS_SPEEDDIAL    0x02
00396 #define STIMULUS_HOLD         0x03
00397 #define STIMULUS_TRANSFER     0x04
00398 #define STIMULUS_FORWARDALL      0x05
00399 #define STIMULUS_FORWARDBUSY     0x06
00400 #define STIMULUS_FORWARDNOANSWER 0x07
00401 #define STIMULUS_DISPLAY      0x08
00402 #define STIMULUS_LINE         0x09
00403 #define STIMULUS_VOICEMAIL    0x0F
00404 #define STIMULUS_AUTOANSWER      0x11
00405 #define STIMULUS_CONFERENCE      0x7D
00406 #define STIMULUS_CALLPARK     0x7E
00407 #define STIMULUS_CALLPICKUP      0x7F
00408 #define STIMULUS_NONE         0xFF
00409 
00410 /* Button types */
00411 #define BT_REDIAL       STIMULUS_REDIAL
00412 #define BT_SPEEDDIAL       STIMULUS_SPEEDDIAL
00413 #define BT_HOLD            STIMULUS_HOLD
00414 #define BT_TRANSFER        STIMULUS_TRANSFER
00415 #define BT_FORWARDALL         STIMULUS_FORWARDALL
00416 #define BT_FORWARDBUSY        STIMULUS_FORWARDBUSY
00417 #define BT_FORWARDNOANSWER    STIMULUS_FORWARDNOANSWER
00418 #define BT_DISPLAY         STIMULUS_DISPLAY
00419 #define BT_LINE            STIMULUS_LINE
00420 #define BT_VOICEMAIL       STIMULUS_VOICEMAIL
00421 #define BT_AUTOANSWER         STIMULUS_AUTOANSWER
00422 #define BT_CONFERENCE         STIMULUS_CONFERENCE
00423 #define BT_CALLPARK        STIMULUS_CALLPARK
00424 #define BT_CALLPICKUP         STIMULUS_CALLPICKUP
00425 #define BT_NONE            0x00
00426 
00427 /* Custom button types - add our own between 0xB0 and 0xCF.
00428    This may need to be revised in the future,
00429    if stimuluses are ever added in this range. */
00430 #define BT_CUST_LINESPEEDDIAL    0xB0  /* line or speeddial */
00431 #define BT_CUST_HINT       0xB1  /* pipe dream */
00432 
00433 struct button_template_res_message {
00434    uint32_t buttonOffset;
00435    uint32_t buttonCount;
00436    uint32_t totalButtonCount;
00437    struct button_definition definition[42];
00438 };
00439 
00440 #define VERSION_RES_MESSAGE 0x0098
00441 struct version_res_message {
00442    char version[16];
00443 };
00444 
00445 #define DISPLAYTEXT_MESSAGE 0x0099
00446 struct displaytext_message {
00447    char text[40];
00448 };
00449 
00450 #define CLEAR_NOTIFY_MESSAGE  0x0115
00451 #define CLEAR_DISPLAY_MESSAGE 0x009A
00452 
00453 #define CAPABILITIES_REQ_MESSAGE 0x009B
00454 
00455 #define REGISTER_REJ_MESSAGE 0x009D
00456 struct register_rej_message {
00457    char errMsg[33];
00458 };
00459 
00460 #define SERVER_RES_MESSAGE 0x009E
00461 struct server_identifier {
00462    char serverName[48];
00463 };
00464 
00465 struct server_res_message {
00466    struct server_identifier server[5];
00467    uint32_t serverListenPort[5];
00468    uint32_t serverIpAddr[5];
00469 };
00470 
00471 #define RESET_MESSAGE 0x009F
00472 struct reset_message {
00473    uint32_t resetType;
00474 };
00475 
00476 #define KEEP_ALIVE_ACK_MESSAGE 0x0100
00477 
00478 #define OPEN_RECEIVE_CHANNEL_MESSAGE 0x0105
00479 struct open_receive_channel_message {
00480    uint32_t conferenceId;
00481    uint32_t partyId;
00482    uint32_t packets;
00483    uint32_t capability;
00484    uint32_t echo;
00485    uint32_t bitrate;
00486    uint32_t space[16];
00487 };
00488 
00489 #define CLOSE_RECEIVE_CHANNEL_MESSAGE 0x0106
00490 struct close_receive_channel_message {
00491    uint32_t conferenceId;
00492    uint32_t partyId;
00493    uint32_t space[2];
00494 };
00495 
00496 #define SOFT_KEY_TEMPLATE_RES_MESSAGE 0x0108
00497 
00498 struct soft_key_template_definition {
00499    char softKeyLabel[16];
00500    uint32_t softKeyEvent;
00501 };
00502 
00503 #define KEYDEF_ONHOOK         0
00504 #define KEYDEF_CONNECTED      1
00505 #define KEYDEF_ONHOLD         2
00506 #define KEYDEF_RINGIN         3
00507 #define KEYDEF_OFFHOOK        4
00508 #define KEYDEF_CONNWITHTRANS     5
00509 #define KEYDEF_DADFD       6 /* Digits After Dialing First Digit */
00510 #define KEYDEF_CONNWITHCONF      7
00511 #define KEYDEF_RINGOUT        8
00512 #define KEYDEF_OFFHOOKWITHFEAT      9
00513 #define KEYDEF_UNKNOWN        10
00514 
00515 #define SOFTKEY_NONE       0x00
00516 #define SOFTKEY_REDIAL        0x01
00517 #define SOFTKEY_NEWCALL       0x02
00518 #define SOFTKEY_HOLD       0x03
00519 #define SOFTKEY_TRNSFER       0x04
00520 #define SOFTKEY_CFWDALL       0x05
00521 #define SOFTKEY_CFWDBUSY      0x06
00522 #define SOFTKEY_CFWDNOANSWER     0x07
00523 #define SOFTKEY_BKSPC         0x08
00524 #define SOFTKEY_ENDCALL       0x09
00525 #define SOFTKEY_RESUME        0x0A
00526 #define SOFTKEY_ANSWER        0x0B
00527 #define SOFTKEY_INFO       0x0C
00528 #define SOFTKEY_CONFRN        0x0D
00529 #define SOFTKEY_PARK       0x0E
00530 #define SOFTKEY_JOIN       0x0F
00531 #define SOFTKEY_MEETME        0x10
00532 #define SOFTKEY_PICKUP        0x11
00533 #define SOFTKEY_GPICKUP       0x12
00534 
00535 struct soft_key_template_definition soft_key_template_default[] = {
00536    { "Redial",    0x01 },
00537    { "NewCall",      0x02 },
00538    { "Hold",      0x03 },
00539    { "Trnsfer",      0x04 },
00540    { "CFwdAll",      0x05 },
00541    { "CFwdBusy",     0x06 },
00542    { "CFwdNoAnswer", 0x07 },
00543    { "<<",        0x08 },
00544    { "EndCall",      0x09 },
00545    { "Resume",    0x0A },
00546    { "Answer",    0x0B },
00547    { "Info",      0x0C },
00548    { "Confrn",    0x0D },
00549    { "Park",      0x0E },
00550    { "Join",      0x0F },
00551    { "MeetMe",    0x10 },
00552    { "PickUp",    0x11 },
00553    { "GPickUp",      0x12 },
00554 };
00555 
00556 struct soft_key_definitions {
00557    const uint8_t mode;
00558    const uint8_t *defaults;
00559    const int count;
00560 };
00561 
00562 static const uint8_t soft_key_default_onhook[] = {
00563    SOFTKEY_REDIAL,
00564    SOFTKEY_NEWCALL,
00565    SOFTKEY_CFWDALL,
00566    SOFTKEY_CFWDBUSY,
00567    SOFTKEY_GPICKUP,
00568    SOFTKEY_CONFRN,
00569 };
00570 
00571 static const uint8_t soft_key_default_connected[] = {
00572    SOFTKEY_HOLD,
00573    SOFTKEY_ENDCALL,
00574    SOFTKEY_TRNSFER,
00575    SOFTKEY_PARK,
00576    SOFTKEY_CFWDALL,
00577    SOFTKEY_CFWDBUSY,
00578 };
00579 
00580 static const uint8_t soft_key_default_onhold[] = {
00581    SOFTKEY_RESUME,
00582    SOFTKEY_NEWCALL,
00583    SOFTKEY_ENDCALL,
00584    SOFTKEY_TRNSFER,
00585 };
00586 
00587 static const uint8_t soft_key_default_ringin[] = {
00588    SOFTKEY_ANSWER,
00589    SOFTKEY_ENDCALL,
00590    SOFTKEY_TRNSFER,
00591 };
00592 
00593 static const uint8_t soft_key_default_offhook[] = {
00594    SOFTKEY_REDIAL,
00595    SOFTKEY_ENDCALL,
00596    SOFTKEY_CFWDALL,
00597    SOFTKEY_CFWDBUSY,
00598    SOFTKEY_GPICKUP,
00599 };
00600 
00601 static const uint8_t soft_key_default_connwithtrans[] = {
00602    SOFTKEY_HOLD,
00603    SOFTKEY_ENDCALL,
00604    SOFTKEY_TRNSFER,
00605    SOFTKEY_PARK,
00606    SOFTKEY_CFWDALL,
00607    SOFTKEY_CFWDBUSY,
00608 };
00609 
00610 static const uint8_t soft_key_default_dadfd[] = {
00611    SOFTKEY_BKSPC,
00612    SOFTKEY_ENDCALL,
00613 };
00614 
00615 static const uint8_t soft_key_default_connwithconf[] = {
00616    SOFTKEY_NONE,
00617 };
00618 
00619 static const uint8_t soft_key_default_ringout[] = {
00620    SOFTKEY_NONE,
00621    SOFTKEY_ENDCALL,
00622 };
00623 
00624 static const uint8_t soft_key_default_offhookwithfeat[] = {
00625    SOFTKEY_REDIAL,
00626    SOFTKEY_ENDCALL,
00627 };
00628 
00629 static const uint8_t soft_key_default_unknown[] = {
00630    SOFTKEY_NONE,
00631 };
00632 
00633 static const struct soft_key_definitions soft_key_default_definitions[] = {
00634    {KEYDEF_ONHOOK, soft_key_default_onhook, sizeof(soft_key_default_onhook) / sizeof(uint8_t)},
00635    {KEYDEF_CONNECTED, soft_key_default_connected, sizeof(soft_key_default_connected) / sizeof(uint8_t)},
00636    {KEYDEF_ONHOLD, soft_key_default_onhold, sizeof(soft_key_default_onhold) / sizeof(uint8_t)},
00637    {KEYDEF_RINGIN, soft_key_default_ringin, sizeof(soft_key_default_ringin) / sizeof(uint8_t)},
00638    {KEYDEF_OFFHOOK, soft_key_default_offhook, sizeof(soft_key_default_offhook) / sizeof(uint8_t)},
00639    {KEYDEF_CONNWITHTRANS, soft_key_default_connwithtrans, sizeof(soft_key_default_connwithtrans) / sizeof(uint8_t)},
00640    {KEYDEF_DADFD, soft_key_default_dadfd, sizeof(soft_key_default_dadfd) / sizeof(uint8_t)},
00641    {KEYDEF_CONNWITHCONF, soft_key_default_connwithconf, sizeof(soft_key_default_connwithconf) / sizeof(uint8_t)},
00642    {KEYDEF_RINGOUT, soft_key_default_ringout, sizeof(soft_key_default_ringout) / sizeof(uint8_t)},
00643    {KEYDEF_OFFHOOKWITHFEAT, soft_key_default_offhookwithfeat, sizeof(soft_key_default_offhookwithfeat) / sizeof(uint8_t)},
00644    {KEYDEF_UNKNOWN, soft_key_default_unknown, sizeof(soft_key_default_unknown) / sizeof(uint8_t)}
00645 };
00646 
00647 struct soft_key_template_res_message {
00648    uint32_t softKeyOffset;
00649    uint32_t softKeyCount;
00650    uint32_t totalSoftKeyCount;
00651    struct soft_key_template_definition softKeyTemplateDefinition[32];
00652 };
00653 
00654 #define SOFT_KEY_SET_RES_MESSAGE 0x0109
00655 
00656 struct soft_key_set_definition {
00657    uint8_t softKeyTemplateIndex[16];
00658    uint16_t softKeyInfoIndex[16];
00659 };
00660 
00661 struct soft_key_set_res_message {
00662    uint32_t softKeySetOffset;
00663    uint32_t softKeySetCount;
00664    uint32_t totalSoftKeySetCount;
00665    struct soft_key_set_definition softKeySetDefinition[16];
00666    uint32_t res;
00667 };
00668 
00669 #define SELECT_SOFT_KEYS_MESSAGE 0x0110
00670 struct select_soft_keys_message {
00671    uint32_t instance;
00672    uint32_t reference;
00673    uint32_t softKeySetIndex;
00674    uint32_t validKeyMask;
00675 };
00676 
00677 #define CALL_STATE_MESSAGE 0x0111
00678 struct call_state_message {
00679    uint32_t callState;
00680    uint32_t lineInstance;
00681    uint32_t callReference;
00682    uint32_t space[3];
00683 };
00684 
00685 #define DISPLAY_PROMPT_STATUS_MESSAGE 0x0112
00686 struct display_prompt_status_message {
00687    uint32_t messageTimeout;
00688    char promptMessage[32];
00689    uint32_t lineInstance;
00690    uint32_t callReference;
00691 };
00692 
00693 #define CLEAR_PROMPT_MESSAGE  0x0113
00694 struct clear_prompt_message {
00695        uint32_t lineInstance;
00696        uint32_t callReference;
00697 };
00698 
00699 #define DISPLAY_NOTIFY_MESSAGE 0x0114
00700 struct display_notify_message {
00701    uint32_t displayTimeout;
00702    char displayMessage[100];
00703 };
00704 
00705 #define ACTIVATE_CALL_PLANE_MESSAGE 0x0116
00706 struct activate_call_plane_message {
00707    uint32_t lineInstance;
00708 };
00709 
00710 #define DIALED_NUMBER_MESSAGE 0x011D
00711 struct dialed_number_message {
00712    char dialedNumber[24];
00713    uint32_t lineInstance;
00714    uint32_t callReference;
00715 };
00716 
00717 union skinny_data {
00718    struct alarm_message alarm;
00719    struct speed_dial_stat_req_message speeddialreq;
00720    struct register_message reg;
00721    struct register_ack_message regack;
00722    struct register_rej_message regrej;
00723    struct capabilities_res_message caps;
00724    struct version_res_message version;
00725    struct button_template_res_message buttontemplate;
00726    struct displaytext_message displaytext;
00727    struct display_prompt_status_message displaypromptstatus;
00728    struct clear_prompt_message clearpromptstatus;
00729    struct definetimedate_message definetimedate;
00730    struct start_tone_message starttone;
00731    struct stop_tone_message stoptone;
00732    struct speed_dial_stat_res_message speeddial;
00733    struct line_state_req_message line;
00734    struct line_stat_res_message linestat;
00735    struct soft_key_set_res_message softkeysets;
00736    struct soft_key_template_res_message softkeytemplate;
00737    struct server_res_message serverres;
00738    struct reset_message reset;
00739    struct set_lamp_message setlamp;
00740    struct set_ringer_message setringer;
00741    struct call_state_message callstate;
00742    struct keypad_button_message keypad;
00743    struct select_soft_keys_message selectsoftkey;
00744    struct activate_call_plane_message activatecallplane;
00745    struct stimulus_message stimulus;
00746    struct offhook_message offhook;
00747    struct onhook_message onhook;
00748    struct set_speaker_message setspeaker;
00749    struct set_microphone_message setmicrophone;
00750    struct call_info_message callinfo;
00751    struct start_media_transmission_message startmedia;
00752    struct stop_media_transmission_message stopmedia;
00753    struct open_receive_channel_message openreceivechannel;
00754    struct open_receive_channel_ack_message openreceivechannelack;
00755    struct close_receive_channel_message closereceivechannel;
00756    struct display_notify_message displaynotify;
00757    struct dialed_number_message dialednumber;
00758    struct soft_key_event_message softkeyeventmessage;
00759    struct enbloc_call_message enbloccallmessage;
00760 };
00761 
00762 /* packet composition */
00763 struct skinny_req {
00764    int len;
00765    int res;
00766    int e;
00767    union skinny_data data;
00768 };
00769 
00770 /* XXX This is the combined size of the variables above.  (len, res, e)
00771    If more are added, this MUST change.
00772    (sizeof(skinny_req) - sizeof(skinny_data)) DOES NOT WORK on all systems (amd64?). */
00773 int skinny_header_size = 12;
00774 
00775 /*****************************
00776  * Asterisk specific globals *
00777  *****************************/
00778 
00779 static int skinnydebug = 0;
00780 
00781 /* a hostname, portnumber, socket and such is usefull for VoIP protocols */
00782 static struct sockaddr_in bindaddr;
00783 static char ourhost[256];
00784 static int ourport;
00785 static struct in_addr __ourip;
00786 struct ast_hostent ahp;
00787 struct hostent *hp;
00788 static int skinnysock = -1;
00789 static pthread_t accept_t;
00790 static char context[AST_MAX_CONTEXT] = "default";
00791 static char language[MAX_LANGUAGE] = "";
00792 static char mohinterpret[MAX_MUSICCLASS] = "default";
00793 static char mohsuggest[MAX_MUSICCLASS] = "";
00794 static char cid_num[AST_MAX_EXTENSION] = "";
00795 static char cid_name[AST_MAX_EXTENSION] = "";
00796 static char linelabel[AST_MAX_EXTENSION] ="";
00797 static int nat = 0;
00798 static ast_group_t cur_callergroup = 0;
00799 static ast_group_t cur_pickupgroup = 0;
00800 static int immediate = 0;
00801 static int callwaiting = 0;
00802 static int callreturn = 0;
00803 static int threewaycalling = 0;
00804 static int mwiblink = 0;
00805 /* This is for flashhook transfers */
00806 static int transfer = 0;
00807 static int cancallforward = 0;
00808 /* static int busycount = 3;*/
00809 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
00810 static char mailbox[AST_MAX_EXTENSION];
00811 static int amaflags = 0;
00812 static int callnums = 1;
00813 
00814 #define SKINNY_DEVICE_UNKNOWN    -1
00815 #define SKINNY_DEVICE_NONE    0
00816 #define SKINNY_DEVICE_30SPPLUS      1
00817 #define SKINNY_DEVICE_12SPPLUS      2
00818 #define SKINNY_DEVICE_12SP    3
00819 #define SKINNY_DEVICE_12      4
00820 #define SKINNY_DEVICE_30VIP      5
00821 #define SKINNY_DEVICE_7910    6
00822 #define SKINNY_DEVICE_7960    7
00823 #define SKINNY_DEVICE_7940    8
00824 #define SKINNY_DEVICE_7935    9
00825 #define SKINNY_DEVICE_ATA186     12 /* Cisco ATA-186 */
00826 #define SKINNY_DEVICE_7941    115
00827 #define SKINNY_DEVICE_7971    119
00828 #define SKINNY_DEVICE_7985    302
00829 #define SKINNY_DEVICE_7911    307
00830 #define SKINNY_DEVICE_7961GE     308
00831 #define SKINNY_DEVICE_7941GE     309
00832 #define SKINNY_DEVICE_7921    365
00833 #define SKINNY_DEVICE_7905    20000
00834 #define SKINNY_DEVICE_7920    30002
00835 #define SKINNY_DEVICE_7970    30006
00836 #define SKINNY_DEVICE_7912    30007
00837 #define SKINNY_DEVICE_7902    30008
00838 #define SKINNY_DEVICE_CIPC    30016 /* Cisco IP Communicator */
00839 #define SKINNY_DEVICE_7961    30018
00840 #define SKINNY_DEVICE_7936    30019
00841 #define SKINNY_DEVICE_SCCPGATEWAY_AN   30027 /* ??? */
00842 #define SKINNY_DEVICE_SCCPGATEWAY_BRI  30028 /* ??? */
00843 
00844 #define SKINNY_SPEAKERON 1
00845 #define SKINNY_SPEAKEROFF 2
00846 
00847 #define SKINNY_MICON 1
00848 #define SKINNY_MICOFF 2
00849 
00850 #define SKINNY_OFFHOOK 1
00851 #define SKINNY_ONHOOK 2
00852 #define SKINNY_RINGOUT 3
00853 #define SKINNY_RINGIN 4
00854 #define SKINNY_CONNECTED 5
00855 #define SKINNY_BUSY 6
00856 #define SKINNY_CONGESTION 7
00857 #define SKINNY_HOLD 8
00858 #define SKINNY_CALLWAIT 9
00859 #define SKINNY_TRANSFER 10
00860 #define SKINNY_PARK 11
00861 #define SKINNY_PROGRESS 12
00862 #define SKINNY_INVALID 14
00863 
00864 #define SKINNY_SILENCE     0x00
00865 #define SKINNY_DIALTONE    0x21
00866 #define SKINNY_BUSYTONE    0x23
00867 #define SKINNY_ALERT    0x24
00868 #define SKINNY_REORDER     0x25
00869 #define SKINNY_CALLWAITTONE   0x2D
00870 #define SKINNY_NOTONE      0x7F
00871 
00872 #define SKINNY_LAMP_OFF 1
00873 #define SKINNY_LAMP_ON 2
00874 #define SKINNY_LAMP_WINK 3
00875 #define SKINNY_LAMP_FLASH 4
00876 #define SKINNY_LAMP_BLINK 5
00877 
00878 #define SKINNY_RING_OFF 1
00879 #define SKINNY_RING_INSIDE 2
00880 #define SKINNY_RING_OUTSIDE 3
00881 #define SKINNY_RING_FEATURE 4
00882 
00883 #define TYPE_TRUNK 1
00884 #define TYPE_LINE 2
00885 
00886 /* Skinny rtp stream modes. Do we really need this? */
00887 #define SKINNY_CX_SENDONLY 0
00888 #define SKINNY_CX_RECVONLY 1
00889 #define SKINNY_CX_SENDRECV 2
00890 #define SKINNY_CX_CONF     3
00891 #define SKINNY_CX_CONFERENCE  3
00892 #define SKINNY_CX_MUTE     4
00893 #define SKINNY_CX_INACTIVE 4
00894 
00895 #if 0
00896 static char *skinny_cxmodes[] = {
00897    "sendonly",
00898    "recvonly",
00899    "sendrecv",
00900    "confrnce",
00901    "inactive"
00902 };
00903 #endif
00904 
00905 /* driver scheduler */
00906 static struct sched_context *sched = NULL;
00907 static struct io_context *io;
00908 
00909 /* Protect the monitoring thread, so only one process can kill or start it, and not
00910    when it's doing something critical. */
00911 AST_MUTEX_DEFINE_STATIC(monlock);
00912 /* Protect the network socket */
00913 AST_MUTEX_DEFINE_STATIC(netlock);
00914 /* Protect the session list */
00915 AST_MUTEX_DEFINE_STATIC(sessionlock);
00916 /* Protect the device list */
00917 AST_MUTEX_DEFINE_STATIC(devicelock);
00918 #if 0
00919 /* Protect the paging device list */
00920 AST_MUTEX_DEFINE_STATIC(pagingdevicelock);
00921 #endif
00922 
00923 /* This is the thread for the monitor which checks for input on the channels
00924    which are not currently in use. */
00925 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00926 
00927 /* Wait up to 16 seconds for first digit */
00928 static int firstdigittimeout = 16000;
00929 
00930 /* How long to wait for following digits */
00931 static int gendigittimeout = 8000;
00932 
00933 /* How long to wait for an extra digit, if there is an ambiguous match */
00934 static int matchdigittimeout = 3000;
00935 
00936 struct skinny_subchannel {
00937    ast_mutex_t lock;
00938    struct ast_channel *owner;
00939    struct ast_rtp *rtp;
00940    struct ast_rtp *vrtp;
00941    unsigned int callid;
00942    /* time_t lastouttime; */        /* Unused */
00943    int progress;
00944    int ringing;
00945    int onhold;
00946    /* int lastout; */            /* Unused */
00947    int cxmode;
00948    int nat;
00949    int outgoing;
00950    int alreadygone;
00951 
00952    struct skinny_subchannel *next;
00953    struct skinny_line *parent;
00954 };
00955 
00956 struct skinny_line {
00957    ast_mutex_t lock;
00958    char name[80];
00959    char label[24];               /* Label that shows next to the line buttons */
00960    char accountcode[AST_MAX_ACCOUNT_CODE];
00961    char exten[AST_MAX_EXTENSION];         /* Extension where to start */
00962    char context[AST_MAX_CONTEXT];
00963    char language[MAX_LANGUAGE];
00964    char cid_num[AST_MAX_EXTENSION];    /* Caller*ID */
00965    char cid_name[AST_MAX_EXTENSION];      /* Caller*ID */
00966    char lastcallerid[AST_MAX_EXTENSION];     /* Last Caller*ID */
00967    char call_forward[AST_MAX_EXTENSION];
00968    char mailbox[AST_MAX_EXTENSION];
00969    char mohinterpret[MAX_MUSICCLASS];
00970    char mohsuggest[MAX_MUSICCLASS];
00971    char lastnumberdialed[AST_MAX_EXTENSION]; /* Last number that was dialed - used for redial */
00972    int curtone;               /* Current tone being played */
00973    ast_group_t callgroup;
00974    ast_group_t pickupgroup;
00975    int callwaiting;
00976    int transfer;
00977    int threewaycalling;
00978    int mwiblink;
00979    int cancallforward;
00980    int callreturn;
00981    int dnd; /* How does this affect callwait?  Do we just deny a skinny_request if we're dnd? */
00982    int hascallerid;
00983    int hidecallerid;
00984    int amaflags;
00985    int type;
00986    int instance;
00987    int group;
00988    int needdestroy;
00989    int capability;
00990    int nonCodecCapability;
00991    int onhooktime;
00992    int msgstate;              /* voicemail message state */
00993    int immediate;
00994    int hookstate;
00995    int nat;
00996 
00997    struct ast_codec_pref prefs;
00998    struct skinny_subchannel *sub;
00999    struct skinny_line *next;
01000    struct skinny_device *parent;
01001 };
01002 
01003 struct skinny_speeddial {
01004    ast_mutex_t lock;
01005    char label[42];
01006    char exten[AST_MAX_EXTENSION];
01007    int instance;
01008 
01009    struct skinny_speeddial *next;
01010    struct skinny_device *parent;
01011 };
01012 
01013 struct skinny_addon {
01014    ast_mutex_t lock;
01015    char type[10];
01016 
01017    struct skinny_addon *next;
01018    struct skinny_device *parent;
01019 };
01020 
01021 static struct skinny_device {
01022    /* A device containing one or more lines */
01023    char name[80];
01024    char id[16];
01025    char version_id[16];
01026    int type;
01027    int registered;
01028    int lastlineinstance;
01029    int lastcallreference;
01030    int capability;
01031    char exten[AST_MAX_EXTENSION];
01032    struct sockaddr_in addr;
01033    struct in_addr ourip;
01034    struct skinny_line *lines;
01035    struct skinny_speeddial *speeddials;
01036    struct skinny_addon *addons;
01037    struct ast_codec_pref prefs;
01038    struct ast_ha *ha;
01039    struct skinnysession *session;
01040    struct skinny_device *next;
01041 } *devices = NULL;
01042 
01043 struct skinny_paging_device {
01044    char name[80];
01045    char id[16];
01046    struct skinny_device ** devices;
01047    struct skinny_paging_device *next;
01048 };
01049 
01050 static struct skinnysession {
01051    pthread_t t;
01052    ast_mutex_t lock;
01053    struct sockaddr_in sin;
01054    int fd;
01055    char inbuf[SKINNY_MAX_PACKET];
01056    char outbuf[SKINNY_MAX_PACKET];
01057    struct skinny_device *device;
01058    struct skinnysession *next;
01059 } *sessions = NULL;
01060 
01061 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause);
01062 static int skinny_call(struct ast_channel *ast, char *dest, int timeout);
01063 static int skinny_hangup(struct ast_channel *ast);
01064 static int skinny_answer(struct ast_channel *ast);
01065 static struct ast_frame *skinny_read(struct ast_channel *ast);
01066 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame);
01067 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
01068 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01069 static int skinny_senddigit_begin(struct ast_channel *ast, char digit);
01070 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01071 static int handle_time_date_req_message(struct skinny_req *req, struct skinnysession *s);
01072 
01073 static const struct ast_channel_tech skinny_tech = {
01074    .type = "Skinny",
01075    .description = tdesc,
01076    .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
01077    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01078    .requester = skinny_request,
01079    .call = skinny_call,
01080    .hangup = skinny_hangup,
01081    .answer = skinny_answer,
01082    .read = skinny_read,
01083    .write = skinny_write,
01084    .indicate = skinny_indicate,
01085    .fixup = skinny_fixup,
01086    .send_digit_begin = skinny_senddigit_begin,
01087    .send_digit_end = skinny_senddigit_end,
01088 /* .bridge = ast_rtp_bridge, */
01089 };
01090 
01091 static void *get_button_template(struct skinnysession *s, struct button_definition_template *btn)
01092 {
01093    struct skinny_device *d = s->device;
01094    struct skinny_addon *a = d->addons;
01095    int i;
01096 
01097    switch (d->type) {
01098       case SKINNY_DEVICE_30SPPLUS:
01099       case SKINNY_DEVICE_30VIP:
01100          /* 13 rows, 2 columns */
01101          for (i = 0; i < 4; i++)
01102             (btn++)->buttonDefinition = BT_LINE;
01103          (btn++)->buttonDefinition = BT_REDIAL;
01104          (btn++)->buttonDefinition = BT_VOICEMAIL;
01105          (btn++)->buttonDefinition = BT_CALLPARK;
01106          (btn++)->buttonDefinition = BT_FORWARDALL;
01107          (btn++)->buttonDefinition = BT_CONFERENCE;
01108          for (i = 0; i < 4; i++)
01109             (btn++)->buttonDefinition = BT_NONE;
01110          for (i = 0; i < 13; i++)
01111             (btn++)->buttonDefinition = BT_SPEEDDIAL;
01112          
01113          break;
01114       case SKINNY_DEVICE_12SPPLUS:
01115       case SKINNY_DEVICE_12SP:
01116       case SKINNY_DEVICE_12:
01117          /* 6 rows, 2 columns */
01118          for (i = 0; i < 2; i++)
01119             (btn++)->buttonDefinition = BT_LINE;
01120          (btn++)->buttonDefinition = BT_REDIAL;
01121          for (i = 0; i < 3; i++)
01122             (btn++)->buttonDefinition = BT_SPEEDDIAL;
01123          (btn++)->buttonDefinition = BT_HOLD;
01124          (btn++)->buttonDefinition = BT_TRANSFER;
01125          (btn++)->buttonDefinition = BT_FORWARDALL;
01126          (btn++)->buttonDefinition = BT_CALLPARK;
01127          (btn++)->buttonDefinition = BT_VOICEMAIL;
01128          (btn++)->buttonDefinition = BT_CONFERENCE;
01129          break;
01130       case SKINNY_DEVICE_7910:
01131          (btn++)->buttonDefinition = BT_LINE;
01132          (btn++)->buttonDefinition = BT_HOLD;
01133          (btn++)->buttonDefinition = BT_TRANSFER;
01134          (btn++)->buttonDefinition = BT_DISPLAY;
01135          (btn++)->buttonDefinition = BT_VOICEMAIL;
01136          (btn++)->buttonDefinition = BT_CONFERENCE;
01137          (btn++)->buttonDefinition = BT_FORWARDALL;
01138          for (i = 0; i < 2; i++)
01139             (btn++)->buttonDefinition = BT_SPEEDDIAL;
01140          (btn++)->buttonDefinition = BT_REDIAL;
01141          break;
01142       case SKINNY_DEVICE_7960:
01143       case SKINNY_DEVICE_7961:
01144       case SKINNY_DEVICE_7961GE:
01145          for (i = 0; i < 6; i++)
01146             (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
01147          break;
01148       case SKINNY_DEVICE_7940:
01149       case SKINNY_DEVICE_7941:
01150       case SKINNY_DEVICE_7941GE:
01151          for (i = 0; i < 2; i++)
01152             (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
01153          break;
01154       case SKINNY_DEVICE_7935:
01155       case SKINNY_DEVICE_7936:
01156          for (i = 0; i < 2; i++)
01157             (btn++)->buttonDefinition = BT_LINE;
01158          break;
01159       case SKINNY_DEVICE_ATA186:
01160          (btn++)->buttonDefinition = BT_LINE;
01161          break;
01162       case SKINNY_DEVICE_7970:
01163       case SKINNY_DEVICE_7971:
01164       case SKINNY_DEVICE_CIPC:
01165          for (i = 0; i < 8; i++)
01166             (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
01167          break;
01168       case SKINNY_DEVICE_7985:
01169          /* XXX I have no idea what the buttons look like on these. */
01170          ast_log(LOG_WARNING, "Unsupported device type '%d (7985)' found.\n", d->type);
01171          break;
01172       case SKINNY_DEVICE_7912:
01173       case SKINNY_DEVICE_7911:
01174       case SKINNY_DEVICE_7905:
01175          (btn++)->buttonDefinition = BT_LINE;
01176          (btn++)->buttonDefinition = BT_HOLD;
01177          break;
01178       case SKINNY_DEVICE_7920:
01179       case SKINNY_DEVICE_7921:
01180          /* XXX I don't know if this is right. */
01181          for (i = 0; i < 4; i++)
01182             (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
01183          break;
01184       case SKINNY_DEVICE_7902:
01185          ast_log(LOG_WARNING, "Unsupported device type '%d (7902)' found.\n", d->type);
01186          break;
01187       case SKINNY_DEVICE_SCCPGATEWAY_AN:
01188       case SKINNY_DEVICE_SCCPGATEWAY_BRI:
01189          ast_log(LOG_WARNING, "Unsupported device type '%d (SCCP gateway)' found.\n", d->type);
01190          break;
01191       default:
01192          ast_log(LOG_WARNING, "Unknown device type '%d' found.\n", d->type);
01193          break;
01194    }
01195 
01196    for (a = d->addons; a; a = a->next) {
01197       if (!strcasecmp(a->type, "7914")) {
01198          for (i = 0; i < 14; i++)
01199             (btn++)->buttonDefinition = BT_CUST_LINESPEEDDIAL;
01200       } else {
01201          ast_log(LOG_WARNING, "Unknown addon type '%s' found.  Skipping.\n", a->type);
01202       }
01203    }
01204 
01205    return btn;
01206 }
01207 
01208 static struct skinny_req *req_alloc(size_t size, int response_message)
01209 {
01210    struct skinny_req *req;
01211 
01212    if (!(req = ast_calloc(1, skinny_header_size + size + 4)))
01213       return NULL;
01214 
01215    req->len = htolel(size+4);
01216    req->e = htolel(response_message);
01217 
01218    return req;
01219 }
01220 
01221 static struct skinny_line *find_line_by_instance(struct skinny_device *d, int instance)
01222 {
01223    struct skinny_line *l;
01224 
01225    if (!instance)
01226       instance = 1;
01227 
01228    for (l = d->lines; l; l = l->next) {
01229       if (l->instance == instance)
01230          break;
01231    }
01232 
01233    if (!l) {
01234       ast_log(LOG_WARNING, "Could not find line with instance '%d' on device '%s'\n", instance, d->name);
01235    }
01236    return l;
01237 }
01238 
01239 static struct skinny_line *find_line_by_name(const char *dest)
01240 {
01241    struct skinny_line *l;
01242    struct skinny_device *d;
01243    char line[256];
01244    char *at;
01245    char *device;
01246 
01247    ast_copy_string(line, dest, sizeof(line));
01248    at = strchr(line, '@');
01249    if (!at) {
01250       ast_log(LOG_NOTICE, "Device '%s' has no @ (at) sign!\n", dest);
01251       return NULL;
01252    }
01253    *at++ = '\0';
01254    device = at;
01255    ast_mutex_lock(&devicelock);
01256    for (d = devices; d; d = d->next) {
01257       if (!strcasecmp(d->name, device)) {
01258          if (skinnydebug)
01259             ast_verbose("Found device: %s\n", d->name);
01260          /* Found the device */
01261          for (l = d->lines; l; l = l->next) {
01262             /* Search for the right line */
01263             if (!strcasecmp(l->name, line)) {
01264                ast_mutex_unlock(&devicelock);
01265                return l;
01266             }
01267          }
01268       }
01269    }
01270    /* Device not found */
01271    ast_mutex_unlock(&devicelock);
01272    return NULL;
01273 }
01274 
01275 /* It's quicker/easier to find the subchannel when we know the instance number too */
01276 static struct skinny_subchannel *find_subchannel_by_instance_reference(struct skinny_device *d, int instance, int reference)
01277 {
01278    struct skinny_line *l = find_line_by_instance(d, instance);
01279    struct skinny_subchannel *sub;
01280 
01281    if (!l) {
01282       return NULL;
01283    }
01284 
01285    if (!reference)
01286       sub = l->sub;
01287    else {
01288       for (sub = l->sub; sub; sub = sub->next) {
01289          if (sub->callid == reference)
01290             break;
01291       }
01292    }
01293 
01294    if (!sub) {
01295       ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s'\n", reference, d->name);
01296    }
01297    return sub;
01298 }
01299 
01300 /* Find the subchannel when we only have the callid - this shouldn't happen often */
01301 static struct skinny_subchannel *find_subchannel_by_reference(struct skinny_device *d, int reference)
01302 {
01303    struct skinny_line *l;
01304    struct skinny_subchannel *sub = NULL;
01305 
01306    for (l = d->lines; l; l = l->next) {
01307       for (sub = l->sub; sub; sub = sub->next) {
01308          if (sub->callid == reference)
01309             break;
01310       }
01311       if (sub)
01312          break;
01313    }
01314 
01315    if (!l) {
01316       ast_log(LOG_WARNING, "Could not find any lines that contained a subchannel with reference '%d' on device '%s'\n", reference, d->name);
01317    } else {
01318       if (!sub) {
01319          ast_log(LOG_WARNING, "Could not find subchannel with reference '%d' on '%s@%s'\n", reference, l->name, d->name);
01320       }
01321    }
01322    return sub;
01323 }
01324 
01325 static struct skinny_speeddial *find_speeddial_by_instance(struct skinny_device *d, int instance)
01326 {
01327    struct skinny_speeddial *sd;
01328 
01329    for (sd = d->speeddials; sd; sd = sd->next) {
01330       if (sd->instance == instance)
01331          break;
01332    }
01333 
01334    if (!sd) {
01335       ast_log(LOG_WARNING, "Could not find speeddial with instance '%d' on device '%s'\n", instance, d->name);
01336    }
01337    return sd;
01338 }
01339 
01340 static int codec_skinny2ast(enum skinny_codecs skinnycodec)
01341 {
01342    switch (skinnycodec) {
01343    case SKINNY_CODEC_ALAW:
01344       return AST_FORMAT_ALAW;
01345    case SKINNY_CODEC_ULAW:
01346       return AST_FORMAT_ULAW;
01347    case SKINNY_CODEC_G723_1:
01348       return AST_FORMAT_G723_1;
01349    case SKINNY_CODEC_G729A:
01350       return AST_FORMAT_G729A;
01351    case SKINNY_CODEC_G726_32:
01352       return AST_FORMAT_G726_AAL2; /* XXX Is this right? */
01353    case SKINNY_CODEC_H261:
01354       return AST_FORMAT_H261;
01355    case SKINNY_CODEC_H263:
01356       return AST_FORMAT_H263;
01357    default:
01358       return 0;
01359    }
01360 }
01361 
01362 static int codec_ast2skinny(int astcodec)
01363 {
01364    switch (astcodec) {
01365    case AST_FORMAT_ALAW:
01366       return SKINNY_CODEC_ALAW;
01367    case AST_FORMAT_ULAW:
01368       return SKINNY_CODEC_ULAW;
01369    case AST_FORMAT_G723_1:
01370       return SKINNY_CODEC_G723_1;
01371    case AST_FORMAT_G729A:
01372       return SKINNY_CODEC_G729A;
01373    case AST_FORMAT_G726_AAL2: /* XXX Is this right? */
01374       return SKINNY_CODEC_G726_32;
01375    case AST_FORMAT_H261:
01376       return SKINNY_CODEC_H261;
01377    case AST_FORMAT_H263:
01378       return SKINNY_CODEC_H263;
01379    default:
01380       return 0;
01381    }
01382 }
01383 
01384 
01385 static int skinny_register(struct skinny_req *req, struct skinnysession *s)
01386 {
01387    struct skinny_device *d;
01388    struct sockaddr_in sin;
01389    socklen_t slen;
01390 
01391    ast_mutex_lock(&devicelock);
01392    for (d = devices; d; d = d->next) {
01393       if (!strcasecmp(req->data.reg.name, d->id)
01394             && ast_apply_ha(d->ha, &(s->sin))) {
01395          s->device = d;
01396          d->type = letohl(req->data.reg.type);
01397          if (ast_strlen_zero(d->version_id)) {
01398             ast_copy_string(d->version_id, version_id, sizeof(d->version_id));
01399          }
01400          d->registered = 1;
01401          d->session = s;
01402 
01403          slen = sizeof(sin);
01404          if (getsockname(s->fd, (struct sockaddr *)&sin, &slen)) {
01405             ast_log(LOG_WARNING, "Cannot get socket name\n");
01406             sin.sin_addr = __ourip;
01407          }
01408          d->ourip = sin.sin_addr;
01409          break;
01410       }
01411    }
01412    ast_mutex_unlock(&devicelock);
01413    if (!d) {
01414       return 0;
01415    }
01416    return 1;
01417 }
01418 
01419 static int skinny_unregister(struct skinny_req *req, struct skinnysession *s)
01420 {
01421    struct skinny_device *d;
01422 
01423    d = s->device;
01424 
01425    if (d) {
01426       d->session = NULL;
01427       d->registered = 0;
01428    }
01429 
01430    return -1; /* main loop will destroy the session */
01431 }
01432 
01433 static int transmit_response(struct skinnysession *s, struct skinny_req *req)
01434 {
01435    int res = 0;
01436 
01437    if (!s) {
01438       ast_log(LOG_WARNING, "Asked to transmit to a non-existant session!\n");
01439       return -1;
01440    }
01441 
01442    ast_mutex_lock(&s->lock);
01443 
01444    if (skinnydebug)
01445       ast_log(LOG_VERBOSE, "writing packet type %04X (%d bytes) to socket %d\n", letohl(req->e), letohl(req->len)+8, s->fd);
01446 
01447    if (letohl(req->len > SKINNY_MAX_PACKET) || letohl(req->len < 0)) {
01448       ast_log(LOG_WARNING, "transmit_response: the length of the request is out of bounds\n");
01449       return -1;
01450    }
01451 
01452    memset(s->outbuf,0,sizeof(s->outbuf));
01453    memcpy(s->outbuf, req, skinny_header_size);
01454    memcpy(s->outbuf+skinny_header_size, &req->data, letohl(req->len));
01455 
01456    res = write(s->fd, s->outbuf, letohl(req->len)+8);
01457 
01458    if (res != letohl(req->len)+8) {
01459       ast_log(LOG_WARNING, "Transmit: write only sent %d out of %d bytes: %s\n", res, letohl(req->len)+8, strerror(errno));
01460       if (res == -1) {
01461          if (skinnydebug)
01462             ast_log(LOG_WARNING, "Transmit: Skinny Client was lost, unregistering\n");
01463          skinny_unregister(NULL, s);
01464       }
01465       
01466    }
01467    
01468    ast_mutex_unlock(&s->lock);
01469    return 1;
01470 }
01471 
01472 static void transmit_speaker_mode(struct skinnysession *s, int mode)
01473 {
01474    struct skinny_req *req;
01475 
01476    if (!(req = req_alloc(sizeof(struct set_speaker_message), SET_SPEAKER_MESSAGE)))
01477       return;
01478 
01479    req->data.setspeaker.mode = htolel(mode);
01480    transmit_response(s, req);
01481 }
01482 /*
01483 static void transmit_microphone_mode(struct skinnysession *s, int mode)
01484 {
01485    struct skinny_req *req;
01486 
01487    if (!(req = req_alloc(sizeof(struct set_microphone_message), SET_MICROPHONE_MESSAGE)))
01488       return;
01489 
01490    req->data.setmicrophone.mode = htolel(mode);
01491    transmit_response(s, req);
01492 }
01493 */
01494 
01495 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)
01496 {
01497    struct skinny_req *req;
01498 
01499    if (!(req = req_alloc(sizeof(struct call_info_message), CALL_INFO_MESSAGE)))
01500       return;
01501 
01502    if (skinnydebug)
01503          ast_verbose("Setting Callinfo to %s(%s) from %s(%s) on %s(%d)\n", fromname, fromnum, toname, tonum, s->device->name, instance);
01504 
01505    if (fromname) {
01506       ast_copy_string(req->data.callinfo.callingPartyName, fromname, sizeof(req->data.callinfo.callingPartyName));
01507    }
01508    if (fromnum) {
01509       ast_copy_string(req->data.callinfo.callingParty, fromnum, sizeof(req->data.callinfo.callingParty));
01510    }
01511    if (toname) {
01512       ast_copy_string(req->data.callinfo.calledPartyName, toname, sizeof(req->data.callinfo.calledPartyName));
01513    }
01514    if (tonum) {
01515       ast_copy_string(req->data.callinfo.calledParty, tonum, sizeof(req->data.callinfo.calledParty));
01516    }
01517    req->data.callinfo.instance = htolel(instance);
01518    req->data.callinfo.reference = htolel(callid);
01519    req->data.callinfo.type = htolel(calltype);
01520    transmit_response(s, req);
01521 }
01522 
01523 static void transmit_connect(struct skinnysession *s, struct skinny_subchannel *sub)
01524 {
01525    struct skinny_req *req;
01526    struct skinny_line *l = sub->parent;
01527    struct ast_format_list fmt;
01528 
01529    if (!(req = req_alloc(sizeof(struct open_receive_channel_message), OPEN_RECEIVE_CHANNEL_MESSAGE)))
01530       return;
01531 
01532    fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
01533 
01534    req->data.openreceivechannel.conferenceId = htolel(sub->callid);
01535    req->data.openreceivechannel.partyId = htolel(sub->callid);
01536    req->data.openreceivechannel.packets = htolel(fmt.cur_ms);
01537    req->data.openreceivechannel.capability = htolel(codec_ast2skinny(fmt.bits));
01538    req->data.openreceivechannel.echo = htolel(0);
01539    req->data.openreceivechannel.bitrate = htolel(0);
01540    transmit_response(s, req);
01541 }
01542 
01543 static void transmit_tone(struct skinnysession *s, int tone, int instance, int reference)
01544 {
01545    struct skinny_req *req;
01546 
01547    if (tone == SKINNY_NOTONE) {
01548       /* This is bad, mmm'kay? */
01549       return;
01550    }
01551 
01552    if (tone > 0) {
01553       if (!(req = req_alloc(sizeof(struct start_tone_message), START_TONE_MESSAGE)))
01554          return;
01555       req->data.starttone.tone = htolel(tone);
01556       req->data.starttone.instance = htolel(instance);
01557       req->data.starttone.reference = htolel(reference);
01558    } else {
01559       if (!(req = req_alloc(sizeof(struct stop_tone_message), STOP_TONE_MESSAGE)))
01560          return;
01561       req->data.stoptone.instance = htolel(instance);
01562       req->data.stoptone.reference = htolel(reference);
01563    }
01564 
01565    if (tone > 0) {
01566       req->data.starttone.tone = htolel(tone);
01567    }
01568    transmit_response(s, req);
01569 }
01570 
01571 static void transmit_selectsoftkeys(struct skinnysession *s, int instance, int callid, int softkey)
01572 {
01573    struct skinny_req *req;
01574 
01575    if (!(req = req_alloc(sizeof(struct select_soft_keys_message), SELECT_SOFT_KEYS_MESSAGE)))
01576       return;
01577 
01578    req->data.selectsoftkey.instance = htolel(instance);
01579    req->data.selectsoftkey.reference = htolel(callid);
01580    req->data.selectsoftkey.softKeySetIndex = htolel(softkey);
01581    req->data.selectsoftkey.validKeyMask = htolel(0xFFFFFFFF);
01582    transmit_response(s, req);
01583 }
01584 
01585 static void transmit_lamp_indication(struct skinnysession *s, int stimulus, int instance, int indication)
01586 {
01587    struct skinny_req *req;
01588 
01589    if (!(req = req_alloc(sizeof(struct set_lamp_message), SET_LAMP_MESSAGE)))
01590       return;
01591 
01592    req->data.setlamp.stimulus = htolel(stimulus);
01593    req->data.setlamp.stimulusInstance = htolel(instance);
01594    req->data.setlamp.deviceStimulus = htolel(indication);
01595    transmit_response(s, req);
01596 }
01597 
01598 static void transmit_ringer_mode(struct skinnysession *s, int mode)
01599 {
01600    struct skinny_req *req;
01601 
01602    if (skinnydebug)
01603       ast_verbose("Setting ringer mode to '%d'.\n", mode);
01604 
01605    if (!(req = req_alloc(sizeof(struct set_ringer_message), SET_RINGER_MESSAGE)))
01606       return;
01607 
01608    req->data.setringer.ringerMode = htolel(mode);
01609    /* XXX okay, I don't quite know what this is, but here's what happens (on a 7960).
01610       Note: The phone will always show as ringing on the display.
01611 
01612       1: phone will audibly ring over and over
01613       2: phone will audibly ring only once
01614       any other value, will NOT cause the phone to audibly ring
01615    */
01616    req->data.setringer.unknown1 = htolel(1);
01617    /* XXX the value here doesn't seem to change anything.  Must be higher than 0.
01618       Perhaps a packet capture can shed some light on this. */
01619    req->data.setringer.unknown2 = htolel(1);
01620    transmit_response(s, req);
01621 }
01622 
01623 static void transmit_displaymessage(struct skinnysession *s, const char *text, int instance, int reference)
01624 {
01625    struct skinny_req *req;
01626 
01627    if (text == 0) {
01628       if (!(req = req_alloc(0, CLEAR_DISPLAY_MESSAGE)))
01629          return;
01630 
01631       req->data.clearpromptstatus.lineInstance = instance;
01632       req->data.clearpromptstatus.callReference = reference;
01633 
01634       if (skinnydebug)
01635          ast_verbose("Clearing Display\n");
01636    } else {
01637       if (!(req = req_alloc(sizeof(struct displaytext_message), DISPLAYTEXT_MESSAGE)))
01638          return;
01639 
01640       ast_copy_string(req->data.displaytext.text, text, sizeof(req->data.displaytext.text));
01641       if (skinnydebug)
01642          ast_verbose("Displaying message '%s'\n", req->data.displaytext.text);
01643    }
01644 
01645    transmit_response(s, req);
01646 }
01647 
01648 static void transmit_displaynotify(struct skinnysession *s, const char *text, int t)
01649 {
01650    struct skinny_req *req;
01651 
01652    if (!(req = req_alloc(sizeof(struct display_notify_message), DISPLAY_NOTIFY_MESSAGE)))
01653       return;
01654 
01655    ast_copy_string(req->data.displaynotify.displayMessage, text, sizeof(req->data.displaynotify.displayMessage));
01656    req->data.displaynotify.displayTimeout = htolel(t);
01657 
01658    if (skinnydebug)
01659       ast_verbose("Displaying notify '%s'\n", text);
01660 
01661    transmit_response(s, req);
01662 }
01663 
01664 static void transmit_displaypromptstatus(struct skinnysession *s, const char *text, int t, int instance, int callid)
01665 {
01666    struct skinny_req *req;
01667 
01668    if (text == 0) {
01669       if (!(req = req_alloc(sizeof(struct clear_prompt_message), CLEAR_PROMPT_MESSAGE)))
01670          return;
01671 
01672       req->data.clearpromptstatus.lineInstance = htolel(instance);
01673       req->data.clearpromptstatus.callReference = htolel(callid);
01674 
01675       if (skinnydebug)
01676          ast_verbose("Clearing Prompt\n");
01677    } else {
01678       if (!(req = req_alloc(sizeof(struct display_prompt_status_message), DISPLAY_PROMPT_STATUS_MESSAGE)))
01679          return;
01680 
01681       ast_copy_string(req->data.displaypromptstatus.promptMessage, text, sizeof(req->data.displaypromptstatus.promptMessage));
01682       req->data.displaypromptstatus.messageTimeout = htolel(t);
01683       req->data.displaypromptstatus.lineInstance = htolel(instance);
01684       req->data.displaypromptstatus.callReference = htolel(callid);
01685 
01686       if (skinnydebug)
01687          ast_verbose("Displaying Prompt Status '%s'\n", text);
01688    }
01689 
01690    transmit_response(s, req);
01691 }
01692 
01693 static void transmit_dialednumber(struct skinnysession *s, const char *text, int instance, int callid)
01694 {
01695    struct skinny_req *req;
01696 
01697    if (!(req = req_alloc(sizeof(struct dialed_number_message), DIALED_NUMBER_MESSAGE)))
01698       return;
01699 
01700    ast_copy_string(req->data.dialednumber.dialedNumber, text, sizeof(req->data.dialednumber.dialedNumber));
01701    req->data.dialednumber.lineInstance = htolel(instance);
01702    req->data.dialednumber.callReference = htolel(callid);
01703 
01704    transmit_response(s, req);
01705 }
01706 
01707 static void transmit_callstate(struct skinnysession *s, int instance, int state, unsigned callid)
01708 {
01709    struct skinny_req *req;
01710 
01711    if (state == SKINNY_ONHOOK) {
01712       if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
01713          return;
01714 
01715       req->data.closereceivechannel.conferenceId = htolel(callid);
01716       req->data.closereceivechannel.partyId = htolel(callid);
01717       transmit_response(s, req);
01718 
01719       if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
01720          return;
01721 
01722       req->data.stopmedia.conferenceId = htolel(callid);
01723       req->data.stopmedia.passThruPartyId = htolel(callid);
01724       transmit_response(s, req);
01725 
01726       transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
01727 
01728       transmit_displaypromptstatus(s, NULL, 0, instance, callid);
01729    }
01730 
01731    if (!(req = req_alloc(sizeof(struct call_state_message), CALL_STATE_MESSAGE)))
01732       return;
01733 
01734    req->data.callstate.callState = htolel(state);
01735    req->data.callstate.lineInstance = htolel(instance);
01736    req->data.callstate.callReference = htolel(callid);
01737    transmit_response(s, req);
01738 
01739    if (state == SKINNY_ONHOOK) {
01740       transmit_selectsoftkeys(s, 0, 0, KEYDEF_ONHOOK);
01741    }
01742 
01743    if (state == SKINNY_OFFHOOK || state == SKINNY_ONHOOK) {
01744       if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
01745          return;
01746 
01747       req->data.activatecallplane.lineInstance = htolel(instance);
01748       transmit_response(s, req);
01749    }
01750 }
01751 
01752 /*
01753 static int has_voicemail(struct skinny_line *l)
01754 {
01755    return ast_app_has_voicemail(l->mailbox, NULL);
01756 }
01757 */
01758 
01759 static void do_housekeeping(struct skinnysession *s)
01760 {
01761 /*
01762    int new;
01763    int old;
01764    struct skinny_device *d = s->device;
01765    struct skinny_line *l;
01766 */
01767 
01768    /* Update time on device */
01769    handle_time_date_req_message(NULL, s);
01770 
01771 /*
01772    for (l = d->lines; l; l = l->next) {
01773       if (has_voicemail(l)) {
01774          if (skinnydebug)
01775             ast_verbose("Checking for voicemail Skinny %s@%s\n", l->name, d->name);
01776          ast_app_inboxcount(l->mailbox, &new, &old);
01777          if (skinnydebug)
01778             ast_verbose("Skinny %s@%s has voicemail!\n", l->name, d->name);
01779          transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, l->mwiblink?SKINNY_LAMP_BLINK:SKINNY_LAMP_ON);
01780       } else {
01781          transmit_lamp_indication(s, STIMULUS_VOICEMAIL, l->instance, SKINNY_LAMP_OFF);
01782       }
01783    }
01784 */
01785 }
01786 
01787 /* I do not believe skinny can deal with video.
01788    Anyone know differently? */
01789 /* Yes, it can.  Currently 7985 and Cisco VT Advantage do video. */
01790 static enum ast_rtp_get_result skinny_get_vrtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
01791 {
01792    struct skinny_subchannel *sub = NULL;
01793 
01794    if (!(sub = c->tech_pvt) || !(sub->vrtp))
01795       return AST_RTP_GET_FAILED;
01796 
01797    *rtp = sub->vrtp;
01798 
01799    return AST_RTP_TRY_NATIVE;
01800 }
01801 
01802 static enum ast_rtp_get_result skinny_get_rtp_peer(struct ast_channel *c, struct ast_rtp **rtp)
01803 {
01804    struct skinny_subchannel *sub = NULL;
01805 
01806    if (!(sub = c->tech_pvt) || !(sub->rtp))
01807       return AST_RTP_GET_FAILED;
01808 
01809    *rtp = sub->rtp;
01810 
01811    return AST_RTP_TRY_NATIVE;
01812 }
01813 
01814 static int skinny_set_rtp_peer(struct ast_channel *c, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
01815 {
01816    struct skinny_subchannel *sub;
01817    sub = c->tech_pvt;
01818    if (sub) {
01819       /* transmit_modify_with_sdp(sub, rtp); @@FIXME@@ if needed */
01820       return 0;
01821    }
01822    return -1;
01823 }
01824 
01825 static struct ast_rtp_protocol skinny_rtp = {
01826    .type = "Skinny",
01827    .get_rtp_info = skinny_get_rtp_peer,
01828    .get_vrtp_info = skinny_get_vrtp_peer,
01829    .set_rtp_peer = skinny_set_rtp_peer,
01830 };
01831 
01832 static int skinny_do_debug(int fd, int argc, char *argv[])
01833 {
01834    if (argc != 3) {
01835       return RESULT_SHOWUSAGE;
01836    }
01837    skinnydebug = 1;
01838    ast_cli(fd, "Skinny Debugging Enabled\n");
01839    return RESULT_SUCCESS;
01840 }
01841 
01842 static int skinny_no_debug(int fd, int argc, char *argv[])
01843 {
01844    if (argc != 4) {
01845       return RESULT_SHOWUSAGE;
01846    }
01847    skinnydebug = 0;
01848    ast_cli(fd, "Skinny Debugging Disabled\n");
01849    return RESULT_SUCCESS;
01850 }
01851 
01852 static char *complete_skinny_reset(const char *line, const char *word, int pos, int state)
01853 {
01854    struct skinny_device *d;
01855 
01856    char *result = NULL;
01857    int wordlen = strlen(word);
01858    int which = 0;
01859 
01860    if (pos == 2) {
01861       for (d = devices; d && !result; d = d->next) {
01862          if (!strncasecmp(word, d->id, wordlen) && ++which > state)
01863             result = ast_strdup(d->id);
01864       }
01865    }
01866 
01867    return result;
01868 }
01869 
01870 static int skinny_reset_device(int fd, int argc, char *argv[])
01871 {
01872    struct skinny_device *d;
01873    struct skinny_req *req;
01874 
01875    if (argc < 3 || argc > 4) {
01876       return RESULT_SHOWUSAGE;
01877    }
01878    ast_mutex_lock(&devicelock);
01879 
01880    for (d = devices; d; d = d->next) {
01881       int fullrestart = 0;
01882       if (!strcasecmp(argv[2], d->id) || !strcasecmp(argv[2], "all")) {
01883          if (!(d->session))
01884             continue;
01885 
01886          if (!(req = req_alloc(sizeof(struct reset_message), RESET_MESSAGE)))
01887             continue;
01888 
01889          if (argc == 4 && !strcasecmp(argv[3], "restart"))
01890             fullrestart = 1;
01891 
01892          if (fullrestart)
01893             req->data.reset.resetType = 2;
01894          else
01895             req->data.reset.resetType = 1;
01896 
01897          if (option_verbose > 2)
01898             ast_verbose(VERBOSE_PREFIX_3 "%s device %s.\n", (fullrestart) ? "Restarting" : "Resetting", d->id);
01899          transmit_response(d->session, req);
01900       }
01901    }
01902    ast_mutex_unlock(&devicelock);
01903    return RESULT_SUCCESS;
01904 }
01905 
01906 static char *device2str(int type)
01907 {
01908    char *tmp;
01909 
01910    switch (type) {
01911    case SKINNY_DEVICE_NONE:
01912       return "No Device";
01913    case SKINNY_DEVICE_30SPPLUS:
01914       return "30SP Plus";
01915    case SKINNY_DEVICE_12SPPLUS:
01916       return "12SP Plus";
01917    case SKINNY_DEVICE_12SP:
01918       return "12SP";
01919    case SKINNY_DEVICE_12:
01920       return "12";
01921    case SKINNY_DEVICE_30VIP:
01922       return "30VIP";
01923    case SKINNY_DEVICE_7910:
01924       return "7910";
01925    case SKINNY_DEVICE_7960:
01926       return "7960";
01927    case SKINNY_DEVICE_7940:
01928       return "7940";
01929    case SKINNY_DEVICE_7935:
01930       return "7935";
01931    case SKINNY_DEVICE_ATA186:
01932       return "ATA186";
01933    case SKINNY_DEVICE_7941:
01934       return "7941";
01935    case SKINNY_DEVICE_7971:
01936       return "7971";
01937    case SKINNY_DEVICE_7985:
01938       return "7985";
01939    case SKINNY_DEVICE_7911:
01940       return "7911";
01941    case SKINNY_DEVICE_7961GE:
01942       return "7961GE";
01943    case SKINNY_DEVICE_7941GE:
01944       return "7941GE";
01945    case SKINNY_DEVICE_7921:
01946       return "7921";
01947    case SKINNY_DEVICE_7905:
01948       return "7905";
01949    case SKINNY_DEVICE_7920:
01950       return "7920";
01951    case SKINNY_DEVICE_7970:
01952       return "7970";
01953    case SKINNY_DEVICE_7912:
01954       return "7912";
01955    case SKINNY_DEVICE_7902:
01956       return "7902";
01957    case SKINNY_DEVICE_CIPC:
01958       return "IP Communicator";
01959    case SKINNY_DEVICE_7961:
01960       return "7961";
01961    case SKINNY_DEVICE_7936:
01962       return "7936";
01963    case SKINNY_DEVICE_SCCPGATEWAY_AN:
01964       return "SCCPGATEWAY_AN";
01965    case SKINNY_DEVICE_SCCPGATEWAY_BRI:
01966       return "SCCPGATEWAY_BRI";
01967    case SKINNY_DEVICE_UNKNOWN:
01968       return "Unknown";
01969    default:
01970       if (!(tmp = ast_threadstorage_get(&device2str_threadbuf, DEVICE2STR_BUFSIZE)))
01971          return "Unknown";
01972       snprintf(tmp, DEVICE2STR_BUFSIZE, "UNKNOWN-%d", type);
01973       return tmp;
01974    }
01975 }
01976 
01977 static int skinny_show_devices(int fd, int argc, char *argv[])
01978 {
01979    struct skinny_device *d;
01980    struct skinny_line *l;
01981    int numlines = 0;
01982 
01983    if (argc != 3) {
01984       return RESULT_SHOWUSAGE;
01985    }
01986    ast_mutex_lock(&devicelock);
01987 
01988    ast_cli(fd, "Name                 DeviceId         IP              Type            R NL\n");
01989    ast_cli(fd, "-------------------- ---------------- --------------- --------------- - --\n");
01990    for (d = devices; d; d = d->next) {
01991       numlines = 0;
01992       for (l = d->lines; l; l = l->next) {
01993          numlines++;
01994       }
01995 
01996       ast_cli(fd, "%-20s %-16s %-15s %-15s %c %2d\n",
01997             d->name,
01998             d->id,
01999             d->session?ast_inet_ntoa(d->session->sin.sin_addr):"",
02000             device2str(d->type),
02001             d->registered?'Y':'N',
02002             numlines);
02003    }
02004    ast_mutex_unlock(&devicelock);
02005    return RESULT_SUCCESS;
02006 }
02007 
02008 static int skinny_show_lines(int fd, int argc, char *argv[])
02009 {
02010    struct skinny_device *d;
02011    struct skinny_line *l;
02012 
02013    if (argc != 3) {
02014       return RESULT_SHOWUSAGE;
02015    }
02016    ast_mutex_lock(&devicelock);
02017 
02018    ast_cli(fd, "Device Name          Instance Name                 Label               \n");
02019    ast_cli(fd, "-------------------- -------- -------------------- --------------------\n");
02020    for (d = devices; d; d = d->next) {
02021       for (l = d->lines; l; l = l->next) {
02022          ast_cli(fd, "%-20s %8d %-20s %-20s\n",
02023             d->name,
02024             l->instance,
02025             l->name,
02026             l->label);
02027       }
02028    }
02029 
02030    ast_mutex_unlock(&devicelock);
02031    return RESULT_SUCCESS;
02032 }
02033 
02034 static char show_devices_usage[] =
02035 "Usage: skinny show devices\n"
02036 "       Lists all devices known to the Skinny subsystem.\n";
02037 
02038 static char show_lines_usage[] =
02039 "Usage: skinny show lines\n"
02040 "       Lists all lines known to the Skinny subsystem.\n";
02041 
02042 static char debug_usage[] =
02043 "Usage: skinny set debug\n"
02044 "       Enables dumping of Skinny packets for debugging purposes\n";
02045 
02046 static char no_debug_usage[] =
02047 "Usage: skinny set debug off\n"
02048 "       Disables dumping of Skinny packets for debugging purposes\n";
02049 
02050 static char reset_usage[] =
02051 "Usage: skinny reset <DeviceId|all> [restart]\n"
02052 "       Causes a Skinny device to reset itself, optionally with a full restart\n";
02053 
02054 static struct ast_cli_entry cli_skinny[] = {
02055    { { "skinny", "show", "devices", NULL },
02056    skinny_show_devices, "List defined Skinny devices",
02057    show_devices_usage },
02058 
02059    { { "skinny", "show", "lines", NULL },
02060    skinny_show_lines, "List defined Skinny lines per device",
02061    show_lines_usage },
02062 
02063    { { "skinny", "set", "debug", NULL },
02064    skinny_do_debug, "Enable Skinny debugging",
02065    debug_usage },
02066 
02067    { { "skinny", "set", "debug", "off", NULL },
02068    skinny_no_debug, "Disable Skinny debugging",
02069    no_debug_usage },
02070 
02071    { { "skinny", "reset", NULL },
02072    skinny_reset_device, "Reset Skinny device(s)",
02073    reset_usage, complete_skinny_reset },
02074 };
02075 
02076 #if 0
02077 static struct skinny_paging_device *build_paging_device(const char *cat, struct ast_variable *v)
02078 {
02079    return NULL;
02080 }
02081 #endif
02082 
02083 static struct skinny_device *build_device(const char *cat, struct ast_variable *v)
02084 {
02085    struct skinny_device *d;
02086    struct skinny_line *l;
02087    struct skinny_speeddial *sd;
02088    struct skinny_addon *a;
02089    int lineInstance = 1;
02090    int speeddialInstance = 1;
02091    int y = 0;
02092 
02093    if (!(d = ast_calloc(1, sizeof(struct skinny_device)))) {
02094       return NULL;
02095    } else {
02096       ast_copy_string(d->name, cat, sizeof(d->name));
02097       d->lastlineinstance = 1;
02098       d->capability = default_capability;
02099       d->prefs = default_prefs;
02100       while(v) {
02101          if (!strcasecmp(v->name, "host")) {
02102             if (ast_get_ip(&d->addr, v->value)) {
02103                free(d);
02104                return NULL;
02105             }
02106          } else if (!strcasecmp(v->name, "port")) {
02107             d->addr.sin_port = htons(atoi(v->value));
02108          } else if (!strcasecmp(v->name, "device")) {
02109             ast_copy_string(d->id, v->value, sizeof(d->id));
02110          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
02111             d->ha = ast_append_ha(v->name, v->value, d->ha);
02112          } else if (!strcasecmp(v->name, "context")) {
02113             ast_copy_string(context, v->value, sizeof(context));
02114          } else if (!strcasecmp(v->name, "allow")) {
02115             ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 1);
02116          } else if (!strcasecmp(v->name, "disallow")) {
02117             ast_parse_allow_disallow(&d->prefs, &d->capability, v->value, 0);
02118          } else if (!strcasecmp(v->name, "version")) {
02119             ast_copy_string(d->version_id, v->value, sizeof(d->version_id));
02120          } else if (!strcasecmp(v->name, "nat")) {
02121             nat = ast_true(v->value);
02122          } else if (!strcasecmp(v->name, "callerid")) {
02123             if (!strcasecmp(v->value, "asreceived")) {
02124                cid_num[0] = '\0';
02125                cid_name[0] = '\0';
02126             } else {
02127                ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
02128             }
02129          } else if (!strcasecmp(v->name, "language")) {
02130             ast_copy_string(language, v->value, sizeof(language));
02131          } else if (!strcasecmp(v->name, "accountcode")) {
02132             ast_copy_string(accountcode, v->value, sizeof(accountcode));
02133          } else if (!strcasecmp(v->name, "amaflags")) {
02134             y = ast_cdr_amaflags2int(v->value);
02135             if (y < 0) {
02136                ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
02137             } else {
02138                amaflags = y;
02139             }
02140          } else if (!strcasecmp(v->name, "mohinterpret") || !strcasecmp(v->name, "musiconhold")) {
02141             ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
02142          } else if (!strcasecmp(v->name, "mohsuggest")) {
02143             ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
02144          } else if (!strcasecmp(v->name, "callgroup")) {
02145             cur_callergroup = ast_get_group(v->value);
02146          } else if (!strcasecmp(v->name, "pickupgroup")) {
02147             cur_pickupgroup = ast_get_group(v->value);
02148          } else if (!strcasecmp(v->name, "immediate")) {
02149             immediate = ast_true(v->value);
02150          } else if (!strcasecmp(v->name, "cancallforward")) {
02151             cancallforward = ast_true(v->value);
02152          } else if (!strcasecmp(v->name, "mailbox")) {
02153             ast_copy_string(mailbox, v->value, sizeof(mailbox));
02154          } else if (!strcasecmp(v->name, "callreturn")) {
02155             callreturn = ast_true(v->value);
02156          } else if (!strcasecmp(v->name, "callwaiting")) {
02157             callwaiting = ast_true(v->value);
02158          } else if (!strcasecmp(v->name, "transfer")) {
02159             transfer = ast_true(v->value);
02160          } else if (!strcasecmp(v->name, "threewaycalling")) {
02161             threewaycalling = ast_true(v->value);
02162          } else if (!strcasecmp(v->name, "mwiblink")) {
02163             mwiblink = ast_true(v->value);
02164          } else if (!strcasecmp(v->name, "linelabel")) {
02165             ast_copy_string(linelabel, v->value, sizeof(linelabel));
02166          } else if (!strcasecmp(v->name, "speeddial")) {
02167             if (!(sd = ast_calloc(1, sizeof(struct skinny_speeddial)))) {
02168                return NULL;
02169             } else {
02170                char *stringp, *exten, *label;
02171                stringp = v->value;
02172                exten = strsep(&stringp, ",");
02173                label = strsep(&stringp, ",");
02174                ast_mutex_init(&sd->lock);
02175                ast_copy_string(sd->exten, exten, sizeof(sd->exten));
02176                if (label)
02177                   ast_copy_string(sd->label, label, sizeof(sd->label));
02178                else
02179                   ast_copy_string(sd->label, exten, sizeof(sd->label));
02180                sd->instance = speeddialInstance++;
02181 
02182                sd->parent = d;
02183 
02184                sd->next = d->speeddials;
02185                d->speeddials = sd;
02186             }
02187          } else if (!strcasecmp(v->name, "addon")) {
02188             if (!(a = ast_calloc(1, sizeof(struct skinny_addon)))) {
02189                return NULL;
02190             } else {
02191                ast_mutex_init(&a->lock);
02192                ast_copy_string(a->type, v->value, sizeof(a->type));
02193 
02194                a->next = d->addons;
02195                d->addons = a;
02196             }
02197          } else if (!strcasecmp(v->name, "trunk") || !strcasecmp(v->name, "line")) {
02198             if (!(l = ast_calloc(1, sizeof(struct skinny_line)))) {
02199                return NULL;
02200             } else {
02201                ast_mutex_init(&l->lock);
02202                ast_copy_string(l->name, v->value, sizeof(l->name));
02203 
02204                /* XXX Should we check for uniqueness?? XXX */
02205                ast_copy_string(l->context, context, sizeof(l->context));
02206                ast_copy_string(l->cid_num, cid_num, sizeof(l->cid_num));
02207                ast_copy_string(l->cid_name, cid_name, sizeof(l->cid_name));
02208                ast_copy_string(l->label, linelabel, sizeof(l->label));
02209                ast_copy_string(l->language, language, sizeof(l->language));
02210                ast_copy_string(l->mohinterpret, mohinterpret, sizeof(l->mohinterpret));
02211                ast_copy_string(l->mohsuggest, mohsuggest, sizeof(l->mohsuggest));
02212                ast_copy_string(l->mailbox, mailbox, sizeof(l->mailbox));
02213                if (!ast_strlen_zero(mailbox)) {
02214                   if (option_verbose > 2)
02215                      ast_verbose(VERBOSE_PREFIX_3 "Setting mailbox '%s' on %s@%s\n", mailbox, d->name, l->name);
02216                }
02217                l->msgstate = -1;
02218                l->capability = d->capability;
02219                l->prefs = d->prefs;
02220                l->parent = d;
02221                if (!strcasecmp(v->name, "trunk")) {
02222                   l->type = TYPE_TRUNK;
02223                } else {
02224                   l->type = TYPE_LINE;
02225                }
02226                l->immediate = immediate;
02227                l->callgroup = cur_callergroup;
02228                l->pickupgroup = cur_pickupgroup;
02229                l->callreturn = callreturn;
02230                l->cancallforward = cancallforward;
02231                l->callwaiting = callwaiting;
02232                l->transfer = transfer;
02233                l->threewaycalling = threewaycalling;
02234                l->mwiblink = mwiblink;
02235                l->onhooktime = time(NULL);
02236                l->instance = lineInstance++;
02237                /* ASSUME we're onhook at this point */
02238                l->hookstate = SKINNY_ONHOOK;
02239                l->nat = nat;
02240 
02241                l->next = d->lines;
02242                d->lines = l;
02243             }
02244          } else {
02245             ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
02246          }
02247          v = v->next;
02248       }
02249 
02250       if (!d->lines) {
02251          ast_log(LOG_ERROR, "A Skinny device must have at least one line!\n");
02252          return NULL;
02253       }
02254       if (/*d->addr.sin_addr.s_addr && */!ntohs(d->addr.sin_port)) {
02255          d->addr.sin_port = htons(DEFAULT_SKINNY_PORT);
02256       }
02257 #if 0
02258       /* I don't think we need this anymore at all, since d->ourip is set in skinny_register now */
02259       if (d->addr.sin_addr.s_addr) {
02260          /* XXX See note above, in 'host' option. */
02261          if (ast_ouraddrfor(&d->addr.sin_addr, &d->ourip)) {
02262             d->ourip = __ourip;
02263          }
02264       } else {
02265          d->ourip = __ourip;
02266       }
02267 #endif
02268    }
02269    return d;
02270 }
02271 
02272 static void start_rtp(struct skinny_subchannel *sub)
02273 {
02274    struct skinny_line *l = sub->parent;
02275    struct skinny_device *d = l->parent;
02276    int hasvideo = 0;
02277 
02278    ast_mutex_lock(&sub->lock);
02279    /* Allocate the RTP */
02280    sub->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
02281    if (hasvideo)
02282       sub->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
02283    
02284    if (sub->rtp && sub->owner) {
02285       sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
02286       sub->owner->fds[1] = ast_rtcp_fd(sub->rtp);
02287    }
02288    if (hasvideo && sub->vrtp && sub->owner) {
02289       sub->owner->fds[2] = ast_rtp_fd(sub->vrtp);
02290       sub->owner->fds[3] = ast_rtcp_fd(sub->vrtp);
02291    }
02292    if (sub->rtp) {
02293       ast_rtp_setnat(sub->rtp, l->nat);
02294    }
02295    if (sub->vrtp) {
02296       ast_rtp_setnat(sub->vrtp, l->nat);
02297    }
02298    /* Set Frame packetization */
02299    if (sub->rtp)
02300       ast_rtp_codec_setpref(sub->rtp, &l->prefs);
02301 
02302    /* Create the RTP connection */
02303    transmit_connect(d->session, sub);
02304    ast_mutex_unlock(&sub->lock);
02305 }
02306 
02307 static void *skinny_newcall(void *data)
02308 {
02309    struct ast_channel *c = data;
02310    struct skinny_subchannel *sub = c->tech_pvt;
02311    struct skinny_line *l = sub->parent;
02312    struct skinny_device *d = l->parent;
02313    struct skinnysession *s = d->session;
02314    int res = 0;
02315 
02316    ast_copy_string(l->lastnumberdialed, c->exten, sizeof(l->lastnumberdialed));
02317    ast_set_callerid(c,
02318       l->hidecallerid ? "" : l->cid_num,
02319       l->hidecallerid ? "" : l->cid_name,
02320       c->cid.cid_ani ? NULL : l->cid_num);
02321    ast_setstate(c, AST_STATE_RING);
02322    res = ast_pbx_run(c);
02323    if (res) {
02324       ast_log(LOG_WARNING, "PBX exited non-zero\n");
02325       transmit_tone(s, SKINNY_REORDER, l->instance, sub->callid);
02326    }
02327    return NULL;
02328 }
02329 
02330 static void *skinny_ss(void *data)
02331 {
02332    struct ast_channel *c = data;
02333    struct skinny_subchannel *sub = c->tech_pvt;
02334    struct skinny_line *l = sub->parent;
02335    struct skinny_device *d = l->parent;
02336    struct skinnysession *s = d->session;
02337    int len = 0;
02338    int timeout = firstdigittimeout;
02339    int res = 0;
02340    int getforward=0;
02341    int loop_pause = 100;
02342 
02343    if (option_verbose > 2)
02344       ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s@%s'\n", l->name, d->name);
02345    len = strlen(d->exten);
02346 
02347    while (len < AST_MAX_EXTENSION-1) {
02348 
02349       res = 1;  /* Assume we will get a digit */
02350       while (strlen(d->exten) == len) {
02351          ast_safe_sleep(c, loop_pause);
02352          timeout -= loop_pause;
02353          if (timeout <= 0){
02354             res = 0;
02355             break;
02356          }
02357       }
02358 
02359       len = strlen(d->exten);
02360 
02361       if (!ast_ignore_pattern(c->context, d->exten)) {
02362          transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
02363       }
02364 
02365       if (ast_exists_extension(c, c->context, d->exten, 1, l->cid_num)) {
02366          if (!res || !ast_matchmore_extension(c, c->context, d->exten, 1, l->cid_num)) {
02367             if (getforward) {
02368                /* Record this as the forwarding extension */
02369                ast_copy_string(l->call_forward, d->exten, sizeof(l->call_forward));
02370                if (option_verbose > 2)
02371                   ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n",
02372                      l->call_forward, c->name);
02373                transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
02374                if (res) {
02375                   break;
02376                }
02377                ast_safe_sleep(c, 500);
02378                ast_indicate(c, -1);
02379                ast_safe_sleep(c, 1000);
02380                memset(d->exten, 0, sizeof(d->exten));
02381                transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
02382                len = 0;
02383                getforward = 0;
02384             } else {
02385                ast_copy_string(c->exten, d->exten, sizeof(c->exten));
02386                ast_copy_string(l->lastnumberdialed, d->exten, sizeof(l->lastnumberdialed));
02387                memset (d->exten, 0, sizeof(d->exten));
02388                skinny_newcall(c);
02389                return NULL;
02390             }
02391          } else {
02392             /* It's a match, but they just typed a digit, and there is an ambiguous match,
02393                so just set the timeout to matchdigittimeout and wait some more */
02394             timeout = matchdigittimeout;
02395          }
02396       } else if (res == 0) {
02397          ast_log(LOG_DEBUG, "Not enough digits (and no ambiguous match)...\n");
02398          memset(d->exten, 0, sizeof(d->exten));
02399          transmit_tone(s, SKINNY_REORDER, l->instance, sub->callid);
02400          if (sub->owner && sub->owner->_state != AST_STATE_UP) {
02401             ast_indicate(c, -1);
02402             ast_hangup(c);
02403          }
02404          return NULL;
02405       } else if (!ast_canmatch_extension(c, c->context, d->exten, 1, c->cid.cid_num) &&
02406             ((d->exten[0] != '*') || (!ast_strlen_zero(d->exten) > 2))) {
02407          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);
02408          memset(d->exten, 0, sizeof(d->exten));
02409          transmit_tone(s, SKINNY_REORDER, l->instance, sub->callid);
02410          /* hang out for 3 seconds to let congestion play */
02411          ast_safe_sleep(c, 3000);
02412          break;
02413       }
02414       if (!timeout) {
02415          timeout = gendigittimeout;
02416       }
02417       if (len && !ast_ignore_pattern(c->context, d->exten)) {
02418          ast_indicate(c, -1);
02419       }
02420    }
02421    if (c)
02422       ast_hangup(c);
02423 
02424    memset(d->exten, 0, sizeof(d->exten));
02425    return NULL;
02426 }
02427 
02428 
02429 
02430 static int skinny_call(struct ast_channel *ast, char *dest, int timeout)
02431 {
02432    int res = 0;
02433    int tone = 0;
02434    struct skinny_subchannel *sub = ast->tech_pvt;
02435    struct skinny_line *l = sub->parent;
02436    struct skinny_device *d = l->parent;
02437    struct skinnysession *s = d->session;
02438 
02439    if (!d->registered) {
02440       ast_log(LOG_ERROR, "Device not registered, cannot call %s\n", dest);
02441       return -1;
02442    }
02443 
02444    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
02445       ast_log(LOG_WARNING, "skinny_call called on %s, neither down nor reserved\n", ast->name);
02446       return -1;
02447    }
02448 
02449    if (skinnydebug)
02450       ast_verbose(VERBOSE_PREFIX_3 "skinny_call(%s)\n", ast->name);
02451 
02452    if (l->dnd) {
02453       ast_queue_control(ast, AST_CONTROL_BUSY);
02454       return -1;
02455    }
02456 
02457    switch (l->hookstate) {
02458    case SKINNY_OFFHOOK:
02459       tone = SKINNY_CALLWAITTONE;
02460       break;
02461    case SKINNY_ONHOOK:
02462       tone = SKINNY_ALERT;
02463       break;
02464    default:
02465       ast_log(LOG_ERROR, "Don't know how to deal with hookstate %d\n", l->hookstate);
02466       break;
02467    }
02468 
02469    transmit_callstate(s, l->instance, SKINNY_RINGIN, sub->callid);
02470    transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGIN);
02471    transmit_displaypromptstatus(s, "Ring-In", 0, l->instance, sub->callid);
02472    transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, l->cid_name, l->cid_num, l->instance, sub->callid, 1);
02473    transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
02474    transmit_ringer_mode(s, SKINNY_RING_INSIDE);
02475 
02476    ast_setstate(ast, AST_STATE_RINGING);
02477    ast_queue_control(ast, AST_CONTROL_RINGING);
02478    sub->outgoing = 1;
02479    return res;
02480 }
02481 
02482 static int skinny_hangup(struct ast_channel *ast)
02483 {
02484    struct skinny_subchannel *sub = ast->tech_pvt;
02485    struct skinny_line *l;
02486    struct skinny_device *d;
02487    struct skinnysession *s;
02488 
02489    if (!sub) {
02490       ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
02491       return 0;
02492    }
02493    l = sub->parent;
02494    d = l->parent;
02495    s = d->session;
02496    if (skinnydebug)
02497       ast_verbose("skinny_hangup(%s) on %s@%s\n", ast->name, l->name, d->name);
02498 
02499    if (d->registered) {
02500       if ((l->type = TYPE_LINE) && (l->hookstate == SKINNY_OFFHOOK)) {
02501          l->hookstate = SKINNY_ONHOOK;
02502          transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
02503          transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
02504          transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
02505       } else if ((l->type = TYPE_LINE) && (l->hookstate == SKINNY_ONHOOK)) {
02506          transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
02507          transmit_callstate(s, l->instance, SKINNY_ONHOOK, sub->callid);
02508          transmit_ringer_mode(s, SKINNY_RING_OFF);
02509          transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_OFF);
02510          do_housekeeping(s);
02511       }
02512    }
02513    ast_mutex_lock(&sub->lock);
02514    sub->owner = NULL;
02515    ast->tech_pvt = NULL;
02516    sub->alreadygone = 0;
02517    sub->outgoing = 0;
02518    if (sub->rtp) {
02519       ast_rtp_destroy(sub->rtp);
02520       sub->rtp = NULL;
02521    }
02522    ast_mutex_unlock(&sub->lock);
02523    return 0;
02524 }
02525 
02526 static int skinny_answer(struct ast_channel *ast)
02527 {
02528    int res = 0;
02529    struct skinny_subchannel *sub = ast->tech_pvt;
02530    struct skinny_line *l = sub->parent;
02531    struct skinny_device *d = l->parent;
02532    struct skinnysession *s = d->session;
02533    char exten[AST_MAX_EXTENSION] = "";
02534 
02535    ast_copy_string(exten, S_OR(ast->macroexten, ast->exten), sizeof(exten));
02536 
02537    sub->cxmode = SKINNY_CX_SENDRECV;
02538    if (!sub->rtp) {
02539       start_rtp(sub);
02540    }
02541    if (skinnydebug)
02542       ast_verbose("skinny_answer(%s) on %s@%s-%d\n", ast->name, l->name, d->name, sub->callid);
02543    if (ast->_state != AST_STATE_UP) {
02544       ast_setstate(ast, AST_STATE_UP);
02545    }
02546 
02547    transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
02548    /* order matters here...
02549       for some reason, transmit_callinfo must be before transmit_callstate,
02550       or you won't get keypad messages in some situations. */
02551    transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, exten, exten, l->instance, sub->callid, 2);
02552    transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
02553    transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
02554    transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
02555    return res;
02556 }
02557 
02558 /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
02559 static struct ast_frame *skinny_rtp_read(struct skinny_subchannel *sub)
02560 {
02561    struct ast_channel *ast = sub->owner;
02562    struct ast_frame *f;
02563 
02564    if (!sub->rtp) {
02565       /* We have no RTP allocated for this channel */
02566       return &ast_null_frame;
02567    }
02568 
02569    switch(ast->fdno) {
02570    case 0:
02571       f = ast_rtp_read(sub->rtp);   /* RTP Audio */
02572       break;
02573    case 1:
02574       f = ast_rtcp_read(sub->rtp);  /* RTCP Control Channel */
02575       break;
02576    case 2:
02577       f = ast_rtp_read(sub->vrtp);  /* RTP Video */
02578       break;
02579    case 3:
02580       f = ast_rtcp_read(sub->vrtp); /* RTCP Control Channel for video */
02581       break;
02582 #if 0
02583    case 5:
02584       /* Not yet supported */
02585       f = ast_udptl_read(sub->udptl);  /* UDPTL for T.38 */
02586       break;
02587 #endif
02588    default:
02589       f = &ast_null_frame;
02590    }
02591 
02592    if (ast) {
02593       /* We already hold the channel lock */
02594       if (f->frametype == AST_FRAME_VOICE) {
02595          if (f->subclass != ast->nativeformats) {
02596             ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
02597             ast->nativeformats = f->subclass;
02598             ast_set_read_format(ast, ast->readformat);
02599             ast_set_write_format(ast, ast->writeformat);
02600          }
02601       }
02602    }
02603    return f;
02604 }
02605 
02606 static struct ast_frame *skinny_read(struct ast_channel *ast)
02607 {
02608    struct ast_frame *fr;
02609    struct skinny_subchannel *sub = ast->tech_pvt;
02610    ast_mutex_lock(&sub->lock);
02611    fr = skinny_rtp_read(sub);
02612    ast_mutex_unlock(&sub->lock);
02613    return fr;
02614 }
02615 
02616 static int skinny_write(struct ast_channel *ast, struct ast_frame *frame)
02617 {
02618    struct skinny_subchannel *sub = ast->tech_pvt;
02619    int res = 0;
02620    if (frame->frametype != AST_FRAME_VOICE) {
02621       if (frame->frametype == AST_FRAME_IMAGE) {
02622          return 0;
02623       } else {
02624          ast_log(LOG_WARNING, "Can't send %d type frames with skinny_write\n", frame->frametype);
02625          return 0;
02626       }
02627    } else {
02628       if (!(frame->subclass & ast->nativeformats)) {
02629          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
02630             frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
02631          return -1;
02632       }
02633    }
02634    if (sub) {
02635       ast_mutex_lock(&sub->lock);
02636       if (sub->rtp) {
02637          res = ast_rtp_write(sub->rtp, frame);
02638       }
02639       ast_mutex_unlock(&sub->lock);
02640    }
02641    return res;
02642 }
02643 
02644 static int skinny_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
02645 {
02646    struct skinny_subchannel *sub = newchan->tech_pvt;
02647    ast_log(LOG_NOTICE, "skinny_fixup(%s, %s)\n", oldchan->name, newchan->name);
02648    if (sub->owner != oldchan) {
02649       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
02650       return -1;
02651    }
02652    sub->owner = newchan;
02653    return 0;
02654 }
02655 
02656 static int skinny_senddigit_begin(struct ast_channel *ast, char digit)
02657 {
02658    return -1; /* Start inband indications */
02659 }
02660 
02661 static int skinny_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
02662 {
02663 #if 0
02664    struct skinny_subchannel *sub = ast->tech_pvt;
02665    struct skinny_line *l = sub->parent;
02666    struct skinny_device *d = l->parent;
02667    int tmp;
02668    /* not right */
02669    sprintf(tmp, "%d", digit);
02670    transmit_tone(d->session, digit, l->instance, sub->callid);
02671 #endif
02672    return -1; /* Stop inband indications */
02673 }
02674 
02675 static char *control2str(int ind) {
02676    char *tmp;
02677 
02678    switch (ind) {
02679    case AST_CONTROL_HANGUP:
02680       return "Other end has hungup";
02681    case AST_CONTROL_RING:
02682       return "Local ring";
02683    case AST_CONTROL_RINGING:
02684       return "Remote end is ringing";
02685    case AST_CONTROL_ANSWER:
02686       return "Remote end has answered";
02687    case AST_CONTROL_BUSY:
02688       return "Remote end is busy";
02689    case AST_CONTROL_TAKEOFFHOOK:
02690       return "Make it go off hook";
02691    case AST_CONTROL_OFFHOOK:
02692       return "Line is off hook";
02693    case AST_CONTROL_CONGESTION:
02694       return "Congestion (circuits busy)";
02695    case AST_CONTROL_FLASH:
02696       return "Flash hook";
02697    case AST_CONTROL_WINK:
02698       return "Wink";
02699    case AST_CONTROL_OPTION:
02700       return "Set a low-level option";
02701    case AST_CONTROL_RADIO_KEY:
02702       return "Key Radio";
02703    case AST_CONTROL_RADIO_UNKEY:
02704       return "Un-Key Radio";
02705    case AST_CONTROL_PROGRESS:
02706       return "Remote end is making Progress";
02707    case AST_CONTROL_PROCEEDING:
02708       return "Remote end is proceeding";
02709    case AST_CONTROL_HOLD:
02710       return "Hold";
02711    case AST_CONTROL_UNHOLD:
02712       return "Unhold";
02713    case -1:
02714       return "Stop tone";
02715    default:
02716       if (!(tmp = ast_threadstorage_get(&control2str_threadbuf, CONTROL2STR_BUFSIZE)))
02717                         return "Unknown";
02718       snprintf(tmp, CONTROL2STR_BUFSIZE, "UNKNOWN-%d", ind);
02719       return tmp;
02720    }
02721 }
02722 
02723 
02724 static int skinny_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
02725 {
02726    struct skinny_subchannel *sub = ast->tech_pvt;
02727    struct skinny_line *l = sub->parent;
02728    struct skinny_device *d = l->parent;
02729    struct skinnysession *s = d->session;
02730    char exten[AST_MAX_EXTENSION] = "";
02731 
02732    if (!s) {
02733       ast_log(LOG_NOTICE, "Asked to indicate '%s' condition on channel %s, but session does not exist.\n", control2str(ind), ast->name);
02734       return -1;
02735    }
02736 
02737    ast_copy_string(exten, S_OR(ast->macroexten, ast->exten), sizeof(exten));
02738 
02739    if (skinnydebug)
02740       ast_verbose(VERBOSE_PREFIX_3 "Asked to indicate '%s' condition on channel %s\n", control2str(ind), ast->name);
02741    switch(ind) {
02742    case AST_CONTROL_RINGING:
02743       if (ast->_state != AST_STATE_UP) {
02744          if (!sub->progress) {
02745             transmit_tone(s, SKINNY_ALERT, l->instance, sub->callid);
02746             transmit_callstate(s, l->instance, SKINNY_RINGOUT, sub->callid);
02747             transmit_dialednumber(s, exten, l->instance, sub->callid);
02748             transmit_displaypromptstatus(s, "Ring Out", 0, l->instance, sub->callid);
02749             transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, exten, exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
02750             sub->ringing = 1;
02751             break;
02752          }
02753       }
02754       return -1;
02755    case AST_CONTROL_BUSY:
02756       if (ast->_state != AST_STATE_UP) {
02757          transmit_tone(s, SKINNY_BUSYTONE, l->instance, sub->callid);
02758          transmit_callstate(s, l->instance, SKINNY_BUSY, sub->callid);
02759          sub->alreadygone = 1;
02760          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
02761          break;
02762       }
02763       return -1;
02764    case AST_CONTROL_CONGESTION:
02765       if (ast->_state != AST_STATE_UP) {
02766          transmit_tone(s, SKINNY_REORDER, l->instance, sub->callid);
02767          transmit_callstate(s, l->instance, SKINNY_CONGESTION, sub->callid);
02768          sub->alreadygone = 1;
02769          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
02770          break;
02771       }
02772       return -1;
02773    case AST_CONTROL_PROGRESS:
02774       if ((ast->_state != AST_STATE_UP) && !sub->progress && !sub->outgoing) {
02775          transmit_tone(s, SKINNY_ALERT, l->instance, sub->callid);
02776          transmit_callstate(s, l->instance, SKINNY_PROGRESS, sub->callid);
02777          transmit_displaypromptstatus(s, "Call Progress", 0, l->instance, sub->callid);
02778          transmit_callinfo(s, ast->cid.cid_name, ast->cid.cid_num, exten, exten, l->instance, sub->callid, 2); /* 2 = outgoing from phone */
02779          sub->progress = 1;
02780          break;
02781       }
02782       return -1;
02783    case -1:
02784       transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
02785       break;
02786    case AST_CONTROL_HOLD:
02787       ast_moh_start(ast, data, l->mohinterpret);
02788       break;
02789    case AST_CONTROL_UNHOLD:
02790       ast_moh_stop(ast);
02791       break;
02792    case AST_CONTROL_PROCEEDING:
02793       break;
02794    default:
02795       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
02796       return -1;
02797    }
02798    return 0;
02799 }
02800 
02801 static struct ast_channel *skinny_new(struct skinny_line *l, int state)
02802 {
02803    struct ast_channel *tmp;
02804    struct skinny_subchannel *sub;
02805    struct skinny_device *d = l->parent;
02806    int fmt;
02807 
02808    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);
02809    if (!tmp) {
02810       ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
02811       return NULL;
02812    } else {
02813       sub = ast_calloc(1, sizeof(struct skinny_subchannel));
02814       if (!sub) {
02815          ast_log(LOG_WARNING, "Unable to allocate Skinny subchannel\n");
02816          return NULL;
02817       } else {
02818          ast_mutex_init(&sub->lock);
02819 
02820          sub->owner = tmp;
02821          sub->callid = callnums++;
02822          d->lastlineinstance = l->instance;
02823          d->lastcallreference = sub->callid;
02824          sub->cxmode = SKINNY_CX_INACTIVE;
02825          sub->nat = l->nat;
02826          sub->parent = l;
02827          sub->onhold = 0;
02828 
02829          sub->next = l->sub;
02830          l->sub = sub;
02831       }
02832       tmp->tech = &skinny_tech;
02833       tmp->tech_pvt = sub;
02834       tmp->nativeformats = l->capability;
02835       if (!tmp->nativeformats)
02836          tmp->nativeformats = default_capability;
02837       fmt = ast_best_codec(tmp->nativeformats);
02838       if (skinnydebug)
02839          ast_verbose("skinny_new: tmp->nativeformats=%d fmt=%d\n", tmp->nativeformats, fmt);
02840       if (sub->rtp) {
02841          tmp->fds[0] = ast_rtp_fd(sub->rtp);
02842       }
02843       if (state == AST_STATE_RING) {
02844          tmp->rings = 1;
02845       }
02846       tmp->writeformat = fmt;
02847       tmp->rawwriteformat = fmt;
02848       tmp->readformat = fmt;
02849       tmp->rawreadformat = fmt;
02850       if (!ast_strlen_zero(l->language))
02851          ast_string_field_set(tmp, language, l->language);
02852       if (!ast_strlen_zero(l->accountcode))
02853          ast_string_field_set(tmp, accountcode, l->accountcode);
02854       if (l->amaflags)
02855          tmp->amaflags = l->amaflags;
02856 
02857       ast_module_ref(ast_module_info->self);
02858       tmp->callgroup = l->callgroup;
02859       tmp->pickupgroup = l->pickupgroup;
02860       ast_string_field_set(tmp, call_forward, l->call_forward);
02861       ast_copy_string(tmp->context, l->context, sizeof(tmp->context));
02862       ast_copy_string(tmp->exten, l->exten, sizeof(tmp->exten));
02863 
02864       /* Don't use ast_set_callerid() here because it will
02865        * generate a needless NewCallerID event */
02866       tmp->cid.cid_num = ast_strdup(l->cid_num);
02867       tmp->cid.cid_ani = ast_strdup(l->cid_num);
02868       tmp->cid.cid_name = ast_strdup(l->cid_name);
02869 
02870       tmp->priority = 1;
02871       tmp->adsicpe = AST_ADSI_UNAVAILABLE;
02872 
02873       if (sub->rtp)
02874          ast_jb_configure(tmp, &global_jbconf);
02875 
02876       if (state != AST_STATE_DOWN) {
02877          if (ast_pbx_start(tmp)) {
02878             ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
02879             ast_hangup(tmp);
02880             tmp = NULL;
02881          }
02882       }
02883    }
02884    return tmp;
02885 }
02886 
02887 static int skinny_hold(struct skinny_subchannel *sub)
02888 {
02889    struct skinny_line *l = sub->parent;
02890    struct skinny_device *d = l->parent;
02891    struct skinnysession *s = d->session;
02892    struct skinny_req *req;
02893 
02894    /* Don't try to hold a channel that doesn't exist */
02895    if (!sub || !sub->owner)
02896       return 0;
02897 
02898    /* Channel needs to be put on hold */
02899    if (skinnydebug)
02900       ast_verbose("Putting on Hold(%d)\n", l->instance);
02901 
02902    ast_queue_control_data(sub->owner, AST_CONTROL_HOLD,
02903       S_OR(l->mohsuggest, NULL),
02904       !ast_strlen_zero(l->mohsuggest) ? strlen(l->mohsuggest) + 1 : 0);
02905 
02906    if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
02907       return 0;
02908 
02909    req->data.activatecallplane.lineInstance = htolel(l->instance);
02910    transmit_response(s, req);
02911 
02912    if (!(req = req_alloc(sizeof(struct close_receive_channel_message), CLOSE_RECEIVE_CHANNEL_MESSAGE)))
02913       return 0;
02914 
02915    req->data.closereceivechannel.conferenceId = htolel(sub->callid);
02916    req->data.closereceivechannel.partyId = htolel(sub->callid);
02917    transmit_response(s, req);
02918 
02919    if (!(req = req_alloc(sizeof(struct stop_media_transmission_message), STOP_MEDIA_TRANSMISSION_MESSAGE)))
02920       return 0;
02921 
02922    req->data.stopmedia.conferenceId = htolel(sub->callid);
02923    req->data.stopmedia.passThruPartyId = htolel(sub->callid);
02924    transmit_response(s, req);
02925 
02926    transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_BLINK);
02927    sub->onhold = 1;
02928    return 1;
02929 }
02930 
02931 static int skinny_unhold(struct skinny_subchannel *sub)
02932 {
02933    struct skinny_line *l = sub->parent;
02934    struct skinny_device *d = l->parent;
02935    struct skinnysession *s = d->session;
02936    struct skinny_req *req;
02937 
02938    /* Don't try to unhold a channel that doesn't exist */
02939    if (!sub || !sub->owner)
02940       return 0;
02941 
02942    /* Channel is on hold, so we will unhold */
02943    if (skinnydebug)
02944       ast_verbose("Taking off Hold(%d)\n", l->instance);
02945 
02946    ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
02947 
02948    if (!(req = req_alloc(sizeof(struct activate_call_plane_message), ACTIVATE_CALL_PLANE_MESSAGE)))
02949       return 0;
02950 
02951    req->data.activatecallplane.lineInstance = htolel(l->instance);
02952    transmit_response(s, req);
02953 
02954    transmit_connect(s, sub);
02955    transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
02956    sub->onhold = 0;
02957    return 1;
02958 }
02959 
02960 static int handle_keep_alive_message(struct skinny_req *req, struct skinnysession *s)
02961 {
02962    if (!(req = req_alloc(0, KEEP_ALIVE_ACK_MESSAGE)))
02963       return -1;
02964 
02965    transmit_response(s, req);
02966    do_housekeeping(s);
02967    return 1;
02968 }
02969 
02970 static int handle_register_message(struct skinny_req *req, struct skinnysession *s)
02971 {
02972    char name[16];
02973    int res;
02974 
02975    memcpy(&name, req->data.reg.name, sizeof(name));
02976 
02977    res = skinny_register(req, s);
02978    if (!res) {
02979       ast_log(LOG_ERROR, "Rejecting Device %s: Device not found\n", name);
02980       if (!(req = req_alloc(sizeof(struct register_rej_message), REGISTER_REJ_MESSAGE)))
02981          return -1;
02982 
02983       snprintf(req->data.regrej.errMsg, sizeof(req->data.regrej.errMsg), "No Authority: %s", name);
02984       transmit_response(s, req);
02985       return 0;
02986    }
02987    if (option_verbose > 2)
02988       ast_verbose(VERBOSE_PREFIX_3 "Device '%s' successfully registered\n", name);
02989 
02990    if (!(req = req_alloc(sizeof(struct register_ack_message), REGISTER_ACK_MESSAGE)))
02991       return -1;
02992 
02993    req->data.regack.res[0] = '0';
02994    req->data.regack.res[1] = '\0';
02995    req->data.regack.keepAlive = htolel(keep_alive);
02996    memcpy(req->data.regack.dateTemplate, date_format, sizeof(req->data.regack.dateTemplate));
02997    req->data.regack.res2[0] = '0';
02998    req->data.regack.res2[1] = '\0';
02999    req->data.regack.secondaryKeepAlive = htolel(keep_alive);
03000    transmit_response(s, req);
03001    if (skinnydebug)
03002       ast_verbose("Requesting capabilities\n");
03003 
03004    if (!(req = req_alloc(0, CAPABILITIES_REQ_MESSAGE)))
03005       return -1;
03006 
03007    transmit_response(s, req);
03008 
03009    return res;
03010 }
03011 
03012 static int handle_ip_port_message(struct skinny_req *req, struct skinnysession *s)
03013 {
03014    /* no response necessary */
03015    return 1;
03016 }
03017 
03018 static int handle_keypad_button_message(struct skinny_req *req, struct skinnysession *s)
03019 {
03020    struct skinny_subchannel *sub = NULL;
03021    struct skinny_line *l;
03022    struct skinny_device *d = s->device;
03023    struct ast_frame f = { 0, };
03024    char dgt;
03025    int digit;
03026    int lineInstance;
03027    int callReference;
03028 
03029    digit = letohl(req->data.keypad.button);
03030    lineInstance = letohl(req->data.keypad.lineInstance);
03031    callReference = letohl(req->data.keypad.callReference);
03032 
03033    if (digit == 14) {
03034       dgt = '*';
03035    } else if (digit == 15) {
03036       dgt = '#';
03037    } else if (digit >= 0 && digit <= 9) {
03038       dgt = '0' + digit;
03039    } else {
03040       /* digit=10-13 (A,B,C,D ?), or
03041        * digit is bad value
03042        *
03043        * probably should not end up here, but set
03044        * value for backward compatibility, and log
03045        * a warning.
03046        */
03047       dgt = '0' + digit;
03048       ast_log(LOG_WARNING, "Unsupported digit %d\n", digit);
03049    }
03050 
03051    f.subclass = dgt;
03052 
03053    f.src = "skinny";
03054 
03055    if (lineInstance && callReference)
03056       sub = find_subchannel_by_instance_reference(d, lineInstance, callReference);
03057    else
03058       sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
03059 
03060    if (!sub)
03061       return 0;
03062 
03063    l = sub->parent;
03064    if (sub->owner) {
03065       if (sub->owner->_state == 0) {
03066          f.frametype = AST_FRAME_DTMF_BEGIN;
03067          ast_queue_frame(sub->owner, &f);
03068       }
03069       /* XXX MUST queue this frame to all lines in threeway call if threeway call is active */
03070       f.frametype = AST_FRAME_DTMF_END;
03071       ast_queue_frame(sub->owner, &f);
03072       /* XXX This seriously needs to be fixed */
03073       if (sub->next && sub->next->owner) {
03074          if (sub->owner->_state == 0) {
03075             f.frametype = AST_FRAME_DTMF_BEGIN;
03076             ast_queue_frame(sub->next->owner, &f);
03077          }
03078          f.frametype = AST_FRAME_DTMF_END;
03079          ast_queue_frame(sub->next->owner, &f);
03080       }
03081    } else {
03082       if (skinnydebug)
03083          ast_verbose("No owner: %s\n", l->name);
03084    }
03085    return 1;
03086 }
03087 
03088 static int handle_stimulus_message(struct skinny_req *req, struct skinnysession *s)
03089 {
03090    struct skinny_device *d = s->device;
03091    struct skinny_line *l;
03092    struct skinny_subchannel *sub;
03093    /*struct skinny_speeddial *sd;*/
03094    struct ast_channel *c;
03095    pthread_t t;
03096    int event;
03097    int instance;
03098    int callreference;
03099    /*int res = 0;*/
03100 
03101    event = letohl(req->data.stimulus.stimulus);
03102    instance = letohl(req->data.stimulus.stimulusInstance);
03103    callreference = letohl(req->data.stimulus.callreference); 
03104    if (skinnydebug)
03105       ast_verbose("callreference in handle_stimulus_message is '%d'\n", callreference);
03106 
03107    /*  Note that this call should be using the passed in instance and callreference */
03108    sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
03109 
03110    if (!sub) {
03111       l = find_line_by_instance(d, d->lastlineinstance);
03112       if (!l) {
03113          return 0;
03114       }
03115    } else {
03116       l = sub->parent;
03117    }
03118 
03119    switch(event) {
03120    case STIMULUS_REDIAL:
03121       if (skinnydebug)
03122          ast_verbose("Received Stimulus: Redial(%d/%d)\n", instance, callreference);
03123 
03124 #if 0
03125       if (ast_strlen_zero(l->lastnumberdialed)) {
03126          ast_log(LOG_WARNING, "Attempted redial, but no previously dialed number found.\n");
03127          l->hookstate = SKINNY_ONHOOK;
03128          transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
03129          transmit_callstate(s, l->instance, SKINNY_ONHOOK, instance);
03130          break;
03131       }
03132 
03133       c = skinny_new(l, AST_STATE_DOWN);
03134       if(!c) {
03135          ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
03136       } else {
03137          sub = c->tech_pvt;
03138          transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
03139          if (skinnydebug)
03140             ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
03141          transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
03142          transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
03143          transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGOUT);
03144 
03145          if (!ast_ignore_pattern(c->context, l->lastnumberdialed)) {
03146             transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
03147          }
03148          ast_copy_string(c->exten, l->lastnumberdialed, sizeof(c->exten));
03149          if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
03150             ast_log(LOG_WARNING, "Unable to create new call thread: %s\n", strerror(errno));
03151             ast_hangup(c);
03152          }
03153       }
03154 #endif
03155       break;
03156    case STIMULUS_SPEEDDIAL:
03157       if (skinnydebug)
03158          ast_verbose("Received Stimulus: SpeedDial(%d/%d)\n", instance, callreference);
03159 
03160 #if 0
03161       if (!(sd = find_speeddial_by_instance(d, instance))) {
03162          return 0;
03163       }
03164 
03165       if (ast_strlen_zero(l->lastnumberdialed)) {
03166          ast_log(LOG_WARNING, "Attempted redial, but no previously dialed number found.\n");
03167          l->hookstate = SKINNY_ONHOOK;
03168          transmit_speaker_mode(s, SKINNY_SPEAKEROFF);
03169          transmit_callstate(s, l->instance, SKINNY_ONHOOK, instance);
03170          break;
03171       }
03172 
03173       c = skinny_new(l, AST_STATE_DOWN);
03174       if(c) {
03175          sub = c->tech_pvt;
03176          l = sub->parent;
03177          transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
03178          if (skinnydebug)
03179             ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
03180          transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
03181          transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
03182          transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGOUT);
03183 
03184          if (!ast_ignore_pattern(c->context, sd->exten)) {
03185             transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
03186          }
03187          if (ast_exists_extension(c, c->context, sd->exten, 1, l->cid_num)) {
03188             if (!ast_matchmore_extension(c, c->context, sd->exten, 1, l->cid_num)) {
03189                ast_copy_string(c->exten, sd->exten, sizeof(c->exten));
03190                ast_copy_string(l->lastnumberdialed, sd->exten, sizeof(l->lastnumberdialed));
03191                skinny_newcall(c);
03192                break;
03193             }
03194          }
03195       } else {
03196          ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
03197       }
03198 #endif
03199       break;
03200    case STIMULUS_HOLD:
03201       if (skinnydebug)
03202          ast_verbose("Received Stimulus: Hold(%d/%d)\n", instance, callreference);
03203 
03204       if (!sub)
03205          break;
03206 
03207       if (sub->onhold) {
03208          skinny_unhold(sub);
03209       } else {
03210          skinny_hold(sub);
03211       }
03212       break;
03213    case STIMULUS_TRANSFER:
03214       if (skinnydebug)
03215          ast_verbose("Received Stimulus: Transfer(%d/%d)\n", instance, callreference);
03216       /* XXX figure out how to transfer */
03217       break;
03218    case STIMULUS_CONFERENCE:
03219       if (skinnydebug)
03220          ast_verbose("Received Stimulus: Conference(%d/%d)\n", instance, callreference);
03221       /* XXX determine the best way to pull off a conference.  Meetme? */
03222       break;
03223    case STIMULUS_VOICEMAIL:
03224       if (skinnydebug)
03225          ast_verbose("Received Stimulus: Voicemail(%d/%d)\n", instance, callreference);
03226       /* XXX Find and dial voicemail extension */
03227       break;
03228    case STIMULUS_CALLPARK:
03229       if (skinnydebug)
03230          ast_verbose("Received Stimulus: Park Call(%d/%d)\n", instance, callreference);
03231       /* XXX Park the call */
03232       break;
03233    case STIMULUS_FORWARDALL:
03234       if (skinnydebug)
03235          ast_verbose("Received Stimulus: Forward All(%d/%d)\n", instance, callreference);
03236       /* Why is DND under FORWARDALL? */
03237       /* Because it's the same thing. */
03238 
03239       /* Do not disturb */
03240       if (l->dnd != 0){
03241          if (option_verbose > 2)
03242             ast_verbose(VERBOSE_PREFIX_3 "Disabling DND on %s@%s\n", l->name, d->name);
03243          l->dnd = 0;
03244          transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
03245          transmit_displaynotify(s, "DnD disabled", 10);
03246       } else {
03247          if (option_verbose > 2)
03248             ast_verbose(VERBOSE_PREFIX_3 "Enabling DND on %s@%s\n", l->name, d->name);
03249          l->dnd = 1;
03250          transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_OFF);
03251          transmit_displaynotify(s, "DnD enabled", 10);
03252       }
03253       break;
03254    case STIMULUS_FORWARDBUSY:
03255       if (skinnydebug)
03256          ast_verbose("Received Stimulus: Forward Busy (%d/%d)\n", instance, callreference);
03257       break;
03258    case STIMULUS_FORWARDNOANSWER:
03259       if (skinnydebug)
03260          ast_verbose("Received Stimulus: Forward No Answer (%d/%d)\n", instance, callreference);
03261       break;
03262    case STIMULUS_DISPLAY:
03263       /* Not sure what this is */
03264       if (skinnydebug)
03265          ast_verbose("Received Stimulus: Display(%d/%d)\n", instance, callreference);
03266       break;
03267    case STIMULUS_LINE:
03268       if (skinnydebug)
03269          ast_verbose("Received Stimulus: Line(%d/%d)\n", instance, callreference);
03270 
03271       l = find_line_by_instance(s->device, instance);
03272 
03273       if (!l) {
03274          return 0;
03275       }
03276 
03277       /* turn the speaker on */
03278       transmit_speaker_mode(s, SKINNY_SPEAKERON);
03279       transmit_ringer_mode(s, SKINNY_RING_OFF);
03280       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
03281 
03282       l->hookstate = SKINNY_OFFHOOK;
03283 
03284       if (sub && sub->outgoing) {
03285          /* We're answering a ringing call */
03286          ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
03287          transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
03288          transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
03289          transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
03290          transmit_displaypromptstatus(s, "Connected", 0, l->instance, sub->callid);
03291          transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
03292          start_rtp(sub);
03293          ast_setstate(sub->owner, AST_STATE_UP);
03294       } else {
03295          if (sub && sub->owner) {
03296             ast_log(LOG_DEBUG, "Current subchannel [%s] already has owner\n", sub->owner->name);
03297          } else {
03298             c = skinny_new(l, AST_STATE_DOWN);
03299             if(c) {
03300                sub = c->tech_pvt;
03301                transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
03302                if (skinnydebug)
03303                   ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
03304                transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
03305                transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
03306                transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
03307 
03308                /* start the switch thread */
03309                if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
03310                   ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
03311                   ast_hangup(c);
03312                }
03313             } else {
03314                ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
03315             }
03316          }
03317       }
03318       break;
03319    default:
03320       if (skinnydebug)
03321          ast_verbose("RECEIVED UNKNOWN STIMULUS:  %d(%d/%d)\n", event, instance, callreference);
03322       break;
03323    }
03324    return 1;
03325 }
03326 
03327 static int handle_offhook_message(struct skinny_req *req, struct skinnysession *s)
03328 {
03329    struct skinny_device *d = s->device;
03330    struct skinny_line *l;
03331    struct skinny_subchannel *sub;
03332    struct ast_channel *c;
03333    pthread_t t;
03334    int unknown1;
03335    int unknown2;
03336 
03337    unknown1 = letohl(req->data.offhook.unknown1);
03338    unknown2 = letohl(req->data.offhook.unknown2);
03339 
03340    sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
03341 
03342    if (!sub) {
03343       l = find_line_by_instance(d, d->lastlineinstance);
03344       if (!l) {
03345          return 0;
03346       }
03347    } else {
03348       l = sub->parent;
03349    }
03350 
03351    transmit_ringer_mode(s, SKINNY_RING_OFF);
03352    l->hookstate = SKINNY_OFFHOOK;
03353 
03354    if (sub && sub->onhold) {
03355       return 1;
03356    }
03357 
03358    transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
03359 
03360    if (sub && sub->outgoing) {
03361       /* We're answering a ringing call */
03362       ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
03363       transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
03364       transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
03365       transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
03366       transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
03367       start_rtp(sub);
03368       ast_setstate(sub->owner, AST_STATE_UP);
03369    } else {
03370       if (sub && sub->owner) {
03371          ast_log(LOG_DEBUG, "Current sub [%s] already has owner\n", sub->owner->name);
03372       } else {
03373          c = skinny_new(l, AST_STATE_DOWN);
03374          if(c) {
03375             sub = c->tech_pvt;
03376             transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
03377             if (skinnydebug)
03378                ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
03379             transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
03380             transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
03381             transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
03382 
03383             /* start the switch thread */
03384             if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
03385                ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
03386                ast_hangup(c);
03387             }
03388          } else {
03389             ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
03390          }
03391       }
03392    }
03393    return 1;
03394 }
03395 
03396 static int handle_onhook_message(struct skinny_req *req, struct skinnysession *s)
03397 {
03398    struct skinny_device *d = s->device;
03399    struct skinny_line *l;
03400    struct skinny_subchannel *sub;
03401    int unknown1;
03402    int unknown2;
03403 
03404    unknown1 = letohl(req->data.onhook.unknown1);
03405    unknown2 = letohl(req->data.onhook.unknown2);
03406 
03407    sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
03408 
03409    if (!sub) {
03410       return 0;
03411    }
03412    l = sub->parent;
03413 
03414    if (l->hookstate == SKINNY_ONHOOK) {
03415       /* Something else already put us back on hook */
03416       return 0;
03417    }
03418    l->hookstate = SKINNY_ONHOOK;
03419 
03420    if (sub->onhold) {
03421       return 0;
03422    }
03423 
03424    sub->cxmode = SKINNY_CX_RECVONLY;
03425    transmit_callstate(s, l->instance, l->hookstate, sub->callid);
03426    if (skinnydebug)
03427       ast_verbose("Skinny %s@%s went on hook\n", l->name, d->name);
03428    if (l->transfer && (sub->owner && sub->next && sub->next->owner) && ((!sub->outgoing) || (sub->next && !sub->next->outgoing))) {
03429       /* We're allowed to transfer, we have two active calls and
03430          we made at least one of the calls.  Let's try and transfer */
03431 
03432 #if 0
03433       if ((res = attempt_transfer(p)) < 0) {
03434          if (sub->next && sub->next->owner) {
03435             sub->next->alreadygone = 1;
03436             ast_queue_hangup(sub->next->owner,1);
03437          }
03438       } else if (res) {
03439          ast_log(LOG_WARNING, "Transfer attempt failed\n");
03440          return 0;
03441       }
03442 #endif
03443    } else {
03444       /* Hangup the current call */
03445       /* If there is another active call, skinny_hangup will ring the phone with the other call */
03446       if (sub->owner) {
03447          sub->alreadygone = 1;
03448          ast_queue_hangup(sub->owner);
03449       } else {
03450          ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n",
03451             l->name, d->name, sub->callid);
03452       }
03453    }
03454    if ((l->hookstate == SKINNY_ONHOOK) && (sub->next && !sub->next->rtp)) {
03455       do_housekeeping(s);
03456    }
03457    return 1;
03458 }
03459 
03460 static int handle_capabilities_res_message(struct skinny_req *req, struct skinnysession *s)
03461 {
03462    struct skinny_device *d = s->device;
03463    struct skinny_line *l;
03464    uint32_t count = 0;
03465    int codecs = 0;
03466    int i;
03467 
03468    count = letohl(req->data.caps.count);
03469    if (count > SKINNY_MAX_CAPABILITIES) {
03470       count = SKINNY_MAX_CAPABILITIES;
03471       ast_log(LOG_WARNING, "Received more capabilities than we can handle (%d).  Ignoring the rest.\n", SKINNY_MAX_CAPABILITIES);
03472    }
03473 
03474    for (i = 0; i < count; i++) {
03475       int acodec = 0;
03476       int scodec = 0;
03477       scodec = letohl(req->data.caps.caps[i].codec);
03478       acodec = codec_skinny2ast(scodec);
03479       if (skinnydebug)
03480          ast_verbose("Adding codec capability '%d (%d)'\n", acodec, scodec);
03481       codecs |= acodec;
03482    }
03483 
03484    d->capability &= codecs;
03485    ast_verbose("Device capability set to '%d'\n", d->capability);
03486    for (l = d->lines; l; l = l->next) {
03487       ast_mutex_lock(&l->lock);
03488       l->capability = d->capability;
03489       ast_mutex_unlock(&l->lock);
03490    }
03491 
03492    return 1;
03493 }
03494 
03495 static int handle_speed_dial_stat_req_message(struct skinny_req *req, struct skinnysession *s)
03496 {
03497    struct skinny_device *d = s->device;
03498    struct skinny_speeddial *sd;
03499    int instance;
03500 
03501    instance = letohl(req->data.speeddialreq.speedDialNumber);
03502 
03503    sd = find_speeddial_by_instance(d, instance);
03504 
03505    if (!sd) {
03506       return 0;
03507    }
03508 
03509    if (!(req = req_alloc(sizeof(struct speed_dial_stat_res_message), SPEED_DIAL_STAT_RES_MESSAGE)))
03510       return -1;
03511 
03512    req->data.speeddialreq.speedDialNumber = htolel(instance);
03513    snprintf(req->data.speeddial.speedDialDirNumber, sizeof(req->data.speeddial.speedDialDirNumber), sd->exten);
03514    snprintf(req->data.speeddial.speedDialDisplayName, sizeof(req->data.speeddial.speedDialDisplayName), sd->label);
03515 
03516    transmit_response(s, req);
03517    return 1;
03518 }
03519 
03520 static int handle_line_state_req_message(struct skinny_req *req, struct skinnysession *s)
03521 {
03522    struct skinny_device *d = s->device;
03523    struct skinny_line *l;
03524    int instance;
03525 
03526    instance = letohl(req->data.line.lineNumber);
03527 
03528    ast_mutex_lock(&devicelock);
03529 
03530    l = find_line_by_instance(d, instance);
03531 
03532    if (!l) {
03533       return 0;
03534    }
03535 
03536    ast_mutex_unlock(&devicelock);
03537 
03538    if (!(req = req_alloc(sizeof(struct line_stat_res_message), LINE_STAT_RES_MESSAGE)))
03539       return -1;
03540 
03541    req->data.linestat.lineNumber = letohl(instance);
03542    memcpy(req->data.linestat.lineDirNumber, l->name,
03543          sizeof(req->data.linestat.lineDirNumber));
03544    memcpy(req->data.linestat.lineDisplayName, l->label,
03545          sizeof(req->data.linestat.lineDisplayName));
03546    transmit_response(s,req);
03547    return 1;
03548 }
03549 
03550 static int handle_time_date_req_message(struct skinny_req *req, struct skinnysession *s)
03551 {
03552    time_t timer;
03553    struct tm *cmtime;
03554 
03555    if (!(req = req_alloc(sizeof(struct definetimedate_message), DEFINETIMEDATE_MESSAGE)))
03556       return -1;
03557 
03558    timer = time(NULL);
03559    cmtime = localtime(&timer);
03560    req->data.definetimedate.year = htolel(cmtime->tm_year+1900);
03561    req->data.definetimedate.month = htolel(cmtime->tm_mon+1);
03562    req->data.definetimedate.dayofweek = htolel(cmtime->tm_wday);
03563    req->data.definetimedate.day = htolel(cmtime->tm_mday);
03564    req->data.definetimedate.hour = htolel(cmtime->tm_hour);
03565    req->data.definetimedate.minute = htolel(cmtime->tm_min);
03566    req->data.definetimedate.seconds = htolel(cmtime->tm_sec);
03567    req->data.definetimedate.milliseconds = htolel(0);
03568    req->data.definetimedate.timestamp = htolel(timer);
03569    transmit_response(s, req);
03570    return 1;
03571 }
03572 
03573 static int handle_button_template_req_message(struct skinny_req *req, struct skinnysession *s)
03574 {
03575    struct skinny_device *d = s->device;
03576    struct skinny_line *l;
03577    int i;
03578 
03579    struct skinny_speeddial *sd;
03580    struct button_definition_template btn[42];
03581    int lineInstance = 1;
03582    int speeddialInstance = 1;
03583    int buttonCount = 0;
03584 
03585    if (!(req = req_alloc(sizeof(struct button_template_res_message), BUTTON_TEMPLATE_RES_MESSAGE)))
03586       return -1;
03587 
03588    memset(&btn, 0, sizeof(btn));
03589 
03590    get_button_template(s, btn);
03591 
03592    for (i=0; i<42; i++) {
03593       int btnSet = 0;
03594       switch (btn[i].buttonDefinition) {
03595          case BT_CUST_LINESPEEDDIAL:
03596             /* assume failure */
03597             req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
03598             req->data.buttontemplate.definition[i].instanceNumber = htolel(0);
03599 
03600             for (l = d->lines; l; l = l->next) {
03601                if (l->instance == lineInstance) {
03602                   ast_verbose("Adding button: %d, %d\n", BT_LINE, lineInstance);
03603                   req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
03604                   req->data.buttontemplate.definition[i].instanceNumber = htolel(lineInstance);
03605                   lineInstance++;
03606                   buttonCount++;
03607                   btnSet = 1;
03608                   break;
03609                }
03610             }
03611 
03612             if (!btnSet) {
03613                for (sd = d->speeddials; sd; sd = sd->next) {
03614                   if (sd->instance == speeddialInstance) {
03615                      ast_verbose("Adding button: %d, %d\n", BT_SPEEDDIAL, speeddialInstance);
03616                      req->data.buttontemplate.definition[i].buttonDefinition = BT_SPEEDDIAL;
03617                      req->data.buttontemplate.definition[i].instanceNumber = htolel(speeddialInstance);
03618                      speeddialInstance++;
03619                      buttonCount++;
03620                      btnSet = 1;
03621                      break;
03622                   }
03623                }
03624             }
03625             break;
03626          case BT_LINE:
03627             req->data.buttontemplate.definition[i].buttonDefinition = htolel(BT_NONE);
03628             req->data.buttontemplate.definition[i].instanceNumber = htolel(0);
03629 
03630             for (l = d->lines; l; l = l->next) {
03631                if (l->instance == lineInstance) {
03632                   ast_verbose("Adding button: %d, %d\n", BT_LINE, lineInstance);
03633                   req->data.buttontemplate.definition[i].buttonDefinition = BT_LINE;
03634                   req->data.buttontemplate.definition[i].instanceNumber = htolel(lineInstance);
03635                   lineInstance++;
03636                   buttonCount++;
03637                   btnSet = 1;
03638                   break;
03639                }
03640             }
03641             break;
03642          case BT_SPEEDDIAL:
03643             req->data.buttontemplate.definition[i].buttonDefinition = BT_NONE;
03644             req->data.buttontemplate.definition[i].instanceNumber = 0;
03645 
03646             for (sd = d->speeddials; sd; sd = sd->next) {
03647                if (sd->instance == speeddialInstance) {
03648                   ast_verbose("Adding button: %d, %d\n", BT_SPEEDDIAL, speeddialInstance);
03649                   req->data.buttontemplate.definition[i].buttonDefinition = BT_SPEEDDIAL;
03650                   req->data.buttontemplate.definition[i].instanceNumber = htolel(speeddialInstance);
03651                   speeddialInstance++;
03652                   buttonCount++;
03653                   btnSet = 1;
03654                   break;
03655                }
03656             }
03657             break;
03658          case BT_CUST_HINT:
03659             break;
03660          case BT_NONE:
03661             break;
03662          default:
03663             ast_verbose("Adding button: %d, %d\n", btn[i].buttonDefinition, 0);
03664             req->data.buttontemplate.definition[i].buttonDefinition = htolel(btn[i].buttonDefinition);
03665             req->data.buttontemplate.definition[i].instanceNumber = htolel(0);
03666             buttonCount++;
03667             btnSet = 1;
03668             break;
03669       }
03670    }
03671 
03672    req->data.buttontemplate.buttonOffset = htolel(0);
03673    req->data.buttontemplate.buttonCount = htolel(buttonCount);
03674    req->data.buttontemplate.totalButtonCount = htolel(buttonCount);
03675 
03676    if (skinnydebug)
03677       ast_verbose("Sending %d template to %s\n",
03678                d->type,
03679                d->name);
03680    transmit_response(s, req);
03681    return 1;
03682 }
03683 
03684 static int handle_version_req_message(struct skinny_req *req, struct skinnysession *s)
03685 {
03686    struct skinny_device *d = s->device;
03687    if (!(req = req_alloc(sizeof(struct version_res_message), VERSION_RES_MESSAGE)))
03688       return -1;
03689 
03690    snprintf(req->data.version.version, sizeof(req->data.version.version), d->version_id);
03691    transmit_response(s, req);
03692    return 1;
03693 }
03694 
03695 static int handle_server_request_message(struct skinny_req *req, struct skinnysession *s)
03696 {
03697    struct skinny_device *d = s->device;
03698    if (!(req = req_alloc(sizeof(struct server_res_message), SERVER_RES_MESSAGE)))
03699       return -1;
03700 
03701    memcpy(req->data.serverres.server[0].serverName, ourhost,
03702          sizeof(req->data.serverres.server[0].serverName));
03703    req->data.serverres.serverListenPort[0] = htolel(ourport);
03704    req->data.serverres.serverIpAddr[0] = htolel(d->ourip.s_addr);
03705    transmit_response(s, req);
03706    return 1;
03707 }
03708 
03709 static int handle_alarm_message(struct skinny_req *req, struct skinnysession *s)
03710 {
03711    /* no response necessary */
03712    if (skinnydebug)
03713       ast_verbose("Received Alarm Message: %s\n", req->data.alarm.displayMessage);
03714 
03715    return 1;
03716 }
03717 
03718 static int handle_open_receive_channel_ack_message(struct skinny_req *req, struct skinnysession *s)
03719 {
03720    struct skinny_device *d = s->device;
03721    struct skinny_line *l;
03722    struct skinny_subchannel *sub;
03723    struct ast_format_list fmt;
03724    struct sockaddr_in sin;
03725    struct sockaddr_in us;
03726    uint32_t addr;
03727    int port;
03728    int status;
03729    int passthruid;
03730 
03731    status = letohl(req->data.openreceivechannelack.status);
03732    if (status) {
03733       ast_log(LOG_ERROR, "Open Receive Channel Failure\n");
03734       return 0;
03735    }
03736    addr = letohl(req->data.openreceivechannelack.ipAddr);
03737    port = letohl(req->data.openreceivechannelack.port);
03738    passthruid = letohl(req->data.openreceivechannelack.passThruId);
03739 
03740    sin.sin_family = AF_INET;
03741    sin.sin_addr.s_addr = addr;
03742    sin.sin_port = htons(port);
03743 
03744    sub = find_subchannel_by_reference(d, passthruid);
03745 
03746    if (!sub)
03747       return 0;
03748 
03749    l = sub->parent;
03750 
03751    if (sub->rtp) {
03752       ast_rtp_set_peer(sub->rtp, &sin);
03753       ast_rtp_get_us(sub->rtp, &us);
03754    } else {
03755       ast_log(LOG_ERROR, "No RTP structure, this is very bad\n");
03756       return 0;
03757    }
03758 
03759    if (skinnydebug) {
03760       ast_verbose("ipaddr = %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
03761       ast_verbose("ourip = %s:%d\n", ast_inet_ntoa(d->ourip), ntohs(us.sin_port));
03762    }
03763 
03764    if (!(req = req_alloc(sizeof(struct start_media_transmission_message), START_MEDIA_TRANSMISSION_MESSAGE)))
03765       return -1;
03766 
03767    fmt = ast_codec_pref_getsize(&l->prefs, ast_best_codec(l->capability));
03768 
03769    if (skinnydebug)
03770       ast_verbose("Setting payloadType to '%d' (%d ms)\n", fmt.bits, fmt.cur_ms);
03771 
03772    req->data.startmedia.conferenceId = htolel(sub->callid);
03773    req->data.startmedia.passThruPartyId = htolel(sub->callid);
03774    req->data.startmedia.remoteIp = htolel(d->ourip.s_addr);
03775    req->data.startmedia.remotePort = htolel(ntohs(us.sin_port));
03776    req->data.startmedia.packetSize = htolel(fmt.cur_ms);
03777    req->data.startmedia.payloadType = htolel(codec_ast2skinny(fmt.bits));
03778    req->data.startmedia.qualifier.precedence = htolel(127);
03779    req->data.startmedia.qualifier.vad = htolel(0);
03780    req->data.startmedia.qualifier.packets = htolel(0);
03781    req->data.startmedia.qualifier.bitRate = htolel(0);
03782    transmit_response(s, req);
03783 
03784    return 1;
03785 }
03786 
03787 static int handle_enbloc_call_message(struct skinny_req *req, struct skinnysession *s)
03788 {
03789    struct skinny_device *d = s->device;
03790    struct skinny_line *l;
03791    struct skinny_subchannel *sub = NULL;
03792    struct ast_channel *c;
03793    pthread_t t;
03794 
03795    if (skinnydebug)
03796       ast_verbose("Received Enbloc Call: %s\n", req->data.enbloccallmessage.calledParty);
03797 
03798    sub = find_subchannel_by_instance_reference(d, d->lastlineinstance, d->lastcallreference);
03799 
03800    if (!sub) {
03801       l = find_line_by_instance(d, d->lastlineinstance);
03802       if (!l) {
03803          return 0;
03804       }
03805    } else {
03806       l = sub->parent;
03807    }
03808 
03809    c = skinny_new(l, AST_STATE_DOWN);
03810 
03811    if(!c) {
03812       ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
03813    } else {
03814       l->hookstate = SKINNY_OFFHOOK;
03815 
03816       sub = c->tech_pvt;
03817       transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
03818       if (skinnydebug)
03819          ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
03820       transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
03821       transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
03822 
03823       if (!ast_ignore_pattern(c->context, req->data.enbloccallmessage.calledParty)) {
03824          transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
03825       }
03826       ast_copy_string(c->exten, req->data.enbloccallmessage.calledParty, sizeof(c->exten));
03827       if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
03828          ast_log(LOG_WARNING, "Unable to create new call thread: %s\n", strerror(errno));
03829          ast_hangup(c);
03830       }
03831    }
03832    
03833    return 1;
03834 }
03835 
03836 
03837 static int handle_soft_key_set_req_message(struct skinny_req *req, struct skinnysession *s)
03838 {
03839    int i;
03840    int x;
03841    int y;
03842    const struct soft_key_definitions *softkeymode = soft_key_default_definitions;
03843 
03844    if (!(req = req_alloc(sizeof(struct soft_key_set_res_message), SOFT_KEY_SET_RES_MESSAGE)))
03845       return -1;
03846 
03847    req->data.softkeysets.softKeySetOffset = htolel(0);
03848    req->data.softkeysets.softKeySetCount = htolel(11);
03849    req->data.softkeysets.totalSoftKeySetCount = htolel(11);
03850    for (x = 0; x < sizeof(soft_key_default_definitions) / sizeof(struct soft_key_definitions); x++) {
03851       const uint8_t *defaults = softkeymode->defaults;
03852       /* XXX I wanted to get the size of the array dynamically, but that wasn't wanting to work.
03853          This will have to do for now. */
03854       for (y = 0; y < softkeymode->count; y++) {
03855          for (i = 0; i < (sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition)); i++) {
03856             if (defaults[y] == i+1) {
03857                req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyTemplateIndex[y] = htolel(i+1);
03858                req->data.softkeysets.softKeySetDefinition[softkeymode->mode].softKeyInfoIndex[y] = htolel(i+301);
03859             }
03860          }
03861       }
03862       softkeymode++;
03863    }
03864    transmit_response(s,req);
03865    transmit_selectsoftkeys(s, 0, 0, KEYDEF_ONHOOK);
03866    return 1;
03867 }
03868 
03869 static int handle_soft_key_event_message(struct skinny_req *req, struct skinnysession *s)
03870 {
03871    struct skinny_device *d = s->device;
03872    struct skinny_line *l;
03873    struct skinny_subchannel *sub = NULL;
03874    struct ast_channel *c;
03875    pthread_t t;
03876    int event;
03877    int instance;
03878    int callreference;
03879 
03880    event = letohl(req->data.softkeyeventmessage.softKeyEvent);
03881    instance = letohl(req->data.softkeyeventmessage.instance);
03882    callreference = letohl(req->data.softkeyeventmessage.callreference);
03883 
03884    if (instance) {
03885       l = find_line_by_instance(d, instance);
03886       if (callreference) {
03887          sub = find_subchannel_by_instance_reference(d, instance, callreference);
03888       } else {
03889          sub = find_subchannel_by_instance_reference(d, instance, d->lastcallreference);
03890       }
03891    } else {
03892       l = find_line_by_instance(d, d->lastlineinstance);
03893    }
03894 
03895    if (!l) {
03896       if (skinnydebug)
03897          ast_verbose("Received Softkey Event: %d(%d/%d)\n", event, instance, callreference);
03898       return 0;
03899    }
03900 
03901    switch(event) {
03902    case SOFTKEY_NONE:
03903       if (skinnydebug)
03904          ast_verbose("Received Softkey Event: None(%d/%d)\n", instance, callreference);
03905       break;
03906    case SOFTKEY_REDIAL:
03907       if (skinnydebug)
03908          ast_verbose("Received Softkey Event: Redial(%d/%d)\n", instance, callreference);
03909 
03910 #if 0
03911       if (!sub || !sub->owner) {
03912          c = skinny_new(l, AST_STATE_DOWN);
03913       } else {
03914          c = sub->owner;
03915       }
03916 
03917       if(!c) {
03918          ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
03919       } else {
03920          sub = c->tech_pvt;
03921          transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
03922          if (skinnydebug)
03923             ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
03924          transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
03925          transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
03926          transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_RINGOUT);
03927 
03928          if (!ast_ignore_pattern(c->context, l->lastnumberdialed)) {
03929             transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
03930          }
03931          ast_copy_string(c->exten, l->lastnumberdialed, sizeof(c->exten));
03932          if (ast_pthread_create(&t, NULL, skinny_newcall, c)) {
03933             ast_log(LOG_WARNING, "Unable to create new call thread: %s\n", strerror(errno));
03934             ast_hangup(c);
03935          }
03936       }
03937 #endif
03938       break;
03939    case SOFTKEY_NEWCALL:  /* Actually the DIAL softkey */
03940       if (skinnydebug)
03941          ast_verbose("Received Softkey Event: New Call(%d/%d)\n", instance, callreference);
03942 
03943       if (!sub || !sub->owner) {
03944          c = skinny_new(l, AST_STATE_DOWN);
03945       } else {
03946          c = sub->owner;
03947       }
03948 
03949       if (!c) {
03950          ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", l->name, d->name);
03951       } else {
03952          sub = c->tech_pvt;
03953          if (l->hookstate == SKINNY_ONHOOK) {
03954             l->hookstate = SKINNY_OFFHOOK;
03955             transmit_speaker_mode(s, SKINNY_SPEAKERON);
03956             transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
03957          }
03958 
03959          if (skinnydebug)
03960             ast_verbose("Attempting to Clear display on Skinny %s@%s\n", l->name, d->name);
03961          transmit_displaymessage(s, NULL, l->instance, sub->callid); /* clear display */
03962          transmit_tone(s, SKINNY_DIALTONE, l->instance, sub->callid);
03963          transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_OFFHOOK);
03964 
03965          /* start the switch thread */
03966          if (ast_pthread_create(&t, NULL, skinny_ss, c)) {
03967             ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
03968             ast_hangup(c);
03969          }
03970       }
03971       break;
03972    case SOFTKEY_HOLD:
03973       if (skinnydebug)
03974          ast_verbose("Received Softkey Event: Hold(%d/%d)\n", instance, callreference);
03975 
03976       if (sub) {
03977          if (sub->onhold) {
03978             skinny_unhold(sub);
03979          } else {
03980             skinny_hold(sub);
03981          }
03982       }
03983             
03984       break;
03985    case SOFTKEY_TRNSFER:
03986       if (skinnydebug)
03987          ast_verbose("Received Softkey Event: Transfer(%d/%d)\n", instance, callreference);
03988       /* XXX figure out how to transfer */
03989       break;
03990    case SOFTKEY_CFWDALL:
03991       if (skinnydebug)
03992          ast_verbose("Received Softkey Event: Forward All(%d/%d)\n", instance, callreference);
03993 
03994       /* Do not disturb */
03995       if (l->dnd != 0){
03996          if (option_verbose > 2)
03997             ast_verbose(VERBOSE_PREFIX_3 "Disabling DND on %s@%s\n", l->name, d->name);
03998          l->dnd = 0;
03999          transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_ON);
04000          transmit_displaynotify(s, "DnD disabled", 10);
04001       } else {
04002          if (option_verbose > 2)
04003             ast_verbose(VERBOSE_PREFIX_3 "Enabling DND on %s@%s\n", l->name, d->name);
04004          l->dnd = 1;
04005          transmit_lamp_indication(s, STIMULUS_FORWARDALL, 1, SKINNY_LAMP_OFF);
04006          transmit_displaynotify(s, "DnD enabled", 10);
04007       }
04008       break;
04009    case SOFTKEY_CFWDBUSY:
04010       if (skinnydebug)
04011          ast_verbose("Received Softkey Event: Forward Busy (%d/%d)\n", instance, callreference);
04012       break;
04013    case SOFTKEY_CFWDNOANSWER:
04014       if (skinnydebug)
04015          ast_verbose("Received Softkey Event: Forward No Answer (%d/%d)\n", instance, callreference);
04016       break;
04017    case SOFTKEY_BKSPC:
04018       if (skinnydebug)
04019          ast_verbose("Received Softkey Event: Backspace(%d/%d)\n", instance, callreference);
04020       break;
04021    case SOFTKEY_ENDCALL:
04022       if (skinnydebug)
04023          ast_verbose("Received Softkey Event: End Call(%d/%d)\n", instance, callreference);
04024 
04025       if (l->hookstate == SKINNY_ONHOOK) {
04026          /* Something else already put us back on hook */
04027          break;
04028       }
04029       if (sub) {
04030          sub->cxmode = SKINNY_CX_RECVONLY;
04031          l->hookstate = SKINNY_ONHOOK;
04032          transmit_callstate(s, l->instance, l->hookstate, sub->callid);
04033          if (skinnydebug)
04034             ast_verbose("Skinny %s@%s went on hook\n", l->name, d->name);
04035          if (l->transfer && (sub->owner && sub->next && sub->next->owner) && ((!sub->outgoing) || (sub->next && !sub->next->outgoing))) {
04036             /* We're allowed to transfer, we have two active calls and
04037                we made at least one of the calls.  Let's try and transfer */
04038 
04039 #if 0
04040             if ((res = attempt_transfer(p)) < 0) {
04041                if (sub->next && sub->next->owner) {
04042                   sub->next->alreadygone = 1;
04043                   ast_queue_hangup(sub->next->owner, 1);
04044                }
04045             } else if (res) {
04046                ast_log(LOG_WARNING, "Transfer attempt failed\n");
04047                break;
04048             }
04049 #endif
04050          } else {
04051             /* Hangup the current call */
04052             /* If there is another active call, skinny_hangup will ring the phone with the other call */
04053             if (sub->owner) {
04054                sub->alreadygone = 1;
04055                ast_queue_hangup(sub->owner);
04056             } else {
04057                ast_log(LOG_WARNING, "Skinny(%s@%s-%d) channel already destroyed\n",
04058                   l->name, d->name, sub->callid);
04059             }
04060          }
04061          if ((l->hookstate == SKINNY_ONHOOK) && (sub->next && !sub->next->rtp)) {
04062             do_housekeeping(s);
04063          }
04064       }
04065       break;
04066    case SOFTKEY_RESUME:
04067       if (skinnydebug)
04068          ast_verbose("Received Softkey Event: Resume(%d/%d)\n", instance, callreference);
04069       break;
04070    case SOFTKEY_ANSWER:
04071       if (skinnydebug)
04072          ast_verbose("Received Softkey Event: Answer(%d/%d)\n", instance, callreference);
04073 
04074       transmit_ringer_mode(s,SKINNY_RING_OFF);
04075       transmit_lamp_indication(s, STIMULUS_LINE, l->instance, SKINNY_LAMP_ON);
04076 
04077       l->hookstate = SKINNY_OFFHOOK;
04078 
04079       if (sub && sub->outgoing) {
04080          /* We're answering a ringing call */
04081          ast_queue_control(sub->owner, AST_CONTROL_ANSWER);
04082          transmit_callstate(s, l->instance, SKINNY_OFFHOOK, sub->callid);
04083          transmit_tone(s, SKINNY_SILENCE, l->instance, sub->callid);
04084          transmit_callstate(s, l->instance, SKINNY_CONNECTED, sub->callid);
04085          transmit_selectsoftkeys(s, l->instance, sub->callid, KEYDEF_CONNECTED);
04086          start_rtp(sub);
04087          ast_setstate(sub->owner, AST_STATE_UP);
04088       }
04089       break;
04090    case SOFTKEY_INFO:
04091       if (skinnydebug)
04092          ast_verbose("Received Softkey Event: Info(%d/%d)\n", instance, callreference);
04093       break;
04094    case SOFTKEY_CONFRN:
04095       if (skinnydebug)
04096          ast_verbose("Received Softkey Event: Conference(%d/%d)\n", instance, callreference);
04097       /* XXX determine the best way to pull off a conference.  Meetme? */
04098       break;
04099    case SOFTKEY_PARK:
04100       if (skinnydebug)
04101          ast_verbose("Received Softkey Event: Park Call(%d/%d)\n", instance, callreference);
04102       /* XXX Park the call */
04103       break;
04104    case SOFTKEY_JOIN:
04105       if (skinnydebug)
04106          ast_verbose("Received Softkey Event: Join(%d/%d)\n", instance, callreference);
04107       break;
04108    case SOFTKEY_MEETME:
04109       /* XXX How is this different from CONFRN? */
04110       if (skinnydebug)
04111          ast_verbose("Received Softkey Event: Meetme(%d/%d)\n", instance, callreference);
04112       break;
04113    case SOFTKEY_PICKUP:
04114       if (skinnydebug)
04115          ast_verbose("Received Softkey Event: Pickup(%d/%d)\n", instance, callreference);
04116       break;
04117    case SOFTKEY_GPICKUP:
04118       if (skinnydebug)
04119          ast_verbose("Received Softkey Event: Group Pickup(%d/%d)\n", instance, callreference);
04120       break;
04121    default:
04122       if (skinnydebug)
04123          ast_verbose("Received unknown Softkey Event: %d(%d/%d)\n", event, instance, callreference);
04124       break;
04125    }
04126    return 1;
04127 }
04128 
04129 static int handle_unregister_message(struct skinny_req *req, struct skinnysession *s)
04130 {
04131    return skinny_unregister(req, s);
04132 }
04133 
04134 static int handle_soft_key_template_req_message(struct skinny_req *req, struct skinnysession *s)
04135 {
04136    if (!(req = req_alloc(sizeof(struct soft_key_template_res_message), SOFT_KEY_TEMPLATE_RES_MESSAGE)))
04137       return -1;
04138 
04139    req->data.softkeytemplate.softKeyOffset = htolel(0);
04140    req->data.softkeytemplate.softKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
04141    req->data.softkeytemplate.totalSoftKeyCount = htolel(sizeof(soft_key_template_default) / sizeof(struct soft_key_template_definition));
04142    memcpy(req->data.softkeytemplate.softKeyTemplateDefinition,
04143       soft_key_template_default,
04144       sizeof(soft_key_template_default));
04145    transmit_response(s,req);
04146    return 1;
04147 }
04148 
04149 static int handle_headset_status_message(struct skinny_req *req, struct skinnysession *s)
04150 {
04151    /* XXX umm...okay?  Why do I care? */
04152    return 1;
04153 }
04154 
04155 static int handle_register_available_lines_message(struct skinny_req *req, struct skinnysession *s)
04156 {
04157    /* XXX I have no clue what this is for, but my phone was sending it, so... */
04158    return 1;
04159 }
04160 
04161 static int handle_message(struct skinny_req *req, struct skinnysession *s)
04162 {
04163    int res = 0;
04164    struct skinny_device *d = s->device;
04165    struct skinny_subchannel *sub;
04166    int lineInstance;
04167    int callReference;
04168 
04169    if ((!s->device) && (letohl(req->e) != REGISTER_MESSAGE && letohl(req->e) != ALARM_MESSAGE)) {
04170       ast_log(LOG_WARNING, "Client sent message #%d without first registering.\n", req->e);
04171       free(req);
04172       return 0;
04173    }
04174 
04175    switch(letohl(req->e))  {
04176    case KEEP_ALIVE_MESSAGE:
04177       res = handle_keep_alive_message(req, s);
04178       break;
04179    case REGISTER_MESSAGE:
04180       if (skinnydebug)
04181          ast_verbose("Device %s is attempting to register\n", req->data.reg.name);
04182 
04183       res = handle_register_message(req, s);
04184       break;
04185    case IP_PORT_MESSAGE:
04186       res = handle_ip_port_message(req, s);
04187       break;
04188    case KEYPAD_BUTTON_MESSAGE:
04189       if (skinnydebug)
04190          ast_verbose("Collected digit: [%d]\n", letohl(req->data.keypad.button));
04191 
04192       lineInstance = letohl(req->data.keypad.lineInstance);
04193       callReference = letohl(req->data.keypad.callReference);
04194 
04195       sub = find_subchannel_by_instance_reference(d, lineInstance, callReference);
04196 
04197       if (sub && (sub->owner && sub->owner->_state <  AST_STATE_UP)) {
04198          char dgt;
04199          int digit = letohl(req->data.keypad.button);
04200          size_t len;
04201 
04202          if (digit == 14) {
04203             dgt = '*';
04204          } else if (digit == 15) {
04205             dgt = '#';
04206          } else if (digit >= 0 && digit <= 9) {
04207             dgt = '0' + digit;
04208          } else {
04209             /* digit=10-13 (A,B,C,D ?), or
04210             * digit is bad value
04211             *
04212             * probably should not end up here, but set
04213             * value for backward compatibility, and log
04214             * a warning.
04215             */
04216             dgt = '0' + digit;
04217             ast_log(LOG_WARNING, "Unsupported digit %d\n", digit);
04218          }
04219 
04220          len = strlen(d->exten);
04221          if (len < sizeof(d->exten) - 1) {
04222             d->exten[len] = dgt;
04223             d->exten[len+1] = '\0';
04224          } else {
04225             ast_log(LOG_WARNING, "Dropping digit with value %d because digit queue is full\n", dgt);
04226          }
04227       } else
04228          res = handle_keypad_button_message(req, s);
04229       break;
04230    case ENBLOC_CALL_MESSAGE:
04231       res = handle_enbloc_call_message(req, s);
04232       break;
04233    case STIMULUS_MESSAGE:
04234       res = handle_stimulus_message(req, s);
04235       break;
04236    case OFFHOOK_MESSAGE:
04237       res = handle_offhook_message(req, s);
04238       break;
04239    case ONHOOK_MESSAGE:
04240       res = handle_onhook_message(req, s);
04241       break;
04242    case CAPABILITIES_RES_MESSAGE:
04243       if (skinnydebug)
04244          ast_verbose("Received CapabilitiesRes\n");
04245 
04246       res = handle_capabilities_res_message(req, s);
04247       break;
04248    case SPEED_DIAL_STAT_REQ_MESSAGE:
04249       if (skinnydebug)
04250          ast_verbose("Received SpeedDialStatRequest\n");
04251 
04252       res = handle_speed_dial_stat_req_message(req, s);
04253       break;
04254    case LINE_STATE_REQ_MESSAGE:
04255       if (skinnydebug)
04256          ast_verbose("Received LineStatRequest\n");
04257       res = handle_line_state_req_message(req, s);
04258       break;
04259    case TIME_DATE_REQ_MESSAGE:
04260       if (skinnydebug)
04261          ast_verbose("Received Time/Date Request\n");
04262 
04263       res = handle_time_date_req_message(req, s);
04264       break;
04265    case BUTTON_TEMPLATE_REQ_MESSAGE:
04266       if (skinnydebug)
04267          ast_verbose("Buttontemplate requested\n");
04268 
04269       res = handle_button_template_req_message(req, s);
04270       break;
04271    case VERSION_REQ_MESSAGE:
04272       if (skinnydebug)
04273          ast_verbose("Version Request\n");
04274 
04275       res = handle_version_req_message(req, s);
04276       break;
04277    case SERVER_REQUEST_MESSAGE:
04278       if (skinnydebug)
04279          ast_verbose("Received Server Request\n");
04280 
04281       res = handle_server_request_message(req, s);
04282       break;
04283    case ALARM_MESSAGE:
04284       res = handle_alarm_message(req, s);
04285       break;
04286    case OPEN_RECEIVE_CHANNEL_ACK_MESSAGE:
04287       if (skinnydebug)
04288          ast_verbose("Received Open Receive Channel Ack\n");
04289 
04290       res = handle_open_receive_channel_ack_message(req, s);
04291       break;
04292    case SOFT_KEY_SET_REQ_MESSAGE:
04293       if (skinnydebug)
04294          ast_verbose("Received SoftKeySetReq\n");
04295 
04296       res = handle_soft_key_set_req_message(req, s);
04297       break;
04298    case SOFT_KEY_EVENT_MESSAGE:
04299       res = handle_soft_key_event_message(req, s);
04300       break;
04301    case UNREGISTER_MESSAGE:
04302       if (skinnydebug)
04303          ast_verbose("Received Unregister Request\n");
04304 
04305       res = handle_unregister_message(req, s);
04306       break;
04307    case SOFT_KEY_TEMPLATE_REQ_MESSAGE:
04308       if (skinnydebug)
04309          ast_verbose("Received SoftKey Template Request\n");
04310 
04311       res = handle_soft_key_template_req_message(req, s);
04312       break;
04313    case HEADSET_STATUS_MESSAGE:
04314       res = handle_headset_status_message(req, s);
04315       break;
04316    case REGISTER_AVAILABLE_LINES_MESSAGE:
04317       res = handle_register_available_lines_message(req, s);
04318       break;
04319    default:
04320       if (skinnydebug)
04321          ast_verbose("RECEIVED UNKNOWN MESSAGE TYPE:  %x\n", letohl(req->e));
04322       break;
04323    }
04324    if (res >= 0 && req)
04325       free(req);
04326    return res;
04327 }
04328 
04329 static void destroy_session(struct skinnysession *s)
04330 {
04331    struct skinnysession *cur, *prev = NULL;
04332    ast_mutex_lock(&sessionlock);
04333    cur = sessions;
04334    while(cur) {
04335       if (cur == s) {
04336          break;
04337       }
04338       prev = cur;
04339       cur = cur->next;
04340    }
04341    if (cur) {
04342       if (prev) {
04343          prev->next = cur->next;
04344       } else {
04345          sessions = cur->next;
04346       }
04347       if (s->fd > -1) {
04348          close(s->fd);
04349       }
04350       ast_mutex_destroy(&s->lock);
04351       free(s);
04352    } else {
04353       ast_log(LOG_WARNING, "Trying to delete nonexistent session %p?\n", s);
04354    }
04355    ast_mutex_unlock(&sessionlock);
04356 }
04357 
04358 static int get_input(struct skinnysession *s)
04359 {
04360    int res;
04361    int dlen = 0;
04362    struct pollfd fds[1];
04363 
04364    fds[0].fd = s->fd;
04365    fds[0].events = POLLIN;
04366    fds[0].revents = 0;
04367    res = poll(fds, 1, (keep_alive * 1100)); /* If nothing has happen, client is dead */
04368                    /* we add 10% to the keep_alive to deal */
04369                    /* with network delays, etc */
04370    if (res < 0) {
04371       if (errno != EINTR) {
04372          ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
04373          return res;
04374       }
04375    } else if (res == 0) {
04376       if (skinnydebug)
04377          ast_verbose("Skinny Client was lost, unregistering\n");
04378       skinny_unregister(NULL, s);
04379       return -1;
04380    }
04381            
04382    if (fds[0].revents) {
04383       ast_mutex_lock(&s->lock);
04384       memset(s->inbuf,0,sizeof(s->inbuf));
04385       res = read(s->fd, s->inbuf, 4);
04386       if (res < 0) {
04387          ast_log(LOG_WARNING, "read() returned error: %s\n", strerror(errno));
04388 
04389          if (skinnydebug)
04390             ast_verbose("Skinny Client was lost, unregistering\n");
04391          
04392          skinny_unregister(NULL,s);
04393          ast_mutex_unlock(&s->lock);
04394          return res;
04395       } else if (res != 4) {
04396          ast_log(LOG_WARNING, "Skinny Client sent less data than expected.  Expected 4 but got %d.\n", res);
04397          ast_mutex_unlock(&s->lock);
04398          
04399          if (res == 0) {
04400             if (skinnydebug)
04401                ast_verbose("Skinny Client was lost, unregistering\n");
04402             skinny_unregister(NULL, s);
04403          }
04404            
04405          return -1;
04406       }
04407       
04408       dlen = letohl(*(int *)s->inbuf);
04409       if (dlen < 4) {
04410          ast_log(LOG_WARNING, "Skinny Client sent invalid data.\n");
04411          ast_mutex_unlock(&s->lock);
04412          return -1;
04413       }
04414       if (dlen+8 > sizeof(s->inbuf)) {
04415          dlen = sizeof(s->inbuf) - 8;
04416       }
04417       *(int *)s->inbuf = htolel(dlen);
04418 
04419       res = read(s->fd, s->inbuf+4, dlen+4);
04420       ast_mutex_unlock(&s->lock);
04421       if (res < 0) {
04422          ast_log(LOG_WARNING, "read() returned error: %s\n", strerror(errno));
04423          return res;
04424       } else if (res != (dlen+4)) {
04425          ast_log(LOG_WARNING, "Skinny Client sent less data than expected.\n");
04426          return -1;
04427       }
04428       return res;
04429    }
04430    return 0;
04431 }
04432 
04433 static struct skinny_req *skinny_req_parse(struct skinnysession *s)
04434 {
04435    struct skinny_req *req;
04436 
04437    if (!(req = ast_calloc(1, SKINNY_MAX_PACKET)))
04438       return NULL;
04439 
04440    ast_mutex_lock(&s->lock);
04441    memcpy(req, s->inbuf, skinny_header_size);
04442    memcpy(&req->data, s->inbuf+skinny_header_size, letohl(*(int*)(s->inbuf))-4);
04443 
04444    ast_mutex_unlock(&s->lock);
04445 
04446    if (letohl(req->e) < 0) {
04447       ast_log(LOG_ERROR, "Event Message is NULL from socket %d, This is bad\n", s->fd);
04448       free(req);
04449       return NULL;
04450    }
04451 
04452    return req;
04453 }
04454 
04455 static void *skinny_session(void *data)
04456 {
04457    int res;
04458    struct skinny_req *req;
04459    struct skinnysession *s = data;
04460 
04461    if (option_verbose > 2)
04462       ast_verbose(VERBOSE_PREFIX_3 "Starting Skinny session from %s\n", ast_inet_ntoa(s->sin.sin_addr));
04463 
04464    for (;;) {
04465       res = get_input(s);
04466       if (res < 0) {
04467          break;
04468       }
04469 
04470       if (res > 0)
04471       {
04472          if (!(req = skinny_req_parse(s))) {
04473             destroy_session(s);
04474             return NULL;
04475          }
04476 
04477          res = handle_message(req, s);
04478          if (res < 0) {
04479             destroy_session(s);
04480             return NULL;
04481          }
04482       }
04483    }
04484    ast_log(LOG_NOTICE, "Skinny Session returned: %s\n", strerror(errno));
04485 
04486    if (s) 
04487       destroy_session(s);
04488    
04489    return 0;
04490 }
04491 
04492 static void *accept_thread(void *ignore)
04493 {
04494    int as;
04495    struct sockaddr_in sin;
04496    socklen_t sinlen;
04497    struct skinnysession *s;
04498    struct protoent *p;
04499    int arg = 1;
04500    pthread_attr_t attr;
04501    pthread_t tcp_thread;
04502 
04503    pthread_attr_init(&attr);
04504    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
04505 
04506    for (;;) {
04507       sinlen = sizeof(sin);
04508       as = accept(skinnysock, (struct sockaddr *)&sin, &sinlen);
04509       if (as < 0) {
04510          ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
04511          continue;
04512       }
04513       p = getprotobyname("tcp");
04514       if(p) {
04515          if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
04516             ast_log(LOG_WARNING, "Failed to set Skinny tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
04517          }
04518       }
04519       if (!(s = ast_calloc(1, sizeof(struct skinnysession))))
04520          continue;
04521 
04522       memcpy(&s->sin, &sin, sizeof(sin));
04523       ast_mutex_init(&s->lock);
04524       s->fd = as;
04525       ast_mutex_lock(&sessionlock);
04526       s->next = sessions;
04527       sessions = s;
04528       ast_mutex_unlock(&sessionlock);
04529 
04530       if (ast_pthread_create(&tcp_thread, &attr, skinny_session, s)) {
04531          destroy_session(s);
04532       }
04533    }
04534    if (skinnydebug)
04535       ast_verbose("killing accept thread\n");
04536    close(as);
04537    pthread_attr_destroy(&attr);
04538    return 0;
04539 }
04540 
04541 static void *do_monitor(void *data)
04542 {
04543    int res;
04544 
04545    /* This thread monitors all the interfaces which are not yet in use
04546       (and thus do not have a separate thread) indefinitely */
04547    /* From here on out, we die whenever asked */
04548    for(;;) {
04549       pthread_testcancel();
04550       /* Wait for sched or io */
04551       res = ast_sched_wait(sched);
04552       if ((res < 0) || (res > 1000)) {
04553          res = 1000;
04554       }
04555       res = ast_io_wait(io, res);
04556       ast_mutex_lock(&monlock);
04557       if (res >= 0) {
04558          ast_sched_runq(sched);
04559       }
04560       ast_mutex_unlock(&monlock);
04561    }
04562    /* Never reached */
04563    return NULL;
04564 
04565 }
04566 
04567 static int restart_monitor(void)
04568 {
04569    /* If we're supposed to be stopped -- stay stopped */
04570    if (monitor_thread == AST_PTHREADT_STOP)
04571       return 0;
04572 
04573    ast_mutex_lock(&monlock);
04574    if (monitor_thread == pthread_self()) {
04575       ast_mutex_unlock(&monlock);
04576       ast_log(LOG_WARNING, "Cannot kill myself\n");
04577       return -1;
04578    }
04579    if (monitor_thread != AST_PTHREADT_NULL) {
04580       /* Wake up the thread */
04581       pthread_kill(monitor_thread, SIGURG);
04582    } else {
04583       /* Start a new monitor */
04584       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
04585          ast_mutex_unlock(&monlock);
04586          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
04587          return -1;
04588       }
04589    }
04590    ast_mutex_unlock(&monlock);
04591    return 0;
04592 }
04593 
04594 static struct ast_channel *skinny_request(const char *type, int format, void *data, int *cause)
04595 {
04596    int oldformat;
04597    
04598    struct skinny_line *l;
04599    struct ast_channel *tmpc = NULL;
04600    char tmp[256];
04601    char *dest = data;
04602 
04603    oldformat = format;
04604    
04605    if (!(format &= ((AST_FORMAT_MAX_AUDIO << 1) - 1))) {
04606       ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
04607       return NULL;   
04608    }     
04609 
04610    ast_copy_string(tmp, dest, sizeof(tmp));
04611    if (ast_strlen_zero(tmp)) {
04612       ast_log(LOG_NOTICE, "Skinny channels require a device\n");
04613       return NULL;
04614    }
04615    l = find_line_by_name(tmp);
04616    if (!l) {
04617       ast_log(LOG_NOTICE, "No available lines on: %s\n", dest);
04618       return NULL;
04619    }
04620    if (option_verbose > 2) {
04621       ast_verbose(VERBOSE_PREFIX_3 "skinny_request(%s)\n", tmp);
04622    }
04623    tmpc = skinny_new(l, AST_STATE_DOWN);
04624    if (!tmpc) {
04625       ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
04626    }
04627    restart_monitor();
04628    return tmpc;
04629 }
04630 
04631 static int reload_config(void)
04632 {
04633    int on = 1;
04634    struct ast_config *cfg;
04635    struct ast_variable *v;
04636    char *cat;
04637    struct skinny_device *d;
04638    int oldport = ntohs(bindaddr.sin_port);
04639 
04640    if (gethostname(ourhost, sizeof(ourhost))) {
04641       ast_log(LOG_WARNING, "Unable to get hostname, Skinny disabled\n");
04642       return 0;
04643    }
04644    cfg = ast_config_load(config);
04645 
04646    /* We *must* have a config file otherwise stop immediately */
04647    if (!cfg) {
04648       ast_log(LOG_NOTICE, "Unable to load config %s, Skinny disabled\n", config);
04649       return -1;
04650    }
04651    memset(&bindaddr, 0, sizeof(bindaddr));
04652    memset(&default_prefs, 0, sizeof(default_prefs));
04653 
04654    /* Copy the default jb config over global_jbconf */
04655    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
04656 
04657    /* load the general section */
04658    v = ast_variable_browse(cfg, "general");
04659    while (v) {
04660       /* handle jb conf */
04661       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
04662          v = v->next;
04663          continue;
04664       }
04665 
04666       /* Create the interface list */
04667       if (!strcasecmp(v->name, "bindaddr")) {
04668          if (!(hp = ast_gethostbyname(v->value, &ahp))) {
04669             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
04670          } else {
04671             memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
04672          }
04673       } else if (!strcasecmp(v->name, "keepalive")) {
04674          keep_alive = atoi(v->value);
04675       } else if (!strcasecmp(v->name, "dateformat")) {
04676          memcpy(date_format, v->value, sizeof(date_format));
04677       } else if (!strcasecmp(v->name, "allow")) {
04678          ast_parse_allow_disallow(&default_prefs, &default_capability, v->value, 1);
04679       } else if (!strcasecmp(v->name, "disallow")) {
04680          ast_parse_allow_disallow(&default_prefs, &default_capability, v->value, 0);
04681       } else if (!strcasecmp(v->name, "bindport") || !strcasecmp(v->name, "port")) {
04682          if (sscanf(v->value, "%d", &ourport) == 1) {
04683             bindaddr.sin_port = htons(ourport);
04684          } else {
04685             ast_log(LOG_WARNING, "Invalid bindport '%s' at line %d of %s\n", v->value, v->lineno, config);
04686          }
04687          if (!strcasecmp(v->name, "port")) { /*! \todo Remove 'port' option after 1.4 */
04688             ast_log(LOG_WARNING, "Option 'port' at line %d of %s has been deprecated.  Please use 'bindport' instead.\n", v->lineno, config);
04689          }
04690       }
04691       v = v->next;
04692    }
04693 
04694    if (ntohl(bindaddr.sin_addr.s_addr)) {
04695       __ourip = bindaddr.sin_addr;
04696    } else {
04697       hp = ast_gethostbyname(ourhost, &ahp);
04698       if (!hp) {
04699          ast_log(LOG_WARNING, "Unable to get our IP address, Skinny disabled\n");
04700          ast_config_destroy(cfg);
04701          return 0;
04702       }
04703       memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
04704    }
04705    if (!ntohs(bindaddr.sin_port)) {
04706       bindaddr.sin_port = ntohs(DEFAULT_SKINNY_PORT);
04707    }
04708    bindaddr.sin_family = AF_INET;
04709 
04710    /* load the device sections */
04711    cat = ast_category_browse(cfg, NULL);
04712    while(cat) {
04713       if (!strcasecmp(cat, "general")) {
04714          /* Nothing to do */
04715 #if 0
04716       } else if (!strncasecmp(cat, "paging-", 7)) {
04717          p = build_paging_device(cat, ast_variable_browse(cfg, cat));
04718          if (p) {
04719          }
04720 #endif
04721       } else {
04722          d = build_device(cat, ast_variable_browse(cfg, cat));
04723          if (d) {
04724             if (option_verbose > 2)
04725                ast_verbose(VERBOSE_PREFIX_3 "Added device '%s'\n", d->name);
04726             ast_mutex_lock(&devicelock);
04727             d->next = devices;
04728             devices = d;
04729             ast_mutex_unlock(&devicelock);
04730          }
04731       }
04732       cat = ast_category_browse(cfg, cat);
04733    }
04734    ast_mutex_lock(&netlock);
04735    if ((skinnysock > -1) && (ntohs(bindaddr.sin_port) != oldport)) {
04736       close(skinnysock);
04737       skinnysock = -1;
04738    }
04739    if (skinnysock < 0) {
04740       skinnysock = socket(AF_INET, SOCK_STREAM, 0);
04741       if(setsockopt(skinnysock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
04742          ast_log(LOG_ERROR, "Set Socket Options failed: errno %d, %s\n", errno, strerror(errno));
04743          ast_config_destroy(cfg);
04744          return 0;
04745       }
04746       if (skinnysock < 0) {
04747          ast_log(LOG_WARNING, "Unable to create Skinny socket: %s\n", strerror(errno));
04748       } else {
04749          if (bind(skinnysock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
04750             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
04751                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
04752                      strerror(errno));
04753             close(skinnysock);
04754             skinnysock = -1;
04755             ast_config_destroy(cfg);
04756             return 0;
04757          }
04758          if (listen(skinnysock,DEFAULT_SKINNY_BACKLOG)) {
04759                ast_log(LOG_WARNING, "Failed to start listening to %s:%d: %s\n",
04760                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
04761                      strerror(errno));
04762                close(skinnysock);
04763                skinnysock = -1;
04764                ast_config_destroy(cfg);
04765                return 0;
04766          }
04767          if (option_verbose > 1)
04768             ast_verbose(VERBOSE_PREFIX_2 "Skinny listening on %s:%d\n",
04769                ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
04770          ast_pthread_create_background(&accept_t,NULL, accept_thread, NULL);
04771       }
04772    }
04773    ast_mutex_unlock(&netlock);
04774    ast_config_destroy(cfg);
04775    return 1;
04776 }
04777 
04778 static void delete_devices(void)
04779 {
04780    struct skinny_device *d, *dlast;
04781    struct skinny_line *l, *llast;
04782    struct skinny_speeddial *sd, *sdlast;
04783    struct skinny_addon *a, *alast;
04784 
04785    ast_mutex_lock(&devicelock);
04786 
04787    /* Delete all devices */
04788    for (d=devices;d;) {
04789       /* Delete all lines for this device */
04790       for (l=d->lines;l;) {
04791          llast = l;
04792          l = l->next;
04793          ast_mutex_destroy(&llast->lock);
04794          free(llast);
04795       }
04796       /* Delete all speeddials for this device */
04797       for (sd=d->speeddials;sd;) {
04798          sdlast = sd;
04799          sd = sd->next;
04800          ast_mutex_destroy(&sdlast->lock);
04801          free(sdlast);
04802       }
04803       /* Delete all addons for this device */
04804       for (a=d->addons;a;) {
04805          alast = a;
04806          a = a->next;
04807          ast_mutex_destroy(&alast->lock);
04808          free(alast);
04809       }
04810       dlast = d;
04811       d = d->next;
04812       free(dlast);
04813    }
04814    devices=NULL;
04815    ast_mutex_unlock(&devicelock);
04816 }
04817 
04818 #if 0
04819 /*
04820  * XXX This never worked properly anyways.
04821  * Let's get rid of it, until we can fix it.
04822  */
04823 static int reload(void)
04824 {
04825    delete_devices();
04826    reload_config();
04827    restart_monitor();
04828    return 0;
04829 }
04830 #endif
04831 
04832 static int load_module(void)
04833 {
04834    int res = 0;
04835 
04836    for (; res < (sizeof(soft_key_template_default) / sizeof(soft_key_template_default[0])); res++) {
04837       soft_key_template_default[res].softKeyEvent = htolel(soft_key_template_default[res].softKeyEvent);
04838    }
04839    /* load and parse config */
04840    res = reload_config();
04841    if (res == -1) {
04842       return AST_MODULE_LOAD_DECLINE;
04843    }
04844 
04845    /* Make sure we can register our skinny channel type */
04846    if (ast_channel_register(&skinny_tech)) {
04847       ast_log(LOG_ERROR, "Unable to register channel class 'Skinny'\n");
04848       return -1;
04849    }
04850 
04851    ast_rtp_proto_register(&skinny_rtp);
04852    ast_cli_register_multiple(cli_skinny, sizeof(cli_skinny) / sizeof(struct ast_cli_entry));
04853    sched = sched_context_create();
04854    if (!sched) {
04855       ast_log(LOG_WARNING, "Unable to create schedule context\n");
04856    }
04857    io = io_context_create();
04858    if (!io) {
04859       ast_log(LOG_WARNING, "Unable to create I/O context\n");
04860    }
04861    /* And start the monitor for the first time */
04862    restart_monitor();
04863 
04864    return res;
04865 }
04866 
04867 static int unload_module(void)
04868 {
04869    struct skinnysession *s, *slast;
04870    struct skinny_device *d;
04871    struct skinny_line *l;
04872    struct skinny_subchannel *sub;
04873 
04874    ast_mutex_lock(&sessionlock);
04875    /* Destroy all the interfaces and free their memory */
04876    s = sessions;
04877    while(s) {
04878       slast = s;
04879       s = s->next;
04880       for (d = slast->device; d; d = d->next) {
04881          for (l = d->lines; l; l = l->next) {
04882             ast_mutex_lock(&l->lock);
04883             for (sub = l->sub; sub; sub = sub->next) {
04884                ast_mutex_lock(&sub->lock);
04885                if (sub->owner) {
04886                   sub->alreadygone = 1;
04887                   ast_softhangup(sub->owner, AST_SOFTHANGUP_APPUNLOAD);
04888                }
04889                ast_mutex_unlock(&sub->lock);
04890             }
04891             ast_mutex_unlock(&l->lock);
04892          }
04893       }
04894       if (slast->fd > -1)
04895          close(slast->fd);
04896       ast_mutex_destroy(&slast->lock);
04897       free(slast);
04898    }
04899    sessions = NULL;
04900    ast_mutex_unlock(&sessionlock);
04901 
04902    delete_devices();
04903 
04904    ast_mutex_lock(&monlock);
04905    if ((monitor_thread != AST_PTHREADT_NULL) && (monitor_thread != AST_PTHREADT_STOP)) {
04906       pthread_cancel(monitor_thread);
04907       pthread_kill(monitor_thread, SIGURG);
04908       pthread_join(monitor_thread, NULL);
04909    }
04910    monitor_thread = AST_PTHREADT_STOP;
04911    ast_mutex_unlock(&monlock);
04912 
04913    ast_mutex_lock(&netlock);
04914    if (accept_t && (accept_t != AST_PTHREADT_STOP)) {
04915       pthread_cancel(accept_t);
04916       pthread_kill(accept_t, SIGURG);
04917       pthread_join(accept_t, NULL);
04918    }
04919    accept_t = AST_PTHREADT_STOP;
04920    ast_mutex_unlock(&netlock);
04921 
04922    ast_rtp_proto_unregister(&skinny_rtp);
04923    ast_channel_unregister(&skinny_tech);
04924    ast_cli_unregister_multiple(cli_skinny, sizeof(cli_skinny) / sizeof(struct ast_cli_entry));
04925 
04926    close(skinnysock);
04927    if (sched)
04928       sched_context_destroy(sched);
04929 
04930    return 0;
04931 }
04932 
04933 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Skinny Client Control Protocol (Skinny)",
04934       .load = load_module,
04935       .unload = unload_module,
04936           );

Generated on Wed Aug 15 01:24:19 2007 for Asterisk - the Open Source PBX by  doxygen 1.5.3