chan_phone.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  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Generic Linux Telephony Interface driver
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  * 
00025  * \ingroup channel_drivers
00026  */
00027 
00028 /*! \li \ref chan_phone.c uses the configuration file \ref phone.conf
00029  * \addtogroup configuration_file
00030  */
00031 
00032 /*! \page phone.conf phone.conf
00033  * \verbinclude phone.conf.sample
00034  */
00035 
00036 /*** MODULEINFO
00037    <depend>ixjuser</depend>
00038    <support_level>extended</support_level>
00039  ***/
00040 
00041 #include "asterisk.h"
00042 
00043 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 426573 $")
00044 
00045 #include <ctype.h>
00046 #include <sys/socket.h>
00047 #include <sys/time.h>
00048 #include <arpa/inet.h>
00049 #include <fcntl.h>
00050 #include <sys/ioctl.h>
00051 #include <signal.h>
00052 #ifdef HAVE_LINUX_COMPILER_H
00053 #include <linux/compiler.h>
00054 #endif
00055 #include <linux/telephony.h>
00056 /* Still use some IXJ specific stuff */
00057 #include <linux/version.h>
00058 #include <linux/ixjuser.h>
00059 
00060 #include "asterisk/lock.h"
00061 #include "asterisk/channel.h"
00062 #include "asterisk/config.h"
00063 #include "asterisk/module.h"
00064 #include "asterisk/pbx.h"
00065 #include "asterisk/utils.h"
00066 #include "asterisk/callerid.h"
00067 #include "asterisk/causes.h"
00068 #include "asterisk/stringfields.h"
00069 #include "asterisk/musiconhold.h"
00070 #include "asterisk/format_cache.h"
00071 #include "asterisk/format_compatibility.h"
00072 
00073 #include "chan_phone.h"
00074 
00075 #ifdef QTI_PHONEJACK_TJ_PCI   /* check for the newer quicknet driver v.3.1.0 which has this symbol */
00076 #define QNDRV_VER 310
00077 #else
00078 #define QNDRV_VER 100
00079 #endif
00080 
00081 #if QNDRV_VER > 100
00082 #ifdef __linux__
00083 #define IXJ_PHONE_RING_START(x)  ioctl(p->fd, PHONE_RING_START, &x);
00084 #else /* FreeBSD and others */
00085 #define IXJ_PHONE_RING_START(x)  ioctl(p->fd, PHONE_RING_START, x);
00086 #endif /* __linux__ */
00087 #else /* older driver */
00088 #define IXJ_PHONE_RING_START(x)  ioctl(p->fd, PHONE_RING_START, &x);
00089 #endif
00090 
00091 #define DEFAULT_CALLER_ID "Unknown"
00092 #define PHONE_MAX_BUF 480
00093 #define DEFAULT_GAIN 0x100
00094 
00095 static const char tdesc[] = "Standard Linux Telephony API Driver";
00096 static const char config[] = "phone.conf";
00097 
00098 /* Default context for dialtone mode */
00099 static char context[AST_MAX_EXTENSION] = "default";
00100 
00101 /* Default language */
00102 static char language[MAX_LANGUAGE] = "";
00103 
00104 static int echocancel = AEC_OFF;
00105 
00106 static int silencesupression = 0;
00107 
00108 static struct ast_format_cap *prefcap;
00109 
00110 /* Protect the interface list (of phone_pvt's) */
00111 AST_MUTEX_DEFINE_STATIC(iflock);
00112 
00113 /* Protect the monitoring thread, so only one process can kill or start it, and not
00114    when it's doing something critical. */
00115 AST_MUTEX_DEFINE_STATIC(monlock);
00116 
00117 /* Boolean value whether the monitoring thread shall continue. */
00118 static unsigned int monitor;
00119    
00120 /* This is the thread for the monitor which checks for input on the channels
00121    which are not currently in use.  */
00122 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00123 
00124 static int restart_monitor(void);
00125 
00126 /* The private structures of the Phone Jack channels are linked for
00127    selecting outgoing channels */
00128    
00129 #define MODE_DIALTONE   1
00130 #define MODE_IMMEDIATE  2
00131 #define MODE_FXO  3
00132 #define MODE_FXS        4
00133 #define MODE_SIGMA      5
00134 
00135 static struct phone_pvt {
00136    int fd;                    /* Raw file descriptor for this device */
00137    struct ast_channel *owner;    /* Channel we belong to, possibly NULL */
00138    int mode;                  /* Is this in the  */
00139    struct ast_format *lastformat;            /* Last output format */
00140    struct ast_format *lastinput;             /* Last input format */
00141    int ministate;             /* Miniature state, for dialtone mode */
00142    char dev[256];             /* Device name */
00143    struct phone_pvt *next;       /* Next channel in list */
00144    struct ast_frame fr;       /* Frame */
00145    char offset[AST_FRIENDLY_OFFSET];
00146    char buf[PHONE_MAX_BUF];               /* Static buffer for reading frames */
00147    int obuflen;
00148    int dialtone;
00149    int txgain, rxgain;             /* gain control for playing, recording  */
00150                            /* 0x100 - 1.0, 0x200 - 2.0, 0x80 - 0.5 */
00151    int cpt;                /* Call Progress Tone playing? */
00152    int silencesupression;
00153    char context[AST_MAX_EXTENSION];
00154    char obuf[PHONE_MAX_BUF * 2];
00155    char ext[AST_MAX_EXTENSION];
00156    char language[MAX_LANGUAGE];
00157    char cid_num[AST_MAX_EXTENSION];
00158    char cid_name[AST_MAX_EXTENSION];
00159 } *iflist = NULL;
00160 
00161 static char cid_num[AST_MAX_EXTENSION];
00162 static char cid_name[AST_MAX_EXTENSION];
00163 
00164 static struct ast_channel *phone_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
00165 static int phone_digit_begin(struct ast_channel *ast, char digit);
00166 static int phone_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
00167 static int phone_call(struct ast_channel *ast, const char *dest, int timeout);
00168 static int phone_hangup(struct ast_channel *ast);
00169 static int phone_answer(struct ast_channel *ast);
00170 static struct ast_frame *phone_read(struct ast_channel *ast);
00171 static int phone_write(struct ast_channel *ast, struct ast_frame *frame);
00172 static struct ast_frame *phone_exception(struct ast_channel *ast);
00173 static int phone_send_text(struct ast_channel *ast, const char *text);
00174 static int phone_fixup(struct ast_channel *old, struct ast_channel *new);
00175 static int phone_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
00176 
00177 static struct ast_channel_tech phone_tech = {
00178    .type = "Phone",
00179    .description = tdesc,
00180    .requester = phone_request,
00181    .send_digit_begin = phone_digit_begin,
00182    .send_digit_end = phone_digit_end,
00183    .call = phone_call,
00184    .hangup = phone_hangup,
00185    .answer = phone_answer,
00186    .read = phone_read,
00187    .write = phone_write,
00188    .exception = phone_exception,
00189    .indicate = phone_indicate,
00190    .fixup = phone_fixup
00191 };
00192 
00193 static struct ast_channel_tech phone_tech_fxs = {
00194    .type = "Phone",
00195    .description = tdesc,
00196    .requester = phone_request,
00197    .send_digit_begin = phone_digit_begin,
00198    .send_digit_end = phone_digit_end,
00199    .call = phone_call,
00200    .hangup = phone_hangup,
00201    .answer = phone_answer,
00202    .read = phone_read,
00203    .write = phone_write,
00204    .exception = phone_exception,
00205    .write_video = phone_write,
00206    .send_text = phone_send_text,
00207    .indicate = phone_indicate,
00208    .fixup = phone_fixup
00209 };
00210 
00211 static struct ast_channel_tech *cur_tech;
00212 
00213 static int phone_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
00214 {
00215    struct phone_pvt *p = ast_channel_tech_pvt(chan);
00216    int res=-1;
00217    ast_debug(1, "Requested indication %d on channel %s\n", condition, ast_channel_name(chan));
00218    switch(condition) {
00219    case AST_CONTROL_FLASH:
00220       ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_ON_HOOK);
00221       usleep(320000);
00222       ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_OFF_HOOK);
00223       ao2_cleanup(p->lastformat);
00224       p->lastformat = NULL;
00225       res = 0;
00226       break;
00227    case AST_CONTROL_HOLD:
00228       ast_moh_start(chan, data, NULL);
00229       break;
00230    case AST_CONTROL_UNHOLD:
00231       ast_moh_stop(chan);
00232       break;
00233    case AST_CONTROL_SRCUPDATE:
00234       res = 0;
00235       break;
00236    case AST_CONTROL_PVT_CAUSE_CODE:
00237       break;
00238    default:
00239       ast_log(LOG_WARNING, "Condition %d is not supported on channel %s\n", condition, ast_channel_name(chan));
00240    }
00241    return res;
00242 }
00243 
00244 static int phone_fixup(struct ast_channel *old, struct ast_channel *new)
00245 {
00246    struct phone_pvt *pvt = ast_channel_tech_pvt(old);
00247    if (pvt && pvt->owner == old)
00248       pvt->owner = new;
00249    return 0;
00250 }
00251 
00252 static int phone_digit_begin(struct ast_channel *chan, char digit)
00253 {
00254    /* XXX Modify this callback to let Asterisk support controlling the length of DTMF */
00255    return 0;
00256 }
00257 
00258 static int phone_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
00259 {
00260    struct phone_pvt *p;
00261    int outdigit;
00262    p = ast_channel_tech_pvt(ast);
00263    ast_debug(1, "Dialed %c\n", digit);
00264    switch(digit) {
00265    case '0':
00266    case '1':
00267    case '2':
00268    case '3':
00269    case '4':
00270    case '5':
00271    case '6':
00272    case '7':
00273    case '8':
00274    case '9':
00275       outdigit = digit - '0';
00276       break;
00277    case '*':
00278       outdigit = 11;
00279       break;
00280    case '#':
00281       outdigit = 12;
00282       break;
00283    case 'f':   /*flash*/
00284    case 'F':
00285       ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_ON_HOOK);
00286       usleep(320000);
00287       ioctl(p->fd, IXJCTL_PSTN_SET_STATE, PSTN_OFF_HOOK);
00288       ao2_cleanup(p->lastformat);
00289       p->lastformat = NULL;
00290       return 0;
00291    default:
00292       ast_log(LOG_WARNING, "Unknown digit '%c'\n", digit);
00293       return -1;
00294    }
00295    ast_debug(1, "Dialed %d\n", outdigit);
00296    ioctl(p->fd, PHONE_PLAY_TONE, outdigit);
00297    ao2_cleanup(p->lastformat);
00298    p->lastformat = NULL;
00299    return 0;
00300 }
00301 
00302 static int phone_call(struct ast_channel *ast, const char *dest, int timeout)
00303 {
00304    struct phone_pvt *p;
00305 
00306    PHONE_CID cid;
00307    struct timeval UtcTime = ast_tvnow();
00308    struct ast_tm tm;
00309    int start;
00310 
00311    ast_localtime(&UtcTime, &tm, NULL);
00312 
00313    memset(&cid, 0, sizeof(PHONE_CID));
00314     snprintf(cid.month, sizeof(cid.month), "%02d",(tm.tm_mon + 1));
00315     snprintf(cid.day, sizeof(cid.day),     "%02d", tm.tm_mday);
00316     snprintf(cid.hour, sizeof(cid.hour),   "%02d", tm.tm_hour);
00317     snprintf(cid.min, sizeof(cid.min),     "%02d", tm.tm_min);
00318    /* the standard format of ast->callerid is:  "name" <number>, but not always complete */
00319    if (!ast_channel_connected(ast)->id.name.valid
00320       || ast_strlen_zero(ast_channel_connected(ast)->id.name.str)) {
00321       strcpy(cid.name, DEFAULT_CALLER_ID);
00322    } else {
00323       ast_copy_string(cid.name, ast_channel_connected(ast)->id.name.str, sizeof(cid.name));
00324    }
00325 
00326    if (ast_channel_connected(ast)->id.number.valid && ast_channel_connected(ast)->id.number.str) {
00327       ast_copy_string(cid.number, ast_channel_connected(ast)->id.number.str, sizeof(cid.number));
00328    }
00329 
00330    p = ast_channel_tech_pvt(ast);
00331 
00332    if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
00333       ast_log(LOG_WARNING, "phone_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
00334       return -1;
00335    }
00336    ast_debug(1, "Ringing %s on %s (%d)\n", dest, ast_channel_name(ast), ast_channel_fd(ast, 0));
00337 
00338    start = IXJ_PHONE_RING_START(cid);
00339    if (start == -1)
00340       return -1;
00341    
00342    if (p->mode == MODE_FXS) {
00343       const char *digit = strchr(dest, '/');
00344       if (digit)
00345       {
00346         digit++;
00347         while (*digit)
00348           phone_digit_end(ast, *digit++, 0);
00349       }
00350    }
00351  
00352    ast_setstate(ast, AST_STATE_RINGING);
00353    ast_queue_control(ast, AST_CONTROL_RINGING);
00354    return 0;
00355 }
00356 
00357 static int phone_hangup(struct ast_channel *ast)
00358 {
00359    struct phone_pvt *p;
00360    p = ast_channel_tech_pvt(ast);
00361    ast_debug(1, "phone_hangup(%s)\n", ast_channel_name(ast));
00362    if (!ast_channel_tech_pvt(ast)) {
00363       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
00364       return 0;
00365    }
00366    /* XXX Is there anything we can do to really hang up except stop recording? */
00367    ast_setstate(ast, AST_STATE_DOWN);
00368    if (ioctl(p->fd, PHONE_REC_STOP))
00369       ast_log(LOG_WARNING, "Failed to stop recording\n");
00370    if (ioctl(p->fd, PHONE_PLAY_STOP))
00371       ast_log(LOG_WARNING, "Failed to stop playing\n");
00372    if (ioctl(p->fd, PHONE_RING_STOP))
00373       ast_log(LOG_WARNING, "Failed to stop ringing\n");
00374    if (ioctl(p->fd, PHONE_CPT_STOP))
00375       ast_log(LOG_WARNING, "Failed to stop sounds\n");
00376 
00377    /* If it's an FXO, hang them up */
00378    if (p->mode == MODE_FXO) {
00379       if (ioctl(p->fd, PHONE_PSTN_SET_STATE, PSTN_ON_HOOK))
00380          ast_debug(1, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n",ast_channel_name(ast), strerror(errno));
00381    }
00382 
00383    /* If they're off hook, give a busy signal */
00384    if (ioctl(p->fd, PHONE_HOOKSTATE)) {
00385       ast_debug(1, "Got hunghup, giving busy signal\n");
00386       ioctl(p->fd, PHONE_BUSY);
00387       p->cpt = 1;
00388    }
00389    ao2_cleanup(p->lastformat);
00390    p->lastformat = NULL;
00391    ao2_cleanup(p->lastinput);
00392    p->lastinput = NULL;
00393    p->ministate = 0;
00394    p->obuflen = 0;
00395    p->dialtone = 0;
00396    memset(p->ext, 0, sizeof(p->ext));
00397    ((struct phone_pvt *)(ast_channel_tech_pvt(ast)))->owner = NULL;
00398    ast_module_unref(ast_module_info->self);
00399    ast_verb(3, "Hungup '%s'\n", ast_channel_name(ast));
00400    ast_channel_tech_pvt_set(ast, NULL);
00401    ast_setstate(ast, AST_STATE_DOWN);
00402    restart_monitor();
00403    return 0;
00404 }
00405 
00406 static int phone_setup(struct ast_channel *ast)
00407 {
00408    struct phone_pvt *p;
00409    p = ast_channel_tech_pvt(ast);
00410    ioctl(p->fd, PHONE_CPT_STOP);
00411    /* Nothing to answering really, just start recording */
00412    if (ast_format_cmp(ast_channel_rawreadformat(ast), ast_format_g729) == AST_FORMAT_CMP_EQUAL) {
00413       /* Prefer g729 */
00414       ioctl(p->fd, PHONE_REC_STOP);
00415       if (!p->lastinput || (ast_format_cmp(p->lastinput, ast_format_g729) != AST_FORMAT_CMP_EQUAL)) {
00416          ao2_replace(p->lastinput, ast_format_g729);
00417          if (ioctl(p->fd, PHONE_REC_CODEC, G729)) {
00418             ast_log(LOG_WARNING, "Failed to set codec to g729\n");
00419             return -1;
00420          }
00421       }
00422    } else if (ast_format_cmp(ast_channel_rawreadformat(ast), ast_format_g723) == AST_FORMAT_CMP_EQUAL) {
00423       ioctl(p->fd, PHONE_REC_STOP);
00424       if (!p->lastinput || (ast_format_cmp(p->lastinput, ast_format_g723) != AST_FORMAT_CMP_EQUAL)) {
00425          ao2_replace(p->lastinput, ast_format_g723);
00426          if (ioctl(p->fd, PHONE_REC_CODEC, G723_63)) {
00427             ast_log(LOG_WARNING, "Failed to set codec to g723.1\n");
00428             return -1;
00429          }
00430       }
00431    } else if (ast_format_cmp(ast_channel_rawreadformat(ast), ast_format_slin) == AST_FORMAT_CMP_EQUAL) {
00432       ioctl(p->fd, PHONE_REC_STOP);
00433       if (!p->lastinput || (ast_format_cmp(p->lastinput, ast_format_slin) != AST_FORMAT_CMP_EQUAL)) {
00434          ao2_replace(p->lastinput, ast_format_slin);
00435          if (ioctl(p->fd, PHONE_REC_CODEC, LINEAR16)) {
00436             ast_log(LOG_WARNING, "Failed to set codec to signed linear 16\n");
00437             return -1;
00438          }
00439       }
00440    } else if (ast_format_cmp(ast_channel_rawreadformat(ast), ast_format_ulaw) == AST_FORMAT_CMP_EQUAL) {
00441       ioctl(p->fd, PHONE_REC_STOP);
00442       if (!p->lastinput || (ast_format_cmp(p->lastinput, ast_format_ulaw) != AST_FORMAT_CMP_EQUAL)) {
00443          ao2_replace(p->lastinput, ast_format_ulaw);
00444          if (ioctl(p->fd, PHONE_REC_CODEC, ULAW)) {
00445             ast_log(LOG_WARNING, "Failed to set codec to uLaw\n");
00446             return -1;
00447          }
00448       }
00449    } else if (p->mode == MODE_FXS) {
00450       ioctl(p->fd, PHONE_REC_STOP);
00451       if (!p->lastinput || (ast_format_cmp(p->lastinput, ast_channel_rawreadformat(ast)) == AST_FORMAT_CMP_NOT_EQUAL)) {
00452          ao2_replace(p->lastinput, ast_channel_rawreadformat(ast));
00453          if (ioctl(p->fd, PHONE_REC_CODEC, ast_channel_rawreadformat(ast))) {
00454             ast_log(LOG_WARNING, "Failed to set codec to %s\n", 
00455                ast_format_get_name(ast_channel_rawreadformat(ast)));
00456             return -1;
00457          }
00458       }
00459    } else {
00460       ast_log(LOG_WARNING, "Can't do format %s\n", ast_format_get_name(ast_channel_rawreadformat(ast)));
00461       return -1;
00462    }
00463    if (ioctl(p->fd, PHONE_REC_START)) {
00464       ast_log(LOG_WARNING, "Failed to start recording\n");
00465       return -1;
00466    }
00467    /* set the DTMF times (the default is too short) */
00468    ioctl(p->fd, PHONE_SET_TONE_ON_TIME, 300);
00469    ioctl(p->fd, PHONE_SET_TONE_OFF_TIME, 200);
00470    return 0;
00471 }
00472 
00473 static int phone_answer(struct ast_channel *ast)
00474 {
00475    struct phone_pvt *p;
00476    p = ast_channel_tech_pvt(ast);
00477    /* In case it's a LineJack, take it off hook */
00478    if (p->mode == MODE_FXO) {
00479       if (ioctl(p->fd, PHONE_PSTN_SET_STATE, PSTN_OFF_HOOK))
00480          ast_debug(1, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n", ast_channel_name(ast), strerror(errno));
00481       else
00482          ast_debug(1, "Took linejack off hook\n");
00483    }
00484    phone_setup(ast);
00485    ast_debug(1, "phone_answer(%s)\n", ast_channel_name(ast));
00486    ast_channel_rings_set(ast, 0);
00487    ast_setstate(ast, AST_STATE_UP);
00488    return 0;
00489 }
00490 
00491 #if 0
00492 static char phone_2digit(char c)
00493 {
00494    if (c == 12)
00495       return '#';
00496    else if (c == 11)
00497       return '*';
00498    else if ((c < 10) && (c >= 0))
00499       return '0' + c - 1;
00500    else
00501       return '?';
00502 }
00503 #endif
00504 
00505 static struct ast_frame  *phone_exception(struct ast_channel *ast)
00506 {
00507    int res;
00508    union telephony_exception phonee;
00509    struct phone_pvt *p = ast_channel_tech_pvt(ast);
00510    char digit;
00511 
00512    /* Some nice norms */
00513    p->fr.datalen = 0;
00514    p->fr.samples = 0;
00515    p->fr.data.ptr =  NULL;
00516    p->fr.src = "Phone";
00517    p->fr.offset = 0;
00518    p->fr.mallocd=0;
00519    p->fr.delivery = ast_tv(0,0);
00520    
00521    phonee.bytes = ioctl(p->fd, PHONE_EXCEPTION);
00522    if (phonee.bits.dtmf_ready)  {
00523       ast_debug(1, "phone_exception(): DTMF\n");
00524    
00525       /* We've got a digit -- Just handle this nicely and easily */
00526       digit =  ioctl(p->fd, PHONE_GET_DTMF_ASCII);
00527       p->fr.subclass.integer = digit;
00528       p->fr.frametype = AST_FRAME_DTMF;
00529       return &p->fr;
00530    }
00531    if (phonee.bits.hookstate) {
00532       ast_debug(1, "Hookstate changed\n");
00533       res = ioctl(p->fd, PHONE_HOOKSTATE);
00534       /* See if we've gone on hook, if so, notify by returning NULL */
00535       ast_debug(1, "New hookstate: %d\n", res);
00536       if (!res && (p->mode != MODE_FXO))
00537          return NULL;
00538       else {
00539          if (ast_channel_state(ast) == AST_STATE_RINGING) {
00540             /* They've picked up the phone */
00541             p->fr.frametype = AST_FRAME_CONTROL;
00542             p->fr.subclass.integer = AST_CONTROL_ANSWER;
00543             phone_setup(ast);
00544             ast_setstate(ast, AST_STATE_UP);
00545             return &p->fr;
00546          }  else 
00547             ast_log(LOG_WARNING, "Got off hook in weird state %u\n", ast_channel_state(ast));
00548       }
00549    }
00550 #if 1
00551    if (phonee.bits.pstn_ring)
00552       ast_verbose("Unit is ringing\n");
00553    if (phonee.bits.caller_id) {
00554       ast_verbose("We have caller ID\n");
00555    }
00556    if (phonee.bits.pstn_wink)
00557       ast_verbose("Detected Wink\n");
00558 #endif
00559    /* Strange -- nothing there.. */
00560    p->fr.frametype = AST_FRAME_NULL;
00561    p->fr.subclass.integer = 0;
00562    return &p->fr;
00563 }
00564 
00565 static struct ast_frame  *phone_read(struct ast_channel *ast)
00566 {
00567    int res;
00568    struct phone_pvt *p = ast_channel_tech_pvt(ast);
00569    
00570 
00571    /* Some nice norms */
00572    p->fr.datalen = 0;
00573    p->fr.samples = 0;
00574    p->fr.data.ptr =  NULL;
00575    p->fr.src = "Phone";
00576    p->fr.offset = 0;
00577    p->fr.mallocd=0;
00578    p->fr.delivery = ast_tv(0,0);
00579 
00580    /* Try to read some data... */
00581    CHECK_BLOCKING(ast);
00582    res = read(p->fd, p->buf, PHONE_MAX_BUF);
00583    ast_clear_flag(ast_channel_flags(ast), AST_FLAG_BLOCKING);
00584    if (res < 0) {
00585 #if 0
00586       if (errno == EAGAIN) {
00587          ast_log(LOG_WARNING, "Null frame received\n");
00588          p->fr.frametype = AST_FRAME_NULL;
00589          p->fr.subclass = 0;
00590          return &p->fr;
00591       }
00592 #endif
00593       ast_log(LOG_WARNING, "Error reading: %s\n", strerror(errno));
00594       return NULL;
00595    }
00596    p->fr.data.ptr = p->buf;
00597    if (p->mode != MODE_FXS)
00598    switch(p->buf[0] & 0x3) {
00599    case '0':
00600    case '1':
00601       /* Normal */
00602       break;
00603    case '2':
00604    case '3':
00605       /* VAD/CNG, only send two words */
00606       res = 4;
00607       break;
00608    }
00609    p->fr.samples = 240;
00610    p->fr.datalen = res;
00611    p->fr.frametype = ast_format_get_type(p->lastinput) == AST_MEDIA_TYPE_AUDIO ?
00612       AST_FRAME_VOICE : ast_format_get_type(p->lastinput) == AST_MEDIA_TYPE_IMAGE ?
00613       AST_FRAME_IMAGE : AST_FRAME_VIDEO;
00614    p->fr.subclass.format = p->lastinput;
00615    p->fr.offset = AST_FRIENDLY_OFFSET;
00616    /* Byteswap from little-endian to native-endian */
00617    if (ast_format_cmp(p->fr.subclass.format, ast_format_slin) == AST_FORMAT_CMP_EQUAL)
00618       ast_frame_byteswap_le(&p->fr);
00619    return &p->fr;
00620 }
00621 
00622 static int phone_write_buf(struct phone_pvt *p, const char *buf, int len, int frlen, int swap)
00623 {
00624    int res;
00625    /* Store as much of the buffer as we can, then write fixed frames */
00626    int space = sizeof(p->obuf) - p->obuflen;
00627    /* Make sure we have enough buffer space to store the frame */
00628    if (space < len)
00629       len = space;
00630    if (swap)
00631       ast_swapcopy_samples(p->obuf+p->obuflen, buf, len/2);
00632    else
00633       memcpy(p->obuf + p->obuflen, buf, len);
00634    p->obuflen += len;
00635    while(p->obuflen > frlen) {
00636       res = write(p->fd, p->obuf, frlen);
00637       if (res != frlen) {
00638          if (res < 1) {
00639 /*
00640  * Card is in non-blocking mode now and it works well now, but there are
00641  * lot of messages like this. So, this message is temporarily disabled.
00642  */
00643             return 0;
00644          } else {
00645             ast_log(LOG_WARNING, "Only wrote %d of %d bytes\n", res, frlen);
00646          }
00647       }
00648       p->obuflen -= frlen;
00649       /* Move memory if necessary */
00650       if (p->obuflen) 
00651          memmove(p->obuf, p->obuf + frlen, p->obuflen);
00652    }
00653    return len;
00654 }
00655 
00656 static int phone_send_text(struct ast_channel *ast, const char *text)
00657 {
00658     int length = strlen(text);
00659     return phone_write_buf(ast_channel_tech_pvt(ast), text, length, length, 0) == 
00660            length ? 0 : -1;
00661 }
00662 
00663 static int phone_write(struct ast_channel *ast, struct ast_frame *frame)
00664 {
00665    struct phone_pvt *p = ast_channel_tech_pvt(ast);
00666    int res;
00667    int maxfr=0;
00668    char *pos;
00669    int sofar;
00670    int expected;
00671    int codecset = 0;
00672    char tmpbuf[4];
00673    /* Write a frame of (presumably voice) data */
00674    if (frame->frametype != AST_FRAME_VOICE && p->mode != MODE_FXS) {
00675       if (frame->frametype != AST_FRAME_IMAGE)
00676          ast_log(LOG_WARNING, "Don't know what to do with  frame type '%u'\n", frame->frametype);
00677       return 0;
00678    }
00679 #if 0
00680    /* If we're not in up mode, go into up mode now */
00681    if (ast->_state != AST_STATE_UP) {
00682       ast_setstate(ast, AST_STATE_UP);
00683       phone_setup(ast);
00684    }
00685 #else
00686    if (ast_channel_state(ast) != AST_STATE_UP) {
00687       /* Don't try tos end audio on-hook */
00688       return 0;
00689    }
00690 #endif   
00691    if (ast_format_cmp(frame->subclass.format, ast_format_g729) == AST_FORMAT_CMP_EQUAL) {
00692       if (!p->lastformat || (ast_format_cmp(p->lastformat, ast_format_g729) != AST_FORMAT_CMP_EQUAL)) {
00693          ioctl(p->fd, PHONE_PLAY_STOP);
00694          ioctl(p->fd, PHONE_REC_STOP);
00695          if (ioctl(p->fd, PHONE_PLAY_CODEC, G729)) {
00696             ast_log(LOG_WARNING, "Unable to set G729 mode\n");
00697             return -1;
00698          }
00699          if (ioctl(p->fd, PHONE_REC_CODEC, G729)) {
00700             ast_log(LOG_WARNING, "Unable to set G729 mode\n");
00701             return -1;
00702          }
00703          ao2_replace(p->lastformat, ast_format_g729);
00704          ao2_replace(p->lastinput, ast_format_g729);
00705          /* Reset output buffer */
00706          p->obuflen = 0;
00707          codecset = 1;
00708       }
00709       if (frame->datalen > 80) {
00710          ast_log(LOG_WARNING, "Frame size too large for G.729 (%d bytes)\n", frame->datalen);
00711          return -1;
00712       }
00713       maxfr = 80;
00714     } else if (ast_format_cmp(frame->subclass.format, ast_format_g723) == AST_FORMAT_CMP_EQUAL) {
00715       if (!p->lastformat || (ast_format_cmp(p->lastformat, ast_format_g723) != AST_FORMAT_CMP_EQUAL)) {
00716          ioctl(p->fd, PHONE_PLAY_STOP);
00717          ioctl(p->fd, PHONE_REC_STOP);
00718          if (ioctl(p->fd, PHONE_PLAY_CODEC, G723_63)) {
00719             ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
00720             return -1;
00721          }
00722          if (ioctl(p->fd, PHONE_REC_CODEC, G723_63)) {
00723             ast_log(LOG_WARNING, "Unable to set G723.1 mode\n");
00724             return -1;
00725          }
00726          ao2_replace(p->lastformat, ast_format_g723);
00727          ao2_replace(p->lastinput, ast_format_g723);
00728          /* Reset output buffer */
00729          p->obuflen = 0;
00730          codecset = 1;
00731       }
00732       if (frame->datalen > 24) {
00733          ast_log(LOG_WARNING, "Frame size too large for G.723.1 (%d bytes)\n", frame->datalen);
00734          return -1;
00735       }
00736       maxfr = 24;
00737    } else if (ast_format_cmp(frame->subclass.format, ast_format_slin) == AST_FORMAT_CMP_EQUAL) {
00738       if (!p->lastformat || (ast_format_cmp(p->lastformat, ast_format_slin) != AST_FORMAT_CMP_EQUAL)) {
00739          ioctl(p->fd, PHONE_PLAY_STOP);
00740          ioctl(p->fd, PHONE_REC_STOP);
00741          if (ioctl(p->fd, PHONE_PLAY_CODEC, LINEAR16)) {
00742             ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
00743             return -1;
00744          }
00745          if (ioctl(p->fd, PHONE_REC_CODEC, LINEAR16)) {
00746             ast_log(LOG_WARNING, "Unable to set 16-bit linear mode\n");
00747             return -1;
00748          }
00749          ao2_replace(p->lastformat, ast_format_slin);
00750          ao2_replace(p->lastinput, ast_format_slin);
00751          codecset = 1;
00752          /* Reset output buffer */
00753          p->obuflen = 0;
00754       }
00755       maxfr = 480;
00756    } else if (ast_format_cmp(frame->subclass.format, ast_format_ulaw) == AST_FORMAT_CMP_EQUAL) {
00757       if (!p->lastformat || (ast_format_cmp(p->lastformat, ast_format_ulaw) != AST_FORMAT_CMP_EQUAL)) {
00758          ioctl(p->fd, PHONE_PLAY_STOP);
00759          ioctl(p->fd, PHONE_REC_STOP);
00760          if (ioctl(p->fd, PHONE_PLAY_CODEC, ULAW)) {
00761             ast_log(LOG_WARNING, "Unable to set uLaw mode\n");
00762             return -1;
00763          }
00764          if (ioctl(p->fd, PHONE_REC_CODEC, ULAW)) {
00765             ast_log(LOG_WARNING, "Unable to set uLaw mode\n");
00766             return -1;
00767          }
00768          ao2_replace(p->lastformat, ast_format_ulaw);
00769          ao2_replace(p->lastinput, ast_format_ulaw);
00770          codecset = 1;
00771          /* Reset output buffer */
00772          p->obuflen = 0;
00773       }
00774       maxfr = 240;
00775    } else {
00776       if (!p->lastformat || (ast_format_cmp(p->lastformat, frame->subclass.format) != AST_FORMAT_CMP_EQUAL)) {
00777          ioctl(p->fd, PHONE_PLAY_STOP);
00778          ioctl(p->fd, PHONE_REC_STOP);
00779          if (ioctl(p->fd, PHONE_PLAY_CODEC, ast_format_compatibility_format2bitfield(frame->subclass.format))) {
00780             ast_log(LOG_WARNING, "Unable to set %s mode\n",
00781                ast_format_get_name(frame->subclass.format));
00782             return -1;
00783          }
00784          if (ioctl(p->fd, PHONE_REC_CODEC, ast_format_compatibility_format2bitfield(frame->subclass.format))) {
00785             ast_log(LOG_WARNING, "Unable to set %s mode\n",
00786                ast_format_get_name(frame->subclass.format));
00787             return -1;
00788          }
00789          ao2_replace(p->lastformat, frame->subclass.format);
00790          ao2_replace(p->lastinput, frame->subclass.format);
00791          codecset = 1;
00792          /* Reset output buffer */
00793          p->obuflen = 0;
00794       }
00795       maxfr = 480;
00796    }
00797    if (codecset) {
00798       ioctl(p->fd, PHONE_REC_DEPTH, 3);
00799       ioctl(p->fd, PHONE_PLAY_DEPTH, 3);
00800       if (ioctl(p->fd, PHONE_PLAY_START)) {
00801          ast_log(LOG_WARNING, "Failed to start playback\n");
00802          return -1;
00803       }
00804       if (ioctl(p->fd, PHONE_REC_START)) {
00805          ast_log(LOG_WARNING, "Failed to start recording\n");
00806          return -1;
00807       }
00808    }
00809    /* If we get here, we have a frame of Appropriate data */
00810    sofar = 0;
00811    pos = frame->data.ptr;
00812    while(sofar < frame->datalen) {
00813       /* Write in no more than maxfr sized frames */
00814       expected = frame->datalen - sofar;
00815       if (maxfr < expected)
00816          expected = maxfr;
00817       /* XXX Internet Phone Jack does not handle the 4-byte VAD frame properly! XXX 
00818          we have to pad it to 24 bytes still.  */
00819       if (frame->datalen == 4) {
00820          if (p->silencesupression) {
00821             memcpy(tmpbuf, frame->data.ptr, 4);
00822             expected = 24;
00823             res = phone_write_buf(p, tmpbuf, expected, maxfr, 0);
00824          }
00825          res = 4;
00826          expected=4;
00827       } else {
00828          int swap = 0;
00829 #if __BYTE_ORDER == __BIG_ENDIAN
00830          if (ast_format_cmp(frame->subclass.format, ast_format_slin) == AST_FORMAT_CMP_EQUAL)
00831             swap = 1; /* Swap big-endian samples to little-endian as we copy */
00832 #endif
00833          res = phone_write_buf(p, pos, expected, maxfr, swap);
00834       }
00835       if (res != expected) {
00836          if ((errno != EAGAIN) && (errno != EINTR)) {
00837             if (res < 0) 
00838                ast_log(LOG_WARNING, "Write returned error (%s)\n", strerror(errno));
00839    /*
00840     * Card is in non-blocking mode now and it works well now, but there are
00841     * lot of messages like this. So, this message is temporarily disabled.
00842     */
00843 #if 0
00844             else
00845                ast_log(LOG_WARNING, "Only wrote %d of %d bytes\n", res, frame->datalen);
00846 #endif
00847             return -1;
00848          } else /* Pretend it worked */
00849             res = expected;
00850       }
00851       sofar += res;
00852       pos += res;
00853    }
00854    return 0;
00855 }
00856 
00857 static struct ast_channel *phone_new(struct phone_pvt *i, int state, char *cntx, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor)
00858 {
00859    struct ast_format_cap *caps = NULL;
00860    struct ast_channel *tmp;
00861    struct phone_codec_data queried_codec;
00862    struct ast_format *tmpfmt;
00863    caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
00864    tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "", i->ext, i->context, assignedids, requestor, 0, "Phone/%s", i->dev + 5);
00865    if (tmp && caps) {
00866       ast_channel_lock(tmp);
00867       ast_channel_tech_set(tmp, cur_tech);
00868       ast_channel_set_fd(tmp, 0, i->fd);
00869       /* XXX Switching formats silently causes kernel panics XXX */
00870       if (i->mode == MODE_FXS &&
00871           ioctl(i->fd, PHONE_QUERY_CODEC, &queried_codec) == 0) {
00872          if (queried_codec.type == LINEAR16) {
00873             ast_format_cap_append(caps, ast_format_slin, 0);
00874          } else {
00875             ast_format_cap_remove(prefcap, ast_format_slin);
00876             ast_format_cap_append_from_cap(caps, prefcap, AST_MEDIA_TYPE_UNKNOWN);
00877          }
00878       } else {
00879          ast_format_cap_append_from_cap(caps, prefcap, AST_MEDIA_TYPE_UNKNOWN);
00880       }
00881       tmpfmt = ast_format_cap_get_format(caps, 0);
00882       ast_channel_nativeformats_set(tmp, caps);
00883       ao2_ref(caps, -1);
00884       ast_channel_set_rawreadformat(tmp, tmpfmt);
00885       ast_channel_set_rawwriteformat(tmp, tmpfmt);
00886       ao2_ref(tmpfmt, -1);
00887       /* no need to call ast_setstate: the channel_alloc already did its job */
00888       if (state == AST_STATE_RING)
00889          ast_channel_rings_set(tmp, 1);
00890       ast_channel_tech_pvt_set(tmp, i);
00891       ast_channel_context_set(tmp, cntx);
00892       if (!ast_strlen_zero(i->ext))
00893          ast_channel_exten_set(tmp, i->ext);
00894       else
00895          ast_channel_exten_set(tmp, "s");
00896       if (!ast_strlen_zero(i->language))
00897          ast_channel_language_set(tmp, i->language);
00898 
00899       /* Don't use ast_set_callerid() here because it will
00900        * generate a NewCallerID event before the NewChannel event */
00901       if (!ast_strlen_zero(i->cid_num)) {
00902          ast_channel_caller(tmp)->ani.number.valid = 1;
00903          ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
00904       }
00905 
00906       i->owner = tmp;
00907       ast_module_ref(ast_module_info->self);
00908       ast_channel_unlock(tmp);
00909       if (state != AST_STATE_DOWN) {
00910          if (state == AST_STATE_RING) {
00911             ioctl(ast_channel_fd(tmp, 0), PHONE_RINGBACK);
00912             i->cpt = 1;
00913          }
00914          if (ast_pbx_start(tmp)) {
00915             ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
00916             ast_hangup(tmp);
00917          }
00918       }
00919    } else {
00920       ao2_cleanup(caps);
00921       ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
00922    }
00923    return tmp;
00924 }
00925 
00926 static void phone_mini_packet(struct phone_pvt *i)
00927 {
00928    int res;
00929    char buf[1024];
00930    /* Ignore stuff we read... */
00931    res = read(i->fd, buf, sizeof(buf));
00932    if (res < 1) {
00933       ast_log(LOG_WARNING, "Read returned %d: %s\n", res, strerror(errno));
00934       return;
00935    }
00936 }
00937 
00938 static void phone_check_exception(struct phone_pvt *i)
00939 {
00940    int offhook=0;
00941    char digit[2] = {0 , 0};
00942    union telephony_exception phonee;
00943    /* XXX Do something XXX */
00944 #if 0
00945    ast_debug(1, "Exception!\n");
00946 #endif
00947    phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION);
00948    if (phonee.bits.dtmf_ready)  {
00949       digit[0] = ioctl(i->fd, PHONE_GET_DTMF_ASCII);
00950       if (i->mode == MODE_DIALTONE || i->mode == MODE_FXS || i->mode == MODE_SIGMA) {
00951          ioctl(i->fd, PHONE_PLAY_STOP);
00952          ioctl(i->fd, PHONE_REC_STOP);
00953          ioctl(i->fd, PHONE_CPT_STOP);
00954          i->dialtone = 0;
00955          if (strlen(i->ext) < AST_MAX_EXTENSION - 1)
00956             strncat(i->ext, digit, sizeof(i->ext) - strlen(i->ext) - 1);
00957          if ((i->mode != MODE_FXS ||
00958               !(phonee.bytes = ioctl(i->fd, PHONE_EXCEPTION)) ||
00959               !phonee.bits.dtmf_ready) &&
00960              ast_exists_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
00961             /* It's a valid extension in its context, get moving! */
00962             phone_new(i, AST_STATE_RING, i->context, NULL, NULL);
00963             /* No need to restart monitor, we are the monitor */
00964          } else if (!ast_canmatch_extension(NULL, i->context, i->ext, 1, i->cid_num)) {
00965             /* There is nothing in the specified extension that can match anymore.
00966                Try the default */
00967             if (ast_exists_extension(NULL, "default", i->ext, 1, i->cid_num)) {
00968                /* Check the default, too... */
00969                phone_new(i, AST_STATE_RING, "default", NULL, NULL);
00970                /* XXX This should probably be justified better XXX */
00971             }  else if (!ast_canmatch_extension(NULL, "default", i->ext, 1, i->cid_num)) {
00972                /* It's not a valid extension, give a busy signal */
00973                ast_debug(1, "%s can't match anything in %s or default\n", i->ext, i->context);
00974                ioctl(i->fd, PHONE_BUSY);
00975                i->cpt = 1;
00976             }
00977          }
00978 #if 0
00979          ast_verbose("Extension is %s\n", i->ext);
00980 #endif
00981       }
00982    }
00983    if (phonee.bits.hookstate) {
00984       offhook = ioctl(i->fd, PHONE_HOOKSTATE);
00985       if (offhook) {
00986          if (i->mode == MODE_IMMEDIATE) {
00987             phone_new(i, AST_STATE_RING, i->context, NULL, NULL);
00988          } else if (i->mode == MODE_DIALTONE) {
00989             ast_module_ref(ast_module_info->self);
00990             /* Reset the extension */
00991             i->ext[0] = '\0';
00992             /* Play the dialtone */
00993             i->dialtone++;
00994             ioctl(i->fd, PHONE_PLAY_STOP);
00995             ioctl(i->fd, PHONE_PLAY_CODEC, ULAW);
00996             ioctl(i->fd, PHONE_PLAY_START);
00997             ao2_cleanup(i->lastformat);
00998             i->lastformat = NULL;
00999          } else if (i->mode == MODE_SIGMA) {
01000             ast_module_ref(ast_module_info->self);
01001             /* Reset the extension */
01002             i->ext[0] = '\0';
01003             /* Play the dialtone */
01004             i->dialtone++;
01005             ioctl(i->fd, PHONE_DIALTONE);
01006          }
01007       } else {
01008          if (i->dialtone)
01009             ast_module_unref(ast_module_info->self);
01010          memset(i->ext, 0, sizeof(i->ext));
01011          if (i->cpt)
01012          {
01013             ioctl(i->fd, PHONE_CPT_STOP);
01014             i->cpt = 0;
01015          }
01016          ioctl(i->fd, PHONE_PLAY_STOP);
01017          ioctl(i->fd, PHONE_REC_STOP);
01018          i->dialtone = 0;
01019          ao2_cleanup(i->lastformat);
01020          i->lastformat = NULL;
01021       }
01022    }
01023    if (phonee.bits.pstn_ring) {
01024       ast_verbose("Unit is ringing\n");
01025       phone_new(i, AST_STATE_RING, i->context, NULL, NULL);
01026    }
01027    if (phonee.bits.caller_id)
01028       ast_verbose("We have caller ID\n");
01029    
01030    
01031 }
01032 
01033 static void *do_monitor(void *data)
01034 {
01035    struct pollfd *fds = NULL;
01036    int nfds = 0, inuse_fds = 0, res;
01037    struct phone_pvt *i;
01038    int tonepos = 0;
01039    /* The tone we're playing this round */
01040    struct timeval to = { 0, 0 };
01041    int dotone;
01042    /* This thread monitors all the frame relay interfaces which are not yet in use
01043       (and thus do not have a separate thread) indefinitely */
01044    while (monitor) {
01045       /* Don't let anybody kill us right away.  Nobody should lock the interface list
01046          and wait for the monitor list, but the other way around is okay. */
01047       /* Lock the interface list */
01048       if (ast_mutex_lock(&iflock)) {
01049          ast_log(LOG_ERROR, "Unable to grab interface lock\n");
01050          return NULL;
01051       }
01052       /* Build the stuff we're going to select on, that is the socket of every
01053          phone_pvt that does not have an associated owner channel */
01054       i = iflist;
01055       dotone = 0;
01056       inuse_fds = 0;
01057       for (i = iflist; i; i = i->next) {
01058          if (!i->owner) {
01059             /* This needs to be watched, as it lacks an owner */
01060             if (inuse_fds == nfds) {
01061                void *tmp = ast_realloc(fds, (nfds + 1) * sizeof(*fds));
01062                if (!tmp) {
01063                   /* Avoid leaking */
01064                   continue;
01065                }
01066                fds = tmp;
01067                nfds++;
01068             }
01069             fds[inuse_fds].fd = i->fd;
01070             fds[inuse_fds].events = POLLIN | POLLERR;
01071             fds[inuse_fds].revents = 0;
01072             inuse_fds++;
01073 
01074             if (i->dialtone && i->mode != MODE_SIGMA) {
01075                /* Remember we're going to have to come back and play
01076                   more dialtones */
01077                if (ast_tvzero(to)) {
01078                   /* If we're due for a dialtone, play one */
01079                   if (write(i->fd, DialTone + tonepos, 240) != 240) {
01080                      ast_log(LOG_WARNING, "Dial tone write error\n");
01081                   }
01082                }
01083                dotone++;
01084             }
01085          }
01086       }
01087       /* Okay, now that we know what to do, release the interface lock */
01088       ast_mutex_unlock(&iflock);
01089 
01090       /* Wait indefinitely for something to happen */
01091       if (dotone && i && i->mode != MODE_SIGMA) {
01092          /* If we're ready to recycle the time, set it to 30 ms */
01093          tonepos += 240;
01094          if (tonepos >= sizeof(DialTone)) {
01095             tonepos = 0;
01096          }
01097          if (ast_tvzero(to)) {
01098             to = ast_tv(0, 30000);
01099          }
01100          res = ast_poll2(fds, inuse_fds, &to);
01101       } else {
01102          res = ast_poll(fds, inuse_fds, -1);
01103          to = ast_tv(0, 0);
01104          tonepos = 0;
01105       }
01106       /* Okay, select has finished.  Let's see what happened.  */
01107       if (res < 0) {
01108          ast_debug(1, "poll returned %d: %s\n", res, strerror(errno));
01109          continue;
01110       }
01111       /* If there are no fd's changed, just continue, it's probably time
01112          to play some more dialtones */
01113       if (!res) {
01114          continue;
01115       }
01116       /* Alright, lock the interface list again, and let's look and see what has
01117          happened */
01118       if (ast_mutex_lock(&iflock)) {
01119          ast_log(LOG_WARNING, "Unable to lock the interface list\n");
01120          continue;
01121       }
01122 
01123       for (i = iflist; i; i = i->next) {
01124          int j;
01125          /* Find the record */
01126          for (j = 0; j < inuse_fds; j++) {
01127             if (fds[j].fd == i->fd) {
01128                break;
01129             }
01130          }
01131 
01132          /* Not found? */
01133          if (j == inuse_fds) {
01134             continue;
01135          }
01136 
01137          if (fds[j].revents & POLLIN) {
01138             if (i->owner) {
01139                continue;
01140             }
01141             phone_mini_packet(i);
01142          }
01143          if (fds[j].revents & POLLERR) {
01144             if (i->owner) {
01145                continue;
01146             }
01147             phone_check_exception(i);
01148          }
01149       }
01150       ast_mutex_unlock(&iflock);
01151    }
01152    return NULL;
01153 }
01154 
01155 static int restart_monitor()
01156 {
01157    /* If we're supposed to be stopped -- stay stopped */
01158    if (monitor_thread == AST_PTHREADT_STOP)
01159       return 0;
01160    if (ast_mutex_lock(&monlock)) {
01161       ast_log(LOG_WARNING, "Unable to lock monitor\n");
01162       return -1;
01163    }
01164    if (monitor_thread == pthread_self()) {
01165       ast_mutex_unlock(&monlock);
01166       ast_log(LOG_WARNING, "Cannot kill myself\n");
01167       return -1;
01168    }
01169    if (monitor_thread != AST_PTHREADT_NULL) {
01170       if (ast_mutex_lock(&iflock)) {
01171          ast_mutex_unlock(&monlock);
01172          ast_log(LOG_WARNING, "Unable to lock the interface list\n");
01173          return -1;
01174       }
01175       monitor = 0;
01176       while (pthread_kill(monitor_thread, SIGURG) == 0)
01177          sched_yield();
01178       pthread_join(monitor_thread, NULL);
01179       ast_mutex_unlock(&iflock);
01180    }
01181    monitor = 1;
01182    /* Start a new monitor */
01183    if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
01184       ast_mutex_unlock(&monlock);
01185       ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
01186       return -1;
01187    }
01188    ast_mutex_unlock(&monlock);
01189    return 0;
01190 }
01191 
01192 static struct phone_pvt *mkif(const char *iface, int mode, int txgain, int rxgain)
01193 {
01194    /* Make a phone_pvt structure for this interface */
01195    struct phone_pvt *tmp;
01196    int flags;  
01197    
01198    tmp = ast_calloc(1, sizeof(*tmp));
01199    if (tmp) {
01200       tmp->fd = open(iface, O_RDWR);
01201       if (tmp->fd < 0) {
01202          ast_log(LOG_WARNING, "Unable to open '%s'\n", iface);
01203          ast_free(tmp);
01204          return NULL;
01205       }
01206       if (mode == MODE_FXO) {
01207          if (ioctl(tmp->fd, IXJCTL_PORT, PORT_PSTN)) {
01208             ast_debug(1, "Unable to set port to PSTN\n");
01209          }
01210       } else {
01211          if (ioctl(tmp->fd, IXJCTL_PORT, PORT_POTS)) 
01212              if (mode != MODE_FXS)
01213                   ast_debug(1, "Unable to set port to POTS\n");
01214       }
01215       ioctl(tmp->fd, PHONE_PLAY_STOP);
01216       ioctl(tmp->fd, PHONE_REC_STOP);
01217       ioctl(tmp->fd, PHONE_RING_STOP);
01218       ioctl(tmp->fd, PHONE_CPT_STOP);
01219       if (ioctl(tmp->fd, PHONE_PSTN_SET_STATE, PSTN_ON_HOOK))
01220          ast_debug(1, "ioctl(PHONE_PSTN_SET_STATE) failed on %s (%s)\n",iface, strerror(errno));
01221       if (echocancel != AEC_OFF)
01222          ioctl(tmp->fd, IXJCTL_AEC_START, echocancel);
01223       if (silencesupression) 
01224          tmp->silencesupression = 1;
01225 #ifdef PHONE_VAD
01226       ioctl(tmp->fd, PHONE_VAD, tmp->silencesupression);
01227 #endif
01228       tmp->mode = mode;
01229       flags = fcntl(tmp->fd, F_GETFL);
01230       fcntl(tmp->fd, F_SETFL, flags | O_NONBLOCK);
01231       tmp->owner = NULL;
01232       ao2_cleanup(tmp->lastformat);
01233       tmp->lastformat = NULL;
01234       ao2_cleanup(tmp->lastinput);
01235       tmp->lastinput = NULL;
01236       tmp->ministate = 0;
01237       memset(tmp->ext, 0, sizeof(tmp->ext));
01238       ast_copy_string(tmp->language, language, sizeof(tmp->language));
01239       ast_copy_string(tmp->dev, iface, sizeof(tmp->dev));
01240       ast_copy_string(tmp->context, context, sizeof(tmp->context));
01241       tmp->next = NULL;
01242       tmp->obuflen = 0;
01243       tmp->dialtone = 0;
01244       tmp->cpt = 0;
01245       ast_copy_string(tmp->cid_num, cid_num, sizeof(tmp->cid_num));
01246       ast_copy_string(tmp->cid_name, cid_name, sizeof(tmp->cid_name));
01247       tmp->txgain = txgain;
01248       ioctl(tmp->fd, PHONE_PLAY_VOLUME, tmp->txgain);
01249       tmp->rxgain = rxgain;
01250       ioctl(tmp->fd, PHONE_REC_VOLUME, tmp->rxgain);
01251    }
01252    return tmp;
01253 }
01254 
01255 static struct ast_channel *phone_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
01256 {
01257    struct phone_pvt *p;
01258    struct ast_channel *tmp = NULL;
01259    const char *name = data;
01260 
01261    /* Search for an unowned channel */
01262    if (ast_mutex_lock(&iflock)) {
01263       ast_log(LOG_ERROR, "Unable to lock interface list???\n");
01264       return NULL;
01265    }
01266    p = iflist;
01267    while(p) {
01268       if (p->mode == MODE_FXS || (ast_format_cap_iscompatible(cap, phone_tech.capabilities))) {
01269          size_t length = strlen(p->dev + 5);
01270          if (strncmp(name, p->dev + 5, length) == 0 &&
01271              !isalnum(name[length])) {
01272              if (!p->owner) {
01273                      tmp = phone_new(p, AST_STATE_DOWN, p->context, assignedids, requestor);
01274                      break;
01275                 } else
01276                      *cause = AST_CAUSE_BUSY;
01277             }
01278       }
01279       p = p->next;
01280    }
01281    ast_mutex_unlock(&iflock);
01282    restart_monitor();
01283    if (tmp == NULL) {
01284       if (!(ast_format_cap_iscompatible(cap, phone_tech.capabilities))) {
01285          struct ast_str *codec_buf = ast_str_alloca(64);
01286          ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%s'\n",
01287             ast_format_cap_get_names(cap, &codec_buf));
01288          return NULL;
01289       }
01290    }
01291    return tmp;
01292 }
01293 
01294 /* parse gain value from config file */
01295 static int parse_gain_value(const char *gain_type, const char *value)
01296 {
01297    float gain;
01298 
01299    /* try to scan number */
01300    if (sscanf(value, "%30f", &gain) != 1)
01301    {
01302       ast_log(LOG_ERROR, "Invalid %s value '%s' in '%s' config\n",
01303          value, gain_type, config);
01304       return DEFAULT_GAIN;
01305    }
01306 
01307    /* multiplicate gain by 1.0 gain value */ 
01308    gain = gain * (float)DEFAULT_GAIN;
01309 
01310    /* percentage? */
01311    if (value[strlen(value) - 1] == '%')
01312       return (int)(gain / (float)100);
01313 
01314    return (int)gain;
01315 }
01316 
01317 static int __unload_module(void)
01318 {
01319    struct phone_pvt *p, *pl;
01320    /* First, take us out of the channel loop */
01321    if (cur_tech)
01322       ast_channel_unregister(cur_tech);
01323    if (!ast_mutex_lock(&iflock)) {
01324       /* Hangup all interfaces if they have an owner */
01325       p = iflist;
01326       while(p) {
01327          if (p->owner)
01328             ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
01329          p = p->next;
01330       }
01331       iflist = NULL;
01332       ast_mutex_unlock(&iflock);
01333    } else {
01334       ast_log(LOG_WARNING, "Unable to lock the monitor\n");
01335       return -1;
01336    }
01337    if (!ast_mutex_lock(&monlock)) {
01338       if (monitor_thread > AST_PTHREADT_NULL) {
01339          monitor = 0;
01340          while (pthread_kill(monitor_thread, SIGURG) == 0)
01341             sched_yield();
01342          pthread_join(monitor_thread, NULL);
01343       }
01344       monitor_thread = AST_PTHREADT_STOP;
01345       ast_mutex_unlock(&monlock);
01346    } else {
01347       ast_log(LOG_WARNING, "Unable to lock the monitor\n");
01348       return -1;
01349    }
01350 
01351    if (!ast_mutex_lock(&iflock)) {
01352       /* Destroy all the interfaces and free their memory */
01353       p = iflist;
01354       while(p) {
01355          /* Close the socket, assuming it's real */
01356          if (p->fd > -1)
01357             close(p->fd);
01358          pl = p;
01359          p = p->next;
01360          /* Free associated memory */
01361          ast_free(pl);
01362       }
01363       iflist = NULL;
01364       ast_mutex_unlock(&iflock);
01365    } else {
01366       ast_log(LOG_WARNING, "Unable to lock the monitor\n");
01367       return -1;
01368    }
01369 
01370    ao2_ref(phone_tech.capabilities, -1);
01371    ao2_ref(phone_tech_fxs.capabilities, -1);
01372    ao2_ref(prefcap, -1);
01373 
01374    return 0;
01375 }
01376 
01377 static int unload_module(void)
01378 {
01379    return __unload_module();
01380 }
01381 
01382 static int load_module(void)
01383 {
01384    struct ast_config *cfg;
01385    struct ast_variable *v;
01386    struct phone_pvt *tmp;
01387    int mode = MODE_IMMEDIATE;
01388    int txgain = DEFAULT_GAIN, rxgain = DEFAULT_GAIN; /* default gain 1.0 */
01389    struct ast_flags config_flags = { 0 };
01390 
01391    if (!(phone_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
01392       return AST_MODULE_LOAD_DECLINE;
01393    }
01394 
01395    ast_format_cap_append(phone_tech.capabilities, ast_format_g723, 0);
01396    ast_format_cap_append(phone_tech.capabilities, ast_format_slin, 0);
01397    ast_format_cap_append(phone_tech.capabilities, ast_format_ulaw, 0);
01398    ast_format_cap_append(phone_tech.capabilities, ast_format_g729, 0);
01399 
01400    if (!(prefcap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
01401       return AST_MODULE_LOAD_DECLINE;
01402    }
01403    ast_format_cap_append_from_cap(prefcap, phone_tech.capabilities, AST_MEDIA_TYPE_UNKNOWN);
01404    if (!(phone_tech_fxs.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
01405       return AST_MODULE_LOAD_DECLINE;
01406    }
01407 
01408    if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
01409       ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config);
01410       return AST_MODULE_LOAD_DECLINE;
01411    }
01412 
01413    /* We *must* have a config file otherwise stop immediately */
01414    if (!cfg) {
01415       ast_log(LOG_ERROR, "Unable to load config %s\n", config);
01416       return AST_MODULE_LOAD_DECLINE;
01417    }
01418    if (ast_mutex_lock(&iflock)) {
01419       /* It's a little silly to lock it, but we mind as well just to be sure */
01420       ast_log(LOG_ERROR, "Unable to lock interface list???\n");
01421       return AST_MODULE_LOAD_FAILURE;
01422    }
01423    v = ast_variable_browse(cfg, "interfaces");
01424    while(v) {
01425       /* Create the interface list */
01426       if (!strcasecmp(v->name, "device")) {
01427             tmp = mkif(v->value, mode, txgain, rxgain);
01428             if (tmp) {
01429                tmp->next = iflist;
01430                iflist = tmp;
01431                
01432             } else {
01433                ast_log(LOG_ERROR, "Unable to register channel '%s'\n", v->value);
01434                ast_config_destroy(cfg);
01435                ast_mutex_unlock(&iflock);
01436                __unload_module();
01437                return AST_MODULE_LOAD_FAILURE;
01438             }
01439       } else if (!strcasecmp(v->name, "silencesupression")) {
01440          silencesupression = ast_true(v->value);
01441       } else if (!strcasecmp(v->name, "language")) {
01442          ast_copy_string(language, v->value, sizeof(language));
01443       } else if (!strcasecmp(v->name, "callerid")) {
01444          ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
01445       } else if (!strcasecmp(v->name, "mode")) {
01446          if (!strncasecmp(v->value, "di", 2)) 
01447             mode = MODE_DIALTONE;
01448          else if (!strncasecmp(v->value, "sig", 3))
01449             mode = MODE_SIGMA;
01450          else if (!strncasecmp(v->value, "im", 2))
01451             mode = MODE_IMMEDIATE;
01452          else if (!strncasecmp(v->value, "fxs", 3)) {
01453             mode = MODE_FXS;
01454             ast_format_cap_remove_by_type(prefcap, AST_MEDIA_TYPE_AUDIO); /* All non-voice */
01455          }
01456          else if (!strncasecmp(v->value, "fx", 2))
01457             mode = MODE_FXO;
01458          else
01459             ast_log(LOG_WARNING, "Unknown mode: %s\n", v->value);
01460       } else if (!strcasecmp(v->name, "context")) {
01461          ast_copy_string(context, v->value, sizeof(context));
01462       } else if (!strcasecmp(v->name, "format")) {
01463          if (!strcasecmp(v->value, "g729")) {
01464             ast_format_cap_remove_by_type(prefcap, AST_MEDIA_TYPE_UNKNOWN);
01465             ast_format_cap_append(prefcap, ast_format_g729, 0);
01466          } else if (!strcasecmp(v->value, "g723.1")) {
01467             ast_format_cap_remove_by_type(prefcap, AST_MEDIA_TYPE_UNKNOWN);
01468             ast_format_cap_append(prefcap, ast_format_g723, 0);
01469          } else if (!strcasecmp(v->value, "slinear")) {
01470             if (mode == MODE_FXS) {
01471                ast_format_cap_append(prefcap, ast_format_slin, 0);
01472             } else {
01473                ast_format_cap_remove_by_type(prefcap, AST_MEDIA_TYPE_UNKNOWN);
01474                ast_format_cap_append(prefcap, ast_format_slin, 0);
01475             }
01476          } else if (!strcasecmp(v->value, "ulaw")) {
01477             ast_format_cap_remove_by_type(prefcap, AST_MEDIA_TYPE_UNKNOWN);
01478             ast_format_cap_append(prefcap, ast_format_ulaw, 0);
01479          } else
01480             ast_log(LOG_WARNING, "Unknown format '%s'\n", v->value);
01481       } else if (!strcasecmp(v->name, "echocancel")) {
01482          if (!strcasecmp(v->value, "off")) {
01483             echocancel = AEC_OFF;
01484          } else if (!strcasecmp(v->value, "low")) {
01485             echocancel = AEC_LOW;
01486          } else if (!strcasecmp(v->value, "medium")) {
01487             echocancel = AEC_MED;
01488          } else if (!strcasecmp(v->value, "high")) {
01489             echocancel = AEC_HIGH;
01490          } else 
01491             ast_log(LOG_WARNING, "Unknown echo cancellation '%s'\n", v->value);
01492       } else if (!strcasecmp(v->name, "txgain")) {
01493          txgain = parse_gain_value(v->name, v->value);
01494       } else if (!strcasecmp(v->name, "rxgain")) {
01495          rxgain = parse_gain_value(v->name, v->value);
01496       }  
01497       v = v->next;
01498    }
01499    ast_mutex_unlock(&iflock);
01500 
01501    if (mode == MODE_FXS) {
01502       ast_format_cap_append_from_cap(phone_tech_fxs.capabilities, prefcap, AST_MEDIA_TYPE_UNKNOWN);
01503       cur_tech = &phone_tech_fxs;
01504    } else
01505       cur_tech = (struct ast_channel_tech *) &phone_tech;
01506 
01507    /* Make sure we can register our Adtranphone channel type */
01508 
01509    if (ast_channel_register(cur_tech)) {
01510       ast_log(LOG_ERROR, "Unable to register channel class 'Phone'\n");
01511       ast_config_destroy(cfg);
01512       __unload_module();
01513       return AST_MODULE_LOAD_FAILURE;
01514    }
01515    ast_config_destroy(cfg);
01516    /* And start the monitor for the first time */
01517    restart_monitor();
01518    return AST_MODULE_LOAD_SUCCESS;
01519 }
01520 
01521 AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Linux Telephony API Support");
01522 

Generated on Thu Apr 16 06:27:23 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6