Sat Mar 26 11:06:32 2011

Asterisk developer's documentation


app_rpt.c

Go to the documentation of this file.
00001 #define  NEW_ASTERISK
00002 /* #define OLD_ASTERISK */
00003 /*
00004  * Asterisk -- An open source telephony toolkit.
00005  *
00006  * Copyright (C) 2002-2008, Jim Dixon, WB6NIL
00007  *
00008  * Jim Dixon, WB6NIL <jim@lambdatel.com>
00009  * Serious contributions by Steve RoDgers, WA6ZFT <hwstar@rodgers.sdcoxmail.com>
00010  *
00011  * See http://www.asterisk.org for more information about
00012  * the Asterisk project. Please do not directly contact
00013  * any of the maintainers of this project for assistance;
00014  * the project provides a web site, mailing lists and IRC
00015  * channels for your use.
00016  *
00017  * This program is free software, distributed under the terms of
00018  * the GNU General Public License Version 2. See the LICENSE file
00019  * at the top of the source tree.
00020  */
00021 /*! \file
00022  *
00023  * \brief Radio Repeater / Remote Base program 
00024  *  version 0.115 5/12/08 2055 EDT
00025  * 
00026  * \author Jim Dixon, WB6NIL <jim@lambdatel.com>
00027  *
00028  * \note Serious contributions by Steve RoDgers, WA6ZFT <hwstar@rodgers.sdcoxmail.com>
00029  * \note Steven Henke, W9SH, <w9sh@arrl.net> added a few features here and there.
00030  *
00031  * See http://www.zapatatelephony.org/app_rpt.html
00032  *
00033  *
00034  * Repeater / Remote Functions:
00035  * "Simple" Mode:  * - autopatch access, # - autopatch hangup
00036  * Normal mode:
00037  * See the function list in rpt.conf (autopatchup, autopatchdn)
00038  * autopatchup can optionally take comma delimited setting=value pairs:
00039  *  
00040  *
00041  * context=string    :  Override default context with "string"
00042  * dialtime=ms       :  Specify the max number of milliseconds between phone number digits (1000 milliseconds = 1 second)
00043  * farenddisconnect=1      :  Automatically disconnect when called party hangs up
00044  * noct=1         :  Don't send repeater courtesy tone during autopatch calls
00045  * quiet=1        :  Don't send dial tone, or connect messages. Do not send patch down message when called party hangs up
00046  *
00047  *
00048  * Example: 123=autopatchup,dialtime=20000,noct=1,farenddisconnect=1
00049  *
00050  *  To send an asterisk (*) while dialing or talking on phone,
00051  *  use the autopatch acess code.
00052  *
00053  *
00054  * status cmds:
00055  *
00056  *  1 - Force ID (global)
00057  *  2 - Give Time of Day (global)
00058  *  3 - Give software Version (global)
00059  *  11 - Force ID (local only)
00060  *  12 - Give Time of Day (local only)
00061  *
00062  * cop (control operator) cmds:
00063  *
00064  *  1 - System warm boot
00065  *  2 - System enable
00066  *  3 - System disable
00067  *  4 - Test Tone On/Off
00068  *  5 - Dump System Variables on Console (debug)
00069  *  6 - PTT (phone mode only)
00070  *  7 - Time out timer enable
00071  *  8 - Time out timer disable
00072  *  9 - Autopatch enable
00073  *  10 - Autopatch disable
00074  *  11 - Link enable
00075  *  12 - Link disable
00076  *  13 - Query System State
00077  *  14 - Change System State
00078  *  15 - Scheduler Enable
00079  *  16 - Scheduler Disable
00080  *  17 - User functions (time, id, etc) enable
00081  *  18 - User functions (time, id, etc) disable
00082  *  19 - Select alternate hang timer
00083  *  20 - Select standard hang timer 
00084  *  21 - Enable Parrot Mode
00085  *  22 - Disable Parrot Mode
00086  *  23 - Birdbath (Current Parrot Cleanup/Flush)
00087  *  24 - Flush all telemetry
00088  *  25 - Query last node un-keyed
00089  *  26 - Query all nodes keyed/unkeyed
00090  *  30 - Recall Memory Setting in Attached Xcvr
00091  *  31 - Channel Selector for Parallel Programmed Xcvr
00092  *  32 - Touchtone pad test: command + Digit string + # to playback all digits pressed
00093  *
00094  * ilink cmds:
00095  *
00096  *  1 - Disconnect specified link
00097  *  2 - Connect specified link -- monitor only
00098  *  3 - Connect specified link -- tranceive
00099  *  4 - Enter command mode on specified link
00100  *  5 - System status
00101  *  6 - Disconnect all links
00102  *  11 - Disconnect a previously permanently connected link
00103  *  12 - Permanently connect specified link -- monitor only
00104  *  13 - Permanently connect specified link -- tranceive
00105  *  15 - Full system status (all nodes)
00106  *  16 - Reconnect links disconnected with "disconnect all links"
00107  *  200 thru 215 - (Send DTMF 0-9,*,#,A-D) (200=0, 201=1, 210=*, etc)
00108  *
00109  * remote cmds:
00110  *
00111  *  1 - Recall Memory MM  (*000-*099) (Gets memory from rpt.conf)
00112  *  2 - Set VFO MMMMM*KKK*O   (Mhz digits, Khz digits, Offset)
00113  *  3 - Set Rx PL Tone HHH*D*
00114  *  4 - Set Tx PL Tone HHH*D* (Not currently implemented with DHE RBI-1)
00115  *  5 - Link Status (long)
00116  *  6 - Set operating mode M (FM, USB, LSB, AM, etc)
00117  *  100 - RX PL off (Default)
00118  *  101 - RX PL On
00119  *  102 - TX PL Off (Default)
00120  *  103 - TX PL On
00121  *  104 - Low Power
00122  *  105 - Med Power
00123  *  106 - Hi Power
00124  *  107 - Bump Down 20 Hz
00125  *  108 - Bump Down 100 Hz
00126  *  109 - Bump Down 500 Hz
00127  *  110 - Bump Up 20 Hz
00128  *  111 - Bump Up 100 Hz
00129  *  112 - Bump Up 500 Hz
00130  *  113 - Scan Down Slow
00131  *  114 - Scan Down Medium
00132  *  115 - Scan Down Fast
00133  *  116 - Scan Up Slow
00134  *  117 - Scan Up Medium
00135  *  118 - Scan Up Fast
00136  *  119 - Transmit allowing auto-tune
00137  *  140 - Link Status (brief)
00138  *  200 thru 215 - (Send DTMF 0-9,*,#,A-D) (200=0, 201=1, 210=*, etc)
00139  *
00140  * playback cmds:
00141  *  specify the name of the file to be played (for example, 25=rpt/foo)
00142  *
00143  *
00144  * 'duplex' modes:  (defaults to duplex=2)
00145  *
00146  * 0 - Only remote links key Tx and no main repeat audio.
00147  * 1 - Everything other then main Rx keys Tx, no main repeat audio.
00148  * 2 - Normal mode
00149  * 3 - Normal except no main repeat audio.
00150  * 4 - Normal except no main repeat audio during autopatch only
00151  *
00152 */
00153 
00154 /*** MODULEINFO
00155    <depend>dahdi</depend>
00156    <depend>tonezone</depend>
00157  ***/
00158 
00159 /* Un-comment the following to include support for MDC-1200 digital tone
00160    signalling protocol (using KA6SQG's GPL'ed implementation) */
00161 /* #include "mdc_decode.c" */
00162 
00163 /* Un-comment the following to include support for notch filters in the
00164    rx audio stream (using Tony Fisher's mknotch (mkfilter) implementation) */
00165 /* #include "rpt_notch.c" */
00166 
00167 /* maximum digits in DTMF buffer, and seconds after * for DTMF command timeout */
00168 
00169 #ifdef OLD_ASTERISK
00170 #define ast_free free
00171 #define ast_malloc malloc
00172 #define ast_strdup strdup
00173 #endif
00174 
00175 
00176 #define  MAXDTMF 32
00177 #define  MAXMACRO 2048
00178 #define  MAXLINKLIST 512
00179 #define  LINKLISTTIME 10000
00180 #define  LINKLISTSHORTTIME 200
00181 #define  LINKPOSTTIME 30000
00182 #define  LINKPOSTSHORTTIME 200
00183 #define  KEYPOSTTIME 30000
00184 #define  KEYPOSTSHORTTIME 200
00185 #define  MACROTIME 100
00186 #define  MACROPTIME 500
00187 #define  DTMF_TIMEOUT 3
00188 #define  KENWOOD_RETRIES 5
00189 #define  TOPKEYN 32
00190 #define  TOPKEYWAIT 3
00191 #define  TOPKEYMAXSTR 30
00192 
00193 #define  AUTHTELLTIME 7000
00194 #define  AUTHTXTIME 1000
00195 #define  AUTHLOGOUTTIME 25000
00196 
00197 #ifdef   __RPT_NOTCH
00198 #define  MAXFILTERS 10
00199 #endif
00200 
00201 #define  DISC_TIME 10000  /* report disc after 10 seconds of no connect */
00202 #define  MAX_RETRIES 5
00203 #define  MAX_RETRIES_PERM 1000000000
00204 
00205 #define  REDUNDANT_TX_TIME 2000
00206 
00207 #define  RETRY_TIMER_MS 5000
00208 
00209 #define  PATCH_DIALPLAN_TIMEOUT 1500
00210 
00211 #ifdef OLD_ASTERISK
00212 #define  START_DELAY 10
00213 #else
00214 #define  START_DELAY 2
00215 #endif
00216 
00217 #define  RPT_LOCKOUT_SECS 10
00218 
00219 #define MAXPEERSTR 31
00220 #define  MAXREMSTR 15
00221 
00222 #define  DELIMCHR ','
00223 #define  QUOTECHR 34
00224 
00225 #define  MONITOR_DISK_BLOCKS_PER_MINUTE 38
00226 
00227 #define  DEFAULT_MONITOR_MIN_DISK_BLOCKS 10000
00228 #define  DEFAULT_REMOTE_INACT_TIMEOUT (15 * 60)
00229 #define  DEFAULT_REMOTE_TIMEOUT (60 * 60)
00230 #define  DEFAULT_REMOTE_TIMEOUT_WARNING (3 * 60)
00231 #define  DEFAULT_REMOTE_TIMEOUT_WARNING_FREQ 30
00232 
00233 #define  NODES "nodes"
00234 #define  EXTNODES "extnodes"
00235 #define MEMORY "memory"
00236 #define MACRO "macro"
00237 #define  FUNCTIONS "functions"
00238 #define TELEMETRY "telemetry"
00239 #define MORSE "morse"
00240 #define  TONEMACRO "tonemacro"
00241 #define  FUNCCHAR '*'
00242 #define  ENDCHAR '#'
00243 #define  EXTNODEFILE "/var/lib/asterisk/rpt_extnodes"
00244 #define  NODENAMES "rpt/nodenames"
00245 #define  PARROTFILE "/tmp/parrot_%s_%u"
00246 
00247 #define  PARROTTIME 1000
00248 
00249 #define  DEFAULT_IOBASE 0x378
00250 
00251 #define  DEFAULT_CIV_ADDR 0x58
00252 
00253 #define  MAXCONNECTTIME 5000
00254 
00255 #define MAXNODESTR 300
00256 
00257 #define MAXNODELEN 16
00258 
00259 #define MAXIDENTLEN 32
00260 
00261 #define MAXPATCHCONTEXT 100
00262 
00263 #define ACTIONSIZE 32
00264 
00265 #define TELEPARAMSIZE 256
00266 
00267 #define REM_SCANTIME 100
00268 
00269 #define  DTMF_LOCAL_TIME 250
00270 #define  DTMF_LOCAL_STARTTIME 500
00271 
00272 #define  IC706_PL_MEMORY_OFFSET 50
00273 
00274 #define  VOX_ON_DEBOUNCE_COUNT 3
00275 #define  VOX_OFF_DEBOUNCE_COUNT 20
00276 #define  VOX_MAX_THRESHOLD 10000.0
00277 #define  VOX_MIN_THRESHOLD 3000.0
00278 #define  VOX_TIMEOUT_MS 5000
00279 #define  VOX_RECOVER_MS 500
00280 #define  SIMPLEX_PATCH_DELAY 25
00281 #define  SIMPLEX_PHONE_DELAY 25
00282 
00283 #define  STATPOST_PROGRAM "/usr/bin/wget,-q,--output-document=/dev/null,--no-check-certificate"
00284 
00285 #define  ALLOW_LOCAL_CHANNELS
00286 
00287 enum {REM_OFF,REM_MONITOR,REM_TX};
00288 
00289 enum{ID,PROC,TERM,COMPLETE,UNKEY,REMDISC,REMALREADY,REMNOTFOUND,REMGO,
00290    CONNECTED,CONNFAIL,STATUS,TIMEOUT,ID1, STATS_TIME, PLAYBACK,
00291    STATS_VERSION, IDTALKOVER, ARB_ALPHA, TEST_TONE, REV_PATCH,
00292    TAILMSG, MACRO_NOTFOUND, MACRO_BUSY, LASTNODEKEY, FULLSTATUS,
00293    MEMNOTFOUND, INVFREQ, REMMODE, REMLOGIN, REMXXX, REMSHORTSTATUS,
00294    REMLONGSTATUS, LOGINREQ, SCAN, SCANSTAT, TUNE, SETREMOTE, TOPKEY,
00295    TIMEOUT_WARNING, ACT_TIMEOUT_WARNING, LINKUNKEY, UNAUTHTX, PARROT,
00296    STATS_TIME_LOCAL};
00297 
00298 
00299 enum {REM_SIMPLEX,REM_MINUS,REM_PLUS};
00300 
00301 enum {REM_LOWPWR,REM_MEDPWR,REM_HIPWR};
00302 
00303 enum {DC_INDETERMINATE, DC_REQ_FLUSH, DC_ERROR, DC_COMPLETE, DC_COMPLETEQUIET, DC_DOKEY};
00304 
00305 enum {SOURCE_RPT, SOURCE_LNK, SOURCE_RMT, SOURCE_PHONE, SOURCE_DPHONE, SOURCE_ALT};
00306 
00307 enum {DLY_TELEM, DLY_ID, DLY_UNKEY, DLY_CALLTERM, DLY_COMP, DLY_LINKUNKEY, DLY_PARROT};
00308 
00309 enum {REM_MODE_FM,REM_MODE_USB,REM_MODE_LSB,REM_MODE_AM};
00310 
00311 enum {HF_SCAN_OFF,HF_SCAN_DOWN_SLOW,HF_SCAN_DOWN_QUICK,
00312       HF_SCAN_DOWN_FAST,HF_SCAN_UP_SLOW,HF_SCAN_UP_QUICK,HF_SCAN_UP_FAST};
00313 
00314 #include "asterisk.h"
00315 
00316 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 276347 $")
00317 
00318 #include <signal.h>
00319 #include <stdio.h>
00320 #include <stdint.h>
00321 #include <unistd.h>
00322 #include <string.h>
00323 #include <stdlib.h>
00324 #include <search.h>
00325 #include <sys/types.h>
00326 #include <sys/stat.h>
00327 #include <errno.h>
00328 #include <dirent.h>
00329 #include <ctype.h>
00330 #include <sys/stat.h>
00331 #include <sys/time.h>
00332 #include <sys/file.h>
00333 #include <sys/ioctl.h>
00334 #ifdef HAVE_SYS_IO_H
00335 #include <sys/io.h>
00336 #endif
00337 #include <sys/vfs.h>
00338 #include <math.h>
00339 #include <dahdi/user.h>
00340 #include <dahdi/tonezone.h>
00341 #include <netinet/in.h>
00342 #include <arpa/inet.h>
00343 
00344 #include "asterisk/utils.h"
00345 #include "asterisk/lock.h"
00346 #include "asterisk/file.h"
00347 #include "asterisk/logger.h"
00348 #include "asterisk/channel.h"
00349 #include "asterisk/callerid.h"
00350 #include "asterisk/pbx.h"
00351 #include "asterisk/module.h"
00352 #include "asterisk/translate.h"
00353 #include "asterisk/features.h"
00354 #include "asterisk/options.h"
00355 #include "asterisk/cli.h"
00356 #include "asterisk/config.h"
00357 #include "asterisk/say.h"
00358 #include "asterisk/localtime.h"
00359 #include "asterisk/cdr.h"
00360 #include "asterisk/options.h"
00361 #include "asterisk/manager.h"
00362 #include "asterisk/app.h"
00363 
00364 #include <termios.h>
00365 
00366 #ifdef   NEW_ASTERISK
00367 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
00368 #endif
00369 
00370 
00371 /* Start a tone-list going */
00372 int ast_playtones_start(struct ast_channel *chan, int vol, const char* tonelist, int interruptible);
00373 /*! Stop the tones from playing */
00374 void ast_playtones_stop(struct ast_channel *chan);
00375 
00376 static  char *tdesc = "Radio Repeater / Remote Base  version 0.115  5/12/2008";
00377 
00378 static char *app = "Rpt";
00379 
00380 static char *synopsis = "Radio Repeater/Remote Base Control System";
00381 
00382 static char *descrip = 
00383 "  Rpt(nodename[|options][|M][|*]):  \n"
00384 "    Radio Remote Link or Remote Base Link Endpoint Process.\n"
00385 "\n"
00386 "    Not specifying an option puts it in normal endpoint mode (where source\n"
00387 "    IP and nodename are verified).\n"
00388 "\n"
00389 "    Options are as follows:\n"
00390 "\n"
00391 "        X - Normal endpoint mode WITHOUT security check. Only specify\n"
00392 "            this if you have checked security already (like with an IAX2\n"
00393 "            user/password or something).\n"
00394 "\n"
00395 "        Rannounce-string[|timeout[|timeout-destination]] - Amateur Radio\n"
00396 "            Reverse Autopatch. Caller is put on hold, and announcement (as\n"
00397 "            specified by the 'announce-string') is played on radio system.\n"
00398 "            Users of radio system can access autopatch, dial specified\n"
00399 "            code, and pick up call. Announce-string is list of names of\n"
00400 "            recordings, or \"PARKED\" to substitute code for un-parking,\n"
00401 "            or \"NODE\" to substitute node number.\n"
00402 "\n"
00403 "        P - Phone Control mode. This allows a regular phone user to have\n"
00404 "            full control and audio access to the radio system. For the\n"
00405 "            user to have DTMF control, the 'phone_functions' parameter\n"
00406 "            must be specified for the node in 'rpt.conf'. An additional\n"
00407 "            function (cop,6) must be listed so that PTT control is available.\n"
00408 "\n"
00409 "        D - Dumb Phone Control mode. This allows a regular phone user to\n"
00410 "            have full control and audio access to the radio system. In this\n"
00411 "            mode, the PTT is activated for the entire length of the call.\n"
00412 "            For the user to have DTMF control (not generally recomended in\n"
00413 "            this mode), the 'dphone_functions' parameter must be specified\n"
00414 "            for the node in 'rpt.conf'. Otherwise no DTMF control will be\n"
00415 "            available to the phone user.\n"
00416 "\n"
00417 "        S - Simplex Dumb Phone Control mode. This allows a regular phone user\n"
00418 "            audio-only access to the radio system. In this mode, the\n"
00419 "            transmitter is toggled on and off when the phone user presses the\n"
00420 "            funcchar (*) key on the telephone set. In addition, the transmitter\n"
00421 "            will turn off if the endchar (#) key is pressed. When a user first\n"
00422 "            calls in, the transmitter will be off, and the user can listen for\n"
00423 "            radio traffic. When the user wants to transmit, they press the *\n" 
00424 "            key, start talking, then press the * key again or the # key to turn\n"
00425 "            the transmitter off.  No other functions can be executed by the\n"
00426 "            user on the phone when this mode is selected. Note: If your\n"
00427 "            radio system is full-duplex, we recommend using either P or D\n"
00428 "            modes as they provide more flexibility.\n"
00429 "\n"
00430 "        q - Query Status. Sets channel variables and returns + 101 in plan.\n"
00431 "\n"
00432 "        M - Memory Channel Steer as MXX where XX is the memory channel number.\n"
00433 "\n"
00434 "        * - Alt Macro to execute (e.g. *7 for status)\n"
00435 "\n";
00436 ;
00437 
00438 static int debug = 0;  /* Set this >0 for extra debug output */
00439 static int nrpts = 0;
00440 
00441 static const char remdtmfstr[] = "0123456789*#ABCD";
00442 
00443 enum {TOP_TOP,TOP_WON,WON_BEFREAD,BEFREAD_AFTERREAD};
00444 
00445 int max_chan_stat [] = {22000,1000,22000,100,22000,2000,22000};
00446 
00447 #define NRPTSTAT 7
00448 
00449 struct rpt_chan_stat
00450 {
00451    struct timeval last;
00452    long long total;
00453    unsigned long count;
00454    unsigned long largest;
00455    struct timeval largest_time;
00456 };
00457 
00458 char *discstr = "!!DISCONNECT!!";
00459 char *newkeystr = "!NEWKEY!";
00460 static char *remote_rig_ft897="ft897";
00461 static char *remote_rig_rbi="rbi";
00462 static char *remote_rig_kenwood="kenwood";
00463 static char *remote_rig_tm271="tm271";
00464 static char *remote_rig_ic706="ic706";
00465 static char *remote_rig_rtx150="rtx150";
00466 static char *remote_rig_rtx450="rtx450";
00467 static char *remote_rig_ppp16="ppp16";       // parallel port programmable 16 channels
00468 
00469 #define ISRIG_RTX(x) ((!strcmp(x,remote_rig_rtx150)) || (!strcmp(x,remote_rig_rtx450)))
00470 #define  IS_XPMR(x) (!strncasecmp(x->rxchanname,"rad",3))
00471 
00472 #ifdef   OLD_ASTERISK
00473 STANDARD_LOCAL_USER;
00474 LOCAL_USER_DECL;
00475 #endif
00476 
00477 #define  MSWAIT 200
00478 #define  HANGTIME 5000
00479 #define  TOTIME 180000
00480 #define  IDTIME 300000
00481 #define  MAXRPTS 20
00482 #define MAX_STAT_LINKS 32
00483 #define POLITEID 30000
00484 #define FUNCTDELAY 1500
00485 
00486 #define  MAXXLAT 20
00487 #define  MAXXLATTIME 3
00488 
00489 #define MAX_SYSSTATES 10
00490 
00491 struct vox {
00492    float speech_energy;
00493    float noise_energy;
00494    int   enacount;
00495    char  voxena;
00496    char  lastvox;
00497    int   offdebcnt;
00498    int   ondebcnt;
00499 } ;
00500 
00501 #define  mymax(x,y) ((x > y) ? x : y)
00502 #define  mymin(x,y) ((x < y) ? x : y)
00503 
00504 struct rpt_topkey
00505 {
00506 char  node[TOPKEYMAXSTR];
00507 int   timesince;
00508 int   keyed;
00509 } ;
00510 
00511 struct rpt_xlat
00512 {
00513 char  funccharseq[MAXXLAT];
00514 char  endcharseq[MAXXLAT];
00515 char  passchars[MAXXLAT];
00516 int   funcindex;
00517 int   endindex;
00518 time_t   lastone;
00519 } ;
00520 
00521 static time_t  starttime = 0;
00522 
00523 static  pthread_t rpt_master_thread;
00524 
00525 struct rpt;
00526 
00527 struct rpt_link
00528 {
00529    struct rpt_link *next;
00530    struct rpt_link *prev;
00531    char  mode;       /* 1 if in tx mode */
00532    char  isremote;
00533    char  phonemode;
00534    char  phonevox;      /* vox the phone */
00535    char  name[MAXNODESTR]; /* identifier (routing) string */
00536    char  lasttx;
00537    char  lasttx1;
00538    char  lastrx;
00539    char  lastrealrx;
00540    char  lastrx1;
00541    char  connected;
00542    char  hasconnected;
00543    char  perma;
00544    char  thisconnected;
00545    char  outbound;
00546    char  disced;
00547    char  killme;
00548    long  elaptime;
00549    long  disctime;
00550    long  retrytimer;
00551    long  retxtimer;
00552    long  rerxtimer;
00553    int   retries;
00554    int   max_retries;
00555    int   reconnects;
00556    long long connecttime;
00557    struct ast_channel *chan;  
00558    struct ast_channel *pchan; 
00559    char  linklist[MAXLINKLIST];
00560    time_t   linklistreceived;
00561    long  linklisttimer;
00562    int   dtmfed;
00563    int linkunkeytocttimer;
00564    struct timeval lastlinktv;
00565    struct   ast_frame *lastf1,*lastf2;
00566    struct   rpt_chan_stat chan_stat[NRPTSTAT];
00567    struct vox vox;
00568    char wasvox;
00569    int voxtotimer;
00570    char voxtostate;
00571    char newkey;
00572 #ifdef OLD_ASTERISK
00573         AST_LIST_HEAD(, ast_frame) rxq;
00574 #else
00575    AST_LIST_HEAD_NOLOCK(, ast_frame) rxq;
00576 #endif
00577 } ;
00578 
00579 struct rpt_lstat
00580 {
00581    struct   rpt_lstat *next;
00582    struct   rpt_lstat *prev;
00583    char  peer[MAXPEERSTR];
00584    char  name[MAXNODESTR];
00585    char  mode;
00586    char  outbound;
00587    char  reconnects;
00588    char  thisconnected;
00589    long long   connecttime;
00590    struct   rpt_chan_stat chan_stat[NRPTSTAT];
00591 } ;
00592 
00593 struct rpt_tele
00594 {
00595    struct rpt_tele *next;
00596    struct rpt_tele *prev;
00597    struct rpt *rpt;
00598    struct ast_channel *chan;
00599    int   mode;
00600    struct rpt_link mylink;
00601    char param[TELEPARAMSIZE];
00602    intptr_t submode;
00603    uintptr_t  parrot;
00604    pthread_t threadid;
00605 } ;
00606 
00607 struct function_table_tag
00608 {
00609    char action[ACTIONSIZE];
00610    int (*function)(struct rpt *myrpt, char *param, char *digitbuf, 
00611       int command_source, struct rpt_link *mylink);
00612 } ;
00613 
00614 /* Used to store the morse code patterns */
00615 
00616 struct morse_bits
00617 {       
00618    int len;
00619    int ddcomb;
00620 } ;
00621 
00622 struct telem_defaults
00623 {
00624    char name[20];
00625    char value[80];
00626 } ;
00627 
00628 
00629 struct sysstate
00630 {
00631    char txdisable;
00632    char totdisable;
00633    char linkfundisable;
00634    char autopatchdisable;
00635    char schedulerdisable;
00636    char userfundisable;
00637    char alternatetail;
00638 };
00639 
00640 /* rpt cmd support */
00641 #define CMD_DEPTH 1
00642 #define CMD_STATE_IDLE 0
00643 #define CMD_STATE_BUSY 1
00644 #define CMD_STATE_READY 2
00645 #define CMD_STATE_EXECUTING 3
00646 
00647 struct rpt_cmd_struct
00648 {
00649     int state;
00650     int functionNumber;
00651     char param[MAXDTMF];
00652     char digits[MAXDTMF];
00653     int command_source;
00654 };
00655 
00656 static struct rpt
00657 {
00658    ast_mutex_t lock;
00659    ast_mutex_t remlock;
00660    ast_mutex_t statpost_lock;
00661    struct ast_config *cfg;
00662    char reload;
00663    char xlink;                         // cross link state of a share repeater/remote radio
00664    unsigned int statpost_seqno;
00665 
00666    char *name;
00667    char *rxchanname;
00668    char *txchanname;
00669    char remote;
00670    char *remoterig;
00671    struct   rpt_chan_stat chan_stat[NRPTSTAT];
00672    unsigned int scram;
00673 
00674    struct {
00675       char *ourcontext;
00676       char *ourcallerid;
00677       char *acctcode;
00678       char *ident;
00679       char *tonezone;
00680       char simple;
00681       char *functions;
00682       char *link_functions;
00683       char *phone_functions;
00684       char *dphone_functions;
00685       char *alt_functions;
00686       char *nodes;
00687       char *extnodes;
00688       char *extnodefile;
00689       int hangtime;
00690       int althangtime;
00691       int totime;
00692       int idtime;
00693       int tailmessagetime;
00694       int tailsquashedtime;
00695       int duplex;
00696       int politeid;
00697       char *tailmessages[500];
00698       int tailmessagemax;
00699       char  *memory;
00700       char  *macro;
00701       char  *tonemacro;
00702       char  *startupmacro;
00703       int iobase;
00704       char *ioport;
00705       char funcchar;
00706       char endchar;
00707       char nobusyout;
00708       char notelemtx;
00709       char propagate_dtmf;
00710       char propagate_phonedtmf;
00711       char linktolink;
00712       unsigned char civaddr;
00713       struct rpt_xlat inxlat;
00714       struct rpt_xlat outxlat;
00715       char *archivedir;
00716       int authlevel;
00717       char *csstanzaname;
00718       char *skedstanzaname;
00719       char *txlimitsstanzaname;
00720       long monminblocks;
00721       int remoteinacttimeout;
00722       int remotetimeout;
00723       int remotetimeoutwarning;
00724       int remotetimeoutwarningfreq;
00725       int sysstate_cur;
00726       struct sysstate s[MAX_SYSSTATES];
00727       char parrotmode;
00728       int parrottime;
00729       char *rptnode;
00730       char remote_mars;
00731       int voxtimeout_ms;
00732       int voxrecover_ms;
00733       int simplexpatchdelay;
00734       int simplexphonedelay;
00735       char *statpost_program;
00736       char *statpost_url;
00737    } p;
00738    struct rpt_link links;
00739    int unkeytocttimer;
00740    time_t lastkeyedtime;
00741    time_t lasttxkeyedtime;
00742    char keyed;
00743    char txkeyed;
00744    char exttx;
00745    char localtx;
00746    char remoterx;
00747    char remotetx;
00748    char remoteon;
00749    char remtxfreqok;
00750    char tounkeyed;
00751    char tonotify;
00752    char dtmfbuf[MAXDTMF];
00753    char macrobuf[MAXMACRO];
00754    char rem_dtmfbuf[MAXDTMF];
00755    char lastdtmfcommand[MAXDTMF];
00756    char cmdnode[50];
00757    char nowchan;                 // channel now
00758    char waschan;                 // channel selected initially or by command
00759    char bargechan;                  // barge in channel
00760    char macropatch;              // autopatch via tonemacro state
00761    char parrotstate;
00762    int  parrottimer;
00763    unsigned int parrotcnt;
00764    struct ast_channel *rxchannel,*txchannel, *monchannel, *parrotchannel;
00765    struct ast_channel *pchannel,*txpchannel, *dahdirxchannel, *dahditxchannel;
00766    struct ast_channel *voxchannel;
00767    struct ast_frame *lastf1,*lastf2;
00768    struct rpt_tele tele;
00769    struct timeval lasttv,curtv;
00770    pthread_t rpt_call_thread,rpt_thread;
00771    time_t dtmf_time,rem_dtmf_time,dtmf_time_rem;
00772    int calldigittimer;
00773    int tailtimer,totimer,idtimer,txconf,conf,callmode,cidx,scantimer,tmsgtimer,skedtimer;
00774    int mustid,tailid;
00775    int tailevent;
00776    int telemrefcount;
00777    int dtmfidx,rem_dtmfidx;
00778    int dailytxtime,dailykerchunks,totalkerchunks,dailykeyups,totalkeyups,timeouts;
00779    int totalexecdcommands, dailyexecdcommands;
00780    long  retxtimer;
00781    long  rerxtimer;
00782    long long totaltxtime;
00783    char mydtmf;
00784    char exten[AST_MAX_EXTENSION];
00785    char freq[MAXREMSTR],rxpl[MAXREMSTR],txpl[MAXREMSTR];
00786    char offset;
00787    char powerlevel;
00788    char txplon;
00789    char rxplon;
00790    char remmode;
00791    char tunerequest;
00792    char hfscanmode;
00793    int hfscanstatus;
00794    char hfscanstop;
00795    char lastlinknode[MAXNODESTR];
00796    char savednodes[MAXNODESTR];
00797    int stopgen;
00798    char patchfarenddisconnect;
00799    char patchnoct;
00800    char patchquiet;
00801    char patchcontext[MAXPATCHCONTEXT];
00802    int patchdialtime;
00803    int macro_longest;
00804    int phone_longestfunc;
00805    int alt_longestfunc;
00806    int dphone_longestfunc;
00807    int link_longestfunc;
00808    int longestfunc;
00809    int longestnode;
00810    int threadrestarts;     
00811    int tailmessagen;
00812    time_t disgorgetime;
00813    time_t lastthreadrestarttime;
00814    long  macrotimer;
00815    char  lastnodewhichkeyedusup[MAXNODESTR];
00816    int   dtmf_local_timer;
00817    char  dtmf_local_str[100];
00818    struct ast_filestream *monstream,*parrotstream;
00819    char  loginuser[50];
00820    char  loginlevel[10];
00821    long  authtelltimer;
00822    long  authtimer;
00823    int iofd;
00824    time_t start_time,last_activity_time;
00825    char  lasttone[32];
00826    struct rpt_tele *active_telem;
00827    struct   rpt_topkey topkey[TOPKEYN];
00828    int topkeystate;
00829    time_t topkeytime;
00830    int topkeylong;
00831    struct vox vox;
00832    char wasvox;
00833    int voxtotimer;
00834    char voxtostate;
00835    int linkposttimer;         
00836    int keyposttimer;       
00837    char newkey;
00838    char inpadtest;
00839 #ifdef OLD_ASTERISK
00840    AST_LIST_HEAD(, ast_frame) txq;
00841 #else
00842    AST_LIST_HEAD_NOLOCK(, ast_frame) txq;
00843 #endif
00844    char txrealkeyed;
00845 #ifdef   __RPT_NOTCH
00846    struct rptfilter
00847    {
00848       char  desc[100];
00849       float x0;
00850       float x1;
00851       float x2;
00852       float y0;
00853       float y1;
00854       float y2;
00855       float gain;
00856       float const0;
00857       float const1;
00858       float const2;
00859    } filters[MAXFILTERS];
00860 #endif
00861 #ifdef   _MDC_DECODE_H_
00862    mdc_decoder_t *mdc;
00863    unsigned short lastunit;
00864 #endif
00865    struct rpt_cmd_struct cmdAction;
00866 } rpt_vars[MAXRPTS]; 
00867 
00868 struct nodelog {
00869 struct nodelog *next;
00870 struct nodelog *prev;
00871 time_t   timestamp;
00872 char archivedir[MAXNODESTR];
00873 char str[MAXNODESTR * 2];
00874 } nodelog;
00875 
00876 static int service_scan(struct rpt *myrpt);
00877 static int set_mode_ft897(struct rpt *myrpt, char newmode);
00878 static int set_mode_ic706(struct rpt *myrpt, char newmode);
00879 static int simple_command_ft897(struct rpt *myrpt, char command);
00880 static int setrem(struct rpt *myrpt);
00881 static int setrtx_check(struct rpt *myrpt);
00882 static int channel_revert(struct rpt *myrpt);
00883 static int channel_steer(struct rpt *myrpt, char *data);
00884 
00885 AST_MUTEX_DEFINE_STATIC(nodeloglock);
00886 
00887 AST_MUTEX_DEFINE_STATIC(nodelookuplock);
00888 
00889 #ifdef   APP_RPT_LOCK_DEBUG
00890 
00891 #warning COMPILING WITH LOCK-DEBUGGING ENABLED!!
00892 
00893 #define  MAXLOCKTHREAD 100
00894 
00895 #define rpt_mutex_lock(x) _rpt_mutex_lock(x,myrpt,__LINE__)
00896 #define rpt_mutex_unlock(x) _rpt_mutex_unlock(x,myrpt,__LINE__)
00897 
00898 struct lockthread
00899 {
00900    pthread_t id;
00901    int lockcount;
00902    int lastlock;
00903    int lastunlock;
00904 } lockthreads[MAXLOCKTHREAD];
00905 
00906 
00907 struct by_lightning
00908 {
00909    int line;
00910    struct timeval tv;
00911    struct rpt *rpt;
00912    struct lockthread lockthread;
00913 } lock_ring[32];
00914 
00915 int lock_ring_index = 0;
00916 
00917 AST_MUTEX_DEFINE_STATIC(locklock);
00918 
00919 static struct lockthread *get_lockthread(pthread_t id)
00920 {
00921 int   i;
00922 
00923    for(i = 0; i < MAXLOCKTHREAD; i++)
00924    {
00925       if (lockthreads[i].id == id) return(&lockthreads[i]);
00926    }
00927    return(NULL);
00928 }
00929 
00930 static struct lockthread *put_lockthread(pthread_t id)
00931 {
00932 int   i;
00933 
00934    for(i = 0; i < MAXLOCKTHREAD; i++)
00935    {
00936       if (lockthreads[i].id == id)
00937          return(&lockthreads[i]);
00938    }
00939    for(i = 0; i < MAXLOCKTHREAD; i++)
00940    {
00941       if (!lockthreads[i].id)
00942       {
00943          lockthreads[i].lockcount = 0;
00944          lockthreads[i].lastlock = 0;
00945          lockthreads[i].lastunlock = 0;
00946          lockthreads[i].id = id;
00947          return(&lockthreads[i]);
00948       }
00949    }
00950    return(NULL);
00951 }
00952 
00953 
00954 static void rpt_mutex_spew(void)
00955 {
00956    struct by_lightning lock_ring_copy[32];
00957    int lock_ring_index_copy;
00958    int i,j;
00959    long long diff;
00960    char a[100];
00961    struct timeval lasttv;
00962 
00963    ast_mutex_lock(&locklock);
00964    memcpy(&lock_ring_copy, &lock_ring, sizeof(lock_ring_copy));
00965    lock_ring_index_copy = lock_ring_index;
00966    ast_mutex_unlock(&locklock);
00967 
00968    lasttv.tv_sec = lasttv.tv_usec = 0;
00969    for(i = 0 ; i < 32 ; i++)
00970    {
00971       j = (i + lock_ring_index_copy) % 32;
00972       strftime(a,sizeof(a) - 1,"%m/%d/%Y %H:%M:%S",
00973          localtime(&lock_ring_copy[j].tv.tv_sec));
00974       diff = 0;
00975       if(lasttv.tv_sec)
00976       {
00977          diff = (lock_ring_copy[j].tv.tv_sec - lasttv.tv_sec)
00978             * 1000000;
00979          diff += (lock_ring_copy[j].tv.tv_usec - lasttv.tv_usec);
00980       }
00981       lasttv.tv_sec = lock_ring_copy[j].tv.tv_sec;
00982       lasttv.tv_usec = lock_ring_copy[j].tv.tv_usec;
00983       if (!lock_ring_copy[j].tv.tv_sec) continue;
00984       if (lock_ring_copy[j].line < 0)
00985       {
00986          ast_log(LOG_NOTICE,"LOCKDEBUG [#%d] UNLOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
00987             i - 31,-lock_ring_copy[j].line,lock_ring_copy[j].rpt->name,(int) lock_ring_copy[j].lockthread.id,diff,a,(int)lock_ring_copy[j].tv.tv_usec);
00988       }
00989       else
00990       {
00991          ast_log(LOG_NOTICE,"LOCKDEBUG [#%d] LOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
00992             i - 31,lock_ring_copy[j].line,lock_ring_copy[j].rpt->name,(int) lock_ring_copy[j].lockthread.id,diff,a,(int)lock_ring_copy[j].tv.tv_usec);
00993       }
00994    }
00995 }
00996 
00997 
00998 static void _rpt_mutex_lock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
00999 {
01000 struct lockthread *t;
01001 pthread_t id;
01002 
01003    id = pthread_self();
01004    ast_mutex_lock(&locklock);
01005    t = put_lockthread(id);
01006    if (!t)
01007    {
01008       ast_mutex_unlock(&locklock);
01009       return;
01010    }
01011    if (t->lockcount)
01012    {
01013       int lastline = t->lastlock;
01014       ast_mutex_unlock(&locklock);
01015       ast_log(LOG_NOTICE,"rpt_mutex_lock: Double lock request line %d node %s pid %x, last lock was line %d\n",line,myrpt->name,(int) t->id,lastline);
01016       rpt_mutex_spew();
01017       return;
01018    }
01019    t->lastlock = line;
01020    t->lockcount = 1;
01021    gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
01022    lock_ring[lock_ring_index].rpt = myrpt;
01023    memcpy(&lock_ring[lock_ring_index].lockthread,t,sizeof(struct lockthread));
01024    lock_ring[lock_ring_index++].line = line;
01025    if(lock_ring_index == 32)
01026       lock_ring_index = 0;
01027    ast_mutex_unlock(&locklock);
01028    ast_mutex_lock(lockp);
01029 }
01030 
01031 
01032 static void _rpt_mutex_unlock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
01033 {
01034 struct lockthread *t;
01035 pthread_t id;
01036 
01037    id = pthread_self();
01038    ast_mutex_lock(&locklock);
01039    t = put_lockthread(id);
01040    if (!t)
01041    {
01042       ast_mutex_unlock(&locklock);
01043       return;
01044    }
01045    if (!t->lockcount)
01046    {
01047       int lastline = t->lastunlock;
01048       ast_mutex_unlock(&locklock);
01049       ast_log(LOG_NOTICE,"rpt_mutex_lock: Double un-lock request line %d node %s pid %x, last un-lock was line %d\n",line,myrpt->name,(int) t->id,lastline);
01050       rpt_mutex_spew();
01051       return;
01052    }
01053    t->lastunlock = line;
01054    t->lockcount = 0;
01055    gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
01056    lock_ring[lock_ring_index].rpt = myrpt;
01057    memcpy(&lock_ring[lock_ring_index].lockthread,t,sizeof(struct lockthread));
01058    lock_ring[lock_ring_index++].line = -line;
01059    if(lock_ring_index == 32)
01060       lock_ring_index = 0;
01061    ast_mutex_unlock(&locklock);
01062    ast_mutex_unlock(lockp);
01063 }
01064 
01065 #else  /* APP_RPT_LOCK_DEBUG */
01066 
01067 #define rpt_mutex_lock(x) ast_mutex_lock(x)
01068 #define rpt_mutex_unlock(x) ast_mutex_unlock(x)
01069 
01070 #endif  /* APP_RPT_LOCK_DEBUG */
01071 
01072 /*
01073 * Return 1 if rig is multimode capable
01074 */
01075 
01076 static int multimode_capable(struct rpt *myrpt)
01077 {
01078    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
01079       return 1;
01080    if(!strcmp(myrpt->remoterig, remote_rig_ic706))
01081       return 1;
01082    return 0;
01083 }  
01084 
01085 static void voxinit_rpt(struct rpt *myrpt,char enable)
01086 {
01087 
01088    myrpt->vox.speech_energy = 0.0;
01089    myrpt->vox.noise_energy = 0.0;
01090    myrpt->vox.enacount = 0;
01091    myrpt->vox.voxena = 0;
01092    if (!enable) myrpt->vox.voxena = -1;
01093    myrpt->vox.lastvox = 0;
01094    myrpt->vox.ondebcnt = VOX_ON_DEBOUNCE_COUNT;
01095    myrpt->vox.offdebcnt = VOX_OFF_DEBOUNCE_COUNT;
01096    myrpt->wasvox = 0;
01097    myrpt->voxtotimer = 0;
01098    myrpt->voxtostate = 0;
01099 }
01100 
01101 static void voxinit_link(struct rpt_link *mylink,char enable)
01102 {
01103 
01104    mylink->vox.speech_energy = 0.0;
01105    mylink->vox.noise_energy = 0.0;
01106    mylink->vox.enacount = 0;
01107    mylink->vox.voxena = 0;
01108    if (!enable) mylink->vox.voxena = -1;
01109    mylink->vox.lastvox = 0;
01110    mylink->vox.ondebcnt = VOX_ON_DEBOUNCE_COUNT;
01111    mylink->vox.offdebcnt = VOX_OFF_DEBOUNCE_COUNT;
01112    mylink->wasvox = 0;
01113    mylink->voxtotimer = 0;
01114    mylink->voxtostate = 0;
01115 }
01116 
01117 static int dovox(struct vox *v,short *buf,int bs)
01118 {
01119 
01120    int i;
01121    float esquare = 0.0;
01122    float energy = 0.0;
01123    float threshold = 0.0;
01124    
01125    if (v->voxena < 0) return(v->lastvox);
01126    for(i = 0; i < bs; i++)
01127    {
01128       esquare += (float) buf[i] * (float) buf[i];
01129    }
01130    energy = sqrt(esquare);
01131 
01132    if (energy >= v->speech_energy)
01133       v->speech_energy += (energy - v->speech_energy) / 4;
01134    else
01135       v->speech_energy += (energy - v->speech_energy) / 64;
01136 
01137    if (energy >= v->noise_energy)
01138       v->noise_energy += (energy - v->noise_energy) / 64;
01139    else
01140       v->noise_energy += (energy - v->noise_energy) / 4;
01141    
01142    if (v->voxena) threshold = v->speech_energy / 8;
01143    else
01144    {
01145       threshold = mymax(v->speech_energy / 16,v->noise_energy * 2);
01146       threshold = mymin(threshold,VOX_MAX_THRESHOLD);
01147    }
01148    threshold = mymax(threshold,VOX_MIN_THRESHOLD);
01149    if (energy > threshold)
01150    {
01151       if (v->voxena) v->noise_energy *= 0.75;
01152       v->voxena = 1;
01153    } else   v->voxena = 0;
01154    if (v->lastvox != v->voxena)
01155    {
01156       if (v->enacount++ >= ((v->lastvox) ? v->offdebcnt : v->ondebcnt))
01157       {
01158          v->lastvox = v->voxena;
01159          v->enacount = 0;
01160       }
01161    } else v->enacount = 0;
01162    return(v->lastvox);
01163 }
01164 
01165 
01166 
01167 
01168 /*
01169 * CLI extensions
01170 */
01171 
01172 /* Debug mode */
01173 static int rpt_do_debug(int fd, int argc, const char * const *argv);
01174 static int rpt_do_dump(int fd, int argc, const char * const *argv);
01175 static int rpt_do_stats(int fd, int argc, const char * const *argv);
01176 static int rpt_do_lstats(int fd, int argc, const char * const *argv);
01177 static int rpt_do_nodes(int fd, int argc, const char * const *argv);
01178 static int rpt_do_local_nodes(int fd, int argc, const char * const *argv);
01179 static int rpt_do_reload(int fd, int argc, const char * const *argv);
01180 static int rpt_do_restart(int fd, int argc, const char * const *argv);
01181 static int rpt_do_fun(int fd, int argc, const char * const *argv);
01182 static int rpt_do_fun1(int fd, int argc, const char * const *argv);
01183 static int rpt_do_cmd(int fd, int argc, const char * const *argv);
01184 
01185 static char debug_usage[] =
01186 "Usage: rpt debug level {0-7}\n"
01187 "       Enables debug messages in app_rpt\n";
01188 
01189 static char dump_usage[] =
01190 "Usage: rpt dump <nodename>\n"
01191 "       Dumps struct debug info to log\n";
01192 
01193 static char dump_stats[] =
01194 "Usage: rpt stats <nodename>\n"
01195 "       Dumps node statistics to console\n";
01196 
01197 static char dump_lstats[] =
01198 "Usage: rpt lstats <nodename>\n"
01199 "       Dumps link statistics to console\n";
01200 
01201 static char dump_nodes[] =
01202 "Usage: rpt nodes <nodename>\n"
01203 "       Dumps a list of directly and indirectly connected nodes to the console\n";
01204 
01205 static char usage_local_nodes[] =
01206 "Usage: rpt localnodes\n"
01207 "       Dumps a list of the locally configured node numbers to the console.\n";
01208 
01209 static char reload_usage[] =
01210 "Usage: rpt reload\n"
01211 "       Reloads app_rpt running config parameters\n";
01212 
01213 static char restart_usage[] =
01214 "Usage: rpt restart\n"
01215 "       Restarts app_rpt\n";
01216 
01217 static char fun_usage[] =
01218 "Usage: rpt fun <nodename> <command>\n"
01219 "       Send a DTMF function to a node\n";
01220 
01221 static char cmd_usage[] =
01222 "Usage: rpt cmd <nodename> <cmd-name> <cmd-index> <cmd-args.\n"
01223 "       Send a command to a node.\n        i.e. rpt cmd 2000 ilink 3 2001\n";
01224 
01225 #ifndef  NEW_ASTERISK
01226 
01227 static struct ast_cli_entry  cli_debug =
01228         { { "rpt", "debug", "level" }, rpt_do_debug, 
01229       "Enable app_rpt debugging", debug_usage };
01230 
01231 static struct ast_cli_entry  cli_dump =
01232         { { "rpt", "dump" }, rpt_do_dump,
01233       "Dump app_rpt structs for debugging", dump_usage };
01234 
01235 static struct ast_cli_entry  cli_stats =
01236         { { "rpt", "stats" }, rpt_do_stats,
01237       "Dump node statistics", dump_stats };
01238 
01239 static struct ast_cli_entry  cli_nodes =
01240         { { "rpt", "nodes" }, rpt_do_nodes,
01241       "Dump node list", dump_nodes };
01242 
01243 static struct ast_cli_entry  cli_local_nodes =
01244         { { "rpt", "localnodes" }, rpt_do_local_nodes,
01245       "Dump list of local node numbers", usage_local_nodes };
01246 
01247 static struct ast_cli_entry  cli_lstats =
01248         { { "rpt", "lstats" }, rpt_do_lstats,
01249       "Dump link statistics", dump_lstats };
01250 
01251 static struct ast_cli_entry  cli_reload =
01252         { { "rpt", "reload" }, rpt_do_reload,
01253       "Reload app_rpt config", reload_usage };
01254 
01255 static struct ast_cli_entry  cli_restart =
01256         { { "rpt", "restart" }, rpt_do_restart,
01257       "Restart app_rpt", restart_usage };
01258 
01259 static struct ast_cli_entry  cli_fun =
01260         { { "rpt", "fun" }, rpt_do_fun,
01261       "Execute a DTMF function", fun_usage };
01262 
01263 static struct ast_cli_entry  cli_fun1 =
01264         { { "rpt", "fun1" }, rpt_do_fun1,
01265       "Execute a DTMF function", fun_usage };
01266 
01267 static struct ast_cli_entry  cli_cmd =
01268         { { "rpt", "cmd" }, rpt_do_cmd,
01269       "Execute a DTMF function", cmd_usage };
01270 
01271 #endif
01272 
01273 /*
01274 * Telemetry defaults
01275 */
01276 
01277 
01278 static struct telem_defaults tele_defs[] = {
01279    {"ct1","|t(350,0,100,3072)(500,0,100,3072)(660,0,100,3072)"},
01280    {"ct2","|t(660,880,150,3072)"},
01281    {"ct3","|t(440,0,150,3072)"},
01282    {"ct4","|t(550,0,150,3072)"},
01283    {"ct5","|t(660,0,150,3072)"},
01284    {"ct6","|t(880,0,150,3072)"},
01285    {"ct7","|t(660,440,150,3072)"},
01286    {"ct8","|t(700,1100,150,3072)"},
01287    {"remotemon","|t(1600,0,75,2048)"},
01288    {"remotetx","|t(2000,0,75,2048)(0,0,75,0)(1600,0,75,2048)"},
01289    {"cmdmode","|t(900,904,200,2048)"},
01290    {"functcomplete","|t(1000,0,100,2048)(0,0,100,0)(1000,0,100,2048)"}
01291 } ;
01292 
01293 /*
01294 * Forward decl's - these suppress compiler warnings when funcs coded further down the file than thier invokation
01295 */
01296 
01297 static int setrbi(struct rpt *myrpt);
01298 static int set_ft897(struct rpt *myrpt);
01299 static int set_ic706(struct rpt *myrpt);
01300 static int setkenwood(struct rpt *myrpt);
01301 static int set_tm271(struct rpt *myrpt);
01302 static int setrbi_check(struct rpt *myrpt);
01303 
01304 
01305 
01306 /*
01307 * Define function protos for function table here
01308 */
01309 
01310 static int function_ilink(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01311 static int function_autopatchup(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01312 static int function_autopatchdn(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01313 static int function_status(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01314 static int function_cop(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01315 static int function_remote(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01316 static int function_macro(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01317 static int function_playback(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01318 /*
01319 * Function table
01320 */
01321 
01322 static struct function_table_tag function_table[] = {
01323    {"cop", function_cop},
01324    {"autopatchup", function_autopatchup},
01325    {"autopatchdn", function_autopatchdn},
01326    {"ilink", function_ilink},
01327    {"status", function_status},
01328    {"remote", function_remote},
01329    {"macro", function_macro},
01330    {"playback", function_playback}
01331 } ;
01332 
01333 static long diskavail(struct rpt *myrpt)
01334 {
01335 struct   statfs statfsbuf;
01336 
01337    if (!myrpt->p.archivedir) return(0);
01338    if (statfs(myrpt->p.archivedir,&statfsbuf) == -1)
01339    {
01340       ast_log(LOG_WARNING,"Cannot get filesystem size for %s node %s\n",
01341          myrpt->p.archivedir,myrpt->name);
01342       return(-1);
01343    }
01344    return(statfsbuf.f_bavail);
01345 }
01346 
01347 static void flush_telem(struct rpt *myrpt)
01348 {
01349    struct rpt_tele *telem;
01350    if(debug > 2)
01351       ast_log(LOG_NOTICE, "flush_telem()!!");
01352    rpt_mutex_lock(&myrpt->lock);
01353    telem = myrpt->tele.next;
01354    while(telem != &myrpt->tele)
01355    {
01356       if (telem->mode != SETREMOTE) ast_softhangup(telem->chan,AST_SOFTHANGUP_DEV);
01357       telem = telem->next;
01358    }
01359    rpt_mutex_unlock(&myrpt->lock);
01360 }
01361 /*
01362    return via error priority
01363 */
01364 static int priority_jump(struct rpt *myrpt, struct ast_channel *chan)
01365 {
01366    int res=0;
01367 
01368    // if (ast_test_flag(&flags,OPT_JUMP) && ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101) == 0){
01369    if (ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101) == 0){
01370       res = 0;
01371    } else {
01372       res = -1;
01373    }
01374    return res;
01375 }
01376 /*
01377 */
01378 static int linkcount(struct rpt *myrpt)
01379 {
01380    struct   rpt_link *l;
01381    char *reverse_patch_state;
01382    int numoflinks;
01383 
01384    reverse_patch_state = "DOWN";
01385    numoflinks = 0;
01386    l = myrpt->links.next;
01387    while(l && (l != &myrpt->links)){
01388       if(numoflinks >= MAX_STAT_LINKS){
01389          ast_log(LOG_WARNING,
01390          "maximum number of links exceeds %d in rpt_do_stats()!",MAX_STAT_LINKS);
01391          break;
01392       }
01393       //if (l->name[0] == '0'){ /* Skip '0' nodes */
01394       // reverse_patch_state = "UP";
01395       // l = l->next;
01396       // continue;
01397       //}
01398       numoflinks++;
01399     
01400       l = l->next;
01401    }
01402    ast_log(LOG_NOTICE, "numoflinks=%i\n",numoflinks);
01403    return numoflinks;
01404 }
01405 /*
01406  * Retrieve a memory channel
01407  * Return 0 if sucessful,
01408  * -1 if channel not found,
01409  *  1 if parse error
01410  */
01411 static int retreive_memory(struct rpt *myrpt, char *memory)
01412 {
01413    char tmp[30], *s, *s1, *val;
01414 
01415    if (debug)ast_log(LOG_NOTICE, "memory=%s block=%s\n",memory,myrpt->p.memory);
01416 
01417    val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.memory, memory);
01418    if (!val){
01419       return -1;
01420    }        
01421    strncpy(tmp,val,sizeof(tmp) - 1);
01422    tmp[sizeof(tmp)-1] = 0;
01423 
01424    s = strchr(tmp,',');
01425    if (!s)
01426       return 1; 
01427    *s++ = 0;
01428    s1 = strchr(s,',');
01429    if (!s1)
01430       return 1;
01431    *s1++ = 0;
01432    strncpy(myrpt->freq, tmp, sizeof(myrpt->freq) - 1);
01433    strncpy(myrpt->rxpl, s, sizeof(myrpt->rxpl) - 1);
01434    strncpy(myrpt->txpl, s, sizeof(myrpt->rxpl) - 1);
01435    myrpt->remmode = REM_MODE_FM;
01436    myrpt->offset = REM_SIMPLEX;
01437    myrpt->powerlevel = REM_MEDPWR;
01438    myrpt->txplon = myrpt->rxplon = 0;
01439    while(*s1){
01440       switch(*s1++){
01441          case 'A':
01442          case 'a':
01443             strcpy(myrpt->rxpl, "100.0");
01444             strcpy(myrpt->txpl, "100.0");
01445             myrpt->remmode = REM_MODE_AM; 
01446             break;
01447          case 'B':
01448          case 'b':
01449             strcpy(myrpt->rxpl, "100.0");
01450             strcpy(myrpt->txpl, "100.0");
01451             myrpt->remmode = REM_MODE_LSB;
01452             break;
01453          case 'F':
01454             myrpt->remmode = REM_MODE_FM;
01455             break;
01456          case 'L':
01457          case 'l':
01458             myrpt->powerlevel = REM_LOWPWR;
01459             break;               
01460          case 'H':
01461          case 'h':
01462             myrpt->powerlevel = REM_HIPWR;
01463             break;
01464                
01465          case 'M':
01466          case 'm':
01467             myrpt->powerlevel = REM_MEDPWR;
01468             break;
01469                   
01470          case '-':
01471             myrpt->offset = REM_MINUS;
01472             break;
01473                   
01474          case '+':
01475             myrpt->offset = REM_PLUS;
01476             break;
01477                   
01478          case 'S':
01479          case 's':
01480             myrpt->offset = REM_SIMPLEX;
01481             break;
01482                   
01483          case 'T':
01484          case 't':
01485             myrpt->txplon = 1;
01486             break;
01487                   
01488          case 'R':
01489          case 'r':
01490             myrpt->rxplon = 1;
01491             break;
01492 
01493          case 'U':
01494          case 'u':
01495             strcpy(myrpt->rxpl, "100.0");
01496             strcpy(myrpt->txpl, "100.0");
01497             myrpt->remmode = REM_MODE_USB;
01498             break;
01499          default:
01500             return 1;
01501       }
01502    }
01503    return 0;
01504 }
01505 /*
01506 
01507 */
01508 static void birdbath(struct rpt *myrpt)
01509 {
01510    struct rpt_tele *telem;
01511    if(debug > 2)
01512       ast_log(LOG_NOTICE, "birdbath!!");
01513    rpt_mutex_lock(&myrpt->lock);
01514    telem = myrpt->tele.next;
01515    while(telem != &myrpt->tele)
01516    {
01517       if (telem->mode == PARROT) ast_softhangup(telem->chan,AST_SOFTHANGUP_DEV);
01518       telem = telem->next;
01519    }
01520    rpt_mutex_unlock(&myrpt->lock);
01521 }
01522 
01523 static void do_dtmf_phone(struct rpt *myrpt, struct rpt_link *mylink, char c)
01524 {
01525 struct        rpt_link *l;
01526 
01527        l = myrpt->links.next;
01528        /* go thru all the links */
01529        while(l != &myrpt->links)
01530        {
01531                if (!l->phonemode)
01532                {
01533                        l = l->next;
01534                        continue;
01535                }
01536                /* don't send to self */
01537                if (mylink && (l == mylink))
01538                {
01539                        l = l->next;
01540                        continue;
01541                }
01542 #ifdef   NEW_ASTERISK
01543                if (l->chan) ast_senddigit(l->chan,c,0);
01544 #else
01545                if (l->chan) ast_senddigit(l->chan,c);
01546 #endif
01547                l = l->next;
01548        }
01549        return;
01550 }
01551 
01552 /* node logging function */
01553 static void donodelog(struct rpt *myrpt,char *str)
01554 {
01555 struct nodelog *nodep;
01556 char  datestr[100];
01557 
01558    if (!myrpt->p.archivedir) return;
01559    nodep = (struct nodelog *)ast_malloc(sizeof(struct nodelog));
01560    if (nodep == NULL)
01561    {
01562       ast_log(LOG_ERROR,"Cannot get memory for node log");
01563       return;
01564    }
01565    time(&nodep->timestamp);
01566    strncpy(nodep->archivedir,myrpt->p.archivedir,
01567       sizeof(nodep->archivedir) - 1);
01568    strftime(datestr,sizeof(datestr) - 1,"%Y%m%d%H%M%S",
01569       localtime(&nodep->timestamp));
01570    snprintf(nodep->str,sizeof(nodep->str) - 1,"%s %s,%s\n",
01571       myrpt->name,datestr,str);
01572    ast_mutex_lock(&nodeloglock);
01573    insque((struct qelem *) nodep, (struct qelem *) nodelog.prev);
01574    ast_mutex_unlock(&nodeloglock);
01575 }
01576 
01577 /* must be called locked */
01578 static void do_dtmf_local(struct rpt *myrpt, char c)
01579 {
01580 int   i;
01581 char  digit;
01582 static const char* dtmf_tones[] = {
01583    "!941+1336/200,!0/200", /* 0 */
01584    "!697+1209/200,!0/200", /* 1 */
01585    "!697+1336/200,!0/200", /* 2 */
01586    "!697+1477/200,!0/200", /* 3 */
01587    "!770+1209/200,!0/200", /* 4 */
01588    "!770+1336/200,!0/200", /* 5 */
01589    "!770+1477/200,!0/200", /* 6 */
01590    "!852+1209/200,!0/200", /* 7 */
01591    "!852+1336/200,!0/200", /* 8 */
01592    "!852+1477/200,!0/200", /* 9 */
01593    "!697+1633/200,!0/200", /* A */
01594    "!770+1633/200,!0/200", /* B */
01595    "!852+1633/200,!0/200", /* C */
01596    "!941+1633/200,!0/200", /* D */
01597    "!941+1209/200,!0/200", /* * */
01598    "!941+1477/200,!0/200" };  /* # */
01599 
01600 
01601    if (c)
01602    {
01603       snprintf(myrpt->dtmf_local_str + strlen(myrpt->dtmf_local_str),sizeof(myrpt->dtmf_local_str) - 1,"%c",c);
01604       if (!myrpt->dtmf_local_timer) 
01605           myrpt->dtmf_local_timer = DTMF_LOCAL_STARTTIME;
01606    }
01607    /* if at timeout */
01608    if (myrpt->dtmf_local_timer == 1)
01609    {
01610       if(debug > 6)
01611          ast_log(LOG_NOTICE,"time out dtmf_local_timer=%i\n",myrpt->dtmf_local_timer);
01612 
01613       /* if anything in the string */
01614       if (myrpt->dtmf_local_str[0])
01615       {
01616          digit = myrpt->dtmf_local_str[0];
01617          myrpt->dtmf_local_str[0] = 0;
01618          for(i = 1; myrpt->dtmf_local_str[i]; i++)
01619          {
01620             myrpt->dtmf_local_str[i - 1] =
01621                myrpt->dtmf_local_str[i];
01622          }
01623          myrpt->dtmf_local_str[i - 1] = 0;
01624          myrpt->dtmf_local_timer = DTMF_LOCAL_TIME;
01625          rpt_mutex_unlock(&myrpt->lock);
01626          if (digit >= '0' && digit <='9')
01627             ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[digit-'0'], 0);
01628          else if (digit >= 'A' && digit <= 'D')
01629             ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[digit-'A'+10], 0);
01630          else if (digit == '*')
01631             ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[14], 0);
01632          else if (digit == '#')
01633             ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[15], 0);
01634          else {
01635             /* not handled */
01636             ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, myrpt->txchannel->name);
01637          }
01638          rpt_mutex_lock(&myrpt->lock);
01639       }
01640       else
01641       {
01642          myrpt->dtmf_local_timer = 0;
01643       }
01644    }
01645 }
01646 
01647 static int setdtr(int fd, int enable)
01648 {
01649 struct termios mode;
01650 
01651    if (fd < 0) return -1;
01652    if (tcgetattr(fd, &mode)) {
01653       ast_log(LOG_WARNING, "Unable to get serial parameters for dtr: %s\n", strerror(errno));
01654       return -1;
01655    }
01656    if (enable)
01657    {
01658       cfsetspeed(&mode, B9600);
01659    }
01660    else
01661    {
01662       cfsetspeed(&mode, B0);
01663       usleep(100000);
01664    }
01665    if (tcsetattr(fd, TCSADRAIN, &mode)) {
01666       ast_log(LOG_WARNING, "Unable to set serial parameters for dtr: %s\n", strerror(errno));
01667       return -1;
01668    }
01669    if (enable) usleep(100000);
01670    return 0;
01671 }
01672 
01673 static int openserial(struct rpt *myrpt,char *fname)
01674 {
01675    struct termios mode;
01676    int fd;
01677 
01678    fd = open(fname,O_RDWR);
01679    if (fd == -1)
01680    {
01681       ast_log(LOG_WARNING,"Cannot open serial port %s\n",fname);
01682       return -1;
01683    }
01684    memset(&mode, 0, sizeof(mode));
01685    if (tcgetattr(fd, &mode)) {
01686       ast_log(LOG_WARNING, "Unable to get serial parameters on %s: %s\n", fname, strerror(errno));
01687       return -1;
01688    }
01689 #ifndef  SOLARIS
01690    cfmakeraw(&mode);
01691 #else
01692         mode.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
01693                         |INLCR|IGNCR|ICRNL|IXON);
01694         mode.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
01695         mode.c_cflag &= ~(CSIZE|PARENB|CRTSCTS);
01696         mode.c_cflag |= CS8;
01697    mode.c_cc[VTIME] = 3;
01698    mode.c_cc[VMIN] = 1; 
01699 #endif
01700 
01701    cfsetispeed(&mode, B9600);
01702    cfsetospeed(&mode, B9600);
01703    if (tcsetattr(fd, TCSANOW, &mode)) 
01704       ast_log(LOG_WARNING, "Unable to set serial parameters on %s: %s\n", fname, strerror(errno));
01705    if(!strcmp(myrpt->remoterig, remote_rig_kenwood)) setdtr(fd,0); 
01706    usleep(100000);
01707    if (debug)ast_log(LOG_NOTICE,"Opened serial port %s\n",fname);
01708    return(fd); 
01709 }
01710 
01711 static void mdc1200_notify(struct rpt *myrpt,char *fromnode, unsigned int unit)
01712 {
01713    if (!fromnode)
01714    {
01715       ast_verbose("Got MDC-1200 ID %04X from local system (%s)\n",
01716          unit,myrpt->name);
01717    }
01718    else
01719    {
01720       ast_verbose("Got MDC-1200 ID %04X from node %s (%s)\n",
01721          unit,fromnode,myrpt->name);
01722    }
01723 }
01724 
01725 #ifdef   _MDC_DECODE_H_
01726 
01727 static void mdc1200_send(struct rpt *myrpt, unsigned int unit)
01728 {
01729 struct rpt_link *l;
01730 struct   ast_frame wf;
01731 char  str[200];
01732 
01733 
01734    sprintf(str,"I %s %04X",myrpt->name,unit);
01735 
01736    wf.frametype = AST_FRAME_TEXT;
01737    wf.subclass.integer = 0;
01738    wf.offset = 0;
01739    wf.mallocd = 0;
01740    wf.datalen = strlen(str) + 1;
01741    wf.samples = 0;
01742 
01743 
01744    l = myrpt->links.next;
01745    /* otherwise, send it to all of em */
01746    while(l != &myrpt->links)
01747    {
01748       if (l->name[0] == '0') 
01749       {
01750          l = l->next;
01751          continue;
01752       }
01753       wf.data = str;
01754       if (l->chan) ast_write(l->chan,&wf); 
01755       l = l->next;
01756    }
01757    return;
01758 }
01759 
01760 #endif
01761 
01762 static char func_xlat(struct rpt *myrpt,char c,struct rpt_xlat *xlat)
01763 {
01764 time_t   now;
01765 int   gotone;
01766 
01767    time(&now);
01768    gotone = 0;
01769    /* if too much time, reset the skate machine */
01770    if ((now - xlat->lastone) > MAXXLATTIME)
01771    {
01772       xlat->funcindex = xlat->endindex = 0;
01773    }
01774    if (xlat->funccharseq[0] && (c == xlat->funccharseq[xlat->funcindex++]))
01775    {
01776       time(&xlat->lastone);
01777       gotone = 1;
01778       if (!xlat->funccharseq[xlat->funcindex])
01779       {
01780          xlat->funcindex = xlat->endindex = 0;
01781          return(myrpt->p.funcchar);
01782       }
01783    } else xlat->funcindex = 0;
01784    if (xlat->endcharseq[0] && (c == xlat->endcharseq[xlat->endindex++]))
01785    {
01786       time(&xlat->lastone);
01787       gotone = 1;
01788       if (!xlat->endcharseq[xlat->endindex])
01789       {
01790          xlat->funcindex = xlat->endindex = 0;
01791          return(myrpt->p.endchar);
01792       }
01793    } else xlat->endindex = 0;
01794    /* if in middle of decode seq, send nothing back */
01795    if (gotone) return(0);
01796    /* if no pass chars specified, return em all */
01797    if (!xlat->passchars[0]) return(c);
01798    /* if a "pass char", pass it */
01799    if (strchr(xlat->passchars,c)) return(c);
01800    return(0);
01801 }
01802 
01803 /*
01804  * Return a pointer to the first non-whitespace character
01805  */
01806 
01807 static char *eatwhite(char *s)
01808 {
01809    while((*s == ' ') || (*s == 0x09)){ /* get rid of any leading white space */
01810       if(!*s)
01811          break;
01812       s++;
01813    }
01814    return s;
01815 }
01816 
01817 /*
01818 * Break up a delimited string into a table of substrings
01819 *
01820 * str - delimited string ( will be modified )
01821 * strp- list of pointers to substrings (this is built by this function), NULL will be placed at end of list
01822 * limit- maximum number of substrings to process
01823 */
01824    
01825 
01826 
01827 static int finddelim(char *str, char *strp[], int limit)
01828 {
01829 int     i,l,inquo;
01830 
01831         inquo = 0;
01832         i = 0;
01833         strp[i++] = str;
01834         if (!*str)
01835            {
01836                 strp[0] = 0;
01837                 return(0);
01838            }
01839         for(l = 0; *str && (l < limit) ; str++)
01840            {
01841                 if (*str == QUOTECHR)
01842                    {
01843                         if (inquo)
01844                            {
01845                                 *str = 0;
01846                                 inquo = 0;
01847                            }
01848                         else
01849                            {
01850                                 strp[i - 1] = str + 1;
01851                                 inquo = 1;
01852                            }
01853       }
01854                 if ((*str == DELIMCHR) && (!inquo))
01855                 {
01856                         *str = 0;
01857          l++;
01858                         strp[i++] = str + 1;
01859                 }
01860            }
01861         strp[i] = 0;
01862         return(i);
01863 
01864 }
01865 /*
01866    send asterisk frame text message on the current tx channel
01867 */
01868 static int send_usb_txt(struct rpt *myrpt, char *txt) 
01869 {
01870    struct ast_frame wf;
01871  
01872    if (debug)ast_log(LOG_NOTICE, "send_usb_txt %s\n",txt);
01873    wf.frametype = AST_FRAME_TEXT;
01874    wf.subclass.integer = 0;
01875    wf.offset = 0;
01876    wf.mallocd = 0;
01877    wf.datalen = strlen(txt) + 1;
01878    wf.data.ptr = txt;
01879    wf.samples = 0;
01880    ast_write(myrpt->txchannel,&wf); 
01881    return 0;
01882 }
01883 /* must be called locked */
01884 static void __mklinklist(struct rpt *myrpt, struct rpt_link *mylink, char *buf)
01885 {
01886 struct rpt_link *l;
01887 char mode;
01888 int   i,spos;
01889 
01890    buf[0] = 0; /* clear output buffer */
01891    if (myrpt->remote) return;
01892    /* go thru all links */
01893    for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
01894    {
01895       /* if is not a real link, ignore it */
01896       if (l->name[0] == '0') continue;
01897       /* don't count our stuff */
01898       if (l == mylink) continue;
01899       if (mylink && (!strcmp(l->name,mylink->name))) continue;
01900       /* figure out mode to report */
01901       mode = 'T'; /* use Tranceive by default */
01902       if (!l->mode) mode = 'R'; /* indicate RX for our mode */
01903       if (!l->thisconnected)  mode = 'C'; /* indicate connecting */
01904       spos = strlen(buf); /* current buf size (b4 we add our stuff) */
01905       if (spos)
01906       {
01907          strcat(buf,",");
01908          spos++;
01909       }
01910       /* add nodes into buffer */
01911       if (l->linklist[0])
01912       {
01913          snprintf(buf + spos,MAXLINKLIST - spos,
01914             "%c%s,%s",mode,l->name,l->linklist);
01915       }
01916       else /* if no nodes, add this node into buffer */
01917       {
01918          snprintf(buf + spos,MAXLINKLIST - spos,
01919             "%c%s",mode,l->name);
01920       }
01921       /* if we are in tranceive mode, let all modes stand */
01922       if (mode == 'T') continue;
01923       /* downgrade everyone on this node if appropriate */
01924       for(i = spos; buf[i]; i++)
01925       {
01926          if (buf[i] == 'T') buf[i] = mode;
01927          if ((buf[i] == 'R') && (mode == 'C')) buf[i] = mode;
01928       }
01929    }
01930    return;
01931 }
01932 
01933 /* must be called locked */
01934 static void __kickshort(struct rpt *myrpt)
01935 {
01936 struct rpt_link *l;
01937 
01938    for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
01939    {
01940       /* if is not a real link, ignore it */
01941       if (l->name[0] == '0') continue;
01942       l->linklisttimer = LINKLISTSHORTTIME;
01943    }
01944    myrpt->linkposttimer = LINKPOSTSHORTTIME;
01945    return;
01946 }
01947 
01948 static void statpost(struct rpt *myrpt,char *pairs)
01949 {
01950 char *str,*astr;
01951 char *astrs[100];
01952 int   n,pid;
01953 time_t   now;
01954 unsigned int seq;
01955 
01956    if (!myrpt->p.statpost_url) return;
01957    str = ast_malloc(strlen(pairs) + strlen(myrpt->p.statpost_url) + 200);
01958    astr = ast_strdup(myrpt->p.statpost_program);
01959    if ((!str) || (!astr)) {
01960       ast_free(str);
01961       ast_free(astr);
01962       return;
01963    }
01964    n = finddelim(astr,astrs,100);
01965    if (n < 1) return;
01966    ast_mutex_lock(&myrpt->statpost_lock);
01967    seq = ++myrpt->statpost_seqno;
01968    ast_mutex_unlock(&myrpt->statpost_lock);
01969    astrs[n++] = str;
01970    astrs[n] = NULL;
01971    time(&now);
01972    sprintf(str,"%s?node=%s&time=%u&seqno=%u",myrpt->p.statpost_url,
01973       myrpt->name,(unsigned int) now,seq);
01974    if (pairs) sprintf(str + strlen(str),"&%s",pairs);
01975    if (!(pid = ast_safe_fork(0)))
01976    {
01977       execv(astrs[0],astrs);
01978       ast_log(LOG_ERROR, "exec of %s failed.\n", astrs[0]);
01979       perror("asterisk");
01980       exit(0);
01981    }
01982    ast_free(astr);
01983    ast_free(str);
01984    return;
01985 }
01986 
01987 static char *node_lookup(struct rpt *myrpt,char *digitbuf)
01988 {
01989 
01990 char *val;
01991 int longestnode,j;
01992 struct stat mystat;
01993 static time_t last = 0;
01994 static struct ast_config *ourcfg = NULL;
01995 struct ast_variable *vp;
01996 
01997    /* try to look it up locally first */
01998    val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.nodes, digitbuf);
01999    if (val) return(val);
02000    ast_mutex_lock(&nodelookuplock);
02001    /* if file does not exist */
02002    if (stat(myrpt->p.extnodefile,&mystat) == -1)
02003    {
02004       if (ourcfg) ast_config_destroy(ourcfg);
02005       ourcfg = NULL;
02006       ast_mutex_unlock(&nodelookuplock);
02007       return(NULL);
02008    }
02009    /* if we need to reload */
02010    if (mystat.st_mtime > last)
02011    {
02012       if (ourcfg) ast_config_destroy(ourcfg);
02013 #ifdef   NEW_ASTERISK
02014       ourcfg = ast_config_load(myrpt->p.extnodefile,config_flags);
02015 #else
02016       ourcfg = ast_config_load(myrpt->p.extnodefile);
02017 #endif
02018       /* if file not there, just bail */
02019       if (!ourcfg || ourcfg == CONFIG_STATUS_FILEINVALID)
02020       {
02021          ast_mutex_unlock(&nodelookuplock);
02022          return(NULL);
02023       }
02024       /* reset "last" time */
02025       last = mystat.st_mtime;
02026 
02027       /* determine longest node length again */    
02028       longestnode = 0;
02029       vp = ast_variable_browse(myrpt->cfg, myrpt->p.nodes);
02030       while(vp){
02031          j = strlen(vp->name);
02032          if (j > longestnode)
02033             longestnode = j;
02034          vp = vp->next;
02035       }
02036 
02037       vp = ast_variable_browse(ourcfg, myrpt->p.extnodes);
02038       while(vp){
02039          j = strlen(vp->name);
02040          if (j > longestnode)
02041             longestnode = j;
02042          vp = vp->next;
02043       }
02044 
02045       myrpt->longestnode = longestnode;
02046    }
02047    val = NULL;
02048    if (ourcfg)
02049       val = (char *) ast_variable_retrieve(ourcfg, myrpt->p.extnodes, digitbuf);
02050    ast_mutex_unlock(&nodelookuplock);
02051    return(val);
02052 }
02053 
02054 /*
02055 * Match a keyword in a list, and return index of string plus 1 if there was a match,* else return 0.
02056 * If param is passed in non-null, then it will be set to the first character past the match
02057 */
02058 
02059 static int matchkeyword(char *string, char **param, char *keywords[])
02060 {
02061 int   i,ls;
02062    for( i = 0 ; keywords[i] ; i++){
02063       ls = strlen(keywords[i]);
02064       if(!ls){
02065          *param = NULL;
02066          return 0;
02067       }
02068       if(!strncmp(string, keywords[i], ls)){
02069          if(param)
02070             *param = string + ls;
02071          return i + 1; 
02072       }
02073    }
02074    *param = NULL;
02075    return 0;
02076 }
02077 
02078 /*
02079 * Skip characters in string which are in charlist, and return a pointer to the
02080 * first non-matching character
02081 */
02082 
02083 static char *skipchars(char *string, char *charlist)
02084 {
02085 int i;   
02086    while(*string){
02087       for(i = 0; charlist[i] ; i++){
02088          if(*string == charlist[i]){
02089             string++;
02090             break;
02091          }
02092       }
02093       if(!charlist[i])
02094          return string;
02095    }
02096    return string;
02097 }
02098 
02099 static int myatoi(const char *str)
02100 {
02101    int   ret;
02102 
02103    if (!str) {
02104       return -1;
02105    }
02106 
02107    /* leave this %i alone, non-base-10 input is useful here */
02108    if (sscanf(str, "%30i", &ret) != 1) {
02109       return -1;
02110    }
02111 
02112    return ret;
02113 }
02114 
02115 static int mycompar(const void *a, const void *b)
02116 {
02117 char  **x = (char **) a;
02118 char  **y = (char **) b;
02119 int   xoff,yoff;
02120 
02121    if ((**x < '0') || (**x > '9')) xoff = 1; else xoff = 0;
02122    if ((**y < '0') || (**y > '9')) yoff = 1; else yoff = 0;
02123    return(strcmp((*x) + xoff,(*y) + yoff));
02124 }
02125 
02126 static int topcompar(const void *a, const void *b)
02127 {
02128 struct rpt_topkey *x = (struct rpt_topkey *) a;
02129 struct rpt_topkey *y = (struct rpt_topkey *) b;
02130 
02131    return(x->timesince - y->timesince);
02132 }
02133 
02134 #ifdef   __RPT_NOTCH
02135 
02136 /* rpt filter routine */
02137 static void rpt_filter(struct rpt *myrpt, volatile short *buf, int len)
02138 {
02139 int   i,j;
02140 struct   rptfilter *f;
02141 
02142    for(i = 0; i < len; i++)
02143    {
02144       for(j = 0; j < MAXFILTERS; j++)
02145       {
02146          f = &myrpt->filters[j];
02147          if (!*f->desc) continue;
02148          f->x0 = f->x1; f->x1 = f->x2;
02149               f->x2 = ((float)buf[i]) / f->gain;
02150               f->y0 = f->y1; f->y1 = f->y2;
02151               f->y2 =   (f->x0 + f->x2) +   f->const0 * f->x1
02152                            + (f->const1 * f->y0) + (f->const2 * f->y1);
02153          buf[i] = (short)f->y2;
02154       }
02155    }
02156 }
02157 
02158 #endif
02159 
02160 
02161 /*
02162  Get the time for the machine's time zone
02163  Note: Asterisk requires a copy of localtime
02164  in the /etc directory for this to work properly.
02165  If /etc/localtime is not present, you will get
02166  GMT time! This is especially important on systems
02167  running embedded linux distributions as they don't usually
02168  have support for locales. 
02169 
02170  If OLD_ASTERISK is defined, then the older localtime_r
02171  function will be used. The /etc/localtime file is not
02172  required in this case. This provides backward compatibility
02173  with Asterisk 1.2 systems.
02174 
02175 */
02176 
02177 #ifdef   NEW_ASTERISK
02178 static void rpt_localtime( time_t * t, struct ast_tm *lt)
02179 {
02180    struct timeval when;
02181 
02182    when.tv_sec = *t;
02183    when.tv_usec = 0;
02184    ast_localtime(&when, lt, NULL);
02185 }
02186 
02187 #else
02188 static void rpt_localtime( time_t * t, struct tm *lt)
02189 {
02190 #ifdef OLD_ASTERISK
02191    localtime_r(t, lt);
02192 #else
02193    ast_localtime(t, lt, NULL);
02194 #endif
02195 }
02196 #endif
02197 
02198 
02199 /* Retrieve an int from a config file */
02200                                                                                 
02201 static int retrieve_astcfgint(struct rpt *myrpt,char *category, char *name, int min, int max, int defl)
02202 {
02203         char *var;
02204         int ret;
02205    char include_zero = 0;
02206 
02207    if(min < 0){ /* If min is negative, this means include 0 as a valid entry */
02208       min = -min;
02209       include_zero = 1;
02210    }           
02211                                                                      
02212         var = (char *) ast_variable_retrieve(myrpt->cfg, category, name);
02213         if(var){
02214                 ret = myatoi(var);
02215       if(include_zero && !ret)
02216          return 0;
02217                 if(ret < min)
02218                         ret = min;
02219                 if(ret > max)
02220                         ret = max;
02221         }
02222         else
02223                 ret = defl;
02224         return ret;
02225 }
02226 
02227 
02228 static void load_rpt_vars(int n,int init)
02229 {
02230 char *this,*val;
02231 int   i,j,longestnode;
02232 struct ast_variable *vp;
02233 struct ast_config *cfg;
02234 char *strs[100];
02235 char s1[256];
02236 static char *cs_keywords[] = {"rptena","rptdis","apena","apdis","lnkena","lnkdis","totena","totdis","skena","skdis",
02237             "ufena","ufdis","atena","atdis",NULL};
02238 
02239    if (option_verbose > 2)
02240       ast_verbose(VERBOSE_PREFIX_3 "%s config for repeater %s\n",
02241          (init) ? "Loading initial" : "Re-Loading",rpt_vars[n].name);
02242    ast_mutex_lock(&rpt_vars[n].lock);
02243    if (rpt_vars[n].cfg) ast_config_destroy(rpt_vars[n].cfg);
02244 #ifdef   NEW_ASTERISK
02245    cfg = ast_config_load("rpt.conf",config_flags);
02246 #else
02247    cfg = ast_config_load("rpt.conf");
02248 #endif
02249    if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
02250       ast_mutex_unlock(&rpt_vars[n].lock);
02251       ast_log(LOG_NOTICE, "Unable to open radio repeater configuration rpt.conf.  Radio Repeater disabled.\n");
02252       pthread_exit(NULL);
02253    }
02254    rpt_vars[n].cfg = cfg; 
02255    this = rpt_vars[n].name;
02256    memset(&rpt_vars[n].p,0,sizeof(rpt_vars[n].p));
02257    if (init)
02258    {
02259       char *cp;
02260       int savearea = (char *)&rpt_vars[n].p - (char *)&rpt_vars[n];
02261 
02262       cp = (char *) &rpt_vars[n].p;
02263       memset(cp + sizeof(rpt_vars[n].p),0,
02264          sizeof(rpt_vars[n]) - (sizeof(rpt_vars[n].p) + savearea));
02265       rpt_vars[n].tele.next = &rpt_vars[n].tele;
02266       rpt_vars[n].tele.prev = &rpt_vars[n].tele;
02267       rpt_vars[n].rpt_thread = AST_PTHREADT_NULL;
02268       rpt_vars[n].tailmessagen = 0;
02269    }
02270 #ifdef   __RPT_NOTCH
02271    /* zot out filters stuff */
02272    memset(&rpt_vars[n].filters,0,sizeof(rpt_vars[n].filters));
02273 #endif
02274    val = (char *) ast_variable_retrieve(cfg,this,"context");
02275    if (val) rpt_vars[n].p.ourcontext = val;
02276    else rpt_vars[n].p.ourcontext = this;
02277    val = (char *) ast_variable_retrieve(cfg,this,"callerid");
02278    if (val) rpt_vars[n].p.ourcallerid = val;
02279    val = (char *) ast_variable_retrieve(cfg,this,"accountcode");
02280    if (val) rpt_vars[n].p.acctcode = val;
02281    val = (char *) ast_variable_retrieve(cfg,this,"idrecording");
02282    if (val) rpt_vars[n].p.ident = val;
02283    val = (char *) ast_variable_retrieve(cfg,this,"hangtime");
02284    if (val) rpt_vars[n].p.hangtime = atoi(val);
02285       else rpt_vars[n].p.hangtime = HANGTIME;
02286    val = (char *) ast_variable_retrieve(cfg,this,"althangtime");
02287    if (val) rpt_vars[n].p.althangtime = atoi(val);
02288       else rpt_vars[n].p.althangtime = HANGTIME;
02289    val = (char *) ast_variable_retrieve(cfg,this,"totime");
02290    if (val) rpt_vars[n].p.totime = atoi(val);
02291       else rpt_vars[n].p.totime = TOTIME;
02292    val = (char *) ast_variable_retrieve(cfg,this,"voxtimeout");
02293    if (val) rpt_vars[n].p.voxtimeout_ms = atoi(val);
02294       else rpt_vars[n].p.voxtimeout_ms = VOX_TIMEOUT_MS;
02295    val = (char *) ast_variable_retrieve(cfg,this,"voxrecover");
02296    if (val) rpt_vars[n].p.voxrecover_ms = atoi(val);
02297       else rpt_vars[n].p.voxrecover_ms = VOX_RECOVER_MS;
02298    val = (char *) ast_variable_retrieve(cfg,this,"simplexpatchdelay");
02299    if (val) rpt_vars[n].p.simplexpatchdelay = atoi(val);
02300       else rpt_vars[n].p.simplexpatchdelay = SIMPLEX_PATCH_DELAY;
02301    val = (char *) ast_variable_retrieve(cfg,this,"simplexphonedelay");
02302    if (val) rpt_vars[n].p.simplexphonedelay = atoi(val);
02303       else rpt_vars[n].p.simplexphonedelay = SIMPLEX_PHONE_DELAY;
02304    val = (char *) ast_variable_retrieve(cfg,this,"statpost_program");
02305    if (val) rpt_vars[n].p.statpost_program = val;
02306       else rpt_vars[n].p.statpost_program = STATPOST_PROGRAM;
02307    rpt_vars[n].p.statpost_url = 
02308       (char *) ast_variable_retrieve(cfg,this,"statpost_url");
02309    rpt_vars[n].p.tailmessagetime = retrieve_astcfgint(&rpt_vars[n],this, "tailmessagetime", 0, 2400000, 0);    
02310    rpt_vars[n].p.tailsquashedtime = retrieve_astcfgint(&rpt_vars[n],this, "tailsquashedtime", 0, 2400000, 0);     
02311    rpt_vars[n].p.duplex = retrieve_astcfgint(&rpt_vars[n],this,"duplex",0,4,2);
02312    rpt_vars[n].p.idtime = retrieve_astcfgint(&rpt_vars[n],this, "idtime", -60000, 2400000, IDTIME);   /* Enforce a min max including zero */
02313    rpt_vars[n].p.politeid = retrieve_astcfgint(&rpt_vars[n],this, "politeid", 30000, 300000, POLITEID); /* Enforce a min max */
02314    val = (char *) ast_variable_retrieve(cfg,this,"tonezone");
02315    if (val) rpt_vars[n].p.tonezone = val;
02316    rpt_vars[n].p.tailmessages[0] = 0;
02317    rpt_vars[n].p.tailmessagemax = 0;
02318    val = (char *) ast_variable_retrieve(cfg,this,"tailmessagelist");
02319    if (val) rpt_vars[n].p.tailmessagemax = finddelim(val, rpt_vars[n].p.tailmessages, 500);
02320    val = (char *) ast_variable_retrieve(cfg,this,"memory");
02321    if (!val) val = MEMORY;
02322    rpt_vars[n].p.memory = val;
02323    val = (char *) ast_variable_retrieve(cfg,this,"macro");
02324    if (!val) val = MACRO;
02325    rpt_vars[n].p.macro = val;
02326    val = (char *) ast_variable_retrieve(cfg,this,"tonemacro");
02327    if (!val) val = TONEMACRO;
02328    rpt_vars[n].p.tonemacro = val;
02329    val = (char *) ast_variable_retrieve(cfg,this,"startup_macro");
02330    if (val) rpt_vars[n].p.startupmacro = val;
02331    val = (char *) ast_variable_retrieve(cfg,this,"iobase");
02332    /* do not use atoi() here, we need to be able to have
02333       the input specified in hex or decimal so we use
02334       sscanf with a %i */
02335    if ((!val) || (sscanf(val,"%30i",&rpt_vars[n].p.iobase) != 1))
02336       rpt_vars[n].p.iobase = DEFAULT_IOBASE;
02337    val = (char *) ast_variable_retrieve(cfg,this,"ioport");
02338    rpt_vars[n].p.ioport = val;
02339    val = (char *) ast_variable_retrieve(cfg,this,"functions");
02340    if (!val)
02341       {
02342          val = FUNCTIONS;
02343          rpt_vars[n].p.simple = 1;
02344       } 
02345    rpt_vars[n].p.functions = val;
02346    val =  (char *) ast_variable_retrieve(cfg,this,"link_functions");
02347    if (val) rpt_vars[n].p.link_functions = val;
02348    else 
02349       rpt_vars[n].p.link_functions = rpt_vars[n].p.functions;
02350    val = (char *) ast_variable_retrieve(cfg,this,"phone_functions");
02351    if (val) rpt_vars[n].p.phone_functions = val;
02352    val = (char *) ast_variable_retrieve(cfg,this,"dphone_functions");
02353    if (val) rpt_vars[n].p.dphone_functions = val;
02354    val = (char *) ast_variable_retrieve(cfg,this,"alt_functions");
02355    if (val) rpt_vars[n].p.alt_functions = val;
02356    val = (char *) ast_variable_retrieve(cfg,this,"funcchar");
02357    if (!val) rpt_vars[n].p.funcchar = FUNCCHAR; else 
02358       rpt_vars[n].p.funcchar = *val;      
02359    val = (char *) ast_variable_retrieve(cfg,this,"endchar");
02360    if (!val) rpt_vars[n].p.endchar = ENDCHAR; else 
02361       rpt_vars[n].p.endchar = *val;    
02362    val = (char *) ast_variable_retrieve(cfg,this,"nobusyout");
02363    if (val) rpt_vars[n].p.nobusyout = ast_true(val);
02364    val = (char *) ast_variable_retrieve(cfg,this,"notelemtx");
02365    if (val) rpt_vars[n].p.notelemtx = ast_true(val);
02366    val = (char *) ast_variable_retrieve(cfg,this,"propagate_dtmf");
02367    if (val) rpt_vars[n].p.propagate_dtmf = ast_true(val);
02368    val = (char *) ast_variable_retrieve(cfg,this,"propagate_phonedtmf");
02369    if (val) rpt_vars[n].p.propagate_phonedtmf = ast_true(val);
02370    val = (char *) ast_variable_retrieve(cfg,this,"linktolink");
02371    if (val) rpt_vars[n].p.linktolink = ast_true(val);
02372    val = (char *) ast_variable_retrieve(cfg,this,"nodes");
02373    if (!val) val = NODES;
02374    rpt_vars[n].p.nodes = val;
02375    val = (char *) ast_variable_retrieve(cfg,this,"extnodes");
02376    if (!val) val = EXTNODES;
02377    rpt_vars[n].p.extnodes = val;
02378    val = (char *) ast_variable_retrieve(cfg,this,"extnodefile");
02379    if (!val) val = EXTNODEFILE;
02380    rpt_vars[n].p.extnodefile = val;
02381    val = (char *) ast_variable_retrieve(cfg,this,"archivedir");
02382    if (val) rpt_vars[n].p.archivedir = val;
02383    val = (char *) ast_variable_retrieve(cfg,this,"authlevel");
02384    if (val) rpt_vars[n].p.authlevel = atoi(val); 
02385    else rpt_vars[n].p.authlevel = 0;
02386    val = (char *) ast_variable_retrieve(cfg,this,"parrot");
02387    if (val) rpt_vars[n].p.parrotmode = ast_true(val) * 2;
02388    else rpt_vars[n].p.parrotmode = 0;
02389    val = (char *) ast_variable_retrieve(cfg,this,"parrottime");
02390    if (val) rpt_vars[n].p.parrottime = atoi(val); 
02391    else rpt_vars[n].p.parrottime = PARROTTIME;
02392    val = (char *) ast_variable_retrieve(cfg,this,"rptnode");
02393    rpt_vars[n].p.rptnode = val;
02394    val = (char *) ast_variable_retrieve(cfg,this,"mars");
02395    if (val) rpt_vars[n].p.remote_mars = atoi(val); 
02396    else rpt_vars[n].p.remote_mars = 0;
02397    val = (char *) ast_variable_retrieve(cfg,this,"monminblocks");
02398    if (val) rpt_vars[n].p.monminblocks = atol(val); 
02399    else rpt_vars[n].p.monminblocks = DEFAULT_MONITOR_MIN_DISK_BLOCKS;
02400    val = (char *) ast_variable_retrieve(cfg,this,"remote_inact_timeout");
02401    if (val) rpt_vars[n].p.remoteinacttimeout = atoi(val); 
02402    else rpt_vars[n].p.remoteinacttimeout = DEFAULT_REMOTE_INACT_TIMEOUT;
02403    val = (char *) ast_variable_retrieve(cfg,this,"civaddr");
02404    if (val) rpt_vars[n].p.civaddr = atoi(val); 
02405    else rpt_vars[n].p.civaddr = DEFAULT_CIV_ADDR;
02406    val = (char *) ast_variable_retrieve(cfg,this,"remote_timeout");
02407    if (val) rpt_vars[n].p.remotetimeout = atoi(val); 
02408    else rpt_vars[n].p.remotetimeout = DEFAULT_REMOTE_TIMEOUT;
02409    val = (char *) ast_variable_retrieve(cfg,this,"remote_timeout_warning");
02410    if (val) rpt_vars[n].p.remotetimeoutwarning = atoi(val); 
02411    else rpt_vars[n].p.remotetimeoutwarning = DEFAULT_REMOTE_TIMEOUT_WARNING;
02412    val = (char *) ast_variable_retrieve(cfg,this,"remote_timeout_warning_freq");
02413    if (val) rpt_vars[n].p.remotetimeoutwarningfreq = atoi(val); 
02414    else rpt_vars[n].p.remotetimeoutwarningfreq = DEFAULT_REMOTE_TIMEOUT_WARNING_FREQ;
02415 #ifdef   __RPT_NOTCH
02416    val = (char *) ast_variable_retrieve(cfg,this,"rxnotch");
02417    if (val) {
02418       i = finddelim(val,strs,MAXFILTERS * 2);
02419       i &= ~1; /* force an even number, rounded down */
02420       if (i >= 2) for(j = 0; j < i; j += 2)
02421       {
02422          rpt_mknotch(atof(strs[j]),atof(strs[j + 1]),
02423            &rpt_vars[n].filters[j >> 1].gain,
02424              &rpt_vars[n].filters[j >> 1].const0,
02425             &rpt_vars[n].filters[j >> 1].const1,
02426                 &rpt_vars[n].filters[j >> 1].const2);
02427          sprintf(rpt_vars[n].filters[j >> 1].desc,"%s Hz, BW = %s",
02428             strs[j],strs[j + 1]);
02429       }
02430 
02431    }
02432 #endif
02433    val = (char *) ast_variable_retrieve(cfg,this,"inxlat");
02434    if (val) {
02435       memset(&rpt_vars[n].p.inxlat,0,sizeof(struct rpt_xlat));
02436       i = finddelim(val,strs,3);
02437       if (i) strncpy(rpt_vars[n].p.inxlat.funccharseq,strs[0],MAXXLAT - 1);
02438       if (i > 1) strncpy(rpt_vars[n].p.inxlat.endcharseq,strs[1],MAXXLAT - 1);
02439       if (i > 2) strncpy(rpt_vars[n].p.inxlat.passchars,strs[2],MAXXLAT - 1);
02440    }
02441    val = (char *) ast_variable_retrieve(cfg,this,"outxlat");
02442    if (val) {
02443       memset(&rpt_vars[n].p.outxlat,0,sizeof(struct rpt_xlat));
02444       i = finddelim(val,strs,3);
02445       if (i) strncpy(rpt_vars[n].p.outxlat.funccharseq,strs[0],MAXXLAT - 1);
02446       if (i > 1) strncpy(rpt_vars[n].p.outxlat.endcharseq,strs[1],MAXXLAT - 1);
02447       if (i > 2) strncpy(rpt_vars[n].p.outxlat.passchars,strs[2],MAXXLAT - 1);
02448    }
02449    /* retreive the stanza name for the control states if there is one */
02450    val = (char *) ast_variable_retrieve(cfg,this,"controlstates");
02451    rpt_vars[n].p.csstanzaname = val;
02452       
02453    /* retreive the stanza name for the scheduler if there is one */
02454    val = (char *) ast_variable_retrieve(cfg,this,"scheduler");
02455    rpt_vars[n].p.skedstanzaname = val;
02456 
02457    /* retreive the stanza name for the txlimits */
02458    val = (char *) ast_variable_retrieve(cfg,this,"txlimits");
02459    rpt_vars[n].p.txlimitsstanzaname = val;
02460 
02461    longestnode = 0;
02462 
02463    vp = ast_variable_browse(cfg, rpt_vars[n].p.nodes);
02464       
02465    while(vp){
02466       j = strlen(vp->name);
02467       if (j > longestnode)
02468          longestnode = j;
02469       vp = vp->next;
02470    }
02471 
02472    rpt_vars[n].longestnode = longestnode;
02473       
02474    /*
02475    * For this repeater, Determine the length of the longest function 
02476    */
02477    rpt_vars[n].longestfunc = 0;
02478    vp = ast_variable_browse(cfg, rpt_vars[n].p.functions);
02479    while(vp){
02480       j = strlen(vp->name);
02481       if (j > rpt_vars[n].longestfunc)
02482          rpt_vars[n].longestfunc = j;
02483       vp = vp->next;
02484    }
02485    /*
02486    * For this repeater, Determine the length of the longest function 
02487    */
02488    rpt_vars[n].link_longestfunc = 0;
02489    vp = ast_variable_browse(cfg, rpt_vars[n].p.link_functions);
02490    while(vp){
02491       j = strlen(vp->name);
02492       if (j > rpt_vars[n].link_longestfunc)
02493          rpt_vars[n].link_longestfunc = j;
02494       vp = vp->next;
02495    }
02496    rpt_vars[n].phone_longestfunc = 0;
02497    if (rpt_vars[n].p.phone_functions)
02498    {
02499       vp = ast_variable_browse(cfg, rpt_vars[n].p.phone_functions);
02500       while(vp){
02501          j = strlen(vp->name);
02502          if (j > rpt_vars[n].phone_longestfunc)
02503             rpt_vars[n].phone_longestfunc = j;
02504          vp = vp->next;
02505       }
02506    }
02507    rpt_vars[n].dphone_longestfunc = 0;
02508    if (rpt_vars[n].p.dphone_functions)
02509    {
02510       vp = ast_variable_browse(cfg, rpt_vars[n].p.dphone_functions);
02511       while(vp){
02512          j = strlen(vp->name);
02513          if (j > rpt_vars[n].dphone_longestfunc)
02514             rpt_vars[n].dphone_longestfunc = j;
02515          vp = vp->next;
02516       }
02517    }
02518    rpt_vars[n].alt_longestfunc = 0;
02519    if (rpt_vars[n].p.alt_functions)
02520    {
02521       vp = ast_variable_browse(cfg, rpt_vars[n].p.alt_functions);
02522       while(vp){
02523          j = strlen(vp->name);
02524          if (j > rpt_vars[n].alt_longestfunc)
02525             rpt_vars[n].alt_longestfunc = j;
02526          vp = vp->next;
02527       }
02528    }
02529    rpt_vars[n].macro_longest = 1;
02530    vp = ast_variable_browse(cfg, rpt_vars[n].p.macro);
02531    while(vp){
02532       j = strlen(vp->name);
02533       if (j > rpt_vars[n].macro_longest)
02534          rpt_vars[n].macro_longest = j;
02535       vp = vp->next;
02536    }
02537    
02538    /* Browse for control states */
02539    if(rpt_vars[n].p.csstanzaname)
02540       vp = ast_variable_browse(cfg, rpt_vars[n].p.csstanzaname);
02541    else
02542       vp = NULL;
02543    for( i = 0 ; vp && (i < MAX_SYSSTATES) ; i++){ /* Iterate over the number of control state lines in the stanza */
02544       int k,nukw,statenum;
02545       statenum=atoi(vp->name);
02546       strncpy(s1, vp->value, 255);
02547       s1[255] = 0;
02548       nukw  = finddelim(s1,strs,32);
02549       
02550       for (k = 0 ; k < nukw ; k++){ /* for each user specified keyword */  
02551          for(j = 0 ; cs_keywords[j] != NULL ; j++){ /* try to match to one in our internal table */
02552             if(!strcmp(strs[k],cs_keywords[j])){
02553                switch(j){
02554                   case 0: /* rptena */
02555                      rpt_vars[n].p.s[statenum].txdisable = 0;
02556                      break;
02557                   case 1: /* rptdis */
02558                      rpt_vars[n].p.s[statenum].txdisable = 1;
02559                      break;
02560          
02561                   case 2: /* apena */
02562                      rpt_vars[n].p.s[statenum].autopatchdisable = 0;
02563                      break;
02564 
02565                   case 3: /* apdis */
02566                      rpt_vars[n].p.s[statenum].autopatchdisable = 1;
02567                      break;
02568 
02569                   case 4: /* lnkena */
02570                      rpt_vars[n].p.s[statenum].linkfundisable = 0;
02571                      break;
02572    
02573                   case 5: /* lnkdis */
02574                      rpt_vars[n].p.s[statenum].linkfundisable = 1;
02575                      break;
02576 
02577                   case 6: /* totena */
02578                      rpt_vars[n].p.s[statenum].totdisable = 0;
02579                      break;
02580                
02581                   case 7: /* totdis */
02582                      rpt_vars[n].p.s[statenum].totdisable = 1;
02583                      break;
02584 
02585                   case 8: /* skena */
02586                      rpt_vars[n].p.s[statenum].schedulerdisable = 0;
02587                      break;
02588 
02589                   case 9: /* skdis */
02590                      rpt_vars[n].p.s[statenum].schedulerdisable = 1;
02591                      break;
02592 
02593                   case 10: /* ufena */
02594                      rpt_vars[n].p.s[statenum].userfundisable = 0;
02595                      break;
02596 
02597                   case 11: /* ufdis */
02598                      rpt_vars[n].p.s[statenum].userfundisable = 1;
02599                      break;
02600 
02601                   case 12: /* atena */
02602                      rpt_vars[n].p.s[statenum].alternatetail = 1;
02603                      break;
02604 
02605                   case 13: /* atdis */
02606                      rpt_vars[n].p.s[statenum].alternatetail = 0;
02607                      break;
02608          
02609                   default:
02610                      ast_log(LOG_WARNING,
02611                         "Unhandled control state keyword %s", cs_keywords[i]);
02612                      break;
02613                }
02614             }
02615          }
02616       }
02617       vp = vp->next;
02618    }
02619    ast_mutex_unlock(&rpt_vars[n].lock);
02620 }
02621 
02622 /*
02623 * Enable or disable debug output at a given level at the console
02624 */
02625 static int rpt_do_debug(int fd, int argc, const char * const *argv)
02626 {
02627    int newlevel;
02628 
02629    if (argc != 4) {
02630       return RESULT_SHOWUSAGE;
02631    }
02632 
02633    newlevel = myatoi(argv[3]);
02634 
02635    if (newlevel < 0 || newlevel > 7) {
02636       return RESULT_SHOWUSAGE;
02637    }
02638 
02639    if (newlevel) {
02640       ast_cli(fd, "app_rpt Debugging enabled, previous level: %d, new level: %d\n", debug, newlevel);
02641    } else {
02642       ast_cli(fd, "app_rpt Debugging disabled\n");
02643    }
02644 
02645    debug = newlevel;
02646 
02647    return RESULT_SUCCESS;
02648 }
02649 
02650 /*
02651 * Dump rpt struct debugging onto console
02652 */
02653                                                                                                                                  
02654 static int rpt_do_dump(int fd, int argc, const char * const *argv)
02655 {
02656    int i;
02657 
02658         if (argc != 3)
02659                 return RESULT_SHOWUSAGE;
02660 
02661    for(i = 0; i < nrpts; i++)
02662    {
02663       if (!strcmp(argv[2],rpt_vars[i].name))
02664       {
02665          rpt_vars[i].disgorgetime = time(NULL) + 10; /* Do it 10 seconds later */
02666               ast_cli(fd, "app_rpt struct dump requested for node %s\n",argv[2]);
02667               return RESULT_SUCCESS;
02668       }
02669    }
02670    return RESULT_FAILURE;
02671 }
02672 
02673 /*
02674 * Dump statistics onto console
02675 */
02676 
02677 static int rpt_do_stats(int fd, int argc, const char * const *argv)
02678 {
02679    int i,j,numoflinks;
02680    int dailytxtime, dailykerchunks;
02681    time_t now;
02682    int totalkerchunks, dailykeyups, totalkeyups, timeouts;
02683    int totalexecdcommands, dailyexecdcommands, hours, minutes, seconds;
02684    int uptime;
02685    long long totaltxtime;
02686    struct   rpt_link *l;
02687    char *listoflinks[MAX_STAT_LINKS];  
02688    char *lastdtmfcommand,*parrot_ena;
02689    char *tot_state, *ider_state, *patch_state;
02690    char *reverse_patch_state, *sys_ena, *tot_ena, *link_ena, *patch_ena;
02691    char *sch_ena, *input_signal, *called_number, *user_funs, *tail_type;
02692    struct rpt *myrpt;
02693 
02694    static char *not_applicable = "N/A";
02695 
02696    if(argc != 3)
02697       return RESULT_SHOWUSAGE;
02698 
02699    tot_state = ider_state = 
02700    patch_state = reverse_patch_state = 
02701    input_signal = not_applicable;
02702    called_number = lastdtmfcommand = NULL;
02703 
02704    time(&now);
02705    for(i = 0; i < nrpts; i++)
02706    {
02707       if (!strcmp(argv[2],rpt_vars[i].name)){
02708          /* Make a copy of all stat variables while locked */
02709          myrpt = &rpt_vars[i];
02710          rpt_mutex_lock(&myrpt->lock); /* LOCK */
02711          uptime = (int)(now - starttime);
02712          dailytxtime = myrpt->dailytxtime;
02713          totaltxtime = myrpt->totaltxtime;
02714          dailykeyups = myrpt->dailykeyups;
02715          totalkeyups = myrpt->totalkeyups;
02716          dailykerchunks = myrpt->dailykerchunks;
02717          totalkerchunks = myrpt->totalkerchunks;
02718          dailyexecdcommands = myrpt->dailyexecdcommands;
02719          totalexecdcommands = myrpt->totalexecdcommands;
02720          timeouts = myrpt->timeouts;
02721 
02722          /* Traverse the list of connected nodes */
02723          reverse_patch_state = "DOWN";
02724          numoflinks = 0;
02725          l = myrpt->links.next;
02726          while(l && (l != &myrpt->links)){
02727             if(numoflinks >= MAX_STAT_LINKS){
02728                ast_log(LOG_NOTICE,
02729                "maximum number of links exceeds %d in rpt_do_stats()!",MAX_STAT_LINKS);
02730                break;
02731             }
02732             if (l->name[0] == '0'){ /* Skip '0' nodes */
02733                reverse_patch_state = "UP";
02734                l = l->next;
02735                continue;
02736             }
02737             listoflinks[numoflinks] = ast_strdup(l->name);
02738             if(listoflinks[numoflinks] == NULL){
02739                break;
02740             }
02741             else{
02742                numoflinks++;
02743             }
02744             l = l->next;
02745          }
02746 
02747          if(myrpt->keyed)
02748             input_signal = "YES";
02749          else
02750             input_signal = "NO";
02751 
02752          if(myrpt->p.parrotmode)
02753             parrot_ena = "ENABLED";
02754          else
02755             parrot_ena = "DISABLED";
02756 
02757          if(myrpt->p.s[myrpt->p.sysstate_cur].txdisable)
02758             sys_ena = "DISABLED";
02759          else
02760             sys_ena = "ENABLED";
02761 
02762          if(myrpt->p.s[myrpt->p.sysstate_cur].totdisable)
02763             tot_ena = "DISABLED";
02764          else
02765             tot_ena = "ENABLED";
02766 
02767          if(myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable)
02768             link_ena = "DISABLED";
02769          else
02770             link_ena = "ENABLED";
02771 
02772          if(myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable)
02773             patch_ena = "DISABLED";
02774          else
02775             patch_ena = "ENABLED";
02776 
02777          if(myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable)
02778             sch_ena = "DISABLED";
02779          else
02780             sch_ena = "ENABLED";
02781 
02782          if(myrpt->p.s[myrpt->p.sysstate_cur].userfundisable)
02783             user_funs = "DISABLED";
02784          else
02785             user_funs = "ENABLED";
02786 
02787          if(myrpt->p.s[myrpt->p.sysstate_cur].alternatetail)
02788             tail_type = "ALTERNATE";
02789          else
02790             tail_type = "STANDARD";
02791 
02792          if(!myrpt->totimer)
02793             tot_state = "TIMED OUT!";
02794          else if(myrpt->totimer != myrpt->p.totime)
02795             tot_state = "ARMED";
02796          else
02797             tot_state = "RESET";
02798 
02799          if(myrpt->tailid)
02800             ider_state = "QUEUED IN TAIL";
02801          else if(myrpt->mustid)
02802             ider_state = "QUEUED FOR CLEANUP";
02803          else
02804             ider_state = "CLEAN";
02805 
02806          switch(myrpt->callmode){
02807             case 1:
02808                patch_state = "DIALING";
02809                break;
02810             case 2:
02811                patch_state = "CONNECTING";
02812                break;
02813             case 3:
02814                patch_state = "UP";
02815                break;
02816 
02817             case 4:
02818                patch_state = "CALL FAILED";
02819                break;
02820 
02821             default:
02822                patch_state = "DOWN";
02823          }
02824 
02825          if(strlen(myrpt->exten)){
02826             called_number = ast_strdup(myrpt->exten);
02827          }
02828 
02829          if(strlen(myrpt->lastdtmfcommand)){
02830             lastdtmfcommand = ast_strdup(myrpt->lastdtmfcommand);
02831          }
02832          rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
02833 
02834          ast_cli(fd, "************************ NODE %s STATISTICS *************************\n\n", myrpt->name);
02835          ast_cli(fd, "Selected system state............................: %d\n", myrpt->p.sysstate_cur);
02836          ast_cli(fd, "Signal on input..................................: %s\n", input_signal);
02837          ast_cli(fd, "System...........................................: %s\n", sys_ena);
02838          ast_cli(fd, "Parrot Mode......................................: %s\n", parrot_ena);
02839          ast_cli(fd, "Scheduler........................................: %s\n", sch_ena);
02840          ast_cli(fd, "Tail Time........................................: %s\n", tail_type);
02841          ast_cli(fd, "Time out timer...................................: %s\n", tot_ena);
02842          ast_cli(fd, "Time out timer state.............................: %s\n", tot_state);
02843          ast_cli(fd, "Time outs since system initialization............: %d\n", timeouts);
02844          ast_cli(fd, "Identifier state.................................: %s\n", ider_state);
02845          ast_cli(fd, "Kerchunks today..................................: %d\n", dailykerchunks);
02846          ast_cli(fd, "Kerchunks since system initialization............: %d\n", totalkerchunks);
02847          ast_cli(fd, "Keyups today.....................................: %d\n", dailykeyups);
02848          ast_cli(fd, "Keyups since system initialization...............: %d\n", totalkeyups);
02849          ast_cli(fd, "DTMF commands today..............................: %d\n", dailyexecdcommands);
02850          ast_cli(fd, "DTMF commands since system initialization........: %d\n", totalexecdcommands);
02851          ast_cli(fd, "Last DTMF command executed.......................: %s\n", 
02852          (lastdtmfcommand && strlen(lastdtmfcommand)) ? lastdtmfcommand : not_applicable);
02853          hours = dailytxtime/3600000;
02854          dailytxtime %= 3600000;
02855          minutes = dailytxtime/60000;
02856          dailytxtime %= 60000;
02857          seconds = dailytxtime/1000;
02858          dailytxtime %= 1000;
02859 
02860          ast_cli(fd, "TX time today....................................: %02d:%02d:%02d.%d\n",
02861             hours, minutes, seconds, dailytxtime);
02862 
02863          hours = (int) totaltxtime/3600000;
02864          totaltxtime %= 3600000;
02865          minutes = (int) totaltxtime/60000;
02866          totaltxtime %= 60000;
02867          seconds = (int)  totaltxtime/1000;
02868          totaltxtime %= 1000;
02869 
02870          ast_cli(fd, "TX time since system initialization..............: %02d:%02d:%02d.%d\n",
02871              hours, minutes, seconds, (int) totaltxtime);
02872 
02873                         hours = uptime/3600;
02874                         uptime %= 3600;
02875                         minutes = uptime/60;
02876                         uptime %= 60;
02877 
02878                         ast_cli(fd, "Uptime...........................................: %02d:%02d:%02d\n",
02879                                 hours, minutes, uptime);
02880 
02881          ast_cli(fd, "Nodes currently connected to us..................: ");
02882                         if(!numoflinks){
02883                          ast_cli(fd,"<NONE>");
02884                         }
02885          else{
02886             for(j = 0 ;j < numoflinks; j++){
02887                ast_cli(fd, "%s", listoflinks[j]);
02888                if(j % 4 == 3){
02889                   ast_cli(fd, "\n");
02890                   ast_cli(fd, "                                                 : ");
02891                }  
02892                else{
02893                   if((numoflinks - 1) - j  > 0)
02894                      ast_cli(fd, ", ");
02895                }
02896             }
02897          }
02898          ast_cli(fd,"\n");
02899 
02900          ast_cli(fd, "Autopatch........................................: %s\n", patch_ena);
02901          ast_cli(fd, "Autopatch state..................................: %s\n", patch_state);
02902          ast_cli(fd, "Autopatch called number..........................: %s\n",
02903          (called_number && strlen(called_number)) ? called_number : not_applicable);
02904          ast_cli(fd, "Reverse patch/IAXRPT connected...................: %s\n", reverse_patch_state);
02905          ast_cli(fd, "User linking commands............................: %s\n", link_ena);
02906          ast_cli(fd, "User functions...................................: %s\n\n", user_funs);
02907 
02908          for(j = 0; j < numoflinks; j++){ /* ast_free() all link names */
02909             ast_free(listoflinks[j]);
02910          }
02911          ast_free(called_number);
02912          ast_free(lastdtmfcommand);
02913               return RESULT_SUCCESS;
02914       }
02915    }
02916    return RESULT_FAILURE;
02917 }
02918 
02919 /*
02920 * Link stats function
02921 */
02922 
02923 static int rpt_do_lstats(int fd, int argc, const char * const *argv)
02924 {
02925    int i,j;
02926    char *connstate;
02927    struct rpt *myrpt;
02928    struct rpt_link *l;
02929    struct rpt_lstat *s,*t;
02930    struct rpt_lstat s_head;
02931    if(argc != 3)
02932       return RESULT_SHOWUSAGE;
02933 
02934    s = NULL;
02935    s_head.next = &s_head;
02936    s_head.prev = &s_head;
02937 
02938    for(i = 0; i < nrpts; i++)
02939    {
02940       if (!strcmp(argv[2],rpt_vars[i].name)){
02941          /* Make a copy of all stat variables while locked */
02942          myrpt = &rpt_vars[i];
02943          rpt_mutex_lock(&myrpt->lock); /* LOCK */
02944          /* Traverse the list of connected nodes */
02945          j = 0;
02946          l = myrpt->links.next;
02947          while(l && (l != &myrpt->links)){
02948             if (l->name[0] == '0'){ /* Skip '0' nodes */
02949                l = l->next;
02950                continue;
02951             }
02952             if((s = (struct rpt_lstat *) ast_malloc(sizeof(struct rpt_lstat))) == NULL){
02953                ast_log(LOG_ERROR, "Malloc failed in rpt_do_lstats\n");
02954                rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
02955                return RESULT_FAILURE;
02956             }
02957             memset(s, 0, sizeof(struct rpt_lstat));
02958             strncpy(s->name, l->name, MAXREMSTR - 1);
02959             if (l->chan) pbx_substitute_variables_helper(l->chan, "${IAXPEER(CURRENTCHANNEL)}", s->peer, MAXPEERSTR - 1);
02960             else strcpy(s->peer,"(none)");
02961             s->mode = l->mode;
02962             s->outbound = l->outbound;
02963             s->reconnects = l->reconnects;
02964             s->connecttime = l->connecttime;
02965             s->thisconnected = l->thisconnected;
02966             memcpy(s->chan_stat,l->chan_stat,NRPTSTAT * sizeof(struct rpt_chan_stat));
02967             insque((struct qelem *) s, (struct qelem *) s_head.next);
02968             memset(l->chan_stat,0,NRPTSTAT * sizeof(struct rpt_chan_stat));
02969             l = l->next;
02970          }
02971          rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
02972          ast_cli(fd, "NODE      PEER                RECONNECTS  DIRECTION  CONNECT TIME        CONNECT STATE\n");
02973          ast_cli(fd, "----      ----                ----------  ---------  ------------        -------------\n");
02974 
02975          for(s = s_head.next; s != &s_head; s = s->next){
02976             int hours, minutes, seconds;
02977             long long connecttime = s->connecttime;
02978             char conntime[21];
02979             hours = (int) connecttime/3600000;
02980             connecttime %= 3600000;
02981             minutes = (int) connecttime/60000;
02982             connecttime %= 60000;
02983             seconds = (int)  connecttime/1000;
02984             connecttime %= 1000;
02985             snprintf(conntime, 20, "%02d:%02d:%02d.%d",
02986                hours, minutes, seconds, (int) connecttime);
02987             conntime[20] = 0;
02988             if(s->thisconnected)
02989                connstate  = "ESTABLISHED";
02990             else
02991                connstate = "CONNECTING";
02992             ast_cli(fd, "%-10s%-20s%-12d%-11s%-20s%-20s\n",
02993                s->name, s->peer, s->reconnects, (s->outbound)? "OUT":"IN", conntime, connstate);
02994          }  
02995          /* destroy our local link queue */
02996          s = s_head.next;
02997          while(s != &s_head){
02998             t = s;
02999             s = s->next;
03000             remque((struct qelem *)t);
03001             ast_free(t);
03002          }        
03003          return RESULT_SUCCESS;
03004       }
03005    }
03006    return RESULT_FAILURE;
03007 }
03008 
03009 /*
03010 * List all nodes connected, directly or indirectly
03011 */
03012 
03013 static int rpt_do_nodes(int fd, int argc, const char * const *argv)
03014 {
03015    int i,j;
03016    char ns;
03017    char lbuf[MAXLINKLIST],*strs[MAXLINKLIST];
03018    struct rpt *myrpt;
03019    if(argc != 3)
03020       return RESULT_SHOWUSAGE;
03021 
03022    for(i = 0; i < nrpts; i++)
03023    {
03024       if (!strcmp(argv[2],rpt_vars[i].name)){
03025          /* Make a copy of all stat variables while locked */
03026          myrpt = &rpt_vars[i];
03027          rpt_mutex_lock(&myrpt->lock); /* LOCK */
03028          __mklinklist(myrpt,NULL,lbuf);
03029          rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
03030          /* parse em */
03031          ns = finddelim(lbuf,strs,MAXLINKLIST);
03032          /* sort em */
03033          if (ns) qsort((void *)strs,ns,sizeof(char *),mycompar);
03034          ast_cli(fd,"\n");
03035          ast_cli(fd, "************************* CONNECTED NODES *************************\n\n");
03036          for(j = 0 ;; j++){
03037             if(!strs[j]){
03038                if(!j){
03039                   ast_cli(fd,"<NONE>");
03040                }
03041                break;
03042             }
03043             ast_cli(fd, "%s", strs[j]);
03044             if(j % 8 == 7){
03045                ast_cli(fd, "\n");
03046             }
03047             else{
03048                if(strs[j + 1])
03049                   ast_cli(fd, ", ");
03050             }
03051          }
03052          ast_cli(fd,"\n\n");
03053          return RESULT_SUCCESS;
03054       }
03055    }
03056    return RESULT_FAILURE;
03057 }
03058 
03059 /*
03060 * List all locally configured nodes
03061 */
03062 
03063 static int rpt_do_local_nodes(int fd, int argc, const char * const *argv)
03064 {
03065 
03066     int i;
03067     ast_cli(fd, "\nNode\n----\n");
03068     for (i=0; i< nrpts; i++)
03069     {
03070         ast_cli(fd, "%s\n", rpt_vars[i].name);        
03071     } /* for i */
03072     ast_cli(fd,"\n");
03073     return RESULT_SUCCESS;
03074 } 
03075 
03076 
03077 /*
03078 * reload vars 
03079 */
03080 
03081 static int rpt_do_reload(int fd, int argc, const char * const *argv)
03082 {
03083 int   n;
03084 
03085         if (argc > 2) return RESULT_SHOWUSAGE;
03086 
03087    for(n = 0; n < nrpts; n++) rpt_vars[n].reload = 1;
03088 
03089    return RESULT_FAILURE;
03090 }
03091 
03092 /*
03093 * restart app_rpt
03094 */
03095                                                                                                                                  
03096 static int rpt_do_restart(int fd, int argc, const char * const *argv)
03097 {
03098 int   i;
03099 
03100         if (argc > 2) return RESULT_SHOWUSAGE;
03101    for(i = 0; i < nrpts; i++)
03102    {
03103       if (rpt_vars[i].rxchannel) ast_softhangup(rpt_vars[i].rxchannel,AST_SOFTHANGUP_DEV);
03104    }
03105    return RESULT_FAILURE;
03106 }
03107 
03108 
03109 /*
03110 * send an app_rpt DTMF function from the CLI
03111 */
03112                                                                                                                                  
03113 static int rpt_do_fun(int fd, int argc, const char * const *argv)
03114 {
03115    int   i,busy=0;
03116 
03117         if (argc != 4) return RESULT_SHOWUSAGE;
03118 
03119    for(i = 0; i < nrpts; i++){
03120       if(!strcmp(argv[2], rpt_vars[i].name)){
03121          struct rpt *myrpt = &rpt_vars[i];
03122          rpt_mutex_lock(&myrpt->lock);
03123          if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(argv[3])){
03124             rpt_mutex_unlock(&myrpt->lock);
03125             busy=1;
03126          }
03127          if(!busy){
03128             myrpt->macrotimer = MACROTIME;
03129             strncat(myrpt->macrobuf,argv[3],MAXMACRO - 1);
03130          }
03131          rpt_mutex_unlock(&myrpt->lock);
03132       }
03133    }
03134    if(busy){
03135       ast_cli(fd, "Function decoder busy");
03136    }
03137    return RESULT_FAILURE;
03138 }
03139 /*
03140    the convention is that macros in the data from the rpt() application
03141    are all at the end of the data, separated by the | and start with a *
03142    when put into the macro buffer, the characters have their high bit
03143    set so the macro processor knows they came from the application data
03144    and to use the alt-functions table.
03145    sph:
03146 */
03147 static int rpt_push_alt_macro(struct rpt *myrpt, char *sptr)
03148 {
03149    int   busy=0;
03150 
03151    rpt_mutex_lock(&myrpt->lock);
03152    if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(sptr)){
03153       rpt_mutex_unlock(&myrpt->lock);
03154       busy=1;
03155    }
03156    if(!busy){
03157       int x;
03158       if (debug)ast_log(LOG_NOTICE, "rpt_push_alt_macro %s\n",sptr);
03159       myrpt->macrotimer = MACROTIME;
03160       for(x = 0; *(sptr + x); x++)
03161           myrpt->macrobuf[x] = *(sptr + x) | 0x80;
03162       *(sptr + x) = 0;
03163    }
03164    rpt_mutex_unlock(&myrpt->lock);
03165 
03166    if(busy)ast_log(LOG_WARNING, "Function decoder busy on app_rpt command macro.\n");
03167 
03168    return busy;
03169 }
03170 /*
03171    allows us to test rpt() application data commands
03172 */
03173 static int rpt_do_fun1(int fd, int argc, const char * const *argv)
03174 {
03175    int   i;
03176 
03177     if (argc != 4) return RESULT_SHOWUSAGE;
03178 
03179    for(i = 0; i < nrpts; i++){
03180       if(!strcmp(argv[2], rpt_vars[i].name)){
03181          struct rpt *myrpt = &rpt_vars[i];
03182          rpt_push_alt_macro(myrpt, (char *) argv[3]);
03183       }
03184    }
03185    return RESULT_FAILURE;
03186 }
03187 /*
03188 * send an app_rpt **command** from the CLI
03189 */
03190 
03191 static int rpt_do_cmd(int fd, int argc, const char * const *argv)
03192 {
03193    int i, l;
03194    int busy=0;
03195    int maxActions = sizeof(function_table)/sizeof(struct function_table_tag);
03196 
03197    int thisRpt = -1;
03198    int thisAction = -1;
03199    struct rpt *myrpt = NULL;
03200    if (argc != 6) return RESULT_SHOWUSAGE;
03201    
03202    for(i = 0; i < nrpts; i++)
03203    {
03204       if(!strcmp(argv[2], rpt_vars[i].name))
03205       {
03206          thisRpt = i;
03207          myrpt = &rpt_vars[i];
03208          break;
03209       } /* if !strcmp... */
03210    } /* for i */
03211 
03212    if (thisRpt < 0)
03213    {
03214       ast_cli(fd, "Unknown node number %s.\n", argv[2]);
03215       return RESULT_FAILURE;
03216    } /* if thisRpt < 0 */
03217    
03218    /* Look up the action */
03219    l = strlen(argv[3]);
03220    for(i = 0 ; i < maxActions; i++)
03221    {
03222       if(!strncasecmp(argv[3], function_table[i].action, l))
03223       {
03224          thisAction = i;
03225          break;
03226       } /* if !strncasecmp... */
03227    } /* for i */
03228    
03229    if (thisAction < 0)
03230    {
03231       ast_cli(fd, "Unknown action name %s.\n", argv[3]);
03232       return RESULT_FAILURE;
03233    } /* if thisAction < 0 */
03234 
03235    /* at this point, it looks like all the arguments make sense... */
03236 
03237    rpt_mutex_lock(&myrpt->lock);
03238 
03239    if (rpt_vars[thisRpt].cmdAction.state == CMD_STATE_IDLE)
03240    {
03241       rpt_vars[thisRpt].cmdAction.state = CMD_STATE_BUSY;
03242       rpt_vars[thisRpt].cmdAction.functionNumber = thisAction;
03243       strncpy(rpt_vars[thisRpt].cmdAction.param, argv[4], MAXDTMF);
03244       strncpy(rpt_vars[thisRpt].cmdAction.digits, argv[5], MAXDTMF);
03245       rpt_vars[thisRpt].cmdAction.command_source = SOURCE_RPT;
03246       rpt_vars[thisRpt].cmdAction.state = CMD_STATE_READY;
03247    } /* if (rpt_vars[thisRpt].cmdAction.state == CMD_STATE_IDLE */
03248    else
03249    {
03250       busy = 1;
03251    } /* if (rpt_vars[thisRpt].cmdAction.state == CMD_STATE_IDLE */
03252    rpt_mutex_unlock(&myrpt->lock);
03253 
03254    return (busy ? RESULT_FAILURE : RESULT_SUCCESS);
03255 } /* rpt_do_cmd() */
03256 
03257 static int play_tone_pair(struct ast_channel *chan, int f1, int f2, int duration, int amplitude)
03258 {
03259    int res;
03260 
03261         if ((res = ast_tonepair_start(chan, f1, f2, duration, amplitude)))
03262                 return res;
03263                                                                                                                                             
03264         while(chan->generatordata) {
03265       if (ast_safe_sleep(chan,1)) return -1;
03266    }
03267 
03268         return 0;
03269 }
03270 
03271 static int play_tone(struct ast_channel *chan, int freq, int duration, int amplitude)
03272 {
03273    return play_tone_pair(chan, freq, 0, duration, amplitude);
03274 }
03275 
03276 static int play_silence(struct ast_channel *chan, int duration)
03277 {
03278    return play_tone_pair(chan, 0, 0, duration, 0);
03279 }
03280 
03281 #ifdef   NEW_ASTERISK
03282 
03283 static char *res2cli(int r)
03284 
03285 {
03286    switch (r)
03287    {
03288        case RESULT_SUCCESS:
03289       return(CLI_SUCCESS);
03290        case RESULT_SHOWUSAGE:
03291       return(CLI_SHOWUSAGE);
03292        default:
03293       return(CLI_FAILURE);
03294    }
03295 }
03296 
03297 static char *handle_cli_debug(struct ast_cli_entry *e,
03298    int cmd, struct ast_cli_args *a)
03299 {
03300         switch (cmd) {
03301         case CLI_INIT:
03302                 e->command = "rpt debug level";
03303                 e->usage = debug_usage;
03304                 return NULL;
03305         case CLI_GENERATE:
03306                 return NULL;
03307    }
03308    return res2cli(rpt_do_debug(a->fd, a->argc, a->argv));
03309 }
03310 
03311 static char *handle_cli_dump(struct ast_cli_entry *e,
03312    int cmd, struct ast_cli_args *a)
03313 {
03314         switch (cmd) {
03315         case CLI_INIT:
03316                 e->command = "rpt dump level";
03317                 e->usage = dump_usage;
03318                 return NULL;
03319         case CLI_GENERATE:
03320                 return NULL;
03321    }
03322    return res2cli(rpt_do_dump(a->fd,a->argc,a->argv));
03323 }
03324 
03325 
03326 static char *handle_cli_stats(struct ast_cli_entry *e,
03327    int cmd, struct ast_cli_args *a)
03328 {
03329         switch (cmd) {
03330         case CLI_INIT:
03331                 e->command = "rpt stats";
03332                 e->usage = dump_stats;
03333                 return NULL;
03334         case CLI_GENERATE:
03335                 return NULL;
03336    }
03337    return res2cli(rpt_do_stats(a->fd,a->argc,a->argv));
03338 }
03339 
03340 static char *handle_cli_nodes(struct ast_cli_entry *e,
03341    int cmd, struct ast_cli_args *a)
03342 {
03343         switch (cmd) {
03344         case CLI_INIT:
03345                 e->command = "rpt nodes";
03346                 e->usage = dump_nodes;
03347                 return NULL;
03348         case CLI_GENERATE:
03349                 return NULL;
03350    }
03351    return res2cli(rpt_do_nodes(a->fd,a->argc,a->argv));
03352 }
03353 
03354 static char *handle_cli_local_nodes(struct ast_cli_entry *e,
03355    int cmd, struct ast_cli_args *a)
03356 {
03357         switch (cmd) {
03358         case CLI_INIT:
03359                 e->command = "rpt localnodes";
03360                 e->usage = usage_local_nodes;
03361                 return NULL;
03362         case CLI_GENERATE:
03363                 return NULL;
03364    }
03365    return res2cli(rpt_do_local_nodes(a->fd,a->argc,a->argv));
03366 }
03367 
03368 static char *handle_cli_lstats(struct ast_cli_entry *e,
03369    int cmd, struct ast_cli_args *a)
03370 {
03371         switch (cmd) {
03372         case CLI_INIT:
03373                 e->command = "rpt lstats";
03374                 e->usage = dump_lstats;
03375                 return NULL;
03376         case CLI_GENERATE:
03377                 return NULL;
03378    }
03379    return res2cli(rpt_do_lstats(a->fd,a->argc,a->argv));
03380 }
03381 
03382 static char *handle_cli_reload(struct ast_cli_entry *e,
03383    int cmd, struct ast_cli_args *a)
03384 {
03385         switch (cmd) {
03386         case CLI_INIT:
03387                 e->command = "rpt reload";
03388                 e->usage = reload_usage;
03389                 return NULL;
03390         case CLI_GENERATE:
03391                 return NULL;
03392    }
03393    return res2cli(rpt_do_reload(a->fd,a->argc,a->argv));
03394 }
03395 
03396 static char *handle_cli_restart(struct ast_cli_entry *e,
03397    int cmd, struct ast_cli_args *a)
03398 {
03399         switch (cmd) {
03400         case CLI_INIT:
03401                 e->command = "rpt restart";
03402                 e->usage = restart_usage;
03403                 return NULL;
03404         case CLI_GENERATE:
03405                 return NULL;
03406    }
03407    return res2cli(rpt_do_restart(a->fd,a->argc,a->argv));
03408 }
03409 
03410 static char *handle_cli_fun(struct ast_cli_entry *e,
03411    int cmd, struct ast_cli_args *a)
03412 {
03413         switch (cmd) {
03414         case CLI_INIT:
03415                 e->command = "rpt fun";
03416                 e->usage = fun_usage;
03417                 return NULL;
03418         case CLI_GENERATE:
03419                 return NULL;
03420    }
03421    return res2cli(rpt_do_fun(a->fd,a->argc,a->argv));
03422 }
03423 
03424 static char *handle_cli_fun1(struct ast_cli_entry *e,
03425    int cmd, struct ast_cli_args *a)
03426 {
03427         switch (cmd) {
03428         case CLI_INIT:
03429                 e->command = "rpt fun1";
03430                 e->usage = fun_usage;
03431                 return NULL;
03432         case CLI_GENERATE:
03433                 return NULL;
03434    }
03435    return res2cli(rpt_do_fun1(a->fd,a->argc,a->argv));
03436 }
03437 
03438 static char *handle_cli_cmd(struct ast_cli_entry *e,
03439    int cmd, struct ast_cli_args *a)
03440 {
03441         switch (cmd) {
03442         case CLI_INIT:
03443                 e->command = "rpt cmd";
03444                 e->usage = cmd_usage;
03445                 return NULL;
03446         case CLI_GENERATE:
03447                 return NULL;
03448    }
03449    return res2cli(rpt_do_cmd(a->fd,a->argc,a->argv));
03450 }
03451 
03452 static struct ast_cli_entry rpt_cli[] = {
03453    AST_CLI_DEFINE(handle_cli_debug,"Enable app_rpt debugging"),
03454    AST_CLI_DEFINE(handle_cli_dump,"Dump app_rpt structs for debugging"),
03455    AST_CLI_DEFINE(handle_cli_stats,"Dump node statistics"),
03456    AST_CLI_DEFINE(handle_cli_nodes,"Dump node list"),
03457    AST_CLI_DEFINE(handle_cli_local_nodes, "Dump list of local node numbers"),
03458    AST_CLI_DEFINE(handle_cli_lstats,"Dump link statistics"),
03459    AST_CLI_DEFINE(handle_cli_reload,"Reload app_rpt config"),
03460    AST_CLI_DEFINE(handle_cli_restart,"Restart app_rpt"),
03461    AST_CLI_DEFINE(handle_cli_fun,"Execute a DTMF function"),
03462    AST_CLI_DEFINE(handle_cli_fun1,"Execute a DTMF function"),
03463    AST_CLI_DEFINE(handle_cli_cmd,"Execute a DTMF function")
03464 };
03465 
03466 #endif
03467 
03468 static int send_morse(struct ast_channel *chan, char *string, int speed, int freq, int amplitude)
03469 {
03470 
03471 static struct morse_bits mbits[] = {
03472       {0, 0}, /* SPACE */
03473       {0, 0}, 
03474       {6, 18},/* " */
03475       {0, 0},
03476       {7, 72},/* $ */
03477       {0, 0},
03478       {0, 0},
03479       {6, 30},/* ' */
03480       {5, 13},/* ( */
03481       {6, 29},/* ) */
03482       {0, 0},
03483       {5, 10},/* + */
03484       {6, 51},/* , */
03485       {6, 33},/* - */
03486       {6, 42},/* . */
03487       {5, 9}, /* / */
03488       {5, 31},/* 0 */
03489       {5, 30},/* 1 */
03490       {5, 28},/* 2 */
03491       {5, 24},/* 3 */
03492       {5, 16},/* 4 */
03493       {5, 0}, /* 5 */
03494       {5, 1}, /* 6 */
03495       {5, 3}, /* 7 */
03496       {5, 7}, /* 8 */
03497       {5, 15},/* 9 */
03498       {6, 7}, /* : */
03499       {6, 21},/* ; */
03500       {0, 0},
03501       {5, 33},/* = */
03502       {0, 0},
03503       {6, 12},/* ? */
03504       {0, 0},
03505          {2, 2}, /* A */
03506       {4, 1}, /* B */
03507       {4, 5}, /* C */
03508       {3, 1}, /* D */
03509       {1, 0}, /* E */
03510       {4, 4}, /* F */
03511       {3, 3}, /* G */
03512       {4, 0}, /* H */
03513       {2, 0}, /* I */
03514       {4, 14},/* J */
03515       {3, 5}, /* K */
03516       {4, 2}, /* L */
03517       {2, 3}, /* M */
03518       {2, 1}, /* N */
03519       {3, 7}, /* O */
03520       {4, 6}, /* P */
03521       {4, 11},/* Q */
03522       {3, 2}, /* R */
03523       {3, 0}, /* S */
03524       {1, 1}, /* T */
03525       {3, 4}, /* U */
03526       {4, 8}, /* V */
03527       {3, 6}, /* W */
03528       {4, 9}, /* X */
03529       {4, 13},/* Y */
03530       {4, 3}  /* Z */
03531    };
03532 
03533 
03534    int dottime;
03535    int dashtime;
03536    int intralettertime;
03537    int interlettertime;
03538    int interwordtime;
03539    int len, ddcomb;
03540    int res;
03541    int c;
03542    int i;
03543    int flags;
03544          
03545    res = 0;
03546    
03547    /* Approximate the dot time from the speed arg. */
03548    
03549    dottime = 900/speed;
03550    
03551    /* Establish timing releationships */
03552    
03553    dashtime = 3 * dottime;
03554    intralettertime = dottime;
03555    interlettertime = dottime * 4 ;
03556    interwordtime = dottime * 7;
03557    
03558    for(;(*string) && (!res); string++){
03559    
03560       c = *string;
03561       
03562       /* Convert lower case to upper case */
03563       
03564       if((c >= 'a') && (c <= 'z'))
03565          c -= 0x20;
03566       
03567       /* Can't deal with any char code greater than Z, skip it */
03568       
03569       if(c  > 'Z')
03570          continue;
03571       
03572       /* If space char, wait the inter word time */
03573                
03574       if(c == ' '){
03575          if(!res)
03576             res = play_silence(chan, interwordtime);
03577          continue;
03578       }
03579       
03580       /* Subtract out control char offset to match our table */
03581       
03582       c -= 0x20;
03583       
03584       /* Get the character data */
03585       
03586       len = mbits[c].len;
03587       ddcomb = mbits[c].ddcomb;
03588       
03589       /* Send the character */
03590       
03591       for(; len ; len--){
03592          if(!res)
03593             res = play_tone(chan, freq, (ddcomb & 1) ? dashtime : dottime, amplitude);
03594          if(!res)
03595             res = play_silence(chan, intralettertime);
03596          ddcomb >>= 1;
03597       }
03598       
03599       /* Wait the interletter time */
03600       
03601       if(!res)
03602          res = play_silence(chan, interlettertime - intralettertime);
03603    }
03604    
03605    /* Wait for all the frames to be sent */
03606    
03607    if (!res) 
03608       res = ast_waitstream(chan, "");
03609    ast_stopstream(chan);
03610    
03611    /*
03612    * Wait for the DAHDI driver to physically write the tone blocks to the hardware
03613    */
03614 
03615    for(i = 0; i < 20 ; i++){
03616       flags =  DAHDI_IOMUX_WRITEEMPTY | DAHDI_IOMUX_NOWAIT; 
03617       res = ioctl(chan->fds[0], DAHDI_IOMUX, &flags);
03618       if(flags & DAHDI_IOMUX_WRITEEMPTY)
03619          break;
03620       if( ast_safe_sleep(chan, 50)){
03621          res = -1;
03622          break;
03623       }
03624    }
03625 
03626    
03627    return res;
03628 }
03629 
03630 static int send_tone_telemetry(struct ast_channel *chan, char *tonestring)
03631 {
03632    char *p,*stringp;
03633    char *tonesubset;
03634    int f1,f2;
03635    int duration;
03636    int amplitude;
03637    int res;
03638    int i;
03639    int flags;
03640    
03641    res = 0;
03642 
03643    if(!tonestring)
03644       return res;
03645    
03646    p = stringp = ast_strdup(tonestring);
03647 
03648    for(;tonestring;){
03649       tonesubset = strsep(&stringp,")");
03650       if(!tonesubset)
03651          break;
03652       if(sscanf(tonesubset,"(%30d,%30d,%30d,%30d", &f1, &f2, &duration, &amplitude) != 4)
03653          break;
03654       res = play_tone_pair(chan, f1, f2, duration, amplitude);
03655       if(res)
03656          break;
03657    }
03658    ast_free(p);
03659    if(!res)
03660       res = play_tone_pair(chan, 0, 0, 100, 0); /* This is needed to ensure the last tone segment is timed correctly */
03661    
03662    if (!res) 
03663       res = ast_waitstream(chan, "");
03664 
03665    ast_stopstream(chan);
03666 
03667    /*
03668    * Wait for the DAHDI driver to physically write the tone blocks to the hardware
03669    */
03670 
03671    for(i = 0; i < 20 ; i++){
03672       flags =  DAHDI_IOMUX_WRITEEMPTY | DAHDI_IOMUX_NOWAIT; 
03673       res = ioctl(chan->fds[0], DAHDI_IOMUX, &flags);
03674       if(flags & DAHDI_IOMUX_WRITEEMPTY)
03675          break;
03676       if( ast_safe_sleep(chan, 50)){
03677          res = -1;
03678          break;
03679       }
03680    }
03681       
03682    return res;
03683       
03684 }
03685 
03686 static int sayfile(struct ast_channel *mychannel,char *fname)
03687 {
03688 int   res;
03689 
03690    res = ast_streamfile(mychannel, fname, mychannel->language);
03691    if (!res) 
03692       res = ast_waitstream(mychannel, "");
03693    else
03694        ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
03695    ast_stopstream(mychannel);
03696    return res;
03697 }
03698 
03699 static int saycharstr(struct ast_channel *mychannel,char *str)
03700 {
03701 int   res;
03702 
03703    res = ast_say_character_str(mychannel,str,NULL,mychannel->language);
03704    if (!res) 
03705       res = ast_waitstream(mychannel, "");
03706    else
03707        ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
03708    ast_stopstream(mychannel);
03709    return res;
03710 }
03711 
03712 static int saynum(struct ast_channel *mychannel, int num)
03713 {
03714    int res;
03715    res = ast_say_number(mychannel, num, NULL, mychannel->language, NULL);
03716    if(!res)
03717       res = ast_waitstream(mychannel, "");
03718    else
03719       ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
03720    ast_stopstream(mychannel);
03721    return res;
03722 }
03723 
03724 /* say a node and nodename. Try to look in dir referred to by nodenames in
03725 config, and see if there's a custom node file to play, and if so, play it */
03726 
03727 static int saynode(struct rpt *myrpt, struct ast_channel *mychannel, char *name)
03728 {
03729 int   res;
03730 char  *val,fname[300];
03731 
03732    val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, "nodenames");
03733    if (!val) val = NODENAMES;
03734    snprintf(fname,sizeof(fname) - 1,"%s/%s",val,name);
03735    if (ast_fileexists(fname,NULL,mychannel->language) > 0)
03736       return(sayfile(mychannel,fname));
03737    res = sayfile(mychannel,"rpt/node");
03738    if (!res) 
03739       res = ast_say_character_str(mychannel,name,NULL,mychannel->language);
03740    return res;
03741 }
03742 
03743 static int telem_any(struct rpt *myrpt,struct ast_channel *chan, char *entry)
03744 {
03745    int res;
03746    char c;
03747    
03748    static int morsespeed;
03749    static int morsefreq;
03750    static int morseampl;
03751    static int morseidfreq = 0;
03752    static int morseidampl;
03753    static char mcat[] = MORSE;
03754    
03755    res = 0;
03756    
03757    if(!morseidfreq){ /* Get the morse parameters if not already loaded */
03758       morsespeed = retrieve_astcfgint(myrpt, mcat, "speed", 5, 20, 20);
03759          morsefreq = retrieve_astcfgint(myrpt, mcat, "frequency", 300, 3000, 800);
03760          morseampl = retrieve_astcfgint(myrpt, mcat, "amplitude", 200, 8192, 4096);
03761       morseidampl = retrieve_astcfgint(myrpt, mcat, "idamplitude", 200, 8192, 2048);
03762       morseidfreq = retrieve_astcfgint(myrpt, mcat, "idfrequency", 300, 3000, 330); 
03763    }
03764    
03765    /* Is it a file, or a tone sequence? */
03766          
03767    if(entry[0] == '|'){
03768       c = entry[1];
03769       if((c >= 'a')&&(c <= 'z'))
03770          c -= 0x20;
03771    
03772       switch(c){
03773          case 'I': /* Morse ID */
03774             res = send_morse(chan, entry + 2, morsespeed, morseidfreq, morseidampl);
03775             break;
03776          
03777          case 'M': /* Morse Message */
03778             res = send_morse(chan, entry + 2, morsespeed, morsefreq, morseampl);
03779             break;
03780          
03781          case 'T': /* Tone sequence */
03782             res = send_tone_telemetry(chan, entry + 2);
03783             break;
03784          default:
03785             res = -1;
03786       }
03787    }
03788    else
03789       res = sayfile(chan, entry); /* File */
03790    return res;
03791 }
03792 
03793 /*
03794 * This function looks up a telemetry name in the config file, and does a telemetry response as configured.
03795 *
03796 * 4 types of telemtry are handled: Morse ID, Morse Message, Tone Sequence, and a File containing a recording.
03797 */
03798 
03799 static int telem_lookup(struct rpt *myrpt,struct ast_channel *chan, char *node, char *name)
03800 {
03801    
03802    int res;
03803    int i;
03804    char *entry;
03805    char *telemetry;
03806    char *telemetry_save;
03807 
03808    res = 0;
03809    telemetry_save = NULL;
03810    entry = NULL;
03811    
03812    /* Retrieve the section name for telemetry from the node section */
03813    telemetry = (char *) ast_variable_retrieve(myrpt->cfg, node, TELEMETRY);
03814    if(telemetry ){
03815       telemetry_save = ast_strdup(telemetry);
03816       if(!telemetry_save){
03817          ast_log(LOG_WARNING,"ast_strdup() failed in telem_lookup()\n");
03818          return res;
03819       }
03820       entry = (char *) ast_variable_retrieve(myrpt->cfg, telemetry_save, name);
03821    }
03822    
03823    /* Try to look up the telemetry name */   
03824 
03825    if(!entry){
03826       /* Telemetry name wasn't found in the config file, use the default */
03827       for(i = 0; i < sizeof(tele_defs)/sizeof(struct telem_defaults) ; i++){
03828          if(!strcasecmp(tele_defs[i].name, name))
03829             entry = tele_defs[i].value;
03830       }
03831    }
03832    if(entry){  
03833       if(strlen(entry))
03834          if (chan) telem_any(myrpt,chan, entry);
03835    }
03836    else{
03837       res = -1;
03838    }
03839    ast_free(telemetry_save);
03840    return res;
03841 }
03842 
03843 /*
03844 * Retrieve a wait interval
03845 */
03846 
03847 static int get_wait_interval(struct rpt *myrpt, int type)
03848 {
03849         int interval;
03850         char *wait_times;
03851         char *wait_times_save;
03852                                                                                                                   
03853         wait_times_save = NULL;
03854         wait_times = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, "wait_times");
03855                                                                                                                   
03856         if(wait_times){
03857                 wait_times_save = ast_strdup(wait_times);
03858                 if(!wait_times_save)
03859          return 0;
03860                 
03861         }
03862                                                                                                                   
03863         switch(type){
03864                 case DLY_TELEM:
03865                         if(wait_times)
03866                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "telemwait", 500, 5000, 1000);
03867                         else
03868                                 interval = 1000;
03869                         break;
03870                                                                                                                   
03871                 case DLY_ID:
03872                         if(wait_times)
03873                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "idwait",250,5000,500);
03874                         else
03875                                 interval = 500;
03876                         break;
03877                                                                                                                   
03878                 case DLY_UNKEY:
03879                         if(wait_times)
03880                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "unkeywait",50,5000,1000);
03881                         else
03882                                 interval = 1000;
03883                         break;
03884                                                                                                                   
03885                 case DLY_LINKUNKEY:
03886                         if(wait_times)
03887                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "linkunkeywait",500,5000,1000);
03888                         else
03889                                 interval = 1000;
03890                         break;
03891                                                                                                                   
03892                 case DLY_CALLTERM:
03893                         if(wait_times)
03894                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "calltermwait",500,5000,1500);
03895                         else
03896                                 interval = 1500;
03897                         break;
03898                                                                                                                   
03899                 case DLY_COMP:
03900                         if(wait_times)
03901                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "compwait",500,5000,200);
03902                         else
03903                                 interval = 200;
03904                         break;
03905                                                                                                                   
03906                 case DLY_PARROT:
03907                         if(wait_times)
03908                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "parrotwait",500,5000,200);
03909                         else
03910                                 interval = 200;
03911                         break;
03912                                                                                                                   
03913                 default:
03914          interval = 0;
03915          break;
03916         }
03917    ast_free(wait_times_save);
03918    return interval;
03919 }                                                                                                                  
03920 
03921 
03922 /*
03923 * Wait a configurable interval of time 
03924 */
03925 static void wait_interval(struct rpt *myrpt, int type, struct ast_channel *chan)
03926 {
03927    int interval;
03928    interval = get_wait_interval(myrpt, type);
03929    if(debug)
03930       ast_log(LOG_NOTICE,"Delay interval = %d\n", interval);
03931    if(interval)
03932       ast_safe_sleep(chan,interval);
03933    if(debug)
03934       ast_log(LOG_NOTICE,"Delay complete\n");
03935    return;
03936 }
03937 
03938 static int split_freq(char *mhz, char *decimals, char *freq);
03939 
03940 static void *rpt_tele_thread(void *this)
03941 {
03942 struct dahdi_confinfo ci;  /* conference info */
03943 int   res = 0,haslink,hastx,hasremote,imdone = 0, unkeys_queued, x;
03944 struct   rpt_tele *mytele = (struct rpt_tele *)this;
03945 struct  rpt_tele *tlist;
03946 struct   rpt *myrpt;
03947 struct   rpt_link *l,*l1,linkbase;
03948 struct   ast_channel *mychannel;
03949 int vmajor, vminor, m;
03950 char *p,*ct,*ct_copy,*ident, *nodename,*cp;
03951 time_t t;
03952 #ifdef   NEW_ASTERISK
03953 struct ast_tm localtm;
03954 #else
03955 struct tm localtm;
03956 #endif
03957 char lbuf[MAXLINKLIST],*strs[MAXLINKLIST];
03958 int   i,ns,rbimode;
03959 char mhz[MAXREMSTR];
03960 char decimals[MAXREMSTR];
03961 char  mystr[200];
03962 struct dahdi_params par;
03963 
03964 
03965    /* get a pointer to myrpt */
03966    myrpt = mytele->rpt;
03967 
03968    /* Snag copies of a few key myrpt variables */
03969    rpt_mutex_lock(&myrpt->lock);
03970    nodename = ast_strdup(myrpt->name);
03971    if(!nodename)
03972    {
03973        fprintf(stderr,"rpt:Sorry unable strdup nodename\n");
03974        rpt_mutex_lock(&myrpt->lock);
03975        remque((struct qelem *)mytele);
03976        ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
03977        rpt_mutex_unlock(&myrpt->lock);
03978        ast_free(mytele);
03979        pthread_exit(NULL);
03980    }
03981 
03982    if (myrpt->p.ident){
03983       ident = ast_strdup(myrpt->p.ident);
03984          if(!ident)
03985       {
03986                  fprintf(stderr,"rpt:Sorry unable strdup ident\n");
03987          rpt_mutex_lock(&myrpt->lock);
03988                   remque((struct qelem *)mytele);
03989                   ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",
03990          __LINE__, mytele->mode); /*@@@@@@@@@@@*/
03991                   rpt_mutex_unlock(&myrpt->lock);
03992          ast_free(nodename);
03993                   ast_free(mytele);
03994                   pthread_exit(NULL);
03995          }
03996    }
03997    else
03998    {
03999       ident = "";
04000    }
04001    rpt_mutex_unlock(&myrpt->lock);
04002       
04003 
04004 
04005    /* allocate a pseudo-channel thru asterisk */
04006    mychannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
04007    if (!mychannel)
04008    {
04009       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
04010       rpt_mutex_lock(&myrpt->lock);
04011       remque((struct qelem *)mytele);
04012       ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04013       rpt_mutex_unlock(&myrpt->lock);
04014       ast_free(nodename);
04015       ast_free(ident);
04016       ast_free(mytele);    
04017       pthread_exit(NULL);
04018    }
04019 #ifdef   AST_CDR_FLAG_POST_DISABLED
04020    if (mychannel->cdr) 
04021       ast_set_flag(mychannel->cdr,AST_CDR_FLAG_POST_DISABLED);
04022 #endif
04023    rpt_mutex_lock(&myrpt->lock);
04024    mytele->chan = mychannel;
04025    rpt_mutex_unlock(&myrpt->lock);
04026 
04027    while((mytele->mode != SETREMOTE) && (mytele->mode != UNKEY) &&
04028       (mytele->mode != LINKUNKEY))
04029    {  
04030                 rpt_mutex_lock(&myrpt->lock);
04031       if (!myrpt->active_telem)
04032       {
04033          myrpt->active_telem = mytele;
04034                    rpt_mutex_unlock(&myrpt->lock);
04035          break;
04036       }
04037                 rpt_mutex_unlock(&myrpt->lock);
04038       usleep(100000);
04039    }
04040 
04041    /* make a conference for the tx */
04042    ci.chan = 0;
04043    /* If the telemetry is only intended for a local audience, */
04044    /* only connect the ID audio to the local tx conference so */
04045    /* linked systems can't hear it */
04046    ci.confno = (((mytele->mode == ID) || (mytele->mode == IDTALKOVER) || (mytele->mode == UNKEY) || 
04047       (mytele->mode == TAILMSG) || (mytele->mode == LINKUNKEY) || (mytele->mode == TIMEOUT) || 
04048       (mytele->mode == PARROT) || (mytele->mode == STATS_TIME_LOCAL)) ? 
04049          myrpt->txconf : myrpt->conf);
04050    ci.confmode = DAHDI_CONF_CONFANN;
04051    /* first put the channel on the conference in announce mode */
04052    if (ioctl(mychannel->fds[0],DAHDI_SETCONF,&ci) == -1)
04053    {
04054       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
04055       rpt_mutex_lock(&myrpt->lock);
04056       myrpt->active_telem = NULL;
04057       remque((struct qelem *)mytele);
04058       rpt_mutex_unlock(&myrpt->lock);
04059       ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04060       ast_free(nodename);
04061       ast_free(ident);
04062       ast_free(mytele);    
04063       ast_hangup(mychannel);
04064       pthread_exit(NULL);
04065    }
04066    ast_stopstream(mychannel);
04067    switch(mytele->mode)
04068    {
04069        case ID:
04070        case ID1:
04071       /* wait a bit */
04072       wait_interval(myrpt, (mytele->mode == ID) ? DLY_ID : DLY_TELEM,mychannel);
04073       res = telem_any(myrpt,mychannel, ident); 
04074       imdone=1;   
04075       break;
04076       
04077        case TAILMSG:
04078       res = ast_streamfile(mychannel, myrpt->p.tailmessages[myrpt->tailmessagen], mychannel->language); 
04079       break;
04080       
04081        case IDTALKOVER:
04082          p = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "idtalkover");
04083          if(p)
04084          res = telem_any(myrpt,mychannel, p); 
04085       imdone=1;   
04086          break;
04087             
04088        case PROC:
04089       /* wait a little bit longer */
04090       wait_interval(myrpt, DLY_TELEM, mychannel);
04091       res = telem_lookup(myrpt, mychannel, myrpt->name, "patchup");
04092       if(res < 0){ /* Then default message */
04093          res = ast_streamfile(mychannel, "rpt/callproceeding", mychannel->language);
04094       }
04095       break;
04096        case TERM:
04097       /* wait a little bit longer */
04098       wait_interval(myrpt, DLY_CALLTERM, mychannel);
04099       res = telem_lookup(myrpt, mychannel, myrpt->name, "patchdown");
04100       if(res < 0){ /* Then default message */
04101          res = ast_streamfile(mychannel, "rpt/callterminated", mychannel->language);
04102       }
04103       break;
04104        case COMPLETE:
04105       /* wait a little bit */
04106       wait_interval(myrpt, DLY_TELEM, mychannel);
04107       res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04108       break;
04109        case MACRO_NOTFOUND:
04110       /* wait a little bit */
04111       wait_interval(myrpt, DLY_TELEM, mychannel);
04112       res = ast_streamfile(mychannel, "rpt/macro_notfound", mychannel->language);
04113       break;
04114        case MACRO_BUSY:
04115       /* wait a little bit */
04116       wait_interval(myrpt, DLY_TELEM, mychannel);
04117       res = ast_streamfile(mychannel, "rpt/macro_busy", mychannel->language);
04118       break;
04119        case UNKEY:
04120       if(myrpt->patchnoct && myrpt->callmode){ /* If no CT during patch configured, then don't send one */
04121          imdone = 1;
04122          break;
04123       }
04124          
04125       /*
04126       * Reset the Unkey to CT timer
04127       */
04128 
04129       x = get_wait_interval(myrpt, DLY_UNKEY);
04130       rpt_mutex_lock(&myrpt->lock);
04131       myrpt->unkeytocttimer = x; /* Must be protected as it is changed below */
04132       rpt_mutex_unlock(&myrpt->lock);
04133 
04134       /*
04135       * If there's one already queued, don't do another
04136       */
04137 
04138       tlist = myrpt->tele.next;
04139       unkeys_queued = 0;
04140                 if (tlist != &myrpt->tele)
04141                 {
04142                         rpt_mutex_lock(&myrpt->lock);
04143                         while(tlist != &myrpt->tele){
04144                                 if (tlist->mode == UNKEY) unkeys_queued++;
04145                                 tlist = tlist->next;
04146                         }
04147                         rpt_mutex_unlock(&myrpt->lock);
04148       }
04149       if( unkeys_queued > 1){
04150          imdone = 1;
04151          break;
04152       }
04153 
04154       /* Wait for the telemetry timer to expire */
04155       /* Periodically check the timer since it can be re-initialized above */
04156       while(myrpt->unkeytocttimer)
04157       {
04158          int ctint;
04159          if(myrpt->unkeytocttimer > 100)
04160             ctint = 100;
04161          else
04162             ctint = myrpt->unkeytocttimer;
04163          ast_safe_sleep(mychannel, ctint);
04164          rpt_mutex_lock(&myrpt->lock);
04165          if(myrpt->unkeytocttimer < ctint)
04166             myrpt->unkeytocttimer = 0;
04167          else
04168             myrpt->unkeytocttimer -= ctint;
04169          rpt_mutex_unlock(&myrpt->lock);
04170       }
04171    
04172       /*
04173       * Now, the carrier on the rptr rx should be gone. 
04174       * If it re-appeared, then forget about sending the CT
04175       */
04176       if(myrpt->keyed){
04177          imdone = 1;
04178          break;
04179       }
04180       
04181       rpt_mutex_lock(&myrpt->lock); /* Update the kerchunk counters */
04182       myrpt->dailykerchunks++;
04183       myrpt->totalkerchunks++;
04184       rpt_mutex_unlock(&myrpt->lock);
04185    
04186       haslink = 0;
04187       hastx = 0;
04188       hasremote = 0;    
04189       l = myrpt->links.next;
04190       if (l != &myrpt->links)
04191       {
04192          rpt_mutex_lock(&myrpt->lock);
04193          while(l != &myrpt->links)
04194          {
04195             if (l->name[0] == '0')
04196             {
04197                l = l->next;
04198                continue;
04199             }
04200             haslink = 1;
04201             if (l->mode) {
04202                hastx++;
04203                if (l->isremote) hasremote++;
04204             }
04205             l = l->next;
04206          }
04207          rpt_mutex_unlock(&myrpt->lock);
04208       }
04209       if (haslink)
04210       {
04211 
04212          res = telem_lookup(myrpt,mychannel, myrpt->name, (!hastx) ? "remotemon" : "remotetx");
04213          if(res)
04214             ast_log(LOG_WARNING, "telem_lookup:remotexx failed on %s\n", mychannel->name);
04215          
04216       
04217          /* if in remote cmd mode, indicate it */
04218          if (myrpt->cmdnode[0])
04219          {
04220             ast_safe_sleep(mychannel,200);
04221             res = telem_lookup(myrpt,mychannel, myrpt->name, "cmdmode");
04222             if(res)
04223                ast_log(LOG_WARNING, "telem_lookup:cmdmode failed on %s\n", mychannel->name);
04224             ast_stopstream(mychannel);
04225          }
04226       }
04227       else if((ct = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "unlinkedct"))){ /* Unlinked Courtesy Tone */
04228          ct_copy = ast_strdup(ct);
04229          if(ct_copy)
04230          {
04231             res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
04232             ast_free(ct_copy);
04233          }
04234          else
04235             res = -1;
04236          if(res)
04237             ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);     
04238       }  
04239       if (hasremote && (!myrpt->cmdnode[0]))
04240       {
04241          /* set for all to hear */
04242          ci.chan = 0;
04243          ci.confno = myrpt->conf;
04244          ci.confmode = DAHDI_CONF_CONFANN;
04245          /* first put the channel on the conference in announce mode */
04246          if (ioctl(mychannel->fds[0],DAHDI_SETCONF,&ci) == -1)
04247          {
04248             ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
04249             rpt_mutex_lock(&myrpt->lock);
04250             myrpt->active_telem = NULL;
04251             remque((struct qelem *)mytele);
04252             rpt_mutex_unlock(&myrpt->lock);
04253             ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04254             ast_free(nodename);
04255             ast_free(ident);
04256             ast_free(mytele);    
04257             ast_hangup(mychannel);
04258             pthread_exit(NULL);
04259          }
04260          if((ct = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "remotect"))){ /* Unlinked Courtesy Tone */
04261             ast_safe_sleep(mychannel,200);
04262             ct_copy = ast_strdup(ct);
04263             if(ct_copy)
04264             {
04265                res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
04266                ast_free(ct_copy);
04267             }
04268             else
04269                res = -1;
04270       
04271             if(res)
04272                ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);     
04273          }  
04274       }
04275 #if   defined(_MDC_DECODE_H_) && defined(MDC_SAY_WHEN_DOING_CT)
04276       if (myrpt->lastunit)
04277       {
04278          char mystr[10];
04279 
04280          ast_safe_sleep(mychannel,200);
04281          /* set for all to hear */
04282          ci.chan = 0;
04283          ci.confno = myrpt->txconf;
04284          ci.confmode = DAHDI_CONF_CONFANN;
04285          /* first put the channel on the conference in announce mode */
04286          if (ioctl(mychannel->fds[0],DAHDI_SETCONF,&ci) == -1)
04287          {
04288             ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
04289             rpt_mutex_lock(&myrpt->lock);
04290             myrpt->active_telem = NULL;
04291             remque((struct qelem *)mytele);
04292             rpt_mutex_unlock(&myrpt->lock);
04293             ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04294             ast_free(nodename);
04295             ast_free(ident);
04296             ast_free(mytele);    
04297             ast_hangup(mychannel);
04298             pthread_exit(NULL);
04299          }
04300          sprintf(mystr,"%04x",myrpt->lastunit);
04301          myrpt->lastunit = 0;
04302          ast_say_character_str(mychannel,mystr,NULL,mychannel->language);
04303          break;
04304       }
04305 #endif
04306       imdone = 1;
04307       break;
04308        case LINKUNKEY:
04309       if(myrpt->patchnoct && myrpt->callmode){ /* If no CT during patch configured, then don't send one */
04310          imdone = 1;
04311          break;
04312       }
04313          
04314       /*
04315       * Reset the Unkey to CT timer
04316       */
04317 
04318       x = get_wait_interval(myrpt, DLY_LINKUNKEY);
04319       mytele->mylink.linkunkeytocttimer = x; /* Must be protected as it is changed below */
04320 
04321       /*
04322       * If there's one already queued, don't do another
04323       */
04324 
04325       tlist = myrpt->tele.next;
04326       unkeys_queued = 0;
04327                 if (tlist != &myrpt->tele)
04328                 {
04329                         rpt_mutex_lock(&myrpt->lock);
04330                         while(tlist != &myrpt->tele){
04331                                 if (tlist->mode == LINKUNKEY) unkeys_queued++;
04332                                 tlist = tlist->next;
04333                         }
04334                         rpt_mutex_unlock(&myrpt->lock);
04335       }
04336       if( unkeys_queued > 1){
04337          imdone = 1;
04338          break;
04339       }
04340 
04341       /* Wait for the telemetry timer to expire */
04342       /* Periodically check the timer since it can be re-initialized above */
04343       while(mytele->mylink.linkunkeytocttimer)
04344       {
04345          int ctint;
04346          if(mytele->mylink.linkunkeytocttimer > 100)
04347             ctint = 100;
04348          else
04349             ctint = mytele->mylink.linkunkeytocttimer;
04350          ast_safe_sleep(mychannel, ctint);
04351          rpt_mutex_lock(&myrpt->lock);
04352          if(mytele->mylink.linkunkeytocttimer < ctint)
04353             mytele->mylink.linkunkeytocttimer = 0;
04354          else
04355             mytele->mylink.linkunkeytocttimer -= ctint;
04356          rpt_mutex_unlock(&myrpt->lock);
04357       }
04358    
04359       if((ct = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "linkunkeyct"))){ /* Unlinked Courtesy Tone */
04360          ct_copy = ast_strdup(ct);
04361          if(ct_copy){
04362             res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
04363             ast_free(ct_copy);
04364          }
04365          else
04366             res = -1;
04367          if(res)
04368             ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);     
04369       }  
04370       imdone = 1;
04371       break;
04372        case REMDISC:
04373       /* wait a little bit */
04374       wait_interval(myrpt, DLY_TELEM, mychannel);
04375       l = myrpt->links.next;
04376       haslink = 0;
04377       /* don't report if a link for this one still on system */
04378       if (l != &myrpt->links)
04379       {
04380          rpt_mutex_lock(&myrpt->lock);
04381          while(l != &myrpt->links)
04382          {
04383             if (l->name[0] == '0')
04384             {
04385                l = l->next;
04386                continue;
04387             }
04388             if (!strcmp(l->name,mytele->mylink.name))
04389             {
04390                haslink = 1;
04391                break;
04392             }
04393             l = l->next;
04394          }
04395          rpt_mutex_unlock(&myrpt->lock);
04396       }
04397       if (haslink)
04398       {
04399          imdone = 1;
04400          break;
04401       }
04402       res = saynode(myrpt,mychannel,mytele->mylink.name);
04403       if (!res) 
04404           res = ast_streamfile(mychannel, ((mytele->mylink.hasconnected) ? 
04405          "rpt/remote_disc" : "rpt/remote_busy"), mychannel->language);
04406       break;
04407        case REMALREADY:
04408       /* wait a little bit */
04409       wait_interval(myrpt, DLY_TELEM, mychannel);
04410       res = ast_streamfile(mychannel, "rpt/remote_already", mychannel->language);
04411       break;
04412        case REMNOTFOUND:
04413       /* wait a little bit */
04414       wait_interval(myrpt, DLY_TELEM, mychannel);
04415       res = ast_streamfile(mychannel, "rpt/remote_notfound", mychannel->language);
04416       break;
04417        case REMGO:
04418       /* wait a little bit */
04419       wait_interval(myrpt, DLY_TELEM, mychannel);
04420       res = ast_streamfile(mychannel, "rpt/remote_go", mychannel->language);
04421       break;
04422        case CONNECTED:
04423       /* wait a little bit */
04424       wait_interval(myrpt, DLY_TELEM,  mychannel);
04425       res = saynode(myrpt,mychannel,mytele->mylink.name);
04426       if (!res)
04427           res = ast_streamfile(mychannel, "rpt/connected", mychannel->language);
04428       if (!res) 
04429          res = ast_waitstream(mychannel, "");
04430       else
04431           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04432       ast_stopstream(mychannel);
04433       res = ast_streamfile(mychannel, "digits/2", mychannel->language);
04434       if (!res) 
04435          res = ast_waitstream(mychannel, "");
04436       else
04437           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04438       ast_stopstream(mychannel);
04439       res = saynode(myrpt,mychannel,myrpt->name);
04440       imdone = 1;
04441       break;
04442        case CONNFAIL:
04443       res = saynode(myrpt,mychannel,mytele->mylink.name);
04444       if (!res) 
04445           res = ast_streamfile(mychannel, "rpt/connection_failed", mychannel->language);
04446       break;
04447        case MEMNOTFOUND:
04448       /* wait a little bit */
04449       wait_interval(myrpt, DLY_TELEM, mychannel);
04450       res = ast_streamfile(mychannel, "rpt/memory_notfound", mychannel->language);
04451       break;
04452        case PLAYBACK:
04453       /* wait a little bit */
04454       wait_interval(myrpt, DLY_TELEM, mychannel);
04455       res = ast_streamfile(mychannel, mytele->param, mychannel->language);
04456       break;
04457        case TOPKEY:
04458       /* wait a little bit */
04459       wait_interval(myrpt, DLY_TELEM, mychannel);
04460       for(i = 0; i < TOPKEYN; i++)
04461       {
04462          if (!myrpt->topkey[i].node[0]) continue;
04463          if ((!myrpt->topkeylong) && (myrpt->topkey[i].keyed)) continue;
04464          res = saynode(myrpt, mychannel,  myrpt->topkey[i].node);
04465          if (!res) res = sayfile(mychannel,(myrpt->topkey[i].keyed) ?
04466             "rpt/keyedfor" : "rpt/unkeyedfor");
04467          if (!res) res = saynum(mychannel,
04468             myrpt->topkey[i].timesince);
04469          if (!res) res = sayfile(mychannel,"rpt/seconds");
04470          if (!myrpt->topkeylong) break;
04471       }
04472       imdone = 1;
04473       break;
04474        case SETREMOTE:
04475       ast_mutex_lock(&myrpt->remlock);
04476       res = 0;
04477       if(!strcmp(myrpt->remoterig, remote_rig_ft897))
04478       {
04479          res = set_ft897(myrpt);
04480       }
04481       else if(!strcmp(myrpt->remoterig, remote_rig_tm271))
04482       {
04483          res = set_tm271(myrpt);
04484       }
04485       else if(!strcmp(myrpt->remoterig, remote_rig_ic706))
04486       {
04487          res = set_ic706(myrpt);
04488       }
04489 #ifdef HAVE_IOPERM
04490       else if(!strcmp(myrpt->remoterig, remote_rig_rbi)||!strcmp(myrpt->remoterig, remote_rig_ppp16))
04491       {
04492          if (ioperm(myrpt->p.iobase,1,1) == -1)
04493          {
04494             rpt_mutex_unlock(&myrpt->lock);
04495             ast_log(LOG_WARNING, "Cant get io permission on IO port %x hex\n",myrpt->p.iobase);
04496             res = -1;
04497          }
04498          else res = setrbi(myrpt);
04499       }
04500 #endif
04501       else if(!strcmp(myrpt->remoterig, remote_rig_kenwood))
04502       {
04503          if (myrpt->iofd >= 0) setdtr(myrpt->iofd,1);
04504          res = setkenwood(myrpt);
04505          if (myrpt->iofd >= 0) setdtr(myrpt->iofd,0);
04506          if (ast_safe_sleep(mychannel,200) == -1)
04507          {
04508             ast_mutex_unlock(&myrpt->remlock);
04509             res = -1;
04510             break;
04511          }
04512          if (myrpt->iofd < 0)
04513          {
04514             i = DAHDI_FLUSH_EVENT;
04515             if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_FLUSH,&i) == -1)
04516             {
04517                ast_mutex_unlock(&myrpt->remlock);
04518                ast_log(LOG_ERROR,"Cant flush events");
04519                res = -1;
04520                break;
04521             }
04522             if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_GET_PARAMS,&par) == -1)
04523             {
04524                ast_mutex_unlock(&myrpt->remlock);
04525                ast_log(LOG_ERROR,"Cant get params");
04526                res = -1;
04527                break;
04528             }
04529             myrpt->remoterx = 
04530                (par.rxisoffhook || (myrpt->tele.next != &myrpt->tele));
04531          }
04532       }
04533 
04534       ast_mutex_unlock(&myrpt->remlock);
04535       if (!res)
04536       {
04537          imdone = 1;
04538          break;
04539       }
04540       /* fall thru to invalid freq */
04541        case INVFREQ:
04542       /* wait a little bit */
04543       wait_interval(myrpt, DLY_TELEM, mychannel);
04544       res = ast_streamfile(mychannel, "rpt/invalid-freq", mychannel->language);
04545       break;
04546        case REMMODE:
04547       cp = 0;
04548       wait_interval(myrpt, DLY_TELEM, mychannel);
04549       switch(myrpt->remmode)
04550       {
04551           case REM_MODE_FM:
04552          saycharstr(mychannel,"FM");
04553          break;
04554           case REM_MODE_USB:
04555          saycharstr(mychannel,"USB");
04556          break;
04557           case REM_MODE_LSB:
04558          saycharstr(mychannel,"LSB");
04559          break;
04560           case REM_MODE_AM:
04561          saycharstr(mychannel,"AM");
04562          break;
04563       }
04564       wait_interval(myrpt, DLY_COMP, mychannel);
04565       if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04566       break;
04567        case LOGINREQ:
04568       wait_interval(myrpt, DLY_TELEM, mychannel);
04569       sayfile(mychannel,"rpt/login");
04570       saycharstr(mychannel,myrpt->name);
04571       break;
04572        case REMLOGIN:
04573       wait_interval(myrpt, DLY_TELEM, mychannel);
04574       saycharstr(mychannel,myrpt->loginuser);
04575       saynode(myrpt,mychannel,myrpt->name);
04576       wait_interval(myrpt, DLY_COMP, mychannel);
04577       if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04578       break;
04579        case REMXXX:
04580       wait_interval(myrpt, DLY_TELEM, mychannel);
04581       res = 0;
04582       switch(mytele->submode)
04583       {
04584           case 100: /* RX PL Off */
04585          sayfile(mychannel, "rpt/rxpl");
04586          sayfile(mychannel, "rpt/off");
04587          break;
04588           case 101: /* RX PL On */
04589          sayfile(mychannel, "rpt/rxpl");
04590          sayfile(mychannel, "rpt/on");
04591          break;
04592           case 102: /* TX PL Off */
04593          sayfile(mychannel, "rpt/txpl");
04594          sayfile(mychannel, "rpt/off");
04595          break;
04596           case 103: /* TX PL On */
04597          sayfile(mychannel, "rpt/txpl");
04598          sayfile(mychannel, "rpt/on");
04599          break;
04600           case 104: /* Low Power */
04601          sayfile(mychannel, "rpt/lopwr");
04602          break;
04603           case 105: /* Medium Power */
04604          sayfile(mychannel, "rpt/medpwr");
04605          break;
04606           case 106: /* Hi Power */
04607          sayfile(mychannel, "rpt/hipwr");
04608          break;
04609           case 113: /* Scan down slow */
04610          sayfile(mychannel,"rpt/down");
04611          sayfile(mychannel, "rpt/slow");
04612          break;
04613           case 114: /* Scan down quick */
04614          sayfile(mychannel,"rpt/down");
04615          sayfile(mychannel, "rpt/quick");
04616          break;
04617           case 115: /* Scan down fast */
04618          sayfile(mychannel,"rpt/down");
04619          sayfile(mychannel, "rpt/fast");
04620          break;
04621           case 116: /* Scan up slow */
04622          sayfile(mychannel,"rpt/up");
04623          sayfile(mychannel, "rpt/slow");
04624          break;
04625           case 117: /* Scan up quick */
04626          sayfile(mychannel,"rpt/up");
04627          sayfile(mychannel, "rpt/quick");
04628          break;
04629           case 118: /* Scan up fast */
04630          sayfile(mychannel,"rpt/up");
04631          sayfile(mychannel, "rpt/fast");
04632          break;
04633           default:
04634          res = -1;
04635       }
04636       wait_interval(myrpt, DLY_COMP, mychannel);
04637       if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04638       break;
04639        case SCAN:
04640       ast_mutex_lock(&myrpt->remlock);
04641       if (myrpt->hfscanstop)
04642       {
04643          myrpt->hfscanstatus = 0;
04644          myrpt->hfscanmode = 0;
04645          myrpt->hfscanstop = 0;
04646          mytele->mode = SCANSTAT;
04647          ast_mutex_unlock(&myrpt->remlock);
04648          if (ast_safe_sleep(mychannel,1000) == -1) break;
04649          sayfile(mychannel, "rpt/stop"); 
04650          imdone = 1;
04651          break;
04652       }
04653       if (myrpt->hfscanstatus > -2) service_scan(myrpt);
04654       i = myrpt->hfscanstatus;
04655       myrpt->hfscanstatus = 0;
04656       if (i) mytele->mode = SCANSTAT;
04657       ast_mutex_unlock(&myrpt->remlock);
04658       if (i < 0) sayfile(mychannel, "rpt/stop"); 
04659       else if (i > 0) saynum(mychannel,i);
04660       imdone = 1;
04661       break;
04662        case TUNE:
04663       ast_mutex_lock(&myrpt->remlock);
04664       if (!strcmp(myrpt->remoterig,remote_rig_ic706))
04665       {
04666          set_mode_ic706(myrpt, REM_MODE_AM);
04667          if(play_tone(mychannel, 800, 6000, 8192) == -1) break;
04668          ast_safe_sleep(mychannel,500);
04669          set_mode_ic706(myrpt, myrpt->remmode);
04670          myrpt->tunerequest = 0;
04671          ast_mutex_unlock(&myrpt->remlock);
04672          imdone = 1;
04673          break;
04674       }
04675       set_mode_ft897(myrpt, REM_MODE_AM);
04676       simple_command_ft897(myrpt, 8);
04677       if(play_tone(mychannel, 800, 6000, 8192) == -1) break;
04678       simple_command_ft897(myrpt, 0x88);
04679       ast_safe_sleep(mychannel,500);
04680       set_mode_ft897(myrpt, myrpt->remmode);
04681       myrpt->tunerequest = 0;
04682       ast_mutex_unlock(&myrpt->remlock);
04683       imdone = 1;
04684       break;
04685        case REMSHORTSTATUS:
04686        case REMLONGSTATUS: 
04687       wait_interval(myrpt, DLY_TELEM, mychannel);
04688       res = saynode(myrpt,mychannel,myrpt->name);
04689       if(!res)
04690          res = sayfile(mychannel,"rpt/frequency");
04691       if(!res)
04692          res = split_freq(mhz, decimals, myrpt->freq);
04693       if (!multimode_capable(myrpt)) decimals[3] = 0;
04694       if(!res){
04695          m = atoi(mhz);
04696          if(m < 100)
04697             res = saynum(mychannel, m);
04698          else
04699             res = saycharstr(mychannel, mhz);
04700       }
04701       if(!res)
04702          res = sayfile(mychannel, "letters/dot");
04703       if(!res)
04704          res = saycharstr(mychannel, decimals);
04705    
04706       if(res)  break;
04707       if(myrpt->remmode == REM_MODE_FM){ /* Mode FM? */
04708          switch(myrpt->offset){
04709    
04710             case REM_MINUS:
04711                res = sayfile(mychannel,"rpt/minus");
04712                break;
04713             
04714             case REM_SIMPLEX:
04715                res = sayfile(mychannel,"rpt/simplex");
04716                break;
04717                
04718             case REM_PLUS:
04719                res = sayfile(mychannel,"rpt/plus");
04720                break;
04721                
04722             default:
04723                break;
04724          }
04725       }
04726       else{ /* Must be USB, LSB, or AM */
04727          switch(myrpt->remmode){
04728 
04729             case REM_MODE_USB:
04730                res = saycharstr(mychannel, "USB");
04731                break;
04732 
04733             case REM_MODE_LSB:
04734                res = saycharstr(mychannel, "LSB");
04735                break;
04736 
04737             case REM_MODE_AM:
04738                res = saycharstr(mychannel, "AM");
04739                break;
04740 
04741 
04742             default:
04743                break;
04744          }
04745       }
04746 
04747       if (res == -1) break;
04748 
04749       if(mytele->mode == REMSHORTSTATUS){ /* Short status? */
04750          wait_interval(myrpt, DLY_COMP, mychannel);
04751          if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04752          break;
04753       }
04754 
04755       if (strcmp(myrpt->remoterig,remote_rig_ic706))
04756       {
04757          switch(myrpt->powerlevel){
04758 
04759             case REM_LOWPWR:
04760                res = sayfile(mychannel,"rpt/lopwr") ;
04761                break;
04762             case REM_MEDPWR:
04763                res = sayfile(mychannel,"rpt/medpwr");
04764                break;
04765             case REM_HIPWR:
04766                res = sayfile(mychannel,"rpt/hipwr"); 
04767                break;
04768             }
04769       }
04770 
04771       rbimode = ((!strncmp(myrpt->remoterig,remote_rig_rbi,3))
04772         || (!strncmp(myrpt->remoterig,remote_rig_ic706,3)));
04773       if (res || (sayfile(mychannel,"rpt/rxpl") == -1)) break;
04774       if (rbimode && (sayfile(mychannel,"rpt/txpl") == -1)) break;
04775       if ((sayfile(mychannel,"rpt/frequency") == -1) ||
04776          (saycharstr(mychannel,myrpt->rxpl) == -1)) break;
04777       if ((!rbimode) && ((sayfile(mychannel,"rpt/txpl") == -1) ||
04778          (sayfile(mychannel,"rpt/frequency") == -1) ||
04779          (saycharstr(mychannel,myrpt->txpl) == -1))) break;
04780       if(myrpt->remmode == REM_MODE_FM){ /* Mode FM? */
04781          if ((sayfile(mychannel,"rpt/rxpl") == -1) ||
04782             (sayfile(mychannel,((myrpt->rxplon) ? "rpt/on" : "rpt/off")) == -1) ||
04783             (sayfile(mychannel,"rpt/txpl") == -1) ||
04784             (sayfile(mychannel,((myrpt->txplon) ? "rpt/on" : "rpt/off")) == -1))
04785             {
04786                break;
04787             }
04788       }
04789       wait_interval(myrpt, DLY_COMP, mychannel);
04790       if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04791       break;
04792        case STATUS:
04793       /* wait a little bit */
04794       wait_interval(myrpt, DLY_TELEM, mychannel);
04795       hastx = 0;
04796       linkbase.next = &linkbase;
04797       linkbase.prev = &linkbase;
04798       rpt_mutex_lock(&myrpt->lock);
04799       /* make our own list of links */
04800       l = myrpt->links.next;
04801       while(l != &myrpt->links)
04802       {
04803          if (l->name[0] == '0')
04804          {
04805             l = l->next;
04806             continue;
04807          }
04808          l1 = ast_malloc(sizeof(struct rpt_link));
04809          if (!l1)
04810          {
04811             ast_log(LOG_WARNING, "Cannot alloc memory on %s\n", mychannel->name);
04812             remque((struct qelem *)mytele);
04813             myrpt->active_telem = NULL;
04814             rpt_mutex_unlock(&myrpt->lock);
04815             ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04816             ast_free(nodename);
04817             ast_free(ident);
04818             ast_free(mytele);    
04819             ast_hangup(mychannel);
04820             pthread_exit(NULL);
04821          }
04822          memcpy(l1,l,sizeof(struct rpt_link));
04823          l1->next = l1->prev = NULL;
04824          insque((struct qelem *)l1,(struct qelem *)linkbase.next);
04825          l = l->next;
04826       }
04827       rpt_mutex_unlock(&myrpt->lock);
04828       res = saynode(myrpt,mychannel,myrpt->name);
04829       if (myrpt->callmode)
04830       {
04831          hastx = 1;
04832          res = ast_streamfile(mychannel, "rpt/autopatch_on", mychannel->language);
04833          if (!res) 
04834             res = ast_waitstream(mychannel, "");
04835          else
04836              ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04837          ast_stopstream(mychannel);
04838       }
04839       l = linkbase.next;
04840       while(l != &linkbase)
04841       {
04842          char *s;
04843 
04844          hastx = 1;
04845          res = saynode(myrpt,mychannel,l->name);
04846          s = "rpt/tranceive";
04847          if (!l->mode) s = "rpt/monitor";
04848          if (!l->thisconnected) s = "rpt/connecting";
04849          res = ast_streamfile(mychannel, s, mychannel->language);
04850          if (!res) 
04851             res = ast_waitstream(mychannel, "");
04852          else
04853             ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04854          ast_stopstream(mychannel);
04855          l = l->next;
04856       }        
04857       if (!hastx)
04858       {
04859          res = ast_streamfile(mychannel, "rpt/repeat_only", mychannel->language);
04860          if (!res) 
04861             res = ast_waitstream(mychannel, "");
04862          else
04863              ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04864          ast_stopstream(mychannel);
04865       }
04866       /* destroy our local link queue */
04867       l = linkbase.next;
04868       while(l != &linkbase)
04869       {
04870          l1 = l;
04871          l = l->next;
04872          remque((struct qelem *)l1);
04873          ast_free(l1);
04874       }        
04875       imdone = 1;
04876       break;
04877        case FULLSTATUS:
04878       rpt_mutex_lock(&myrpt->lock);
04879       /* get all the nodes */
04880       __mklinklist(myrpt,NULL,lbuf);
04881       rpt_mutex_unlock(&myrpt->lock);
04882       /* parse em */
04883       ns = finddelim(lbuf,strs,MAXLINKLIST);
04884       /* sort em */
04885       if (ns) qsort((void *)strs,ns,sizeof(char *),mycompar);
04886       /* wait a little bit */
04887       wait_interval(myrpt, DLY_TELEM, mychannel);
04888       hastx = 0;
04889       res = saynode(myrpt,mychannel,myrpt->name);
04890       if (myrpt->callmode)
04891       {
04892          hastx = 1;
04893          res = ast_streamfile(mychannel, "rpt/autopatch_on", mychannel->language);
04894          if (!res) 
04895             res = ast_waitstream(mychannel, "");
04896          else
04897              ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04898          ast_stopstream(mychannel);
04899       }
04900       /* go thru all the nodes in list */
04901       for(i = 0; i < ns; i++)
04902       {
04903          char *s,mode = 'T';
04904 
04905          /* if a mode spec at first, handle it */
04906          if ((*strs[i] < '0') || (*strs[i] > '9'))
04907          {
04908             mode = *strs[i];
04909             strs[i]++;
04910          }
04911 
04912          hastx = 1;
04913          res = saynode(myrpt,mychannel,strs[i]);
04914          s = "rpt/tranceive";
04915          if (mode == 'R') s = "rpt/monitor";
04916          if (mode == 'C') s = "rpt/connecting";
04917          res = ast_streamfile(mychannel, s, mychannel->language);
04918          if (!res) 
04919             res = ast_waitstream(mychannel, "");
04920          else
04921             ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04922          ast_stopstream(mychannel);
04923       }        
04924       if (!hastx)
04925       {
04926          res = ast_streamfile(mychannel, "rpt/repeat_only", mychannel->language);
04927          if (!res) 
04928             res = ast_waitstream(mychannel, "");
04929          else
04930              ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04931          ast_stopstream(mychannel);
04932       }
04933       imdone = 1;
04934       break;
04935 
04936        case LASTNODEKEY: /* Identify last node which keyed us up */
04937       rpt_mutex_lock(&myrpt->lock);
04938       if(myrpt->lastnodewhichkeyedusup){
04939          p = ast_strdup(myrpt->lastnodewhichkeyedusup); /* Make a local copy of the node name */
04940          if(!p){
04941             ast_log(LOG_WARNING, "ast_strdup failed in telemetery LASTNODEKEY");
04942             imdone = 1;
04943             break;
04944          }
04945       }
04946       else
04947          p = NULL;
04948       rpt_mutex_unlock(&myrpt->lock);
04949       if(!p){
04950          imdone = 1; /* no node previously keyed us up, or the node which did has been disconnected */
04951          break;
04952       }
04953       wait_interval(myrpt, DLY_TELEM, mychannel);
04954       res = saynode(myrpt,mychannel,p);
04955       ast_free(p);
04956       imdone = 1;
04957       break;      
04958 
04959        case UNAUTHTX: /* Say unauthorized transmit frequency */
04960       wait_interval(myrpt, DLY_TELEM, mychannel);
04961       res = ast_streamfile(mychannel, "rpt/unauthtx", mychannel->language);
04962       if (!res) 
04963          res = ast_waitstream(mychannel, "");
04964       else
04965           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04966       ast_stopstream(mychannel);
04967       imdone = 1;
04968       break;
04969 
04970        case PARROT: /* Repeat stuff */
04971 
04972       sprintf(mystr,PARROTFILE,myrpt->name,(unsigned int)mytele->parrot);
04973       if (ast_fileexists(mystr,NULL,mychannel->language) <= 0)
04974       {
04975          imdone = 1;
04976          myrpt->parrotstate = 0;
04977          break;
04978       }
04979       wait_interval(myrpt, DLY_PARROT, mychannel);
04980       sprintf(mystr,PARROTFILE,myrpt->name,(unsigned int)mytele->parrot);
04981       res = ast_streamfile(mychannel, mystr, mychannel->language);
04982       if (!res) 
04983          res = ast_waitstream(mychannel, "");
04984       else
04985           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04986       ast_stopstream(mychannel);
04987       sprintf(mystr,PARROTFILE,myrpt->name,(unsigned int)mytele->parrot);
04988       strcat(mystr,".wav");
04989       unlink(mystr);       
04990       imdone = 1;
04991       myrpt->parrotstate = 0;
04992       break;
04993 
04994        case TIMEOUT:
04995       res = saynode(myrpt,mychannel,myrpt->name);
04996       if (!res)
04997          res = ast_streamfile(mychannel, "rpt/timeout", mychannel->language);
04998       break;
04999       
05000        case TIMEOUT_WARNING:
05001       time(&t);
05002       res = saynode(myrpt,mychannel,myrpt->name);
05003       if (!res)
05004          res = ast_streamfile(mychannel, "rpt/timeout-warning", mychannel->language);
05005       if (!res) 
05006          res = ast_waitstream(mychannel, "");
05007       else
05008           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
05009       ast_stopstream(mychannel);
05010       if(!res) /* Say number of seconds */
05011          ast_say_number(mychannel, myrpt->p.remotetimeout - 
05012              (t - myrpt->last_activity_time), 
05013             "", mychannel->language, (char *) NULL);
05014       if (!res) 
05015          res = ast_waitstream(mychannel, "");
05016       ast_stopstream(mychannel); 
05017       res = ast_streamfile(mychannel, "queue-seconds", mychannel->language);
05018       break;
05019 
05020        case ACT_TIMEOUT_WARNING:
05021       time(&t);
05022       res = saynode(myrpt,mychannel,myrpt->name);
05023       if (!res)
05024           res = ast_streamfile(mychannel, "rpt/act-timeout-warning", mychannel->language);
05025       if (!res) 
05026          res = ast_waitstream(mychannel, "");
05027       else
05028           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
05029       ast_stopstream(mychannel);
05030       if(!res) /* Say number of seconds */
05031          ast_say_number(mychannel, myrpt->p.remoteinacttimeout - 
05032              (t - myrpt->last_activity_time), 
05033             "", mychannel->language, (char *) NULL);
05034       if (!res) 
05035          res = ast_waitstream(mychannel, "");
05036       ast_stopstream(mychannel); 
05037       res = ast_streamfile(mychannel, "queue-seconds", mychannel->language);
05038       break;
05039       
05040        case STATS_TIME:
05041             case STATS_TIME_LOCAL:
05042          wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
05043       t = time(NULL);
05044       rpt_localtime(&t, &localtm);
05045       /* Say the phase of the day is before the time */
05046       if((localtm.tm_hour >= 0) && (localtm.tm_hour < 12))
05047          p = "rpt/goodmorning";
05048       else if((localtm.tm_hour >= 12) && (localtm.tm_hour < 18))
05049          p = "rpt/goodafternoon";
05050       else
05051          p = "rpt/goodevening";
05052       if (sayfile(mychannel,p) == -1)
05053       {
05054          imdone = 1;
05055          break;
05056       }
05057       /* Say the time is ... */     
05058       if (sayfile(mychannel,"rpt/thetimeis") == -1)
05059       {
05060          imdone = 1;
05061          break;
05062       }
05063       /* Say the time */            
05064          res = ast_say_time(mychannel, t, "", mychannel->language);
05065       if (!res) 
05066          res = ast_waitstream(mychannel, "");
05067       ast_stopstream(mychannel);    
05068       imdone = 1;
05069          break;
05070        case STATS_VERSION:
05071       p = strstr(tdesc, "version"); 
05072       if(!p)
05073          break;   
05074       if(sscanf(p, "version %30d.%30d", &vmajor, &vminor) != 2)
05075          break;
05076          wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
05077       /* Say "version" */
05078       if (sayfile(mychannel,"rpt/version") == -1)
05079       {
05080          imdone = 1;
05081          break;
05082       }
05083       if(!res) /* Say "X" */
05084          ast_say_number(mychannel, vmajor, "", mychannel->language, (char *) NULL);
05085       if (!res) 
05086          res = ast_waitstream(mychannel, "");
05087       ast_stopstream(mychannel); 
05088       if (saycharstr(mychannel,".") == -1)
05089       {
05090          imdone = 1;
05091          break;
05092       }
05093       if(!res) /* Say "Y" */
05094          ast_say_number(mychannel, vminor, "", mychannel->language, (char *) NULL);
05095       if (!res){
05096          res = ast_waitstream(mychannel, "");
05097          ast_stopstream(mychannel);
05098       }  
05099       else
05100           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
05101       imdone = 1;
05102          break;
05103        case ARB_ALPHA:
05104          wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
05105          if(mytele->param)
05106             saycharstr(mychannel, mytele->param);
05107          imdone = 1;
05108       break;
05109        case REV_PATCH:
05110          wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
05111          if(mytele->param) {
05112 
05113          /* Parts of this section taken from app_parkandannounce */
05114          char *tpl_working, *tpl_current;
05115          char *tmp[100], *myparm;
05116          int looptemp=0,idx=0, dres = 0;
05117    
05118 
05119          tpl_working = ast_strdup(mytele->param);
05120          myparm = strsep(&tpl_working,",");
05121          tpl_current=strsep(&tpl_working, ":");
05122 
05123          while(tpl_current && looptemp < sizeof(tmp)) {
05124             tmp[looptemp]=tpl_current;
05125             looptemp++;
05126             tpl_current=strsep(&tpl_working,":");
05127          }
05128 
05129          for(idx=0; idx<looptemp; idx++) {
05130             if(!strcmp(tmp[idx], "PARKED")) {
05131                ast_say_digits(mychannel, atoi(myparm), "", mychannel->language);
05132             } else if(!strcmp(tmp[idx], "NODE")) {
05133                ast_say_digits(mychannel, atoi(myrpt->name), "", mychannel->language);
05134             } else {
05135                dres = ast_streamfile(mychannel, tmp[idx], mychannel->language);
05136                if(!dres) {
05137                   dres = ast_waitstream(mychannel, "");
05138                } else {
05139                   ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", tmp[idx], mychannel->name);
05140                   dres = 0;
05141                }
05142             }
05143          }
05144          ast_free(tpl_working);
05145       }
05146          imdone = 1;
05147       break;
05148        case TEST_TONE:
05149       imdone = 1;
05150       if (myrpt->stopgen) break;
05151       myrpt->stopgen = -1;
05152            if ((res = ast_tonepair_start(mychannel, 1004.0, 0, 99999999, 7200.0))) 
05153       {
05154          myrpt->stopgen = 0;
05155          break;
05156       }
05157            while(mychannel->generatordata && (myrpt->stopgen <= 0)) {
05158          if (ast_safe_sleep(mychannel,1)) break;
05159             imdone = 1;
05160          }
05161       myrpt->stopgen = 0;
05162       break;
05163        default:
05164          break;
05165    }
05166    if (!imdone)
05167    {
05168       if (!res) 
05169          res = ast_waitstream(mychannel, "");
05170       else {
05171          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
05172          res = 0;
05173       }
05174    }
05175    ast_stopstream(mychannel);
05176    rpt_mutex_lock(&myrpt->lock);
05177    if (mytele->mode == TAILMSG)
05178    {
05179       if (!res)
05180       {
05181          myrpt->tailmessagen++;
05182          if(myrpt->tailmessagen >= myrpt->p.tailmessagemax) myrpt->tailmessagen = 0;
05183       }
05184       else
05185       {
05186          myrpt->tmsgtimer = myrpt->p.tailsquashedtime;
05187       }
05188    }
05189    remque((struct qelem *)mytele);
05190    myrpt->active_telem = NULL;
05191    rpt_mutex_unlock(&myrpt->lock);
05192    ast_free(nodename);
05193    ast_free(ident);
05194    ast_free(mytele);    
05195    ast_hangup(mychannel);
05196 #ifdef  APP_RPT_LOCK_DEBUG
05197    {
05198       struct lockthread *t;
05199 
05200       sleep(5);
05201       ast_mutex_lock(&locklock);
05202       t = get_lockthread(pthread_self());
05203       if (t) memset(t,0,sizeof(struct lockthread));
05204       ast_mutex_unlock(&locklock);
05205    }        
05206 #endif
05207    pthread_exit(NULL);
05208 }
05209 
05210 static void rpt_telemetry(struct rpt *myrpt,int mode, void *data)
05211 {
05212 struct rpt_tele *tele;
05213 struct rpt_link *mylink = NULL;
05214 int res;
05215 pthread_attr_t attr;
05216 char *v1, *v2;
05217 
05218    if(debug > 6)
05219       ast_log(LOG_NOTICE,"mode=%i  data=%s\n",mode, (char *)data);
05220 
05221    switch(mode)
05222    {
05223        case UNKEY:
05224       /* if any of the following are defined, go ahead and do it,
05225          otherwise, don't bother */
05226       v1 = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, 
05227          "unlinkedct");
05228       v2 = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, 
05229          "remotect");
05230       if (telem_lookup(myrpt,NULL, myrpt->name, "remotemon") &&
05231         telem_lookup(myrpt,NULL, myrpt->name, "remotetx") &&
05232         telem_lookup(myrpt,NULL, myrpt->name, "cmdmode") &&
05233         (!(v1 && telem_lookup(myrpt,NULL, myrpt->name, v1))) && 
05234         (!(v2 && telem_lookup(myrpt,NULL, myrpt->name, v2)))) return;
05235       break;
05236        case LINKUNKEY:
05237       if (!ast_variable_retrieve(myrpt->cfg, myrpt->name, "linkunkeyct"))
05238          return;
05239       break;
05240        default:
05241       break;
05242    }
05243    tele = ast_malloc(sizeof(struct rpt_tele));
05244    if (!tele)
05245    {
05246       ast_log(LOG_WARNING, "Unable to allocate memory\n");
05247       pthread_exit(NULL);
05248       return;
05249    }
05250    /* zero it out */
05251    memset((char *)tele,0,sizeof(struct rpt_tele));
05252    tele->rpt = myrpt;
05253    tele->mode = mode;
05254    if (mode == PARROT) tele->parrot = (uintptr_t) data;
05255    else mylink = (struct rpt_link *) data;
05256    rpt_mutex_lock(&myrpt->lock);
05257    if((mode == CONNFAIL) || (mode == REMDISC) || (mode == CONNECTED) ||
05258        (mode == LINKUNKEY)){
05259       memset(&tele->mylink,0,sizeof(struct rpt_link));
05260       if (mylink){
05261          memcpy(&tele->mylink,mylink,sizeof(struct rpt_link));
05262       }
05263    }
05264    else if ((mode == ARB_ALPHA) || (mode == REV_PATCH) || (mode == PLAYBACK)) {
05265       strncpy(tele->param, (char *) data, TELEPARAMSIZE - 1);
05266       tele->param[TELEPARAMSIZE - 1] = 0;
05267    }
05268    if (mode == REMXXX) tele->submode = (intptr_t) data;
05269    insque((struct qelem *)tele, (struct qelem *)myrpt->tele.next);
05270    rpt_mutex_unlock(&myrpt->lock);
05271         pthread_attr_init(&attr);
05272         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
05273    res = ast_pthread_create(&tele->threadid,&attr,rpt_tele_thread,(void *) tele);
05274    if(res < 0){
05275       rpt_mutex_lock(&myrpt->lock);
05276       remque((struct qlem *) tele); /* We don't like stuck transmitters, remove it from the queue */
05277       rpt_mutex_unlock(&myrpt->lock);  
05278       ast_log(LOG_WARNING, "Could not create telemetry thread: %s",strerror(res));
05279    }
05280    return;
05281 }
05282 
05283 static void *rpt_call(void *this)
05284 {
05285 struct dahdi_confinfo ci;  /* conference info */
05286 struct   rpt *myrpt = (struct rpt *)this;
05287 int   res;
05288 int stopped,congstarted,dialtimer,lastcidx,aborted;
05289 struct ast_channel *mychannel,*genchannel;
05290 
05291    myrpt->mydtmf = 0;
05292    /* allocate a pseudo-channel thru asterisk */
05293    mychannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
05294    if (!mychannel)
05295    {
05296       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
05297       pthread_exit(NULL);
05298    }
05299 #ifdef   AST_CDR_FLAG_POST_DISABLED
05300    if (mychannel->cdr)
05301       ast_set_flag(mychannel->cdr,AST_CDR_FLAG_POST_DISABLED);
05302 #endif
05303    ci.chan = 0;
05304    ci.confno = myrpt->conf; /* use the pseudo conference */
05305 #if   0
05306    ci.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER
05307       | DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER; 
05308 #endif
05309    ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
05310    /* first put the channel on the conference */
05311    if (ioctl(mychannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05312    {
05313       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05314       ast_hangup(mychannel);
05315       myrpt->callmode = 0;
05316       pthread_exit(NULL);
05317    }
05318    /* allocate a pseudo-channel thru asterisk */
05319    genchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
05320    if (!genchannel)
05321    {
05322       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
05323       ast_hangup(mychannel);
05324       pthread_exit(NULL);
05325    }
05326 #ifdef   AST_CDR_FLAG_POST_DISABLED
05327    if (genchannel->cdr)
05328       ast_set_flag(genchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
05329 #endif
05330    ci.chan = 0;
05331    ci.confno = myrpt->conf;
05332    ci.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER
05333       | DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER; 
05334    /* first put the channel on the conference */
05335    if (ioctl(genchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05336    {
05337       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05338       ast_hangup(mychannel);
05339       ast_hangup(genchannel);
05340       myrpt->callmode = 0;
05341       pthread_exit(NULL);
05342    }
05343    if (myrpt->p.tonezone && (tone_zone_set_zone(mychannel->fds[0],myrpt->p.tonezone) == -1))
05344    {
05345       ast_log(LOG_WARNING, "Unable to set tone zone %s\n",myrpt->p.tonezone);
05346       ast_hangup(mychannel);
05347       ast_hangup(genchannel);
05348       myrpt->callmode = 0;
05349       pthread_exit(NULL);
05350    }
05351    if (myrpt->p.tonezone && (tone_zone_set_zone(genchannel->fds[0],myrpt->p.tonezone) == -1))
05352    {
05353       ast_log(LOG_WARNING, "Unable to set tone zone %s\n",myrpt->p.tonezone);
05354       ast_hangup(mychannel);
05355       ast_hangup(genchannel);
05356       myrpt->callmode = 0;
05357       pthread_exit(NULL);
05358    }
05359    /* start dialtone if patchquiet is 0. Special patch modes don't send dial tone */
05360    if ((!myrpt->patchquiet) && (tone_zone_play_tone(genchannel->fds[0],DAHDI_TONE_DIALTONE) < 0))
05361    {
05362       ast_log(LOG_WARNING, "Cannot start dialtone\n");
05363       ast_hangup(mychannel);
05364       ast_hangup(genchannel);
05365       myrpt->callmode = 0;
05366       pthread_exit(NULL);
05367    }
05368    stopped = 0;
05369    congstarted = 0;
05370    dialtimer = 0;
05371    lastcidx = 0;
05372    myrpt->calldigittimer = 0;
05373    aborted = 0;
05374 
05375    while ((myrpt->callmode == 1) || (myrpt->callmode == 4))
05376    {
05377       if((myrpt->patchdialtime)&&(myrpt->callmode == 1)&&(myrpt->cidx != lastcidx)){
05378          dialtimer = 0;
05379          lastcidx = myrpt->cidx;
05380       }     
05381 
05382       if((myrpt->patchdialtime)&&(dialtimer >= myrpt->patchdialtime)){ 
05383           if(debug)
05384             ast_log(LOG_NOTICE, "dialtimer %i > patchdialtime %i\n", dialtimer,myrpt->patchdialtime);
05385          rpt_mutex_lock(&myrpt->lock);
05386          aborted = 1;
05387          myrpt->callmode = 0;
05388          rpt_mutex_unlock(&myrpt->lock);
05389          break;
05390       }
05391    
05392       if ((!myrpt->patchquiet) && (!stopped) && (myrpt->callmode == 1) && (myrpt->cidx > 0))
05393       {
05394          stopped = 1;
05395          /* stop dial tone */
05396          tone_zone_play_tone(genchannel->fds[0],-1);
05397       }
05398       if (myrpt->callmode == 1)
05399       {
05400          if(myrpt->calldigittimer > PATCH_DIALPLAN_TIMEOUT)
05401          {
05402             myrpt->callmode = 2;
05403             break;
05404          }
05405          /* bump timer if active */
05406          if (myrpt->calldigittimer) 
05407             myrpt->calldigittimer += MSWAIT;
05408       }
05409       if (myrpt->callmode == 4)
05410       {
05411          if(!congstarted){
05412             congstarted = 1;
05413             /* start congestion tone */
05414             tone_zone_play_tone(genchannel->fds[0],DAHDI_TONE_CONGESTION);
05415          }
05416       }
05417       res = ast_safe_sleep(mychannel, MSWAIT);
05418       if (res < 0)
05419       {
05420           if(debug)
05421             ast_log(LOG_NOTICE, "ast_safe_sleep=%i\n", res);
05422          ast_hangup(mychannel);
05423          ast_hangup(genchannel);
05424          rpt_mutex_lock(&myrpt->lock);
05425          myrpt->callmode = 0;
05426          rpt_mutex_unlock(&myrpt->lock);
05427          pthread_exit(NULL);
05428       }
05429       dialtimer += MSWAIT;
05430    }
05431    /* stop any tone generation */
05432    tone_zone_play_tone(genchannel->fds[0],-1);
05433    /* end if done */
05434    if (!myrpt->callmode)
05435    {
05436       if(debug)
05437          ast_log(LOG_NOTICE, "callmode==0\n");
05438       ast_hangup(mychannel);
05439       ast_hangup(genchannel);
05440       rpt_mutex_lock(&myrpt->lock);
05441       myrpt->callmode = 0;
05442       myrpt->macropatch=0;
05443       channel_revert(myrpt);
05444       rpt_mutex_unlock(&myrpt->lock);
05445       if((!myrpt->patchquiet) && aborted)
05446          rpt_telemetry(myrpt, TERM, NULL);
05447       pthread_exit(NULL);        
05448    }
05449 
05450    if (myrpt->p.ourcallerid && *myrpt->p.ourcallerid){
05451       char *name, *loc, *instr;
05452       instr = ast_strdup(myrpt->p.ourcallerid);
05453       if(instr){
05454          ast_callerid_parse(instr, &name, &loc);
05455          if(loc){
05456             mychannel->caller.id.number.valid = 1;
05457             ast_free(mychannel->caller.id.number.str);
05458             mychannel->caller.id.number.str = ast_strdup(loc);
05459          }
05460          if(name){
05461             mychannel->caller.id.name.valid = 1;
05462             ast_free(mychannel->caller.id.name.str);
05463             mychannel->caller.id.name.str = ast_strdup(name);
05464          }
05465          ast_free(instr);
05466       }
05467    }
05468 
05469    ast_copy_string(mychannel->exten, myrpt->exten, sizeof(mychannel->exten) - 1);
05470    ast_copy_string(mychannel->context, myrpt->patchcontext, sizeof(mychannel->context) - 1);
05471    
05472    if (myrpt->p.acctcode)
05473       ast_cdr_setaccount(mychannel,myrpt->p.acctcode);
05474    mychannel->priority = 1;
05475    ast_channel_undefer_dtmf(mychannel);
05476    if (ast_pbx_start(mychannel) < 0)
05477    {
05478       ast_log(LOG_WARNING, "Unable to start PBX!!\n");
05479       ast_hangup(mychannel);
05480       ast_hangup(genchannel);
05481       rpt_mutex_lock(&myrpt->lock);
05482       myrpt->callmode = 0;
05483       rpt_mutex_unlock(&myrpt->lock);
05484       pthread_exit(NULL);
05485    }
05486    usleep(10000);
05487    rpt_mutex_lock(&myrpt->lock);
05488    myrpt->callmode = 3;
05489    /* set appropriate conference for the pseudo */
05490    ci.chan = 0;
05491    ci.confno = myrpt->conf;
05492    ci.confmode = (myrpt->p.duplex == 2) ? DAHDI_CONF_CONFANNMON :
05493       (DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER);
05494    /* first put the channel on the conference in announce mode */
05495    if (ioctl(myrpt->pchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05496    {
05497       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05498       ast_hangup(mychannel);
05499       ast_hangup(genchannel);
05500       myrpt->callmode = 0;
05501       pthread_exit(NULL);
05502    }
05503    /* get its channel number */
05504    if (ioctl(mychannel->fds[0],DAHDI_CHANNO,&res) == -1)
05505    {
05506       ast_log(LOG_WARNING, "Unable to get autopatch channel number\n");
05507       ast_hangup(mychannel);
05508       myrpt->callmode = 0;
05509       pthread_exit(NULL);
05510    }
05511    ci.chan = 0;
05512    ci.confno = res;
05513    ci.confmode = DAHDI_CONF_MONITOR;
05514    /* put vox channel monitoring on the channel  */
05515    if (ioctl(myrpt->voxchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05516    {
05517       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05518       ast_hangup(mychannel);
05519       myrpt->callmode = 0;
05520       pthread_exit(NULL);
05521    }
05522    while(myrpt->callmode)
05523    {
05524       if ((!mychannel->pbx) && (myrpt->callmode != 4))
05525       {
05526           /* If patch is setup for far end disconnect */
05527          if(myrpt->patchfarenddisconnect || (myrpt->p.duplex < 2)){ 
05528             if(debug)ast_log(LOG_NOTICE,"callmode=%i, patchfarenddisconnect=%i, duplex=%i\n",\
05529                   myrpt->callmode,myrpt->patchfarenddisconnect,myrpt->p.duplex);
05530             myrpt->callmode = 0;
05531             myrpt->macropatch=0;
05532             if(!myrpt->patchquiet){
05533                rpt_mutex_unlock(&myrpt->lock);
05534                rpt_telemetry(myrpt, TERM, NULL);
05535                rpt_mutex_lock(&myrpt->lock);
05536             }
05537          }
05538          else{ /* Send congestion until patch is downed by command */
05539             myrpt->callmode = 4;
05540             rpt_mutex_unlock(&myrpt->lock);
05541             /* start congestion tone */
05542             tone_zone_play_tone(genchannel->fds[0],DAHDI_TONE_CONGESTION);
05543             rpt_mutex_lock(&myrpt->lock);
05544          }
05545       }
05546       if (myrpt->mydtmf)
05547       {
05548          struct ast_frame wf = {AST_FRAME_DTMF, } ;
05549          wf.subclass.integer = myrpt->mydtmf;
05550          rpt_mutex_unlock(&myrpt->lock);
05551          ast_queue_frame(mychannel,&wf);
05552 #ifdef   NEW_ASTERISK
05553          ast_senddigit(genchannel,myrpt->mydtmf,0);
05554 #else
05555          ast_senddigit(genchannel,myrpt->mydtmf);
05556 #endif
05557          rpt_mutex_lock(&myrpt->lock);
05558          myrpt->mydtmf = 0;
05559       }
05560       rpt_mutex_unlock(&myrpt->lock);
05561       usleep(MSWAIT * 1000);
05562       rpt_mutex_lock(&myrpt->lock);
05563    }
05564    if(debug)
05565       ast_log(LOG_NOTICE, "exit channel loop\n");
05566    rpt_mutex_unlock(&myrpt->lock);
05567    tone_zone_play_tone(genchannel->fds[0],-1);
05568    if (mychannel->pbx) ast_softhangup(mychannel,AST_SOFTHANGUP_DEV);
05569    ast_hangup(genchannel);
05570    rpt_mutex_lock(&myrpt->lock);
05571    myrpt->callmode = 0;
05572    myrpt->macropatch=0;
05573    channel_revert(myrpt);
05574    rpt_mutex_unlock(&myrpt->lock);
05575    /* set appropriate conference for the pseudo */
05576    ci.chan = 0;
05577    ci.confno = myrpt->conf;
05578    ci.confmode = ((myrpt->p.duplex == 2) || (myrpt->p.duplex == 4)) ? DAHDI_CONF_CONFANNMON :
05579       (DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER);
05580    /* first put the channel on the conference in announce mode */
05581    if (ioctl(myrpt->pchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05582    {
05583       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05584    }
05585    pthread_exit(NULL);
05586 }
05587 
05588 static void send_link_dtmf(struct rpt *myrpt,char c)
05589 {
05590 char  str[300];
05591 struct   ast_frame wf;
05592 struct   rpt_link *l;
05593 
05594    snprintf(str, sizeof(str), "D %s %s %d %c", myrpt->cmdnode, myrpt->name, ++(myrpt->dtmfidx), c);
05595    wf.frametype = AST_FRAME_TEXT;
05596    wf.subclass.integer = 0;
05597    wf.offset = 0;
05598    wf.mallocd = 0;
05599    wf.datalen = strlen(str) + 1;
05600    wf.samples = 0;
05601    l = myrpt->links.next;
05602    /* first, see if our dude is there */
05603    while(l != &myrpt->links)
05604    {
05605       if (l->name[0] == '0') 
05606       {
05607          l = l->next;
05608          continue;
05609       }
05610       /* if we found it, write it and were done */
05611       if (!strcmp(l->name,myrpt->cmdnode))
05612       {
05613          wf.data.ptr = str;
05614          if (l->chan) ast_write(l->chan,&wf);
05615          return;
05616       }
05617       l = l->next;
05618    }
05619    l = myrpt->links.next;
05620    /* if not, give it to everyone */
05621    while(l != &myrpt->links)
05622    {
05623       wf.data.ptr = str;
05624       if (l->chan) ast_write(l->chan,&wf);
05625       l = l->next;
05626    }
05627    return;
05628 }
05629 
05630 static void send_link_keyquery(struct rpt *myrpt)
05631 {
05632 char  str[300];
05633 struct   ast_frame wf;
05634 struct   rpt_link *l;
05635 
05636    rpt_mutex_lock(&myrpt->lock);
05637    memset(myrpt->topkey,0,sizeof(myrpt->topkey));
05638    myrpt->topkeystate = 1;
05639    time(&myrpt->topkeytime);
05640    rpt_mutex_unlock(&myrpt->lock);
05641    snprintf(str, sizeof(str), "K? * %s 0 0", myrpt->name);
05642    wf.frametype = AST_FRAME_TEXT;
05643    wf.subclass.integer = 0;
05644    wf.offset = 0;
05645    wf.mallocd = 0;
05646    wf.datalen = strlen(str) + 1;
05647    wf.samples = 0;
05648    l = myrpt->links.next;
05649    /* give it to everyone */
05650    while(l != &myrpt->links)
05651    {
05652       wf.data.ptr = str;
05653       if (l->chan) ast_write(l->chan,&wf);
05654       l = l->next;
05655    }
05656    return;
05657 }
05658 
05659 /* send newkey request */
05660 
05661 static void send_newkey(struct ast_channel *chan)
05662 {
05663 
05664    /* ast_safe_sleep(chan,10); */
05665    ast_sendtext(chan,newkeystr);
05666    return;
05667 }
05668 
05669 
05670 /* 
05671  * Connect a link 
05672  *
05673  * Return values:
05674  * -2: Attempt to connect to self 
05675  * -1: No such node
05676  *  0: Success
05677  *  1: No match yet
05678  *  2: Already connected to this node
05679  */
05680 
05681 static int connect_link(struct rpt *myrpt, char* node, int mode, int perma)
05682 {
05683    char *val, *s, *s1, *s2, *tele;
05684    char lstr[MAXLINKLIST],*strs[MAXLINKLIST];
05685    char tmp[300], deststr[300] = "",modechange = 0;
05686    char sx[320],*sy;
05687    struct rpt_link *l;
05688    int reconnects = 0;
05689    int i,n;
05690    struct dahdi_confinfo ci;  /* conference info */
05691 
05692    val = node_lookup(myrpt,node);
05693    if (!val){
05694       if(strlen(node) >= myrpt->longestnode)
05695          return -1; /* No such node */
05696       return 1; /* No match yet */
05697    }
05698 
05699    if(!strcmp(myrpt->name,node)) /* Do not allow connections to self */
05700       return -2;
05701       
05702    if(debug > 3){
05703       ast_log(LOG_NOTICE,"Connect attempt to node %s\n", node);
05704       ast_log(LOG_NOTICE,"Mode: %s\n",(mode)?"Transceive":"Monitor");
05705       ast_log(LOG_NOTICE,"Connection type: %s\n",(perma)?"Permalink":"Normal");
05706    }
05707 
05708    strncpy(tmp,val,sizeof(tmp) - 1);
05709    s = tmp;
05710    s1 = strsep(&s,",");
05711    if (!strchr(s1,':') && strchr(s1,'/') && strncasecmp(s1, "local/", 6))
05712    {
05713       sy = strchr(s1,'/');    
05714       *sy = 0;
05715       sprintf(sx,"%s:4569/%s",s1,sy + 1);
05716       s1 = sx;
05717    }
05718    s2 = strsep(&s,",");
05719    rpt_mutex_lock(&myrpt->lock);
05720    l = myrpt->links.next;
05721    /* try to find this one in queue */
05722    while(l != &myrpt->links){
05723       if (l->name[0] == '0') 
05724       {
05725          l = l->next;
05726          continue;
05727       }
05728    /* if found matching string */
05729       if (!strcmp(l->name, node))
05730          break;
05731       l = l->next;
05732    }
05733    /* if found */
05734    if (l != &myrpt->links){ 
05735    /* if already in this mode, just ignore */
05736       if ((l->mode) || (!l->chan)) {
05737          rpt_mutex_unlock(&myrpt->lock);
05738          return 2; /* Already linked */
05739       }
05740       reconnects = l->reconnects;
05741       rpt_mutex_unlock(&myrpt->lock);
05742       if (l->chan) ast_softhangup(l->chan, AST_SOFTHANGUP_DEV);
05743       l->retries = l->max_retries + 1;
05744       l->disced = 2;
05745       modechange = 1;
05746    } else
05747    {
05748       __mklinklist(myrpt,NULL,lstr);
05749       rpt_mutex_unlock(&myrpt->lock);
05750       n = finddelim(lstr,strs,MAXLINKLIST);
05751       for(i = 0; i < n; i++)
05752       {
05753          if ((*strs[i] < '0') || 
05754              (*strs[i] > '9')) strs[i]++;
05755          if (!strcmp(strs[i],node))
05756          {
05757             return 2; /* Already linked */
05758          }
05759       }
05760    }
05761    strncpy(myrpt->lastlinknode,node,MAXNODESTR - 1);
05762    /* establish call */
05763    l = ast_malloc(sizeof(struct rpt_link));
05764    if (!l)
05765    {
05766       ast_log(LOG_WARNING, "Unable to malloc\n");
05767       return -1;
05768    }
05769    /* zero the silly thing */
05770    memset((char *)l,0,sizeof(struct rpt_link));
05771    l->mode = mode;
05772    l->outbound = 1;
05773    l->thisconnected = 0;
05774    voxinit_link(l,1);
05775    strncpy(l->name, node, MAXNODESTR - 1);
05776    l->isremote = (s && ast_true(s));
05777    if (modechange) l->connected = 1;
05778    l->hasconnected = l->perma = perma;
05779 #ifdef ALLOW_LOCAL_CHANNELS
05780    if ((strncasecmp(s1,"iax2/", 5) == 0) || (strncasecmp(s1, "local/", 6) == 0))
05781          strncpy(deststr, s1, sizeof(deststr));
05782    else
05783            snprintf(deststr, sizeof(deststr), "IAX2/%s", s1);
05784 #else
05785    snprintf(deststr, sizeof(deststr), "IAX2/%s", s1);
05786 #endif
05787    tele = strchr(deststr, '/');
05788    if (!tele){
05789       ast_log(LOG_WARNING,"link3:Dial number (%s) must be in format tech/number\n",deststr);
05790       ast_free(l);
05791       return -1;
05792    }
05793    *tele++ = 0;
05794    l->chan = ast_request(deststr, AST_FORMAT_SLINEAR, NULL, tele, NULL);
05795    if (l->chan){
05796       ast_set_read_format(l->chan, AST_FORMAT_SLINEAR);
05797       ast_set_write_format(l->chan, AST_FORMAT_SLINEAR);
05798 #ifdef   AST_CDR_FLAG_POST_DISABLED
05799       if (l->chan->cdr)
05800          ast_set_flag(l->chan->cdr,AST_CDR_FLAG_POST_DISABLED);
05801 #endif
05802 #ifndef  NEW_ASTERISK
05803       l->chan->whentohangup = 0;
05804 #endif
05805       l->chan->appl = "Apprpt";
05806       l->chan->data = "(Remote Rx)";
05807       if (debug > 3)
05808          ast_log(LOG_NOTICE, "rpt (remote) initiating call to %s/%s on %s\n",
05809       deststr, tele, l->chan->name);
05810       l->chan->caller.id.number.valid = 1;
05811       ast_free(l->chan->caller.id.number.str);
05812       l->chan->caller.id.number.str = ast_strdup(myrpt->name);
05813       ast_call(l->chan,tele,999);
05814    }
05815    else {
05816       if(debug > 3) 
05817          ast_log(LOG_NOTICE, "Unable to place call to %s/%s on %s\n",
05818       deststr,tele,l->chan->name);
05819       if (myrpt->p.archivedir)
05820       {
05821          char str[100];
05822          sprintf(str,"LINKFAIL,%s",l->name);
05823          donodelog(myrpt,str);
05824       }
05825       ast_free(l);
05826       return -1;
05827    }
05828    /* allocate a pseudo-channel thru asterisk */
05829    l->pchan = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
05830    if (!l->pchan){
05831       ast_log(LOG_WARNING,"rpt connect: Sorry unable to obtain pseudo channel\n");
05832       ast_hangup(l->chan);
05833       ast_free(l);
05834       return -1;
05835    }
05836    ast_set_read_format(l->pchan, AST_FORMAT_SLINEAR);
05837    ast_set_write_format(l->pchan, AST_FORMAT_SLINEAR);
05838 #ifdef   AST_CDR_FLAG_POST_DISABLED
05839    if (l->pchan->cdr)
05840       ast_set_flag(l->pchan->cdr,AST_CDR_FLAG_POST_DISABLED);
05841 #endif
05842    /* make a conference for the tx */
05843    ci.chan = 0;
05844    ci.confno = myrpt->conf;
05845    ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER;
05846    /* first put the channel on the conference in proper mode */
05847    if (ioctl(l->pchan->fds[0], DAHDI_SETCONF, &ci) == -1)
05848    {
05849       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05850       ast_hangup(l->chan);
05851       ast_hangup(l->pchan);
05852       ast_free(l);
05853       return -1;
05854    }
05855    rpt_mutex_lock(&myrpt->lock);
05856    l->reconnects = reconnects;
05857    /* insert at end of queue */
05858    l->max_retries = MAX_RETRIES;
05859    if (perma)
05860       l->max_retries = MAX_RETRIES_PERM;
05861    if (l->isremote) l->retries = l->max_retries + 1;
05862    insque((struct qelem *)l,(struct qelem *)myrpt->links.next);
05863    __kickshort(myrpt);
05864    rpt_mutex_unlock(&myrpt->lock);
05865    if (!l->phonemode) send_newkey(l->chan);
05866    return 0;
05867 }
05868 
05869 
05870 
05871 /*
05872 * Internet linking function 
05873 */
05874 
05875 static int function_ilink(struct rpt *myrpt, char *param, char *digits, int command_source, struct rpt_link *mylink)
05876 {
05877 
05878    char *val, *s, *s1, *s2;
05879    char tmp[300];
05880    char digitbuf[MAXNODESTR],*strs[MAXLINKLIST];
05881    char mode,perma;
05882    char sx[320],*sy;
05883    struct rpt_link *l;
05884    int i,r;
05885 
05886    if(!param)
05887       return DC_ERROR;
05888       
05889          
05890    if (myrpt->p.s[myrpt->p.sysstate_cur].txdisable || myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable )
05891       return DC_ERROR;
05892 
05893    strncpy(digitbuf,digits,MAXNODESTR - 1);
05894 
05895    if(debug > 6)
05896       printf("@@@@ ilink param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
05897       
05898    switch(myatoi(param)){
05899       case 11: /* Perm Link off */
05900       case 1: /* Link off */
05901          if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
05902             strcpy(digitbuf,myrpt->lastlinknode);
05903          val = node_lookup(myrpt,digitbuf);
05904          if (!val){
05905             if(strlen(digitbuf) >= myrpt->longestnode)
05906                return DC_ERROR;
05907             break;
05908          }
05909          strncpy(tmp,val,sizeof(tmp) - 1);
05910          s = tmp;
05911          s1 = strsep(&s,",");
05912          if (!strchr(s1,':') && strchr(s1,'/') && strncasecmp(s1, "local/", 6))
05913          {
05914             sy = strchr(s1,'/');    
05915             *sy = 0;
05916             sprintf(sx,"%s:4569/%s",s1,sy + 1);
05917             s1 = sx;
05918          }
05919          s2 = strsep(&s,",");
05920          rpt_mutex_lock(&myrpt->lock);
05921          l = myrpt->links.next;
05922          /* try to find this one in queue */
05923          while(l != &myrpt->links){
05924             if (l->name[0] == '0') 
05925             {
05926                l = l->next;
05927                continue;
05928             }
05929             /* if found matching string */
05930             if (!strcmp(l->name, digitbuf))
05931                break;
05932             l = l->next;
05933          }
05934          if (l != &myrpt->links){ /* if found */
05935             struct   ast_frame wf;
05936 
05937             /* must use perm command on perm link */
05938             if ((myatoi(param) < 10) && 
05939                 (l->max_retries > MAX_RETRIES))
05940             {
05941                rpt_mutex_unlock(&myrpt->lock);
05942                return DC_COMPLETE;
05943             }
05944             strncpy(myrpt->lastlinknode,digitbuf,MAXNODESTR - 1);
05945             l->retries = l->max_retries + 1;
05946             l->disced = 1;
05947             rpt_mutex_unlock(&myrpt->lock);
05948             wf.frametype = AST_FRAME_TEXT;
05949             wf.subclass.integer = 0;
05950             wf.offset = 0;
05951             wf.mallocd = 0;
05952             wf.datalen = strlen(discstr) + 1;
05953             wf.samples = 0;
05954             wf.data.ptr = discstr;
05955             if (l->chan)
05956             {
05957                ast_write(l->chan,&wf);
05958                if (ast_safe_sleep(l->chan,250) == -1) return DC_ERROR;
05959                ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
05960             }
05961             rpt_telemetry(myrpt, COMPLETE, NULL);
05962             return DC_COMPLETE;
05963          }
05964          rpt_mutex_unlock(&myrpt->lock);  
05965          return DC_COMPLETE;
05966       case 2: /* Link Monitor */
05967       case 3: /* Link transceive */
05968       case 12: /* Link Monitor permanent */
05969       case 13: /* Link transceive permanent */
05970          if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
05971             strcpy(digitbuf,myrpt->lastlinknode);
05972          /* Attempt connection  */
05973          perma = (atoi(param) > 10) ? 1 : 0;
05974          mode = (atoi(param) & 1) ? 1 : 0;
05975          r = connect_link(myrpt, digitbuf, mode, perma);
05976          switch(r){
05977             case -2: /* Attempt to connect to self */
05978                return DC_COMPLETE; /* Silent error */
05979 
05980             case 0:
05981                rpt_telemetry(myrpt, COMPLETE, NULL);
05982                return DC_COMPLETE;
05983 
05984             case 1:
05985                break;
05986             
05987             case 2:
05988                rpt_telemetry(myrpt, REMALREADY, NULL);
05989                return DC_COMPLETE;
05990             
05991             default:
05992                rpt_telemetry(myrpt, CONNFAIL, NULL);
05993                return DC_COMPLETE;
05994          }
05995          break;
05996 
05997       case 4: /* Enter Command Mode */
05998       
05999          /* if doesnt allow link cmd, or no links active, return */
06000          if (((command_source != SOURCE_RPT) && 
06001             (command_source != SOURCE_PHONE) &&
06002             (command_source != SOURCE_ALT) &&
06003             (command_source != SOURCE_DPHONE)) ||
06004              (myrpt->links.next == &myrpt->links))
06005             return DC_COMPLETE;
06006          
06007          /* if already in cmd mode, or selected self, fughetabahtit */
06008          if ((myrpt->cmdnode[0]) || (!strcmp(myrpt->name, digitbuf))){
06009          
06010             rpt_telemetry(myrpt, REMALREADY, NULL);
06011             return DC_COMPLETE;
06012          }
06013          if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
06014             strcpy(digitbuf,myrpt->lastlinknode);
06015          /* node must at least exist in list */
06016          val = node_lookup(myrpt,digitbuf);
06017          if (!val){
06018             if(strlen(digitbuf) >= myrpt->longestnode)
06019                return DC_ERROR;
06020             break;
06021          
06022          }
06023          rpt_mutex_lock(&myrpt->lock);
06024          strcpy(myrpt->lastlinknode,digitbuf);
06025          strncpy(myrpt->cmdnode, digitbuf, sizeof(myrpt->cmdnode) - 1);
06026          rpt_mutex_unlock(&myrpt->lock);
06027          rpt_telemetry(myrpt, REMGO, NULL);  
06028          return DC_COMPLETE;
06029          
06030       case 5: /* Status */
06031          rpt_telemetry(myrpt, STATUS, NULL);
06032          return DC_COMPLETE;
06033 
06034       case 15: /* Full Status */
06035          rpt_telemetry(myrpt, FULLSTATUS, NULL);
06036          return DC_COMPLETE;
06037          
06038          
06039       case 6: /* All Links Off, including permalinks */
06040                        rpt_mutex_lock(&myrpt->lock);
06041          myrpt->savednodes[0] = 0;
06042                         l = myrpt->links.next;
06043                         /* loop through all links */
06044                         while(l != &myrpt->links){
06045             struct   ast_frame wf;
06046                                 if (l->name[0] == '0') /* Skip any IAXRPT monitoring */
06047                                 {
06048                                         l = l->next;
06049                                         continue;
06050                                 }
06051             /* Make a string of disconnected nodes for possible restoration */
06052             sprintf(tmp,"%c%c%s",(l->mode) ? 'X' : 'M',(l->perma) ? 'P':'T',l->name);
06053             if(strlen(tmp) + strlen(myrpt->savednodes) + 1 < MAXNODESTR){ 
06054                if(myrpt->savednodes[0])
06055                   strcat(myrpt->savednodes, ",");
06056                strcat(myrpt->savednodes, tmp);
06057             }
06058                               l->retries = l->max_retries + 1;
06059                                 l->disced = 2; /* Silently disconnect */
06060                                 rpt_mutex_unlock(&myrpt->lock);
06061             /* ast_log(LOG_NOTICE,"dumping link %s\n",l->name); */
06062                                 
06063                                 wf.frametype = AST_FRAME_TEXT;
06064                                 wf.subclass.integer = 0;
06065                                 wf.offset = 0;
06066                                 wf.mallocd = 0;
06067                                 wf.datalen = strlen(discstr) + 1;
06068                                 wf.samples = 0;
06069                                 wf.data.ptr = discstr;
06070                                 if (l->chan)
06071                                 {
06072                                         ast_write(l->chan,&wf);
06073                                         ast_safe_sleep(l->chan,250); /* It's dead already, why check the return value? */
06074                                         ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
06075                                 }
06076             rpt_mutex_lock(&myrpt->lock);
06077                                 l = l->next;
06078                         }
06079          rpt_mutex_unlock(&myrpt->lock);
06080          if(debug > 3)
06081             ast_log(LOG_NOTICE,"Nodes disconnected: %s\n",myrpt->savednodes);
06082                         rpt_telemetry(myrpt, COMPLETE, NULL);
06083          return DC_COMPLETE;
06084 
06085       case 7: /* Identify last node which keyed us up */
06086          rpt_telemetry(myrpt, LASTNODEKEY, NULL);
06087          break;
06088 
06089 
06090 #ifdef   _MDC_DECODE_H_
06091       case 8:
06092          myrpt->lastunit = 0xd00d; 
06093          mdc1200_notify(myrpt,NULL,myrpt->lastunit);
06094          mdc1200_send(myrpt,myrpt->lastunit);
06095          break;
06096 #endif
06097 
06098       case 16: /* Restore links disconnected with "disconnect all links" command */
06099          strcpy(tmp, myrpt->savednodes); /* Make a copy */
06100          finddelim(tmp, strs, MAXLINKLIST); /* convert into substrings */
06101          for(i = 0; tmp[0] && strs[i] != NULL && i < MAXLINKLIST; i++){
06102             s1 = strs[i];
06103             mode = (s1[0] == 'X') ? 1 : 0;
06104             perma = (s1[1] == 'P') ? 1 : 0;
06105             connect_link(myrpt, s1 + 2, mode, perma); /* Try to reconnect */
06106          }
06107                         rpt_telemetry(myrpt, COMPLETE, NULL);
06108          break;
06109    
06110       case 200:
06111       case 201:
06112       case 202:
06113       case 203:
06114       case 204:
06115       case 205:
06116       case 206:
06117       case 207:
06118       case 208:
06119       case 209:
06120       case 210:
06121       case 211:
06122       case 212:
06123       case 213:
06124       case 214:
06125       case 215:
06126          if (((myrpt->p.propagate_dtmf) && 
06127               (command_source == SOURCE_LNK)) ||
06128              ((myrpt->p.propagate_phonedtmf) &&
06129             ((command_source == SOURCE_PHONE) ||
06130               (command_source == SOURCE_ALT) ||
06131                 (command_source == SOURCE_DPHONE))))
06132                do_dtmf_local(myrpt,
06133                   remdtmfstr[myatoi(param) - 200]);
06134       default:
06135          return DC_ERROR;
06136          
06137    }
06138    
06139    return DC_INDETERMINATE;
06140 }  
06141 
06142 /*
06143 * Autopatch up
06144 */
06145 
06146 static int function_autopatchup(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06147 {
06148    pthread_attr_t attr;
06149    int i, idx, paramlength;
06150    char *lparam;
06151    char *value = NULL;
06152    char *paramlist[20];
06153 
06154    static char *keywords[] = {
06155    "context",
06156    "dialtime",
06157    "farenddisconnect",
06158    "noct",
06159    "quiet",
06160    NULL
06161    };
06162       
06163    if (myrpt->p.s[myrpt->p.sysstate_cur].txdisable || myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable)
06164       return DC_ERROR;
06165       
06166    if(debug)
06167       printf("@@@@ Autopatch up\n");
06168 
06169    if(!myrpt->callmode){
06170       /* Set defaults */
06171       myrpt->patchnoct = 0;
06172       myrpt->patchdialtime = 0;
06173       myrpt->patchfarenddisconnect = 0;
06174       myrpt->patchquiet = 0;
06175       strncpy(myrpt->patchcontext, myrpt->p.ourcontext, MAXPATCHCONTEXT);
06176 
06177       if(param){
06178          /* Process parameter list */
06179          lparam = ast_strdup(param);
06180          if(!lparam){
06181             ast_log(LOG_ERROR,"App_rpt out of memory on line %d\n",__LINE__);
06182             return DC_ERROR;  
06183          }
06184          paramlength = finddelim(lparam, paramlist, 20);          
06185          for(i = 0; i < paramlength; i++){
06186             idx = matchkeyword(paramlist[i], &value, keywords);
06187             if(value)
06188                value = skipchars(value, "= ");
06189             switch(idx){
06190 
06191                case 1: /* context */
06192                   strncpy(myrpt->patchcontext, value, MAXPATCHCONTEXT - 1) ;
06193                   break;
06194                   
06195                case 2: /* dialtime */
06196                   myrpt->patchdialtime = atoi(value);
06197                   break;
06198 
06199                case 3: /* farenddisconnect */
06200                   myrpt->patchfarenddisconnect = atoi(value);
06201                   break;
06202 
06203                case 4:  /* noct */
06204                   myrpt->patchnoct = atoi(value);
06205                   break;
06206 
06207                case 5: /* quiet */
06208                   myrpt->patchquiet = atoi(value);
06209                   break;
06210                            
06211                default:
06212                   break;
06213             }
06214          }
06215       ast_free(lparam);
06216       }
06217    }
06218                
06219    rpt_mutex_lock(&myrpt->lock);
06220 
06221    /* if on call, force * into current audio stream */
06222    
06223    if ((myrpt->callmode == 2) || (myrpt->callmode == 3)){
06224       myrpt->mydtmf = myrpt->p.endchar;
06225    }
06226    if (myrpt->callmode){
06227       rpt_mutex_unlock(&myrpt->lock);
06228       return DC_COMPLETE;
06229    }
06230    myrpt->callmode = 1;
06231    myrpt->cidx = 0;
06232    myrpt->exten[myrpt->cidx] = 0;
06233    rpt_mutex_unlock(&myrpt->lock);
06234    pthread_attr_init(&attr);
06235    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
06236    ast_pthread_create(&myrpt->rpt_call_thread,&attr,rpt_call,(void *) myrpt);
06237    return DC_COMPLETE;
06238 }
06239 
06240 /*
06241 * Autopatch down
06242 */
06243 
06244 static int function_autopatchdn(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06245 {
06246    if (myrpt->p.s[myrpt->p.sysstate_cur].txdisable || myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable)
06247       return DC_ERROR;
06248    
06249    if(debug)
06250       printf("@@@@ Autopatch down\n");
06251       
06252    rpt_mutex_lock(&myrpt->lock);
06253    
06254    myrpt->macropatch=0;
06255 
06256    if (!myrpt->callmode){
06257       rpt_mutex_unlock(&myrpt->lock);
06258       return DC_COMPLETE;
06259    }
06260    
06261    myrpt->callmode = 0;
06262    channel_revert(myrpt);
06263    rpt_mutex_unlock(&myrpt->lock);
06264    rpt_telemetry(myrpt, TERM, NULL);
06265    return DC_COMPLETE;
06266 }
06267 
06268 /*
06269 * Status
06270 */
06271 
06272 static int function_status(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06273 {
06274 
06275    if (!param)
06276       return DC_ERROR;
06277 
06278    if ((myrpt->p.s[myrpt->p.sysstate_cur].txdisable) || (myrpt->p.s[myrpt->p.sysstate_cur].userfundisable))
06279       return DC_ERROR;
06280 
06281    if(debug)
06282       printf("@@@@ status param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
06283    
06284    switch(myatoi(param)){
06285       case 1: /* System ID */
06286          rpt_telemetry(myrpt, ID1, NULL);
06287          return DC_COMPLETE;
06288       case 2: /* System Time */
06289          rpt_telemetry(myrpt, STATS_TIME, NULL);
06290          return DC_COMPLETE;
06291       case 3: /* app_rpt.c version */
06292          rpt_telemetry(myrpt, STATS_VERSION, NULL);
06293          return DC_COMPLETE;
06294       case 11: /* System ID (local only)*/
06295           rpt_telemetry(myrpt, ID , NULL);
06296             return DC_COMPLETE;
06297         case 12: /* System Time (local only)*/
06298             rpt_telemetry(myrpt, STATS_TIME_LOCAL, NULL);
06299             return DC_COMPLETE;
06300       default:
06301          return DC_ERROR;
06302    }
06303    return DC_INDETERMINATE;
06304 }
06305 /*
06306 *  Macro-oni (without Salami)
06307 */
06308 static int function_macro(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06309 {
06310 char  *val;
06311 int   i;
06312    if (myrpt->remote)
06313       return DC_ERROR;
06314 
06315    if(debug) 
06316       printf("@@@@ macro-oni param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
06317    
06318    if(strlen(digitbuf) < 1) /* needs 1 digit */
06319       return DC_INDETERMINATE;
06320          
06321    for(i = 0 ; i < digitbuf[i] ; i++) {
06322       if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
06323          return DC_ERROR;
06324    }
06325    
06326    if (*digitbuf == '0') val = myrpt->p.startupmacro;
06327    else val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.macro, digitbuf);
06328    /* param was 1 for local buf */
06329    if (!val){
06330                 if (strlen(digitbuf) < myrpt->macro_longest)
06331                         return DC_INDETERMINATE;
06332       rpt_telemetry(myrpt, MACRO_NOTFOUND, NULL);
06333       return DC_COMPLETE;
06334    }        
06335    rpt_mutex_lock(&myrpt->lock);
06336    if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(val))
06337    {
06338       rpt_mutex_unlock(&myrpt->lock);
06339       rpt_telemetry(myrpt, MACRO_BUSY, NULL);
06340       return DC_ERROR;
06341    }
06342    myrpt->macrotimer = MACROTIME;
06343    strncat(myrpt->macrobuf,val,MAXMACRO - 1);
06344    rpt_mutex_unlock(&myrpt->lock);
06345    return DC_COMPLETE;  
06346 }
06347 
06348 /*
06349 *  Playback a recording
06350 */
06351 
06352 static int function_playback(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06353 {
06354 
06355    if (myrpt->remote)
06356       return DC_ERROR;
06357 
06358    if(debug) 
06359       printf("@@@@ playback param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
06360    
06361    if (ast_fileexists(param,NULL,myrpt->rxchannel->language) <= 0)
06362       return DC_ERROR;
06363 
06364    rpt_telemetry(myrpt,PLAYBACK,param);
06365    return DC_COMPLETE;
06366 }
06367 
06368 /*
06369 * COP - Control operator
06370 */
06371 
06372 static int function_cop(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06373 {
06374    char string[16];
06375    int res;
06376 
06377    int i, r;
06378 
06379    if(!param)
06380       return DC_ERROR;
06381    
06382    switch(myatoi(param)){
06383       case 1: /* System reset */
06384          res = system("killall -9 asterisk");
06385          return DC_COMPLETE;
06386 
06387       case 2:
06388          myrpt->p.s[myrpt->p.sysstate_cur].txdisable = 0;
06389          rpt_telemetry(myrpt, ARB_ALPHA, (void *) "RPTENA");
06390          return DC_COMPLETE;
06391          
06392       case 3:
06393          myrpt->p.s[myrpt->p.sysstate_cur].txdisable = 1;
06394          return DC_COMPLETE;
06395          
06396       case 4: /* test tone on */
06397          if (myrpt->stopgen < 0) 
06398          {
06399             myrpt->stopgen = 1;
06400          }
06401          else 
06402          {
06403             myrpt->stopgen = 0;
06404             rpt_telemetry(myrpt, TEST_TONE, NULL);
06405          }
06406          return DC_COMPLETE;
06407 
06408       case 5: /* Disgorge variables to log for debug purposes */
06409          myrpt->disgorgetime = time(NULL) + 10; /* Do it 10 seconds later */
06410          return DC_COMPLETE;
06411 
06412       case 6: /* Simulate COR being activated (phone only) */
06413          if (command_source != SOURCE_PHONE) return DC_INDETERMINATE;
06414          return DC_DOKEY;  
06415 
06416 
06417       case 7: /* Time out timer enable */
06418          myrpt->p.s[myrpt->p.sysstate_cur].totdisable = 0;
06419          rpt_telemetry(myrpt, ARB_ALPHA, (void *) "TOTENA");
06420          return DC_COMPLETE;
06421          
06422       case 8: /* Time out timer disable */
06423          myrpt->p.s[myrpt->p.sysstate_cur].totdisable = 1;
06424          rpt_telemetry(myrpt, ARB_ALPHA, (void *) "TOTDIS");
06425          return DC_COMPLETE;
06426 
06427                 case 9: /* Autopatch enable */
06428                         myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable = 0;
06429                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "APENA");
06430                         return DC_COMPLETE;
06431 
06432                 case 10: /* Autopatch disable */
06433                         myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable = 1;
06434                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "APDIS");
06435                         return DC_COMPLETE;
06436 
06437                 case 11: /* Link Enable */
06438                         myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable = 0;
06439                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "LNKENA");
06440                         return DC_COMPLETE;
06441 
06442                 case 12: /* Link Disable */
06443                         myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable = 1;
06444                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "LNKDIS");
06445                         return DC_COMPLETE;
06446 
06447       case 13: /* Query System State */
06448          string[0] = string[1] = 'S';
06449          string[2] = myrpt->p.sysstate_cur + '0';
06450          string[3] = '\0';
06451          rpt_telemetry(myrpt, ARB_ALPHA, (void *) string);
06452          return DC_COMPLETE;
06453 
06454       case 14: /* Change System State */
06455          if(strlen(digitbuf) == 0)
06456             break;
06457          if((digitbuf[0] < '0') || (digitbuf[0] > '9'))
06458             return DC_ERROR;
06459          myrpt->p.sysstate_cur = digitbuf[0] - '0';
06460                         string[0] = string[1] = 'S';
06461                         string[2] = myrpt->p.sysstate_cur + '0';
06462                         string[3] = '\0';
06463                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) string);
06464                         return DC_COMPLETE;
06465 
06466                 case 15: /* Scheduler Enable */
06467                         myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable = 0;
06468                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "SKENA");
06469                         return DC_COMPLETE;
06470 
06471                 case 16: /* Scheduler Disable */
06472                         myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable = 1;
06473                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "SKDIS");
06474                         return DC_COMPLETE;
06475 
06476                 case 17: /* User functions Enable */
06477                         myrpt->p.s[myrpt->p.sysstate_cur].userfundisable = 0;
06478                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "UFENA");
06479                         return DC_COMPLETE;
06480 
06481                 case 18: /* User Functions Disable */
06482                         myrpt->p.s[myrpt->p.sysstate_cur].userfundisable = 1;
06483                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "UFDIS");
06484                         return DC_COMPLETE;
06485 
06486                 case 19: /* Alternate Tail Enable */
06487                         myrpt->p.s[myrpt->p.sysstate_cur].alternatetail = 1;
06488                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "ATENA");
06489                         return DC_COMPLETE;
06490 
06491                 case 20: /* Alternate Tail Disable */
06492                         myrpt->p.s[myrpt->p.sysstate_cur].alternatetail = 0;
06493                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "ATDIS");
06494                         return DC_COMPLETE;
06495 
06496                 case 21: /* Parrot Mode Disable */
06497          birdbath(myrpt);
06498          if (myrpt->p.parrotmode < 2)
06499          {
06500             myrpt->p.parrotmode = 0;
06501             rpt_telemetry(myrpt,COMPLETE,NULL);
06502             return DC_COMPLETE;
06503          }
06504          break;
06505 
06506                 case 22: /* Parrot Mode Enable */
06507          birdbath(myrpt);
06508          if (myrpt->p.parrotmode < 2)
06509          {
06510             myrpt->p.parrotmode = 1;
06511             rpt_telemetry(myrpt,COMPLETE,NULL);
06512             return DC_COMPLETE;
06513          }
06514          break;
06515       case 23: /* flush parrot in progress */
06516          birdbath(myrpt);
06517          rpt_telemetry(myrpt,COMPLETE,NULL);
06518          return DC_COMPLETE;
06519       case 24: /* flush all telemetry */
06520          flush_telem(myrpt);
06521          rpt_telemetry(myrpt,COMPLETE,NULL);
06522          return DC_COMPLETE;
06523       case 25: /* request keying info (brief) */
06524          send_link_keyquery(myrpt);
06525          myrpt->topkeylong = 0;
06526          rpt_telemetry(myrpt,COMPLETE,NULL);
06527          return DC_COMPLETE;
06528       case 26: /* request keying info (full) */
06529          send_link_keyquery(myrpt);
06530          myrpt->topkeylong = 1;
06531          rpt_telemetry(myrpt,COMPLETE,NULL);
06532          return DC_COMPLETE;
06533 
06534       case 30: /* recall memory location on programmable radio */
06535 
06536          if(strlen(digitbuf) < 2) /* needs 2 digits */
06537             break;
06538          
06539          for(i = 0 ; i < 2 ; i++){
06540             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
06541                return DC_ERROR;
06542          }
06543        
06544          r = retreive_memory(myrpt, digitbuf);
06545          if (r < 0){
06546             rpt_telemetry(myrpt,MEMNOTFOUND,NULL);
06547             return DC_COMPLETE;
06548          }
06549          if (r > 0){
06550             return DC_ERROR;
06551          }
06552          if (setrem(myrpt) == -1) return DC_ERROR;
06553          return DC_COMPLETE;  
06554 
06555       case 31: 
06556           /* set channel. note that it's going to change channel 
06557              then confirm on the new channel! */
06558          if(strlen(digitbuf) < 2) /* needs 2 digits */
06559             break;
06560          
06561          for(i = 0 ; i < 2 ; i++){
06562             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
06563                return DC_ERROR;
06564          }
06565          channel_steer(myrpt,digitbuf);
06566          return DC_COMPLETE;  
06567 
06568       case 32: /* Touch Tone Pad Test */
06569          i = strlen(digitbuf);
06570          if(!i){
06571             if(debug > 3)
06572             ast_log(LOG_NOTICE,"Padtest entered");
06573             myrpt->inpadtest = 1;
06574          }
06575          else{
06576             if(debug > 3)
06577                ast_log(LOG_NOTICE,"Padtest len= %d digits=%s",i,digitbuf);
06578             if(digitbuf[i-1] != myrpt->p.endchar)
06579                break;
06580             rpt_telemetry(myrpt, ARB_ALPHA, digitbuf);
06581             myrpt->inpadtest = 0;
06582             if(debug > 3)
06583                ast_log(LOG_NOTICE,"Padtest exited");
06584             return DC_COMPLETE;
06585          }
06586    }  
06587    return DC_INDETERMINATE;
06588 }
06589 /*
06590 * Collect digits one by one until something matches
06591 */
06592 static int collect_function_digits(struct rpt *myrpt, char *digits, 
06593    int command_source, struct rpt_link *mylink)
06594 {
06595    int i,rv;
06596    char *stringp,*action,*param,*functiondigits;
06597    char function_table_name[30] = "";
06598    char workstring[200];
06599    
06600    struct ast_variable *vp;
06601    
06602    if (debug > 6) ast_log(LOG_NOTICE,"digits=%s  source=%d\n",digits, command_source);
06603 
06604    //if(debug) 
06605    // printf("@@@@ Digits collected: %s, source: %d\n", digits, command_source);
06606    
06607    if (command_source == SOURCE_DPHONE) {
06608       if (!myrpt->p.dphone_functions) return DC_INDETERMINATE;
06609       strncpy(function_table_name, myrpt->p.dphone_functions, sizeof(function_table_name) - 1);
06610       }
06611    else if (command_source == SOURCE_ALT) {
06612       if (!myrpt->p.alt_functions) return DC_INDETERMINATE;
06613       strncpy(function_table_name, myrpt->p.alt_functions, sizeof(function_table_name) - 1);
06614       }
06615    else if (command_source == SOURCE_PHONE) {
06616       if (!myrpt->p.phone_functions) return DC_INDETERMINATE;
06617       strncpy(function_table_name, myrpt->p.phone_functions, sizeof(function_table_name) - 1);
06618       }
06619    else if (command_source == SOURCE_LNK)
06620       strncpy(function_table_name, myrpt->p.link_functions, sizeof(function_table_name) - 1);
06621    else
06622       strncpy(function_table_name, myrpt->p.functions, sizeof(function_table_name) - 1);
06623     /* find context for function table in rpt.conf file */
06624    vp = ast_variable_browse(myrpt->cfg, function_table_name);
06625    while(vp) {
06626       if(!strncasecmp(vp->name, digits, strlen(vp->name)))
06627          break;
06628       vp = vp->next;
06629    }  
06630    /* if function context not found */
06631    if(!vp) {
06632       int n;
06633 
06634       n = myrpt->longestfunc;
06635       if (command_source == SOURCE_LNK) n = myrpt->link_longestfunc;
06636       else 
06637       if (command_source == SOURCE_PHONE) n = myrpt->phone_longestfunc;
06638       else 
06639       if (command_source == SOURCE_ALT) n = myrpt->alt_longestfunc;
06640       else 
06641       if (command_source == SOURCE_DPHONE) n = myrpt->dphone_longestfunc;
06642       
06643       if(strlen(digits) >= n)
06644          return DC_ERROR;
06645       else
06646          return DC_INDETERMINATE;
06647    }  
06648    /* Found a match, retrieve value part and parse */
06649    strncpy(workstring, vp->value, sizeof(workstring) - 1 );
06650    stringp = workstring;
06651    action = strsep(&stringp, ",");
06652    param = stringp;
06653    if(debug)
06654       printf("@@@@ action: %s, param = %s\n",action, (param) ? param : "(null)");
06655    /* Look up the action */
06656    for(i = 0 ; i < (sizeof(function_table)/sizeof(struct function_table_tag)); i++){
06657       if(!strncasecmp(action, function_table[i].action, strlen(action)))
06658          break;
06659    }
06660    if(debug)
06661       printf("@@@@ table index i = %d\n",i);
06662    if(i == (sizeof(function_table)/sizeof(struct function_table_tag))){
06663       /* Error, action not in table */
06664       return DC_ERROR;
06665    }
06666    if(function_table[i].function == NULL){
06667       /* Error, function undefined */
06668       if(debug)
06669          printf("@@@@ NULL for action: %s\n",action);
06670       return DC_ERROR;
06671    }
06672    functiondigits = digits + strlen(vp->name);
06673    rv=(*function_table[i].function)(myrpt, param, functiondigits, command_source, mylink);
06674    if (debug > 6) ast_log(LOG_NOTICE,"rv=%i\n",rv);
06675    return(rv);
06676 }
06677 
06678 
06679 static void handle_link_data(struct rpt *myrpt, struct rpt_link *mylink,
06680    char *str)
06681 {
06682 /* XXX ATTENTION: if you change the size of these arrays you MUST
06683  * change the limits in corresponding sscanf() calls below. */
06684 char  tmp[512],tmp1[512],cmd[300] = "",dest[300],src[300],c;
06685 int   i,seq, res, ts;
06686 struct rpt_link *l;
06687 struct   ast_frame wf;
06688 
06689    wf.frametype = AST_FRAME_TEXT;
06690    wf.subclass.integer = 0;
06691    wf.offset = 0;
06692    wf.mallocd = 0;
06693    wf.datalen = strlen(str) + 1;
06694    wf.samples = 0;
06695    /* put string in our buffer */
06696    strncpy(tmp,str,sizeof(tmp) - 1);
06697 
06698         if (!strcmp(tmp,discstr))
06699         {
06700                 mylink->disced = 1;
06701       mylink->retries = mylink->max_retries + 1;
06702                 ast_softhangup(mylink->chan,AST_SOFTHANGUP_DEV);
06703                 return;
06704         }
06705         if (!strcmp(tmp,newkeystr))
06706         {
06707       mylink->newkey = 1;
06708                 return;
06709         }
06710    if (tmp[0] == 'L')
06711    {
06712       rpt_mutex_lock(&myrpt->lock);
06713       strcpy(mylink->linklist,tmp + 2);
06714       time(&mylink->linklistreceived);
06715       rpt_mutex_unlock(&myrpt->lock);
06716       if (debug > 6) ast_log(LOG_NOTICE,"@@@@ node %s received node list %s from node %s\n",
06717          myrpt->name,tmp,mylink->name);
06718       return;
06719    }
06720    if (tmp[0] == 'K')
06721    {
06722       if (sscanf(tmp, "%299s %299s %299s %30d %30d", cmd, dest, src, &seq, &ts) != 5)
06723       {
06724          ast_log(LOG_WARNING, "Unable to parse keying string %s\n",str);
06725          return;
06726       }
06727       if (dest[0] == '0')
06728       {
06729          strcpy(dest,myrpt->name);
06730       }     
06731       /* if not for me, redistribute to all links */
06732       if (strcmp(dest,myrpt->name))
06733       {
06734          l = myrpt->links.next;
06735          /* see if this is one in list */
06736          while(l != &myrpt->links)
06737          {
06738             if (l->name[0] == '0') 
06739             {
06740                l = l->next;
06741                continue;
06742             }
06743             /* don't send back from where it came */
06744             if ((l == mylink) || (!strcmp(l->name,mylink->name)))
06745             {
06746                l = l->next;
06747                continue;
06748             }
06749             /* if it is, send it and we're done */
06750             if (!strcmp(l->name,dest))
06751             {
06752                /* send, but not to src */
06753                if (strcmp(l->name,src)) {
06754                   wf.data.ptr = str;
06755                   if (l->chan) ast_write(l->chan,&wf);
06756                }
06757                return;
06758             }
06759             l = l->next;
06760          }
06761       }
06762       /* if not for me, or is broadcast, redistribute to all links */
06763       if ((strcmp(dest,myrpt->name)) || (dest[0] == '*'))
06764       {
06765          l = myrpt->links.next;
06766          /* otherwise, send it to all of em */
06767          while(l != &myrpt->links)
06768          {
06769             if (l->name[0] == '0') 
06770             {
06771                l = l->next;
06772                continue;
06773             }
06774             /* don't send back from where it came */
06775             if ((l == mylink) || (!strcmp(l->name,mylink->name)))
06776             {
06777                l = l->next;
06778                continue;
06779             }
06780             /* send, but not to src */
06781             if (strcmp(l->name,src)) {
06782                wf.data.ptr = str;
06783                if (l->chan) ast_write(l->chan,&wf); 
06784             }
06785             l = l->next;
06786          }
06787       }
06788       /* if not for me, end here */
06789       if (strcmp(dest,myrpt->name) && (dest[0] != '*')) return;
06790       if (cmd[1] == '?')
06791       {
06792          time_t now;
06793          int n = 0;
06794 
06795          time(&now);
06796          if (myrpt->lastkeyedtime)
06797          {
06798             n = (int)(now - myrpt->lastkeyedtime);
06799          }
06800          sprintf(tmp1,"K %s %s %d %d",src,myrpt->name,myrpt->keyed,n);
06801          wf.data.ptr = tmp1;
06802          wf.datalen = strlen(tmp1) + 1;
06803          if (mylink->chan) ast_write(mylink->chan,&wf); 
06804          return;
06805       }
06806       if (myrpt->topkeystate != 1) return;
06807       rpt_mutex_lock(&myrpt->lock);
06808       for(i = 0; i < TOPKEYN; i++)
06809       {
06810          if (!strcmp(myrpt->topkey[i].node,src)) break;
06811       }
06812       if (i >= TOPKEYN)
06813       {
06814          for(i = 0; i < TOPKEYN; i++)
06815          {
06816             if (!myrpt->topkey[i].node[0]) break;
06817          }
06818       }
06819       if (i < TOPKEYN)
06820       {
06821          strncpy(myrpt->topkey[i].node,src,TOPKEYMAXSTR - 1);
06822          myrpt->topkey[i].timesince = ts;
06823          myrpt->topkey[i].keyed = seq;
06824       }
06825       rpt_mutex_unlock(&myrpt->lock);
06826       return;
06827    }
06828    if (tmp[0] == 'I')
06829    {
06830       /* XXX WARNING: be very careful with the limits on the folowing
06831        * sscanf() call, make sure they match the values defined above */
06832       if (sscanf(tmp,"%299s %299s %30x",cmd,src,&seq) != 3)
06833       {
06834          ast_log(LOG_WARNING, "Unable to parse ident string %s\n",str);
06835          return;
06836       }
06837       mdc1200_notify(myrpt,src,seq);
06838       strcpy(dest,"*");
06839    }
06840    else
06841    {
06842       /* XXX WARNING: be very careful with the limits on the folowing
06843        * sscanf() call, make sure they match the values defined above */
06844       if (sscanf(tmp,"%299s %299s %299s %30d %1c",cmd,dest,src,&seq,&c) != 5)
06845       {
06846          ast_log(LOG_WARNING, "Unable to parse link string %s\n",str);
06847          return;
06848       }
06849       if (strcmp(cmd,"D"))
06850       {
06851          ast_log(LOG_WARNING, "Unable to parse link string %s\n",str);
06852          return;
06853       }
06854    }
06855    if (dest[0] == '0')
06856    {
06857       strcpy(dest,myrpt->name);
06858    }     
06859 
06860    /* if not for me, redistribute to all links */
06861    if (strcmp(dest,myrpt->name))
06862    {
06863       l = myrpt->links.next;
06864       /* see if this is one in list */
06865       while(l != &myrpt->links)
06866       {
06867          if (l->name[0] == '0') 
06868          {
06869             l = l->next;
06870             continue;
06871          }
06872          /* don't send back from where it came */
06873          if ((l == mylink) || (!strcmp(l->name,mylink->name)))
06874          {
06875             l = l->next;
06876             continue;
06877          }
06878          /* if it is, send it and we're done */
06879          if (!strcmp(l->name,dest))
06880          {
06881             /* send, but not to src */
06882             if (strcmp(l->name,src)) {
06883                wf.data.ptr = str;
06884                if (l->chan) ast_write(l->chan,&wf);
06885             }
06886             return;
06887          }
06888          l = l->next;
06889       }
06890       l = myrpt->links.next;
06891       /* otherwise, send it to all of em */
06892       while(l != &myrpt->links)
06893       {
06894          if (l->name[0] == '0') 
06895          {
06896             l = l->next;
06897             continue;
06898          }
06899          /* don't send back from where it came */
06900          if ((l == mylink) || (!strcmp(l->name,mylink->name)))
06901          {
06902             l = l->next;
06903             continue;
06904          }
06905          /* send, but not to src */
06906          if (strcmp(l->name,src)) {
06907             wf.data.ptr = str;
06908             if (l->chan) ast_write(l->chan,&wf); 
06909          }
06910          l = l->next;
06911       }
06912       return;
06913    }
06914    if (myrpt->p.archivedir)
06915    {
06916       char dtmfstr[100];
06917 
06918       sprintf(dtmfstr,"DTMF,%s,%c",mylink->name,c);
06919       donodelog(myrpt,dtmfstr);
06920    }
06921    c = func_xlat(myrpt,c,&myrpt->p.outxlat);
06922    if (!c) return;
06923    rpt_mutex_lock(&myrpt->lock);
06924    if (c == myrpt->p.endchar) myrpt->stopgen = 1;
06925    if (myrpt->callmode == 1)
06926    {
06927       myrpt->exten[myrpt->cidx++] = c;
06928       myrpt->exten[myrpt->cidx] = 0;
06929       /* if this exists */
06930       if (ast_exists_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
06931       {
06932          /* if this really it, end now */
06933          if (!ast_matchmore_extension(myrpt->pchannel,myrpt->patchcontext,
06934             myrpt->exten,1,NULL)) 
06935          {
06936             myrpt->callmode = 2;
06937             if(!myrpt->patchquiet)
06938             {
06939                rpt_mutex_unlock(&myrpt->lock);
06940                rpt_telemetry(myrpt,PROC,NULL); 
06941                rpt_mutex_lock(&myrpt->lock);
06942             }
06943          }
06944          else /* othewise, reset timer */
06945          {
06946             myrpt->calldigittimer = 1;
06947          }
06948       }
06949       /* if can continue, do so */
06950       if (!ast_canmatch_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
06951       {
06952          /* call has failed, inform user */
06953          myrpt->callmode = 4;
06954       }
06955    }
06956    if ((!myrpt->inpadtest) &&(c == myrpt->p.funcchar))
06957    {
06958       myrpt->rem_dtmfidx = 0;
06959       myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx] = 0;
06960       time(&myrpt->rem_dtmf_time);
06961       rpt_mutex_unlock(&myrpt->lock);
06962       return;
06963    } 
06964    else if (myrpt->rem_dtmfidx < 0)
06965    {
06966       if ((myrpt->callmode == 2) || (myrpt->callmode == 3))
06967       {
06968          myrpt->mydtmf = c;
06969       }
06970       if (myrpt->p.propagate_dtmf) do_dtmf_local(myrpt,c);
06971       if (myrpt->p.propagate_phonedtmf) do_dtmf_phone(myrpt,mylink,c);
06972       rpt_mutex_unlock(&myrpt->lock);
06973       return;
06974    }
06975    else if (((myrpt->inpadtest) || (c != myrpt->p.endchar)) && (myrpt->rem_dtmfidx >= 0))
06976    {
06977       time(&myrpt->rem_dtmf_time);
06978       if (myrpt->rem_dtmfidx < MAXDTMF)
06979       {
06980          myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx++] = c;
06981          myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx] = 0;
06982          
06983          rpt_mutex_unlock(&myrpt->lock);
06984          strncpy(cmd, myrpt->rem_dtmfbuf, sizeof(cmd) - 1);
06985          res = collect_function_digits(myrpt, cmd, SOURCE_LNK, mylink);
06986          rpt_mutex_lock(&myrpt->lock);
06987          
06988          switch(res){
06989 
06990             case DC_INDETERMINATE:
06991                break;
06992             
06993             case DC_REQ_FLUSH:
06994                myrpt->rem_dtmfidx = 0;
06995                myrpt->rem_dtmfbuf[0] = 0;
06996                break;
06997             
06998             
06999             case DC_COMPLETE:
07000             case DC_COMPLETEQUIET:
07001                myrpt->totalexecdcommands++;
07002                myrpt->dailyexecdcommands++;
07003                strncpy(myrpt->lastdtmfcommand, cmd, MAXDTMF-1);
07004                myrpt->lastdtmfcommand[MAXDTMF-1] = '\0';
07005                myrpt->rem_dtmfbuf[0] = 0;
07006                myrpt->rem_dtmfidx = -1;
07007                myrpt->rem_dtmf_time = 0;
07008                break;
07009             
07010             case DC_ERROR:
07011             default:
07012                myrpt->rem_dtmfbuf[0] = 0;
07013                myrpt->rem_dtmfidx = -1;
07014                myrpt->rem_dtmf_time = 0;
07015                break;
07016          }
07017       }
07018 
07019    }
07020    rpt_mutex_unlock(&myrpt->lock);
07021    return;
07022 }
07023 
07024 static void handle_link_phone_dtmf(struct rpt *myrpt, struct rpt_link *mylink,
07025    char c)
07026 {
07027 
07028 char  cmd[300];
07029 int   res;
07030 
07031    if (myrpt->p.archivedir)
07032    {
07033       char str[100];
07034 
07035       sprintf(str,"DTMF(P),%s,%c",mylink->name,c);
07036       donodelog(myrpt,str);
07037    }
07038    rpt_mutex_lock(&myrpt->lock);
07039 
07040    if (mylink->phonemode == 3) /*If in simplex dumb phone mode */
07041    {
07042       if(c == myrpt->p.endchar) /* If end char */
07043       {
07044          mylink->lastrealrx = 0; /* Keying state = off */
07045          rpt_mutex_unlock(&myrpt->lock);
07046          return;
07047       }
07048 
07049       if(c == myrpt->p.funcchar) /* If lead-in char */
07050       {
07051          mylink->lastrealrx = !mylink->lastrealrx; /* Toggle keying state */
07052          rpt_mutex_unlock(&myrpt->lock);
07053          return;
07054       }
07055    }
07056    else
07057    {
07058       if (c == myrpt->p.endchar)
07059       {
07060          if (mylink->lastrx)
07061          {
07062             mylink->lastrealrx = 0;
07063             rpt_mutex_unlock(&myrpt->lock);
07064             return;
07065          }
07066          myrpt->stopgen = 1;
07067          if (myrpt->cmdnode[0])
07068          {
07069             myrpt->cmdnode[0] = 0;
07070             myrpt->dtmfidx = -1;
07071             myrpt->dtmfbuf[0] = 0;
07072             rpt_mutex_unlock(&myrpt->lock);
07073             rpt_telemetry(myrpt,COMPLETE,NULL);
07074             return;
07075          }
07076       }
07077    }
07078    if (myrpt->cmdnode[0])
07079    {
07080       rpt_mutex_unlock(&myrpt->lock);
07081       send_link_dtmf(myrpt,c);
07082       return;
07083    }
07084    if (myrpt->callmode == 1)
07085    {
07086       myrpt->exten[myrpt->cidx++] = c;
07087       myrpt->exten[myrpt->cidx] = 0;
07088       /* if this exists */
07089       if (ast_exists_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
07090       {
07091          /* if this really it, end now */
07092          if (!ast_matchmore_extension(myrpt->pchannel,myrpt->patchcontext,
07093             myrpt->exten,1,NULL)) 
07094          {
07095             myrpt->callmode = 2;
07096             if(!myrpt->patchquiet)
07097             {
07098                rpt_mutex_unlock(&myrpt->lock);
07099                rpt_telemetry(myrpt,PROC,NULL); 
07100                rpt_mutex_lock(&myrpt->lock);
07101             }
07102          }
07103          else /* othewise, reset timer */
07104          {
07105             myrpt->calldigittimer = 1;
07106          }
07107       }
07108       /* if can continue, do so */
07109       if (!ast_canmatch_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
07110       {
07111          /* call has failed, inform user */
07112          myrpt->callmode = 4;
07113       }
07114    }
07115    if ((myrpt->callmode == 2) || (myrpt->callmode == 3))
07116    {
07117       myrpt->mydtmf = c;
07118    }
07119    if ((!myrpt->inpadtest) && (c == myrpt->p.funcchar))
07120    {
07121       myrpt->rem_dtmfidx = 0;
07122       myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx] = 0;
07123       time(&myrpt->rem_dtmf_time);
07124       rpt_mutex_unlock(&myrpt->lock);
07125       return;
07126    } 
07127    else if (((myrpt->inpadtest) || (c != myrpt->p.endchar)) && (myrpt->rem_dtmfidx >= 0))
07128    {
07129       time(&myrpt->rem_dtmf_time);
07130       if (myrpt->rem_dtmfidx < MAXDTMF)
07131       {
07132          myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx++] = c;
07133          myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx] = 0;
07134          
07135          rpt_mutex_unlock(&myrpt->lock);
07136          strncpy(cmd, myrpt->rem_dtmfbuf, sizeof(cmd) - 1);
07137          switch(mylink->phonemode)
07138          {
07139              case 1:
07140             res = collect_function_digits(myrpt, cmd, 
07141                SOURCE_PHONE, mylink);
07142             break;
07143              case 2:
07144             res = collect_function_digits(myrpt, cmd, 
07145                SOURCE_DPHONE,mylink);
07146             break;
07147              case 4:
07148             res = collect_function_digits(myrpt, cmd, 
07149                SOURCE_ALT,mylink);
07150             break;
07151              default:
07152             res = collect_function_digits(myrpt, cmd, 
07153                SOURCE_LNK, mylink);
07154             break;
07155          }
07156 
07157          rpt_mutex_lock(&myrpt->lock);
07158          
07159          switch(res){
07160 
07161             case DC_INDETERMINATE:
07162                break;
07163             
07164             case DC_DOKEY:
07165                mylink->lastrealrx = 1;
07166                break;
07167             
07168             case DC_REQ_FLUSH:
07169                myrpt->rem_dtmfidx = 0;
07170                myrpt->rem_dtmfbuf[0] = 0;
07171                break;
07172             
07173             
07174             case DC_COMPLETE:
07175             case DC_COMPLETEQUIET:
07176                myrpt->totalexecdcommands++;
07177                myrpt->dailyexecdcommands++;
07178                strncpy(myrpt->lastdtmfcommand, cmd, MAXDTMF-1);
07179                myrpt->lastdtmfcommand[MAXDTMF-1] = '\0';
07180                myrpt->rem_dtmfbuf[0] = 0;
07181                myrpt->rem_dtmfidx = -1;
07182                myrpt->rem_dtmf_time = 0;
07183                break;
07184             
07185             case DC_ERROR:
07186             default:
07187                myrpt->rem_dtmfbuf[0] = 0;
07188                myrpt->rem_dtmfidx = -1;
07189                myrpt->rem_dtmf_time = 0;
07190                break;
07191          }
07192       }
07193 
07194    }
07195    rpt_mutex_unlock(&myrpt->lock);
07196    return;
07197 }
07198 
07199 /* Doug Hall RBI-1 serial data definitions:
07200  *
07201  * Byte 0: Expansion external outputs 
07202  * Byte 1: 
07203  * Bits 0-3 are BAND as follows:
07204  * Bits 4-5 are POWER bits as follows:
07205  *    00 - Low Power
07206  *    01 - Hi Power
07207  *    02 - Med Power
07208  * Bits 6-7 are always set
07209  * Byte 2:
07210  * Bits 0-3 MHZ in BCD format
07211  * Bits 4-5 are offset as follows:
07212  *    00 - minus
07213  *    01 - plus
07214  *    02 - simplex
07215  *    03 - minus minus (whatever that is)
07216  * Bit 6 is the 0/5 KHZ bit
07217  * Bit 7 is always set
07218  * Byte 3:
07219  * Bits 0-3 are 10 KHZ in BCD format
07220  * Bits 4-7 are 100 KHZ in BCD format
07221  * Byte 4: PL Tone code and encode/decode enable bits
07222  * Bits 0-5 are PL tone code (comspec binary codes)
07223  * Bit 6 is encode enable/disable
07224  * Bit 7 is decode enable/disable
07225  */
07226 
07227 /* take the frequency from the 10 mhz digits (and up) and convert it
07228    to a band number */
07229 
07230 static int rbi_mhztoband(char *str)
07231 {
07232 int   i;
07233 
07234    i = atoi(str) / 10; /* get the 10's of mhz */
07235    switch(i)
07236    {
07237        case 2:
07238       return 10;
07239        case 5:
07240       return 11;
07241        case 14:
07242       return 2;
07243        case 22:
07244       return 3;
07245        case 44:
07246       return 4;
07247        case 124:
07248       return 0;
07249        case 125:
07250       return 1;
07251        case 126:
07252       return 8;
07253        case 127:
07254       return 5;
07255        case 128:
07256       return 6;
07257        case 129:
07258       return 7;
07259        default:
07260       break;
07261    }
07262    return -1;
07263 }
07264 
07265 /* take a PL frequency and turn it into a code */
07266 static int rbi_pltocode(char *str)
07267 {
07268 int i;
07269 char *s;
07270 
07271    s = strchr(str,'.');
07272    i = 0;
07273    if (s) i = atoi(s + 1);
07274    i += atoi(str) * 10;
07275    switch(i)
07276    {
07277        case 670:
07278       return 0;
07279        case 719:
07280       return 1;
07281        case 744:
07282       return 2;
07283        case 770:
07284       return 3;
07285        case 797:
07286       return 4;
07287        case 825:
07288       return 5;
07289        case 854:
07290       return 6;
07291        case 885:
07292       return 7;
07293        case 915:
07294       return 8;
07295        case 948:
07296       return 9;
07297        case 974:
07298       return 10;
07299        case 1000:
07300       return 11;
07301        case 1035:
07302       return 12;
07303        case 1072:
07304       return 13;
07305        case 1109:
07306       return 14;
07307        case 1148:
07308       return 15;
07309        case 1188:
07310       return 16;
07311        case 1230:
07312       return 17;
07313        case 1273:
07314       return 18;
07315        case 1318:
07316       return 19;
07317        case 1365:
07318       return 20;
07319        case 1413:
07320       return 21;
07321        case 1462:
07322       return 22;
07323        case 1514:
07324       return 23;
07325        case 1567:
07326       return 24;
07327        case 1622:
07328       return 25;
07329        case 1679:
07330       return 26;
07331        case 1738:
07332       return 27;
07333        case 1799:
07334       return 28;
07335        case 1862:
07336       return 29;
07337        case 1928:
07338       return 30;
07339        case 2035:
07340       return 31;
07341        case 2107:
07342       return 32;
07343        case 2181:
07344       return 33;
07345        case 2257:
07346       return 34;
07347        case 2336:
07348       return 35;
07349        case 2418:
07350       return 36;
07351        case 2503:
07352       return 37;
07353    }
07354    return -1;
07355 }
07356 
07357 /*
07358 * Shift out a formatted serial bit stream
07359 */
07360 
07361 static void rbi_out_parallel(struct rpt *myrpt,unsigned char *data)
07362     {
07363 #ifdef __i386__
07364     int i,j;
07365     unsigned char od,d;
07366     static volatile long long delayvar;
07367 
07368     for(i = 0 ; i < 5 ; i++){
07369         od = *data++; 
07370         for(j = 0 ; j < 8 ; j++){
07371             d = od & 1;
07372             outb(d,myrpt->p.iobase);
07373        /* >= 15 us */
07374        for(delayvar = 1; delayvar < 15000; delayvar++); 
07375             od >>= 1;
07376             outb(d | 2,myrpt->p.iobase);
07377        /* >= 30 us */
07378        for(delayvar = 1; delayvar < 30000; delayvar++); 
07379             outb(d,myrpt->p.iobase);
07380        /* >= 10 us */
07381        for(delayvar = 1; delayvar < 10000; delayvar++); 
07382             }
07383         }
07384    /* >= 50 us */
07385         for(delayvar = 1; delayvar < 50000; delayvar++); 
07386 #endif
07387     }
07388 
07389 static void rbi_out(struct rpt *myrpt,unsigned char *data)
07390 {
07391 struct dahdi_radio_param r;
07392 
07393    memset(&r,0,sizeof(struct dahdi_radio_param));
07394    r.radpar = DAHDI_RADPAR_REMMODE;
07395    r.data = DAHDI_RADPAR_REM_RBI1;
07396    /* if setparam ioctl fails, its probably not a pciradio card */
07397    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&r) == -1)
07398    {
07399       rbi_out_parallel(myrpt,data);
07400       return;
07401    }
07402    r.radpar = DAHDI_RADPAR_REMCOMMAND;
07403    memcpy(&r.data,data,5);
07404    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&r) == -1)
07405    {
07406       ast_log(LOG_WARNING,"Cannot send RBI command for channel %s\n",myrpt->dahdirxchannel->name);
07407       return;
07408    }
07409 }
07410 
07411 static int serial_remote_io(struct rpt *myrpt, unsigned char *txbuf, int txbytes, 
07412    unsigned char *rxbuf, int rxmaxbytes, int asciiflag)
07413 {
07414    int i,j,idx,oldmode,olddata;
07415    struct dahdi_radio_param prm;
07416    char c;
07417 
07418     if(debug) {
07419        ast_log(LOG_NOTICE, "ioport=%s  iofd=0x%x\n",myrpt->p.ioport,myrpt->iofd);
07420       printf("String output was:\n");
07421       for(i = 0; i < txbytes; i++)
07422          printf("%02X ", (unsigned char ) txbuf[i]);
07423       printf("\n");
07424    }
07425 
07426    if (myrpt->iofd >= 0)  /* if to do out a serial port */
07427    {
07428       if (write(myrpt->iofd,txbuf,txbytes) != txbytes)
07429       {
07430          return -1;
07431       }
07432       if ((!rxmaxbytes) || (rxbuf == NULL)) 
07433       {
07434          return(0);
07435       }
07436       memset(rxbuf,0,rxmaxbytes);
07437       for(i = 0; i < rxmaxbytes; i++)
07438       {
07439          j = read(myrpt->iofd,&c,1);
07440          if (j < 1) 
07441          {
07442             return(i);
07443          }
07444          rxbuf[i] = c;
07445          if (asciiflag & 1)
07446          {
07447             rxbuf[i + 1] = 0;
07448             if (c == '\r') break;
07449          }
07450       }              
07451       if(debug) {
07452          printf("String returned was:\n");
07453          for(j = 0; j < i; j++)
07454             printf("%02X ", (unsigned char ) rxbuf[j]);
07455          printf("\n");
07456       }
07457       return(i);
07458    }
07459 
07460    /* if not a DAHDI channel, cant use pciradio stuff */
07461    if (myrpt->rxchannel != myrpt->dahdirxchannel) return -1;   
07462 
07463    prm.radpar = DAHDI_RADPAR_UIOMODE;
07464    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_GETPARAM,&prm) == -1) return -1;
07465    oldmode = prm.data;
07466    prm.radpar = DAHDI_RADPAR_UIODATA;
07467    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_GETPARAM,&prm) == -1) return -1;
07468    olddata = prm.data;
07469         prm.radpar = DAHDI_RADPAR_REMMODE;
07470         if (asciiflag & 1)  prm.data = DAHDI_RADPAR_REM_SERIAL_ASCII;
07471         else prm.data = DAHDI_RADPAR_REM_SERIAL;
07472    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07473    if (asciiflag & 2)
07474    {
07475       i = DAHDI_ONHOOK;
07476       if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_HOOK,&i) == -1) return -1;
07477       usleep(100000);
07478    }
07479         prm.radpar = DAHDI_RADPAR_REMCOMMAND;
07480         prm.data = rxmaxbytes;
07481         memcpy(prm.buf,txbuf,txbytes);
07482         prm.index = txbytes;
07483    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07484         if (rxbuf)
07485         {
07486                 *rxbuf = 0;
07487                 memcpy(rxbuf,prm.buf,prm.index);
07488         }
07489    idx = prm.index;
07490         prm.radpar = DAHDI_RADPAR_REMMODE;
07491         prm.data = DAHDI_RADPAR_REM_NONE;
07492    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07493    if (asciiflag & 2)
07494    {
07495       i = DAHDI_OFFHOOK;
07496       if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_HOOK,&i) == -1) return -1;
07497    }
07498    prm.radpar = DAHDI_RADPAR_UIOMODE;
07499    prm.data = oldmode;
07500    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07501    prm.radpar = DAHDI_RADPAR_UIODATA;
07502    prm.data = olddata;
07503    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07504         return(idx);
07505 }
07506 
07507 static int civ_cmd(struct rpt *myrpt,unsigned char *cmd, int cmdlen)
07508 {
07509 unsigned char rxbuf[100];
07510 int   i,rv ;
07511 
07512    rv = serial_remote_io(myrpt,cmd,cmdlen,rxbuf,cmdlen + 6,0);
07513    if (rv == -1) return(-1);
07514    if (rv != (cmdlen + 6)) return(1);
07515    for(i = 0; i < 6; i++)
07516       if (rxbuf[i] != cmd[i]) return(1);
07517    if (rxbuf[cmdlen] != 0xfe) return(1);
07518    if (rxbuf[cmdlen + 1] != 0xfe) return(1);
07519    if (rxbuf[cmdlen + 4] != 0xfb) return(1);
07520    if (rxbuf[cmdlen + 5] != 0xfd) return(1);
07521    return(0);
07522 }
07523 
07524 static int sendkenwood(struct rpt *myrpt,char *txstr, char *rxstr)
07525 {
07526 int   i;
07527 
07528 ast_log(LOG_NOTICE,"Sent to kenwood: %s\n",txstr);
07529    if (debug) printf("Send to kenwood: %s\n",txstr);
07530    i = serial_remote_io(myrpt, (unsigned char *)txstr, strlen(txstr), 
07531       (unsigned char *)rxstr,RAD_SERIAL_BUFLEN - 1,3);
07532    if (i < 0) return -1;
07533    if ((i > 0) && (rxstr[i - 1] == '\r'))
07534       rxstr[i-- - 1] = 0;
07535    if (debug) printf("Got from kenwood: %s\n",rxstr);
07536 ast_log(LOG_NOTICE,"Got from kenwood: %s\n",rxstr);
07537    return(i);
07538 }
07539 
07540 /* take a PL frequency and turn it into a code */
07541 static int kenwood_pltocode(char *str)
07542 {
07543 int i;
07544 char *s;
07545 
07546    s = strchr(str,'.');
07547    i = 0;
07548    if (s) i = atoi(s + 1);
07549    i += atoi(str) * 10;
07550    switch(i)
07551    {
07552        case 670:
07553       return 1;
07554        case 719:
07555       return 3;
07556        case 744:
07557       return 4;
07558        case 770:
07559       return 5;
07560        case 797:
07561       return 6;
07562        case 825:
07563       return 7;
07564        case 854:
07565       return 8;
07566        case 885:
07567       return 9;
07568        case 915:
07569       return 10;
07570        case 948:
07571       return 11;
07572        case 974:
07573       return 12;
07574        case 1000:
07575       return 13;
07576        case 1035:
07577       return 14;
07578        case 1072:
07579       return 15;
07580        case 1109:
07581       return 16;
07582        case 1148:
07583       return 17;
07584        case 1188:
07585       return 18;
07586        case 1230:
07587       return 19;
07588        case 1273:
07589       return 20;
07590        case 1318:
07591       return 21;
07592        case 1365:
07593       return 22;
07594        case 1413:
07595       return 23;
07596        case 1462:
07597       return 24;
07598        case 1514:
07599       return 25;
07600        case 1567:
07601       return 26;
07602        case 1622:
07603       return 27;
07604        case 1679:
07605       return 28;
07606        case 1738:
07607       return 29;
07608        case 1799:
07609       return 30;
07610        case 1862:
07611       return 31;
07612        case 1928:
07613       return 32;
07614        case 2035:
07615       return 33;
07616        case 2107:
07617       return 34;
07618        case 2181:
07619       return 35;
07620        case 2257:
07621       return 36;
07622        case 2336:
07623       return 37;
07624        case 2418:
07625       return 38;
07626        case 2503:
07627       return 39;
07628    }
07629    return -1;
07630 }
07631 
07632 static int sendrxkenwood(struct rpt *myrpt, char *txstr, char *rxstr, 
07633    char *cmpstr)
07634 {
07635 int   i,j;
07636 
07637    for(i = 0;i < KENWOOD_RETRIES;i++)
07638    {
07639       j = sendkenwood(myrpt,txstr,rxstr);
07640       if (j < 0) return(j);
07641       if (j == 0) continue;
07642       if (!strncmp(rxstr,cmpstr,strlen(cmpstr))) return(0);
07643    }
07644    return(-1);
07645 }     
07646 
07647 static int setkenwood(struct rpt *myrpt)
07648 {
07649 char rxstr[RAD_SERIAL_BUFLEN],txstr[RAD_SERIAL_BUFLEN],freq[20];
07650 char mhz[MAXREMSTR],offset[20],band,decimals[MAXREMSTR],band1,band2;
07651 int myrxpl;
07652    
07653 int offsets[] = {0,2,1};
07654 int powers[] = {2,1,0};
07655 
07656    if (sendrxkenwood(myrpt,"VMC 0,0\r",rxstr,"VMC") < 0) return -1;
07657    split_freq(mhz, decimals, myrpt->freq);
07658    if (atoi(mhz) > 400)
07659    {
07660       band = '6';
07661       band1 = '1';
07662       band2 = '5';
07663       strcpy(offset,"005000000");
07664    }
07665    else
07666    {
07667       band = '2';
07668       band1 = '0';
07669       band2 = '2';
07670       strcpy(offset,"000600000");
07671    }
07672    strcpy(freq,"000000");
07673    strncpy(freq,decimals,strlen(decimals));
07674    myrxpl = myrpt->rxplon;
07675    if (IS_XPMR(myrpt)) myrxpl = 0;
07676    sprintf(txstr,"VW %c,%05d%s,0,%d,0,%d,%d,,%02d,,%02d,%s\r",
07677       band,atoi(mhz),freq,offsets[(int)myrpt->offset],
07678       (myrpt->txplon != 0),myrxpl,
07679       kenwood_pltocode(myrpt->txpl),kenwood_pltocode(myrpt->rxpl),
07680       offset);
07681    if (sendrxkenwood(myrpt,txstr,rxstr,"VW") < 0) return -1;
07682    sprintf(txstr,"RBN %c\r",band2);
07683    if (sendrxkenwood(myrpt,txstr,rxstr,"RBN") < 0) return -1;
07684    sprintf(txstr,"PC %c,%d\r",band1,powers[(int)myrpt->powerlevel]);
07685    if (sendrxkenwood(myrpt,txstr,rxstr,"PC") < 0) return -1;
07686    return 0;
07687 }
07688 
07689 static int set_tm271(struct rpt *myrpt)
07690 {
07691 char rxstr[RAD_SERIAL_BUFLEN],txstr[RAD_SERIAL_BUFLEN],freq[20];
07692 char mhz[MAXREMSTR],decimals[MAXREMSTR];
07693    
07694 int offsets[] = {0,2,1};
07695 int powers[] = {2,1,0};
07696 
07697    split_freq(mhz, decimals, myrpt->freq);
07698    strcpy(freq,"000000");
07699    strncpy(freq,decimals,strlen(decimals));
07700 
07701    sprintf(txstr,"VF %04d%s,4,%d,0,%d,0,0,%d,%d,000,00600000,0,0\r",
07702       atoi(mhz),freq,offsets[(int)myrpt->offset],
07703       (myrpt->txplon != 0),kenwood_pltocode(myrpt->txpl),
07704       kenwood_pltocode(myrpt->rxpl));
07705 
07706    if (sendrxkenwood(myrpt,txstr,rxstr,"VF") < 0) return -1;
07707    if (sendrxkenwood(myrpt,"VM 0\r",rxstr,"VM") < 0) return -1;
07708    sprintf(txstr,"PC %d\r",powers[(int)myrpt->powerlevel]);
07709    if (sendrxkenwood(myrpt,txstr,rxstr,"PC") < 0) return -1;
07710    return 0;
07711 }
07712 
07713 static int setrbi(struct rpt *myrpt)
07714 {
07715 char tmp[MAXREMSTR] = "",*s;
07716 unsigned char rbicmd[5];
07717 int   band,txoffset = 0,txpower = 0,rxpl;
07718 
07719    /* must be a remote system */
07720    if (!myrpt->remoterig) return(0);
07721    if (!myrpt->remoterig[0]) return(0);
07722    /* must have rbi hardware */
07723    if (strncmp(myrpt->remoterig,remote_rig_rbi,3)) return(0);
07724    if (setrbi_check(myrpt) == -1) return(-1);
07725    strncpy(tmp, myrpt->freq, sizeof(tmp) - 1);
07726    s = strchr(tmp,'.');
07727    /* if no decimal, is invalid */
07728    
07729    if (s == NULL){
07730       if(debug)
07731          printf("@@@@ Frequency needs a decimal\n");
07732       return -1;
07733    }
07734    
07735    *s++ = 0;
07736    if (strlen(tmp) < 2){
07737       if(debug)
07738          printf("@@@@ Bad MHz digits: %s\n", tmp);
07739       return -1;
07740    }
07741     
07742    if (strlen(s) < 3){
07743       if(debug)
07744          printf("@@@@ Bad KHz digits: %s\n", s);
07745       return -1;
07746    }
07747 
07748    if ((s[2] != '0') && (s[2] != '5')){
07749       if(debug)
07750          printf("@@@@ KHz must end in 0 or 5: %c\n", s[2]);
07751       return -1;
07752    }
07753     
07754    band = rbi_mhztoband(tmp);
07755    if (band == -1){
07756       if(debug)
07757          printf("@@@@ Bad Band: %s\n", tmp);
07758       return -1;
07759    }
07760    
07761    rxpl = rbi_pltocode(myrpt->rxpl);
07762    
07763    if (rxpl == -1){
07764       if(debug)
07765          printf("@@@@ Bad TX PL: %s\n", myrpt->rxpl);
07766       return -1;
07767    }
07768 
07769    
07770    switch(myrpt->offset)
07771    {
07772        case REM_MINUS:
07773       txoffset = 0;
07774       break;
07775        case REM_PLUS:
07776       txoffset = 0x10;
07777       break;
07778        case REM_SIMPLEX:
07779       txoffset = 0x20;
07780       break;
07781    }
07782    switch(myrpt->powerlevel)
07783    {
07784        case REM_LOWPWR:
07785       txpower = 0;
07786       break;
07787        case REM_MEDPWR:
07788       txpower = 0x20;
07789       break;
07790        case REM_HIPWR:
07791       txpower = 0x10;
07792       break;
07793    }
07794    rbicmd[0] = 0;
07795    rbicmd[1] = band | txpower | 0xc0;
07796    rbicmd[2] = (*(s - 2) - '0') | txoffset | 0x80;
07797    if (s[2] == '5') rbicmd[2] |= 0x40;
07798    rbicmd[3] = ((*s - '0') << 4) + (s[1] - '0');
07799    rbicmd[4] = rxpl;
07800    if (myrpt->txplon) rbicmd[4] |= 0x40;
07801    if (myrpt->rxplon) rbicmd[4] |= 0x80;
07802    rbi_out(myrpt,rbicmd);
07803    return 0;
07804 }
07805 
07806 static int setrtx(struct rpt *myrpt)
07807 {
07808 char tmp[MAXREMSTR] = "",*s,rigstr[200],pwr,res = 0;
07809 int   band,txoffset = 0,txpower = 0,rxpl,txpl;
07810 float ofac;
07811 double txfreq;
07812 
07813    /* must be a remote system */
07814    if (!myrpt->remoterig) return(0);
07815    if (!myrpt->remoterig[0]) return(0);
07816    /* must have rtx hardware */
07817    if (!ISRIG_RTX(myrpt->remoterig)) return(0);
07818    /* must be a usbradio interface type */
07819    if (!IS_XPMR(myrpt)) return(0);
07820    strncpy(tmp, myrpt->freq, sizeof(tmp) - 1);
07821    s = strchr(tmp,'.');
07822    /* if no decimal, is invalid */
07823    
07824    if(debug)printf("setrtx() %s %s\n",myrpt->name,myrpt->remoterig);
07825 
07826    if (s == NULL){
07827       if(debug)
07828          printf("@@@@ Frequency needs a decimal\n");
07829       return -1;
07830    }
07831    *s++ = 0;
07832    if (strlen(tmp) < 2){
07833       if(debug)
07834          printf("@@@@ Bad MHz digits: %s\n", tmp);
07835       return -1;
07836    }
07837     
07838    if (strlen(s) < 3){
07839       if(debug)
07840          printf("@@@@ Bad KHz digits: %s\n", s);
07841       return -1;
07842    }
07843 
07844    if ((s[2] != '0') && (s[2] != '5')){
07845       if(debug)
07846          printf("@@@@ KHz must end in 0 or 5: %c\n", s[2]);
07847       return -1;
07848    }
07849     
07850    band = rbi_mhztoband(tmp);
07851    if (band == -1){
07852       if(debug)
07853          printf("@@@@ Bad Band: %s\n", tmp);
07854       return -1;
07855    }
07856    
07857    rxpl = rbi_pltocode(myrpt->rxpl);
07858    
07859    if (rxpl == -1){
07860       if(debug)
07861          printf("@@@@ Bad RX PL: %s\n", myrpt->rxpl);
07862       return -1;
07863    }
07864 
07865    txpl = rbi_pltocode(myrpt->txpl);
07866    
07867    if (txpl == -1){
07868       if(debug)
07869          printf("@@@@ Bad TX PL: %s\n", myrpt->txpl);
07870       return -1;
07871    }
07872    
07873    switch(myrpt->offset)
07874    {
07875        case REM_MINUS:
07876       txoffset = 0;
07877       break;
07878        case REM_PLUS:
07879       txoffset = 0x10;
07880       break;
07881        case REM_SIMPLEX:
07882       txoffset = 0x20;
07883       break;
07884    }
07885    switch(myrpt->powerlevel)
07886    {
07887        case REM_LOWPWR:
07888       txpower = 0;
07889       break;
07890        case REM_MEDPWR:
07891       txpower = 0x20;
07892       break;
07893        case REM_HIPWR:
07894       txpower = 0x10;
07895       break;
07896    }
07897 
07898    res = setrtx_check(myrpt);
07899    if (res < 0) return res;
07900    ofac = 0.0;
07901    if (myrpt->offset == REM_MINUS) ofac = -1.0;
07902    if (myrpt->offset == REM_PLUS) ofac = 1.0;
07903 
07904    if (!strcmp(myrpt->remoterig,remote_rig_rtx450))
07905       txfreq = atof(myrpt->freq) +  (ofac * 5.0);
07906    else
07907       txfreq = atof(myrpt->freq) +  (ofac * 0.6);
07908 
07909    pwr = 'L';
07910    if (myrpt->powerlevel == REM_HIPWR) pwr = 'H';
07911    if (!res)
07912    {
07913       sprintf(rigstr,"SETFREQ %s %f %s %s %c",myrpt->freq,txfreq,
07914          (myrpt->rxplon) ? myrpt->rxpl : "0.0",
07915          (myrpt->txplon) ? myrpt->txpl : "0.0",pwr);
07916       send_usb_txt(myrpt,rigstr);
07917       rpt_telemetry(myrpt,COMPLETE,NULL);
07918       res = 0;
07919    }
07920    return 0;
07921 }
07922 #if 0
07923 /*
07924    sets current signaling code for xpmr routines
07925    under development for new radios.
07926 */
07927 static int setxpmr(struct rpt *myrpt)
07928 {
07929    char rigstr[200];
07930    int rxpl,txpl;
07931 
07932    /* must be a remote system */
07933    if (!myrpt->remoterig) return(0);
07934    if (!myrpt->remoterig[0]) return(0);
07935    /* must not have rtx hardware */
07936    if (ISRIG_RTX(myrpt->remoterig)) return(0);
07937    /* must be a usbradio interface type */
07938    if (!IS_XPMR(myrpt)) return(0);
07939    
07940    if(debug)printf("setxpmr() %s %s\n",myrpt->name,myrpt->remoterig );
07941 
07942    rxpl = rbi_pltocode(myrpt->rxpl);
07943    
07944    if (rxpl == -1){
07945       if(debug)
07946          printf("@@@@ Bad RX PL: %s\n", myrpt->rxpl);
07947       return -1;
07948    }
07949 
07950    txpl = rbi_pltocode(myrpt->txpl);
07951    if (txpl == -1){
07952       if(debug)
07953          printf("@@@@ Bad TX PL: %s\n", myrpt->txpl);
07954       return -1;
07955    }
07956    sprintf(rigstr,"SETFREQ 0.0 0.0 %s %s L",
07957       (myrpt->rxplon) ? myrpt->rxpl : "0.0",
07958       (myrpt->txplon) ? myrpt->txpl : "0.0");
07959    send_usb_txt(myrpt,rigstr);
07960    return 0;
07961 }
07962 #endif
07963 
07964 static int setrbi_check(struct rpt *myrpt)
07965 {
07966 char tmp[MAXREMSTR] = "",*s;
07967 int   band,txpl;
07968 
07969    /* must be a remote system */
07970    if (!myrpt->remote) return(0);
07971    /* must have rbi hardware */
07972    if (strncmp(myrpt->remoterig,remote_rig_rbi,3)) return(0);
07973    strncpy(tmp, myrpt->freq, sizeof(tmp) - 1);
07974    s = strchr(tmp,'.');
07975    /* if no decimal, is invalid */
07976    
07977    if (s == NULL){
07978       if(debug)
07979          printf("@@@@ Frequency needs a decimal\n");
07980       return -1;
07981    }
07982    
07983    *s++ = 0;
07984    if (strlen(tmp) < 2){
07985       if(debug)
07986          printf("@@@@ Bad MHz digits: %s\n", tmp);
07987       return -1;
07988    }
07989     
07990    if (strlen(s) < 3){
07991       if(debug)
07992          printf("@@@@ Bad KHz digits: %s\n", s);
07993       return -1;
07994    }
07995 
07996    if ((s[2] != '0') && (s[2] != '5')){
07997       if(debug)
07998          printf("@@@@ KHz must end in 0 or 5: %c\n", s[2]);
07999       return -1;
08000    }
08001     
08002    band = rbi_mhztoband(tmp);
08003    if (band == -1){
08004       if(debug)
08005          printf("@@@@ Bad Band: %s\n", tmp);
08006       return -1;
08007    }
08008    
08009    txpl = rbi_pltocode(myrpt->txpl);
08010    
08011    if (txpl == -1){
08012       if(debug)
08013          printf("@@@@ Bad TX PL: %s\n", myrpt->txpl);
08014       return -1;
08015    }
08016    return 0;
08017 }
08018 
08019 static int setrtx_check(struct rpt *myrpt)
08020 {
08021 char tmp[MAXREMSTR] = "",*s;
08022 int   band,txpl,rxpl;
08023 
08024    /* must be a remote system */
08025    if (!myrpt->remote) return(0);
08026    /* must have rbi hardware */
08027    if (strncmp(myrpt->remoterig,remote_rig_rbi,3)) return(0);
08028    strncpy(tmp, myrpt->freq, sizeof(tmp) - 1);
08029    s = strchr(tmp,'.');
08030    /* if no decimal, is invalid */
08031    
08032    if (s == NULL){
08033       if(debug)
08034          printf("@@@@ Frequency needs a decimal\n");
08035       return -1;
08036    }
08037    
08038    *s++ = 0;
08039    if (strlen(tmp) < 2){
08040       if(debug)
08041          printf("@@@@ Bad MHz digits: %s\n", tmp);
08042       return -1;
08043    }
08044     
08045    if (strlen(s) < 3){
08046       if(debug)
08047          printf("@@@@ Bad KHz digits: %s\n", s);
08048       return -1;
08049    }
08050 
08051    if ((s[2] != '0') && (s[2] != '5')){
08052       if(debug)
08053          printf("@@@@ KHz must end in 0 or 5: %c\n", s[2]);
08054       return -1;
08055    }
08056     
08057    band = rbi_mhztoband(tmp);
08058    if (band == -1){
08059       if(debug)
08060          printf("@@@@ Bad Band: %s\n", tmp);
08061       return -1;
08062    }
08063    
08064    txpl = rbi_pltocode(myrpt->txpl);
08065    
08066    if (txpl == -1){
08067       if(debug)
08068          printf("@@@@ Bad TX PL: %s\n", myrpt->txpl);
08069       return -1;
08070    }
08071 
08072    rxpl = rbi_pltocode(myrpt->rxpl);
08073    
08074    if (rxpl == -1){
08075       if(debug)
08076          printf("@@@@ Bad RX PL: %s\n", myrpt->rxpl);
08077       return -1;
08078    }
08079    return 0;
08080 }
08081 
08082 static int check_freq_kenwood(int m, int d, int *defmode)
08083 {
08084    int dflmd = REM_MODE_FM;
08085 
08086    if (m == 144){ /* 2 meters */
08087       if(d < 10100)
08088          return -1;
08089    }
08090    else if((m >= 145) && (m < 148)){
08091       ;
08092    }
08093    else if((m >= 430) && (m < 450)){ /* 70 centimeters */
08094       ;
08095    }
08096    else
08097       return -1;
08098    
08099    if(defmode)
08100       *defmode = dflmd; 
08101 
08102 
08103    return 0;
08104 }
08105 
08106 
08107 static int check_freq_tm271(int m, int d, int *defmode)
08108 {
08109    int dflmd = REM_MODE_FM;
08110 
08111    if (m == 144){ /* 2 meters */
08112       if(d < 10100)
08113          return -1;
08114    }
08115    else if((m >= 145) && (m < 148)){
08116       ;
08117    }
08118       return -1;
08119    
08120    if(defmode)
08121       *defmode = dflmd; 
08122 
08123 
08124    return 0;
08125 }
08126 
08127 
08128 /* Check for valid rbi frequency */
08129 /* Hard coded limits now, configurable later, maybe? */
08130 
08131 static int check_freq_rbi(int m, int d, int *defmode)
08132 {
08133    int dflmd = REM_MODE_FM;
08134 
08135    if(m == 50){ /* 6 meters */
08136       if(d < 10100)
08137          return -1;
08138    }
08139    else if((m >= 51) && ( m < 54)){
08140                 ;
08141    }
08142    else if(m == 144){ /* 2 meters */
08143       if(d < 10100)
08144          return -1;
08145    }
08146    else if((m >= 145) && (m < 148)){
08147       ;
08148    }
08149    else if((m >= 222) && (m < 225)){ /* 1.25 meters */
08150       ;
08151    }
08152    else if((m >= 430) && (m < 450)){ /* 70 centimeters */
08153       ;
08154    }
08155    else if((m >= 1240) && (m < 1300)){ /* 23 centimeters */
08156       ;
08157    }
08158    else
08159       return -1;
08160    
08161    if(defmode)
08162       *defmode = dflmd; 
08163 
08164 
08165    return 0;
08166 }
08167 
08168 /* Check for valid rtx frequency */
08169 /* Hard coded limits now, configurable later, maybe? */
08170 
08171 static int check_freq_rtx(int m, int d, int *defmode, struct rpt *myrpt)
08172 {
08173    int dflmd = REM_MODE_FM;
08174 
08175    if (!strcmp(myrpt->remoterig,remote_rig_rtx150))
08176    {
08177 
08178       if(m == 144){ /* 2 meters */
08179          if(d < 10100)
08180             return -1;
08181       }
08182       else if((m >= 145) && (m < 148)){
08183          ;
08184       }
08185       else
08186          return -1;
08187    }
08188    else 
08189    {
08190       if((m >= 430) && (m < 450)){ /* 70 centimeters */
08191          ;
08192       }
08193       else
08194          return -1;
08195    }
08196    if(defmode)
08197       *defmode = dflmd; 
08198 
08199 
08200    return 0;
08201 }
08202 
08203 /*
08204  * Convert decimals of frequency to int
08205  */
08206 
08207 static int decimals2int(char *fraction)
08208 {
08209    int i;
08210    char len = strlen(fraction);
08211    int multiplier = 100000;
08212    int res = 0;
08213 
08214    if(!len)
08215       return 0;
08216    for( i = 0 ; i < len ; i++, multiplier /= 10)
08217       res += (fraction[i] - '0') * multiplier;
08218    return res;
08219 }
08220 
08221 
08222 /*
08223 * Split frequency into mhz and decimals
08224 */
08225  
08226 static int split_freq(char *mhz, char *decimals, char *freq)
08227 {
08228    char freq_copy[MAXREMSTR];
08229    char *decp;
08230 
08231    decp = strchr(strncpy(freq_copy, freq, MAXREMSTR),'.');
08232    if(decp){
08233       *decp++ = 0;
08234       strncpy(mhz, freq_copy, MAXREMSTR);
08235       strcpy(decimals, "00000");
08236       strncpy(decimals, decp, strlen(decp));
08237       decimals[5] = 0;
08238       return 0;
08239    }
08240    else
08241       return -1;
08242 
08243 }
08244    
08245 /*
08246 * Split ctcss frequency into hertz and decimal
08247 */
08248  
08249 static int split_ctcss_freq(char *hertz, char *decimal, char *freq)
08250 {
08251    char freq_copy[MAXREMSTR];
08252    char *decp;
08253 
08254    decp = strchr(strncpy(freq_copy, freq, MAXREMSTR),'.');
08255    if(decp){
08256       *decp++ = 0;
08257       strncpy(hertz, freq_copy, MAXREMSTR);
08258       strncpy(decimal, decp, strlen(decp));
08259       decimal[strlen(decp)] = '\0';
08260       return 0;
08261    }
08262    else
08263       return -1;
08264 }
08265 
08266 
08267 
08268 /*
08269 * FT-897 I/O handlers
08270 */
08271 
08272 /* Check to see that the frequency is valid */
08273 /* Hard coded limits now, configurable later, maybe? */
08274 
08275 
08276 static int check_freq_ft897(int m, int d, int *defmode)
08277 {
08278    int dflmd = REM_MODE_FM;
08279 
08280    if(m == 1){ /* 160 meters */
08281       dflmd =  REM_MODE_LSB; 
08282       if(d < 80000)
08283          return -1;
08284    }
08285    else if(m == 3){ /* 80 meters */
08286       dflmd = REM_MODE_LSB;
08287       if(d < 50000)
08288          return -1;
08289    }
08290    else if(m == 7){ /* 40 meters */
08291       dflmd = REM_MODE_LSB;
08292       if(d > 30000)
08293          return -1;
08294    }
08295    else if(m == 14){ /* 20 meters */
08296       dflmd = REM_MODE_USB;
08297       if(d > 35000)
08298          return -1;
08299    }
08300    else if(m == 18){ /* 17 meters */
08301       dflmd = REM_MODE_USB;
08302       if((d < 6800) || (d > 16800))
08303          return -1;
08304    }
08305    else if(m == 21){ /* 15 meters */
08306       dflmd = REM_MODE_USB;
08307       if((d < 20000) || (d > 45000))
08308          return -1;
08309    }
08310    else if(m == 24){ /* 12 meters */
08311       dflmd = REM_MODE_USB;
08312       if((d < 89000) || (d > 99000))
08313          return -1;
08314    }
08315    else if(m == 28){ /* 10 meters */
08316       dflmd = REM_MODE_USB;
08317    }
08318    else if(m == 29){ 
08319       if(d >= 51000)
08320          dflmd = REM_MODE_FM;
08321       else
08322          dflmd = REM_MODE_USB;
08323       if(d > 70000)
08324          return -1;
08325    }
08326    else if(m == 50){ /* 6 meters */
08327       if(d >= 30000)
08328          dflmd = REM_MODE_FM;
08329       else
08330          dflmd = REM_MODE_USB;
08331 
08332    }
08333    else if((m >= 51) && ( m < 54)){
08334       dflmd = REM_MODE_FM;
08335    }
08336    else if(m == 144){ /* 2 meters */
08337       if(d >= 30000)
08338          dflmd = REM_MODE_FM;
08339       else
08340          dflmd = REM_MODE_USB;
08341    }
08342    else if((m >= 145) && (m < 148)){
08343       dflmd = REM_MODE_FM;
08344    }
08345    else if((m >= 430) && (m < 450)){ /* 70 centimeters */
08346       if(m  < 438)
08347          dflmd = REM_MODE_USB;
08348       else
08349          dflmd = REM_MODE_FM;
08350       ;
08351    }
08352    else
08353       return -1;
08354 
08355    if(defmode)
08356       *defmode = dflmd;
08357 
08358    return 0;
08359 }
08360 
08361 /*
08362 * Set a new frequency for the FT897
08363 */
08364 
08365 static int set_freq_ft897(struct rpt *myrpt, char *newfreq)
08366 {
08367    unsigned char cmdstr[5];
08368    int fd,m,d;
08369    char mhz[MAXREMSTR];
08370    char decimals[MAXREMSTR];
08371 
08372    fd = 0;
08373    if(debug) 
08374       printf("New frequency: %s\n",newfreq);
08375 
08376    if(split_freq(mhz, decimals, newfreq))
08377       return -1; 
08378 
08379    m = atoi(mhz);
08380    d = atoi(decimals);
08381 
08382    /* The FT-897 likes packed BCD frequencies */
08383 
08384    cmdstr[0] = ((m / 100) << 4) + ((m % 100)/10);        /* 100MHz 10Mhz */
08385    cmdstr[1] = ((m % 10) << 4) + (d / 10000);         /* 1MHz 100KHz */
08386    cmdstr[2] = (((d % 10000)/1000) << 4) + ((d % 1000)/ 100);  /* 10KHz 1KHz */
08387    cmdstr[3] = (((d % 100)/10) << 4) + (d % 10);         /* 100Hz 10Hz */
08388    cmdstr[4] = 0x01;                /* command */
08389 
08390    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08391 
08392 }
08393 
08394 /* ft-897 simple commands */
08395 
08396 static int simple_command_ft897(struct rpt *myrpt, char command)
08397 {
08398    unsigned char cmdstr[5];
08399    
08400    memset(cmdstr, 0, 5);
08401 
08402    cmdstr[4] = command; 
08403 
08404    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08405 
08406 }
08407 
08408 /* ft-897 offset */
08409 
08410 static int set_offset_ft897(struct rpt *myrpt, char offset)
08411 {
08412    unsigned char cmdstr[5];
08413    
08414    memset(cmdstr, 0, 5);
08415 
08416    switch(offset){
08417       case  REM_SIMPLEX:
08418          cmdstr[0] = 0x89;
08419          break;
08420 
08421       case  REM_MINUS:
08422          cmdstr[0] = 0x09;
08423          break;
08424       
08425       case  REM_PLUS:
08426          cmdstr[0] = 0x49;
08427          break;   
08428 
08429       default:
08430          return -1;
08431    }
08432 
08433    cmdstr[4] = 0x09; 
08434 
08435    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08436 }
08437 
08438 /* ft-897 mode */
08439 
08440 static int set_mode_ft897(struct rpt *myrpt, char newmode)
08441 {
08442    unsigned char cmdstr[5];
08443    
08444    memset(cmdstr, 0, 5);
08445    
08446    switch(newmode){
08447       case  REM_MODE_FM:
08448          cmdstr[0] = 0x08;
08449          break;
08450 
08451       case  REM_MODE_USB:
08452          cmdstr[0] = 0x01;
08453          break;
08454 
08455       case  REM_MODE_LSB:
08456          cmdstr[0] = 0x00;
08457          break;
08458 
08459       case  REM_MODE_AM:
08460          cmdstr[0] = 0x04;
08461          break;
08462       
08463       default:
08464          return -1;
08465    }
08466    cmdstr[4] = 0x07; 
08467 
08468    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08469 }
08470 
08471 /* Set tone encode and decode modes */
08472 
08473 static int set_ctcss_mode_ft897(struct rpt *myrpt, char txplon, char rxplon)
08474 {
08475    unsigned char cmdstr[5];
08476    
08477    memset(cmdstr, 0, 5);
08478    
08479    if(rxplon && txplon)
08480       cmdstr[0] = 0x2A; /* Encode and Decode */
08481    else if (!rxplon && txplon)
08482       cmdstr[0] = 0x4A; /* Encode only */
08483    else if (rxplon && !txplon)
08484       cmdstr[0] = 0x3A; /* Encode only */
08485    else
08486       cmdstr[0] = 0x8A; /* OFF */
08487 
08488    cmdstr[4] = 0x0A; 
08489 
08490    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08491 }
08492 
08493 
08494 /* Set transmit and receive ctcss tone frequencies */
08495 
08496 static int set_ctcss_freq_ft897(struct rpt *myrpt, char *txtone, char *rxtone)
08497 {
08498    unsigned char cmdstr[5];
08499    char hertz[MAXREMSTR],decimal[MAXREMSTR];
08500    int h,d; 
08501 
08502    memset(cmdstr, 0, 5);
08503 
08504    if(split_ctcss_freq(hertz, decimal, txtone))
08505       return -1; 
08506 
08507    h = atoi(hertz);
08508    d = atoi(decimal);
08509    
08510    cmdstr[0] = ((h / 100) << 4) + (h % 100)/ 10;
08511    cmdstr[1] = ((h % 10) << 4) + (d % 10);
08512    
08513    if(rxtone){
08514    
08515       if(split_ctcss_freq(hertz, decimal, rxtone))
08516          return -1; 
08517 
08518       h = atoi(hertz);
08519       d = atoi(decimal);
08520    
08521       cmdstr[2] = ((h / 100) << 4) + (h % 100)/ 10;
08522       cmdstr[3] = ((h % 10) << 4) + (d % 10);
08523    }
08524    cmdstr[4] = 0x0B; 
08525 
08526    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08527 }  
08528 
08529 
08530 
08531 static int set_ft897(struct rpt *myrpt)
08532 {
08533    int res;
08534    
08535    if(debug)
08536       printf("@@@@ lock on\n");
08537 
08538    res = simple_command_ft897(myrpt, 0x00);  /* LOCK on */  
08539 
08540    if(debug)
08541       printf("@@@@ ptt off\n");
08542 
08543    if(!res)
08544       res = simple_command_ft897(myrpt, 0x88);     /* PTT off */
08545 
08546    if(debug)
08547       printf("Modulation mode\n");
08548 
08549    if(!res)
08550       res = set_mode_ft897(myrpt, myrpt->remmode);    /* Modulation mode */
08551 
08552    if(debug)
08553       printf("Split off\n");
08554 
08555    if(!res)
08556       simple_command_ft897(myrpt, 0x82);        /* Split off */
08557 
08558    if(debug)
08559       printf("Frequency\n");
08560 
08561    if(!res)
08562       res = set_freq_ft897(myrpt, myrpt->freq);    /* Frequency */
08563    if((myrpt->remmode == REM_MODE_FM)){
08564       if(debug)
08565          printf("Offset\n");
08566       if(!res)
08567          res = set_offset_ft897(myrpt, myrpt->offset);   /* Offset if FM */
08568       if((!res)&&(myrpt->rxplon || myrpt->txplon)){
08569          if(debug)
08570             printf("CTCSS tone freqs.\n");
08571          res = set_ctcss_freq_ft897(myrpt, myrpt->txpl, myrpt->rxpl); /* CTCSS freqs if CTCSS is enabled */
08572       }
08573       if(!res){
08574          if(debug)
08575             printf("CTCSS mode\n");
08576          res = set_ctcss_mode_ft897(myrpt, myrpt->txplon, myrpt->rxplon); /* CTCSS mode */
08577       }
08578    }
08579    if((myrpt->remmode == REM_MODE_USB)||(myrpt->remmode == REM_MODE_LSB)){
08580       if(debug)
08581          printf("Clarifier off\n");
08582       simple_command_ft897(myrpt, 0x85);        /* Clarifier off if LSB or USB */
08583    }
08584    return res;
08585 }
08586 
08587 static int closerem_ft897(struct rpt *myrpt)
08588 {
08589    simple_command_ft897(myrpt, 0x88); /* PTT off */
08590    return 0;
08591 }  
08592 
08593 /*
08594 * Bump frequency up or down by a small amount 
08595 * Return 0 if the new frequnecy is valid, or -1 if invalid
08596 * Interval is in Hz, resolution is 10Hz 
08597 */
08598 
08599 static int multimode_bump_freq_ft897(struct rpt *myrpt, int interval)
08600 {
08601    int m,d;
08602    char mhz[MAXREMSTR], decimals[MAXREMSTR];
08603 
08604    if(debug)
08605       printf("Before bump: %s\n", myrpt->freq);
08606 
08607    if(split_freq(mhz, decimals, myrpt->freq))
08608       return -1;
08609    
08610    m = atoi(mhz);
08611    d = atoi(decimals);
08612 
08613    d += (interval / 10); /* 10Hz resolution */
08614    if(d < 0){
08615       m--;
08616       d += 100000;
08617    }
08618    else if(d >= 100000){
08619       m++;
08620       d -= 100000;
08621    }
08622 
08623    if(check_freq_ft897(m, d, NULL)){
08624       if(debug)
08625          printf("Bump freq invalid\n");
08626       return -1;
08627    }
08628 
08629    snprintf(myrpt->freq, MAXREMSTR, "%d.%05d", m, d);
08630 
08631    if(debug)
08632       printf("After bump: %s\n", myrpt->freq);
08633 
08634    return set_freq_ft897(myrpt, myrpt->freq);   
08635 }
08636 
08637 
08638 
08639 /*
08640 * IC-706 I/O handlers
08641 */
08642 
08643 /* Check to see that the frequency is valid */
08644 /* returns 0 if frequency is valid          */
08645 
08646 static int check_freq_ic706(int m, int d, int *defmode, char mars)
08647 {
08648    int dflmd = REM_MODE_FM;
08649    int rv=0;
08650 
08651    if(debug > 6)
08652       ast_log(LOG_NOTICE,"(%i,%i,%i,%i)\n",m,d,*defmode,mars);
08653 
08654    /* first test for standard amateur radio bands */
08655 
08656    if(m == 1){                /* 160 meters */
08657       dflmd =  REM_MODE_LSB; 
08658       if(d < 80000)rv=-1;
08659    }
08660    else if(m == 3){           /* 80 meters */
08661       dflmd = REM_MODE_LSB;
08662       if(d < 50000)rv=-1;
08663    }
08664    else if(m == 7){           /* 40 meters */
08665       dflmd = REM_MODE_LSB;
08666       if(d > 30000)rv=-1;
08667    }
08668    else if(m == 14){             /* 20 meters */
08669       dflmd = REM_MODE_USB;
08670       if(d > 35000)rv=-1;
08671    }
08672    else if(m == 18){                      /* 17 meters */
08673       dflmd = REM_MODE_USB;
08674       if((d < 6800) || (d > 16800))rv=-1;
08675    }
08676    else if(m == 21){ /* 15 meters */
08677       dflmd = REM_MODE_USB;
08678       if((d < 20000) || (d > 45000))rv=-1;
08679    }
08680    else if(m == 24){ /* 12 meters */
08681       dflmd = REM_MODE_USB;
08682       if((d < 89000) || (d > 99000))rv=-1;
08683    }
08684    else if(m == 28){                      /* 10 meters */
08685       dflmd = REM_MODE_USB;
08686    }
08687    else if(m == 29){ 
08688       if(d >= 51000)
08689          dflmd = REM_MODE_FM;
08690       else
08691          dflmd = REM_MODE_USB;
08692       if(d > 70000)rv=-1;
08693    }
08694    else if(m == 50){                      /* 6 meters */
08695       if(d >= 30000)
08696          dflmd = REM_MODE_FM;
08697       else
08698          dflmd = REM_MODE_USB;
08699    }
08700    else if((m >= 51) && ( m < 54)){
08701       dflmd = REM_MODE_FM;
08702    }
08703    else if(m == 144){ /* 2 meters */
08704       if(d >= 30000)
08705          dflmd = REM_MODE_FM;
08706       else
08707          dflmd = REM_MODE_USB;
08708    }
08709    else if((m >= 145) && (m < 148)){
08710       dflmd = REM_MODE_FM;
08711    }
08712    else if((m >= 430) && (m < 450)){         /* 70 centimeters */
08713       if(m  < 438)
08714          dflmd = REM_MODE_USB;
08715       else
08716          dflmd = REM_MODE_FM;
08717    }
08718 
08719    /* check expanded coverage */
08720    if(mars && rv<0){
08721       if((m >= 450) && (m < 470)){        /* LMR */
08722          dflmd = REM_MODE_FM;
08723          rv=0;
08724       }
08725       else if((m >= 148) && (m < 174)){      /* LMR */
08726          dflmd = REM_MODE_FM;
08727          rv=0;
08728       }
08729       else if((m >= 138) && (m < 144)){      /* VHF-AM AIRCRAFT */
08730          dflmd = REM_MODE_AM;
08731          rv=0;
08732       }
08733       else if((m >= 108) && (m < 138)){      /* VHF-AM AIRCRAFT */
08734          dflmd = REM_MODE_AM;
08735          rv=0;
08736       }
08737       else if( (m==0 && d>=55000) || (m==1 && d<=75000) ){  /* AM BCB*/
08738          dflmd = REM_MODE_AM;
08739          rv=0;
08740       }
08741       else if( (m == 1 && d>75000) || (m>1 && m<30) ){      /* HF SWL*/
08742          dflmd = REM_MODE_AM;
08743          rv=0;
08744       }
08745    }
08746 
08747    if(defmode)
08748       *defmode = dflmd;
08749 
08750    if(debug > 1)
08751       ast_log(LOG_NOTICE,"(%i,%i,%i,%i) returning %i\n",m,d,*defmode,mars,rv);
08752 
08753    return rv;
08754 }
08755 
08756 /* take a PL frequency and turn it into a code */
08757 static int ic706_pltocode(char *str)
08758 {
08759    int i;
08760    char *s;
08761    int rv=-1;
08762 
08763    s = strchr(str,'.');
08764    i = 0;
08765    if (s) i = atoi(s + 1);
08766    i += atoi(str) * 10;
08767    switch(i)
08768    {
08769        case 670:
08770          rv=0;
08771        case 693:
08772          rv=1;
08773        case 719:
08774          rv=2;
08775        case 744:
08776          rv=3;
08777        case 770:
08778          rv=4;
08779        case 797:
08780          rv=5;
08781        case 825:
08782          rv=6;
08783        case 854:
08784          rv=7;
08785        case 885:
08786          rv=8;
08787        case 915:
08788          rv=9;
08789        case 948:
08790          rv=10;
08791        case 974:
08792          rv=11;
08793        case 1000:
08794          rv=12;
08795        case 1035:
08796          rv=13;
08797        case 1072:
08798          rv=14;
08799        case 1109:
08800          rv=15;
08801        case 1148:
08802          rv=16;
08803        case 1188:
08804          rv=17;
08805        case 1230:
08806          rv=18;
08807        case 1273:
08808          rv=19;
08809        case 1318:
08810          rv=20;
08811        case 1365:
08812          rv=21;
08813        case 1413:
08814          rv=22;
08815        case 1462:
08816          rv=23;
08817        case 1514:
08818          rv=24;
08819        case 1567:
08820          rv=25;
08821        case 1598:
08822          rv=26;
08823        case 1622:
08824          rv=27;
08825        case 1655:
08826          rv=28;      
08827        case 1679:
08828          rv=29;
08829        case 1713:
08830          rv=30;
08831        case 1738:
08832          rv=31;
08833        case 1773:
08834          rv=32;
08835        case 1799:
08836          rv=33;
08837         case 1835:
08838          rv=34;
08839        case 1862:
08840          rv=35;
08841        case 1899:
08842          rv=36;
08843        case 1928:
08844          rv=37;
08845        case 1966:
08846          rv=38;
08847        case 1995:
08848          rv=39;
08849        case 2035:
08850          rv=40;
08851        case 2065:
08852          rv=41;
08853        case 2107:
08854          rv=42;
08855        case 2181:
08856          rv=43;
08857        case 2257:
08858          rv=44;
08859        case 2291:
08860          rv=45;
08861        case 2336:
08862          rv=46;
08863        case 2418:
08864          rv=47;
08865        case 2503:
08866          rv=48;
08867        case 2541:
08868          rv=49;
08869    }
08870    if(debug > 1)
08871       ast_log(LOG_NOTICE,"%i  rv=%i\n",i, rv);
08872 
08873    return rv;
08874 }
08875 
08876 /* ic-706 simple commands */
08877 
08878 static int simple_command_ic706(struct rpt *myrpt, char command, char subcommand)
08879 {
08880    unsigned char cmdstr[10];
08881    
08882    cmdstr[0] = cmdstr[1] = 0xfe;
08883    cmdstr[2] = myrpt->p.civaddr;
08884    cmdstr[3] = 0xe0;
08885    cmdstr[4] = command;
08886    cmdstr[5] = subcommand;
08887    cmdstr[6] = 0xfd;
08888 
08889    return(civ_cmd(myrpt,cmdstr,7));
08890 }
08891 
08892 /*
08893 * Set a new frequency for the ic706
08894 */
08895 
08896 static int set_freq_ic706(struct rpt *myrpt, char *newfreq)
08897 {
08898    unsigned char cmdstr[20];
08899    char mhz[MAXREMSTR], decimals[MAXREMSTR];
08900    int fd,m,d;
08901 
08902    fd = 0;
08903    if(debug) 
08904       ast_log(LOG_NOTICE,"newfreq:%s\n",newfreq);        
08905 
08906    if(split_freq(mhz, decimals, newfreq))
08907       return -1; 
08908 
08909    m = atoi(mhz);
08910    d = atoi(decimals);
08911 
08912    /* The ic-706 likes packed BCD frequencies */
08913 
08914    cmdstr[0] = cmdstr[1] = 0xfe;
08915    cmdstr[2] = myrpt->p.civaddr;
08916    cmdstr[3] = 0xe0;
08917    cmdstr[4] = 5;
08918    cmdstr[5] = ((d % 10) << 4);
08919    cmdstr[6] = (((d % 1000)/ 100) << 4) + ((d % 100)/10);
08920    cmdstr[7] = ((d / 10000) << 4) + ((d % 10000)/1000);
08921    cmdstr[8] = (((m % 100)/10) << 4) + (m % 10);
08922    cmdstr[9] = (m / 100);
08923    cmdstr[10] = 0xfd;
08924 
08925    return(civ_cmd(myrpt,cmdstr,11));
08926 }
08927 
08928 /* ic-706 offset */
08929 
08930 static int set_offset_ic706(struct rpt *myrpt, char offset)
08931 {
08932    unsigned char c;
08933 
08934    if(debug > 6)
08935       ast_log(LOG_NOTICE,"offset=%i\n",offset);
08936 
08937    switch(offset){
08938       case  REM_SIMPLEX:
08939          c = 0x10;
08940          break;
08941 
08942       case  REM_MINUS:
08943          c = 0x11;
08944          break;
08945       
08946       case  REM_PLUS:
08947          c = 0x12;
08948          break;   
08949 
08950       default:
08951          return -1;
08952    }
08953 
08954    return simple_command_ic706(myrpt,0x0f,c);
08955 
08956 }
08957 
08958 /* ic-706 mode */
08959 
08960 static int set_mode_ic706(struct rpt *myrpt, char newmode)
08961 {
08962    unsigned char c;
08963    
08964    if(debug > 6)
08965       ast_log(LOG_NOTICE,"newmode=%i\n",newmode);
08966 
08967    switch(newmode){
08968       case  REM_MODE_FM:
08969          c = 5;
08970          break;
08971 
08972       case  REM_MODE_USB:
08973          c = 1;
08974          break;
08975 
08976       case  REM_MODE_LSB:
08977          c = 0;
08978          break;
08979 
08980       case  REM_MODE_AM:
08981          c = 2;
08982          break;
08983       
08984       default:
08985          return -1;
08986    }
08987    return simple_command_ic706(myrpt,6,c);
08988 }
08989 
08990 /* Set tone encode and decode modes */
08991 
08992 static int set_ctcss_mode_ic706(struct rpt *myrpt, char txplon, char rxplon)
08993 {
08994    unsigned char cmdstr[10];
08995    int rv;
08996 
08997    if(debug > 6)
08998       ast_log(LOG_NOTICE,"txplon=%i  rxplon=%i \n",txplon,rxplon);
08999 
09000    cmdstr[0] = cmdstr[1] = 0xfe;
09001    cmdstr[2] = myrpt->p.civaddr;
09002    cmdstr[3] = 0xe0;
09003    cmdstr[4] = 0x16;
09004    cmdstr[5] = 0x42;
09005    cmdstr[6] = (txplon != 0);
09006    cmdstr[7] = 0xfd;
09007 
09008    rv = civ_cmd(myrpt,cmdstr,8);
09009    if (rv) return(-1);
09010 
09011    cmdstr[0] = cmdstr[1] = 0xfe;
09012    cmdstr[2] = myrpt->p.civaddr;
09013    cmdstr[3] = 0xe0;
09014    cmdstr[4] = 0x16;
09015    cmdstr[5] = 0x43;
09016    cmdstr[6] = (rxplon != 0);
09017    cmdstr[7] = 0xfd;
09018 
09019    return(civ_cmd(myrpt,cmdstr,8));
09020 }
09021 
09022 #if 0
09023 /* Set transmit and receive ctcss tone frequencies */
09024 
09025 static int set_ctcss_freq_ic706(struct rpt *myrpt, char *txtone, char *rxtone)
09026 {
09027    unsigned char cmdstr[10];
09028    char hertz[MAXREMSTR],decimal[MAXREMSTR];
09029    int h,d,rv;
09030 
09031    memset(cmdstr, 0, 5);
09032 
09033    if(debug > 6)
09034       ast_log(LOG_NOTICE,"txtone=%s  rxtone=%s \n",txtone,rxtone);
09035 
09036    if(split_ctcss_freq(hertz, decimal, txtone))
09037       return -1; 
09038 
09039    h = atoi(hertz);
09040    d = atoi(decimal);
09041    
09042    cmdstr[0] = cmdstr[1] = 0xfe;
09043    cmdstr[2] = myrpt->p.civaddr;
09044    cmdstr[3] = 0xe0;
09045    cmdstr[4] = 0x1b;
09046    cmdstr[5] = 0;
09047    cmdstr[6] = ((h / 100) << 4) + (h % 100)/ 10;
09048    cmdstr[7] = ((h % 10) << 4) + (d % 10);
09049    cmdstr[8] = 0xfd;
09050 
09051    rv = civ_cmd(myrpt,cmdstr,9);
09052    if (rv) return(-1);
09053 
09054    if (!rxtone) return(0);
09055 
09056    if(split_ctcss_freq(hertz, decimal, rxtone))
09057       return -1; 
09058 
09059    h = atoi(hertz);
09060    d = atoi(decimal);
09061 
09062    cmdstr[0] = cmdstr[1] = 0xfe;
09063    cmdstr[2] = myrpt->p.civaddr;
09064    cmdstr[3] = 0xe0;
09065    cmdstr[4] = 0x1b;
09066    cmdstr[5] = 1;
09067    cmdstr[6] = ((h / 100) << 4) + (h % 100)/ 10;
09068    cmdstr[7] = ((h % 10) << 4) + (d % 10);
09069    cmdstr[8] = 0xfd;
09070    return(civ_cmd(myrpt,cmdstr,9));
09071 }  
09072 #endif
09073 
09074 static int vfo_ic706(struct rpt *myrpt)
09075 {
09076    unsigned char cmdstr[10];
09077    
09078    cmdstr[0] = cmdstr[1] = 0xfe;
09079    cmdstr[2] = myrpt->p.civaddr;
09080    cmdstr[3] = 0xe0;
09081    cmdstr[4] = 7;
09082    cmdstr[5] = 0xfd;
09083 
09084    return(civ_cmd(myrpt,cmdstr,6));
09085 }
09086 
09087 static int mem2vfo_ic706(struct rpt *myrpt)
09088 {
09089    unsigned char cmdstr[10];
09090    
09091    cmdstr[0] = cmdstr[1] = 0xfe;
09092    cmdstr[2] = myrpt->p.civaddr;
09093    cmdstr[3] = 0xe0;
09094    cmdstr[4] = 0x0a;
09095    cmdstr[5] = 0xfd;
09096 
09097    return(civ_cmd(myrpt,cmdstr,6));
09098 }
09099 
09100 static int select_mem_ic706(struct rpt *myrpt, int slot)
09101 {
09102    unsigned char cmdstr[10];
09103    
09104    cmdstr[0] = cmdstr[1] = 0xfe;
09105    cmdstr[2] = myrpt->p.civaddr;
09106    cmdstr[3] = 0xe0;
09107    cmdstr[4] = 8;
09108    cmdstr[5] = 0;
09109    cmdstr[6] = ((slot / 10) << 4) + (slot % 10);
09110    cmdstr[7] = 0xfd;
09111 
09112    return(civ_cmd(myrpt,cmdstr,8));
09113 }
09114 
09115 static int set_ic706(struct rpt *myrpt)
09116 {
09117    int res = 0,i;
09118    
09119    if(debug)ast_log(LOG_NOTICE, "Set to VFO A iobase=%i\n",myrpt->p.iobase);
09120 
09121    if (!res)
09122       res = simple_command_ic706(myrpt,7,0);
09123 
09124    if((myrpt->remmode == REM_MODE_FM))
09125    {
09126       i = ic706_pltocode(myrpt->rxpl);
09127       if (i == -1) return -1;
09128       if(debug)
09129          printf("Select memory number\n");
09130       if (!res)
09131          res = select_mem_ic706(myrpt,i + IC706_PL_MEMORY_OFFSET);
09132       if(debug)
09133          printf("Transfer memory to VFO\n");
09134       if (!res)
09135          res = mem2vfo_ic706(myrpt);
09136    }
09137       
09138    if(debug)
09139       printf("Set to VFO\n");
09140 
09141    if (!res)
09142       res = vfo_ic706(myrpt);
09143 
09144    if(debug)
09145       printf("Modulation mode\n");
09146 
09147    if (!res)
09148       res = set_mode_ic706(myrpt, myrpt->remmode);    /* Modulation mode */
09149 
09150    if(debug)
09151       printf("Split off\n");
09152 
09153    if(!res)
09154       simple_command_ic706(myrpt, 0x82,0);         /* Split off */
09155 
09156    if(debug)
09157       printf("Frequency\n");
09158 
09159    if(!res)
09160       res = set_freq_ic706(myrpt, myrpt->freq);    /* Frequency */
09161    if((myrpt->remmode == REM_MODE_FM)){
09162       if(debug)
09163          printf("Offset\n");
09164       if(!res)
09165          res = set_offset_ic706(myrpt, myrpt->offset);   /* Offset if FM */
09166       if(!res){
09167          if(debug)
09168             printf("CTCSS mode\n");
09169          res = set_ctcss_mode_ic706(myrpt, myrpt->txplon, myrpt->rxplon); /* CTCSS mode */
09170       }
09171    }
09172    return res;
09173 }
09174 
09175 /*
09176 * Bump frequency up or down by a small amount 
09177 * Return 0 if the new frequnecy is valid, or -1 if invalid
09178 * Interval is in Hz, resolution is 10Hz 
09179 */
09180 
09181 static int multimode_bump_freq_ic706(struct rpt *myrpt, int interval)
09182 {
09183    int m,d;
09184    char mhz[MAXREMSTR], decimals[MAXREMSTR];
09185    unsigned char cmdstr[20];
09186 
09187    if(debug)
09188       printf("Before bump: %s\n", myrpt->freq);
09189 
09190    if(split_freq(mhz, decimals, myrpt->freq))
09191       return -1;
09192    
09193    m = atoi(mhz);
09194    d = atoi(decimals);
09195 
09196    d += (interval / 10); /* 10Hz resolution */
09197    if(d < 0){
09198       m--;
09199       d += 100000;
09200    }
09201    else if(d >= 100000){
09202       m++;
09203       d -= 100000;
09204    }
09205 
09206    if(check_freq_ic706(m, d, NULL,myrpt->p.remote_mars)){
09207       if(debug)
09208          printf("Bump freq invalid\n");
09209       return -1;
09210    }
09211 
09212    snprintf(myrpt->freq, MAXREMSTR, "%d.%05d", m, d);
09213 
09214    if(debug)
09215       printf("After bump: %s\n", myrpt->freq);
09216 
09217    /* The ic-706 likes packed BCD frequencies */
09218 
09219    cmdstr[0] = cmdstr[1] = 0xfe;
09220    cmdstr[2] = myrpt->p.civaddr;
09221    cmdstr[3] = 0xe0;
09222    cmdstr[4] = 0;
09223    cmdstr[5] = ((d % 10) << 4);
09224    cmdstr[6] = (((d % 1000)/ 100) << 4) + ((d % 100)/10);
09225    cmdstr[7] = ((d / 10000) << 4) + ((d % 10000)/1000);
09226    cmdstr[8] = (((m % 100)/10) << 4) + (m % 10);
09227    cmdstr[9] = (m / 100);
09228    cmdstr[10] = 0xfd;
09229 
09230    return(serial_remote_io(myrpt,cmdstr,11,NULL,0,0));
09231 }
09232 
09233 
09234 
09235 /*
09236 * Dispatch to correct I/O handler 
09237 */
09238 static int setrem(struct rpt *myrpt)
09239 {
09240 char  str[300];
09241 char  *offsets[] = {"SIMPLEX","MINUS","PLUS"};
09242 char  *powerlevels[] = {"LOW","MEDIUM","HIGH"};
09243 char  *modes[] = {"FM","USB","LSB","AM"};
09244 int   res = -1;
09245 
09246 #if   0
09247 printf("FREQ,%s,%s,%s,%s,%s,%s,%d,%d\n",myrpt->freq,
09248    modes[(int)myrpt->remmode],
09249    myrpt->txpl,myrpt->rxpl,offsets[(int)myrpt->offset],
09250    powerlevels[(int)myrpt->powerlevel],myrpt->txplon,
09251    myrpt->rxplon);
09252 #endif
09253    if (myrpt->p.archivedir)
09254    {
09255       sprintf(str,"FREQ,%s,%s,%s,%s,%s,%s,%d,%d",myrpt->freq,
09256          modes[(int)myrpt->remmode],
09257          myrpt->txpl,myrpt->rxpl,offsets[(int)myrpt->offset],
09258          powerlevels[(int)myrpt->powerlevel],myrpt->txplon,
09259          myrpt->rxplon);
09260       donodelog(myrpt,str);
09261    }
09262    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
09263    {
09264       rpt_telemetry(myrpt,SETREMOTE,NULL);
09265       res = 0;
09266    }
09267    if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09268    {
09269       rpt_telemetry(myrpt,SETREMOTE,NULL);
09270       res = 0;
09271    }
09272    if(!strcmp(myrpt->remoterig, remote_rig_tm271))
09273    {
09274       rpt_telemetry(myrpt,SETREMOTE,NULL);
09275       res = 0;
09276    }
09277    else if(!strcmp(myrpt->remoterig, remote_rig_rbi))
09278    {
09279       res = setrbi_check(myrpt);
09280       if (!res)
09281       {
09282          rpt_telemetry(myrpt,SETREMOTE,NULL);
09283          res = 0;
09284       }
09285    }
09286    else if(ISRIG_RTX(myrpt->remoterig))
09287    {
09288       setrtx(myrpt);
09289       res = 0;
09290    }
09291    else if(!strcmp(myrpt->remoterig, remote_rig_kenwood)) {
09292       rpt_telemetry(myrpt,SETREMOTE,NULL);
09293       res = 0;
09294    }
09295    else
09296       res = 0;
09297 
09298    if (res < 0) ast_log(LOG_ERROR,"Unable to send remote command on node %s\n",myrpt->name);
09299 
09300    return res;
09301 }
09302 
09303 static int closerem(struct rpt *myrpt)
09304 {
09305    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
09306       return closerem_ft897(myrpt);
09307    else
09308       return 0;
09309 }
09310 
09311 /*
09312 * Dispatch to correct RX frequency checker
09313 */
09314 
09315 static int check_freq(struct rpt *myrpt, int m, int d, int *defmode)
09316 {
09317    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
09318       return check_freq_ft897(m, d, defmode);
09319    else if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09320       return check_freq_ic706(m, d, defmode,myrpt->p.remote_mars);
09321    else if(!strcmp(myrpt->remoterig, remote_rig_rbi))
09322       return check_freq_rbi(m, d, defmode);
09323    else if(!strcmp(myrpt->remoterig, remote_rig_kenwood))
09324       return check_freq_kenwood(m, d, defmode);
09325    else if(!strcmp(myrpt->remoterig, remote_rig_tm271))
09326       return check_freq_tm271(m, d, defmode);
09327    else if(ISRIG_RTX(myrpt->remoterig))
09328       return check_freq_rtx(m, d, defmode, myrpt);
09329    else
09330       return -1;
09331 }
09332 
09333 /*
09334  * Check TX frequency before transmitting
09335    rv=1 if tx frequency in ok.
09336 */
09337 
09338 static char check_tx_freq(struct rpt *myrpt)
09339 {
09340    int i,rv=0;
09341    int radio_mhz, radio_decimals, ulimit_mhz, ulimit_decimals, llimit_mhz, llimit_decimals;
09342    char radio_mhz_char[MAXREMSTR];
09343    char radio_decimals_char[MAXREMSTR];
09344    char limit_mhz_char[MAXREMSTR];
09345    char limit_decimals_char[MAXREMSTR];
09346    char limits[256];
09347    char *limit_ranges[40];
09348    struct ast_variable *limitlist;
09349    
09350    if(debug > 3){
09351       ast_log(LOG_NOTICE, "myrpt->freq = %s\n", myrpt->freq);
09352    }
09353 
09354    /* Must have user logged in and tx_limits defined */
09355 
09356    if(!myrpt->p.txlimitsstanzaname || !myrpt->loginuser[0] || !myrpt->loginlevel[0]){
09357       if(debug > 3){
09358          ast_log(LOG_NOTICE, "No tx band table defined, or no user logged in. rv=1\n");
09359       }
09360       rv=1;
09361       return 1; /* Assume it's ok otherwise */
09362    }
09363 
09364    /* Retrieve the band table for the loginlevel */
09365    limitlist = ast_variable_browse(myrpt->cfg, myrpt->p.txlimitsstanzaname);
09366 
09367    if(!limitlist){
09368       ast_log(LOG_WARNING, "No entries in %s band table stanza. rv=0\n", myrpt->p.txlimitsstanzaname);
09369       rv=0;
09370       return 0;
09371    }
09372 
09373    split_freq(radio_mhz_char, radio_decimals_char, myrpt->freq);
09374    radio_mhz = atoi(radio_mhz_char);
09375    radio_decimals = decimals2int(radio_decimals_char);
09376 
09377    if(debug > 3){
09378       ast_log(LOG_NOTICE, "Login User = %s, login level = %s\n", myrpt->loginuser, myrpt->loginlevel);
09379    }
09380 
09381    /* Find our entry */
09382 
09383    for(;limitlist; limitlist=limitlist->next){
09384       if(!strcmp(limitlist->name, myrpt->loginlevel))
09385          break;
09386    }
09387 
09388    if(!limitlist){
09389       ast_log(LOG_WARNING, "Can't find %s entry in band table stanza %s. rv=0\n", myrpt->loginlevel, myrpt->p.txlimitsstanzaname);
09390       rv=0;
09391        return 0;
09392    }
09393    
09394    if(debug > 3){
09395       ast_log(LOG_NOTICE, "Auth: %s = %s\n", limitlist->name, limitlist->value);
09396    }
09397 
09398    /* Parse the limits */
09399 
09400    strncpy(limits, limitlist->value, 256);
09401    limits[255] = 0;
09402    finddelim(limits, limit_ranges, 40);
09403    for(i = 0; i < 40 && limit_ranges[i] ; i++){
09404       char range[40];
09405       char *r,*s;
09406       strncpy(range, limit_ranges[i], 40);
09407       range[39] = 0;
09408         if(debug > 3) 
09409          ast_log(LOG_NOTICE, "Check %s within %s\n", myrpt->freq, range);
09410    
09411       r = strchr(range, '-');
09412       if(!r){
09413          ast_log(LOG_WARNING, "Malformed range in %s tx band table entry. rv=0\n", limitlist->name);
09414          rv=0;
09415          break;
09416       }
09417       *r++ = 0;
09418       s = eatwhite(range);
09419       r = eatwhite(r);
09420       split_freq(limit_mhz_char, limit_decimals_char, s);
09421       llimit_mhz = atoi(limit_mhz_char);
09422       llimit_decimals = decimals2int(limit_decimals_char);
09423       split_freq(limit_mhz_char, limit_decimals_char, r);
09424       ulimit_mhz = atoi(limit_mhz_char);
09425       ulimit_decimals = decimals2int(limit_decimals_char);
09426          
09427       if((radio_mhz >= llimit_mhz) && (radio_mhz <= ulimit_mhz)){
09428          if(radio_mhz == llimit_mhz){ /* CASE 1: TX freq is in llimit mhz portion of band */
09429             if(radio_decimals >= llimit_decimals){ /* Cannot be below llimit decimals */
09430                if(llimit_mhz == ulimit_mhz){ /* If bandwidth < 1Mhz, check ulimit decimals */
09431                   if(radio_decimals <= ulimit_decimals){
09432                      rv=1;
09433                      break;
09434                   }
09435                   else{
09436                      if(debug > 3)
09437                         ast_log(LOG_NOTICE, "Invalid TX frequency, debug msg 1\n");
09438                      rv=0;
09439                      break;
09440                   }
09441                }
09442                else{
09443                   rv=1;
09444                   break;
09445                }
09446             }
09447             else{ /* Is below llimit decimals */
09448                if(debug > 3)
09449                   ast_log(LOG_NOTICE, "Invalid TX frequency, debug msg 2\n");
09450                rv=0;
09451                break;
09452             }
09453          }
09454          else if(radio_mhz == ulimit_mhz){ /* CASE 2: TX freq not in llimit mhz portion of band */
09455             if(radio_decimals <= ulimit_decimals){
09456                if(debug > 3)
09457                   ast_log(LOG_NOTICE, "radio_decimals <= ulimit_decimals\n");
09458                rv=1;
09459                break;
09460             }
09461             else{ /* Is above ulimit decimals */
09462                if(debug > 3)
09463                   ast_log(LOG_NOTICE, "Invalid TX frequency, debug msg 3\n");
09464                rv=0;
09465                break;
09466             }
09467          }
09468          else /* CASE 3: TX freq within a multi-Mhz band and ok */
09469             if(debug > 3)
09470                   ast_log(LOG_NOTICE, "Valid TX freq within a multi-Mhz band and ok.\n");
09471             rv=1;
09472             break;
09473       }
09474    }
09475    if(debug > 3)  
09476       ast_log(LOG_NOTICE, "rv=%i\n",rv);
09477 
09478    return rv;
09479 }
09480 
09481 
09482 /*
09483 * Dispatch to correct frequency bumping function
09484 */
09485 
09486 static int multimode_bump_freq(struct rpt *myrpt, int interval)
09487 {
09488    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
09489       return multimode_bump_freq_ft897(myrpt, interval);
09490    else if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09491       return multimode_bump_freq_ic706(myrpt, interval);
09492    else
09493       return -1;
09494 }
09495 
09496 
09497 /*
09498 * Queue announcment that scan has been stopped 
09499 */
09500 
09501 static void stop_scan(struct rpt *myrpt)
09502 {
09503    myrpt->hfscanstop = 1;
09504    rpt_telemetry(myrpt,SCAN,0);
09505 }
09506 
09507 /*
09508 * This is called periodically when in scan mode
09509 */
09510 
09511 
09512 static int service_scan(struct rpt *myrpt)
09513 {
09514    int res, interval;
09515    char mhz[MAXREMSTR], decimals[MAXREMSTR], k10=0i, k100=0;
09516 
09517    switch(myrpt->hfscanmode){
09518 
09519       case HF_SCAN_DOWN_SLOW:
09520          interval = -10; /* 100Hz /sec */
09521          break;
09522 
09523       case HF_SCAN_DOWN_QUICK:
09524          interval = -50; /* 500Hz /sec */
09525          break;
09526 
09527       case HF_SCAN_DOWN_FAST:
09528          interval = -200; /* 2KHz /sec */
09529          break;
09530 
09531       case HF_SCAN_UP_SLOW:
09532          interval = 10; /* 100Hz /sec */
09533          break;
09534 
09535       case HF_SCAN_UP_QUICK:
09536          interval = 50; /* 500 Hz/sec */
09537          break;
09538 
09539       case HF_SCAN_UP_FAST:
09540          interval = 200; /* 2KHz /sec */
09541          break;
09542 
09543       default:
09544          myrpt->hfscanmode = 0; /* Huh? */
09545          return -1;
09546    }
09547 
09548    res = split_freq(mhz, decimals, myrpt->freq);
09549       
09550    if(!res){
09551       k100 =decimals[0];
09552       k10 = decimals[1];
09553       res = multimode_bump_freq(myrpt, interval);
09554    }
09555 
09556    if(!res)
09557       res = split_freq(mhz, decimals, myrpt->freq);
09558 
09559 
09560    if(res){
09561       myrpt->hfscanmode = 0;
09562       myrpt->hfscanstatus = -2;
09563       return -1;
09564    }
09565 
09566    /* Announce 10KHz boundaries */
09567    if(k10 != decimals[1]){
09568       int myhund = (interval < 0) ? k100 : decimals[0];
09569       int myten = (interval < 0) ? k10 : decimals[1];
09570       myrpt->hfscanstatus = (myten == '0') ? (myhund - '0') * 100 : (myten - '0') * 10;
09571    } else myrpt->hfscanstatus = 0;
09572    return res;
09573 
09574 }
09575 /*
09576    retrieve memory setting and set radio
09577 */
09578 static int get_mem_set(struct rpt *myrpt, char *digitbuf)
09579 {
09580    int res=0;
09581    if(debug)ast_log(LOG_NOTICE," digitbuf=%s\n", digitbuf);
09582    res = retreive_memory(myrpt, digitbuf);
09583    if(!res)res=setrem(myrpt); 
09584    if(debug)ast_log(LOG_NOTICE," freq=%s  res=%i\n", myrpt->freq, res);
09585    return res;
09586 }
09587 /*
09588    steer the radio selected channel to either one programmed into the radio
09589    or if the radio is VFO agile, to an rpt.conf memory location.
09590 */
09591 static int channel_steer(struct rpt *myrpt, char *data)
09592 {
09593    int res=0;
09594 
09595    if(debug)ast_log(LOG_NOTICE,"remoterig=%s, data=%s\n",myrpt->remoterig,data);
09596    if (!myrpt->remoterig) return(0);
09597    if(data<=0)
09598    {
09599       res=-1;
09600    }
09601    else
09602    {
09603       myrpt->nowchan=strtod(data,NULL);
09604       if(!strcmp(myrpt->remoterig, remote_rig_ppp16))
09605       {
09606          char string[16];
09607          sprintf(string,"SETCHAN %d ",myrpt->nowchan);
09608          send_usb_txt(myrpt,string);   
09609       }
09610       else
09611       {
09612          if(get_mem_set(myrpt, data))res=-1;
09613       }
09614    }
09615    if(debug)ast_log(LOG_NOTICE,"nowchan=%i  res=%i\n",myrpt->nowchan, res);
09616    return res;
09617 }
09618 /*
09619 */
09620 static int channel_revert(struct rpt *myrpt)
09621 {
09622    int res=0;
09623    if(debug)ast_log(LOG_NOTICE,"remoterig=%s, nowchan=%02d, waschan=%02d\n",myrpt->remoterig,myrpt->nowchan,myrpt->waschan);
09624    if (!myrpt->remoterig) return(0);
09625    if(myrpt->nowchan!=myrpt->waschan)
09626    {
09627       char data[8];
09628         if(debug)ast_log(LOG_NOTICE,"reverting.\n");
09629       sprintf(data,"%02d",myrpt->waschan);
09630       myrpt->nowchan=myrpt->waschan;
09631       channel_steer(myrpt,data);
09632       res=1;
09633    }
09634    return(res);
09635 }
09636 /*
09637 * Remote base function
09638 */
09639 
09640 static int function_remote(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
09641 {
09642    char *s,*s1,*s2;
09643    int i,j,r,ht,k,l,ls2,m,d,offset,offsave, modesave, defmode=0;
09644    intptr_t p;
09645    char multimode = 0;
09646    char oc,*cp,*cp1,*cp2;
09647    char tmp[20], freq[20] = "", savestr[20] = "";
09648    char mhz[MAXREMSTR], decimals[MAXREMSTR];
09649 
09650     if(debug > 6) {
09651       ast_log(LOG_NOTICE,"%s param=%s digitbuf=%s source=%i\n",myrpt->name,param,digitbuf,command_source);
09652    }
09653 
09654    if((!param) || (command_source == SOURCE_RPT) || (command_source == SOURCE_LNK))
09655       return DC_ERROR;
09656       
09657    p = myatoi(param);
09658 
09659    if ((p != 99) && (p != 5) && (p != 140) && myrpt->p.authlevel && 
09660       (!myrpt->loginlevel[0])) return DC_ERROR;
09661    multimode = multimode_capable(myrpt);
09662 
09663    switch(p){
09664 
09665       case 1:  /* retrieve memory */
09666          if(strlen(digitbuf) < 2) /* needs 2 digits */
09667             break;
09668          
09669          for(i = 0 ; i < 2 ; i++){
09670             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
09671                return DC_ERROR;
09672          }
09673          r=get_mem_set(myrpt, digitbuf);
09674          if (r < 0){
09675             rpt_telemetry(myrpt,MEMNOTFOUND,NULL);
09676             return DC_COMPLETE;
09677          }
09678          else if (r > 0){
09679             return DC_ERROR;
09680          }
09681          return DC_COMPLETE;  
09682          
09683       case 2:  /* set freq and offset */
09684       
09685          
09686             for(i = 0, j = 0, k = 0, l = 0 ; digitbuf[i] ; i++){ /* look for M+*K+*O or M+*H+* depending on mode */
09687             if(digitbuf[i] == '*'){
09688                j++;
09689                continue;
09690             }
09691             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
09692                goto invalid_freq;
09693             else{
09694                if(j == 0)
09695                   l++; /* # of digits before first * */
09696                if(j == 1)
09697                   k++; /* # of digits after first * */
09698             }
09699          }
09700       
09701          i = strlen(digitbuf) - 1;
09702          if(multimode){
09703             if((j > 2) || (l > 3) || (k > 6))
09704                goto invalid_freq; /* &^@#! */
09705          }
09706          else{
09707             if((j > 2) || (l > 4) || (k > 3))
09708                goto invalid_freq; /* &^@#! */
09709          }
09710 
09711          /* Wait for M+*K+* */
09712 
09713          if(j < 2)
09714             break; /* Not yet */
09715 
09716          /* We have a frequency */
09717 
09718          strncpy(tmp, digitbuf ,sizeof(tmp) - 1);
09719          
09720          s = tmp;
09721          s1 = strsep(&s, "*"); /* Pick off MHz */
09722          s2 = strsep(&s,"*"); /* Pick off KHz and Hz */
09723          ls2 = strlen(s2); 
09724          
09725          switch(ls2){ /* Allow partial entry of khz and hz digits for laziness support */
09726             case 1:
09727                ht = 0;
09728                k = 100 * atoi(s2);
09729                break;
09730             
09731             case 2:
09732                ht = 0;
09733                k = 10 * atoi(s2);
09734                break;
09735                
09736             case 3:
09737                if(!multimode){
09738                   if((s2[2] != '0')&&(s2[2] != '5'))
09739                      goto invalid_freq;
09740                }
09741                ht = 0;
09742                k = atoi(s2);
09743                   break;
09744             case 4:
09745                k = atoi(s2)/10;
09746                ht = 10 * (atoi(s2+(ls2-1)));
09747                break;
09748 
09749             case 5:
09750                k = atoi(s2)/100;
09751                ht = (atoi(s2+(ls2-2)));
09752                break;
09753                
09754             default:
09755                goto invalid_freq;
09756          }
09757 
09758          /* Check frequency for validity and establish a default mode */
09759          
09760          snprintf(freq, sizeof(freq), "%s.%03d%02d",s1, k, ht);
09761 
09762          if(debug)
09763             ast_log(LOG_NOTICE, "New frequency: %s\n", freq);
09764    
09765          split_freq(mhz, decimals, freq);
09766          m = atoi(mhz);
09767          d = atoi(decimals);
09768 
09769          if(check_freq(myrpt, m, d, &defmode)) /* Check to see if frequency entered is legit */
09770                  goto invalid_freq;
09771 
09772 
09773          if((defmode == REM_MODE_FM) && (digitbuf[i] == '*')) /* If FM, user must enter and additional offset digit */
09774             break; /* Not yet */
09775 
09776 
09777          offset = REM_SIMPLEX; /* Assume simplex */
09778 
09779          if(defmode == REM_MODE_FM){
09780             oc = *s; /* Pick off offset */
09781          
09782             if (oc){
09783                switch(oc){
09784                   case '1':
09785                      offset = REM_MINUS;
09786                      break;
09787                   
09788                   case '2':
09789                      offset = REM_SIMPLEX;
09790                   break;
09791                   
09792                   case '3':
09793                      offset = REM_PLUS;
09794                      break;
09795                   
09796                   default:
09797                      goto invalid_freq;
09798                } 
09799             } 
09800          }  
09801          offsave = myrpt->offset;
09802          modesave = myrpt->remmode;
09803          strncpy(savestr, myrpt->freq, sizeof(savestr) - 1);
09804          strncpy(myrpt->freq, freq, sizeof(myrpt->freq) - 1);
09805          myrpt->offset = offset;
09806          myrpt->remmode = defmode;
09807 
09808          if (setrem(myrpt) == -1){
09809             myrpt->offset = offsave;
09810             myrpt->remmode = modesave;
09811             strncpy(myrpt->freq, savestr, sizeof(myrpt->freq) - 1);
09812             goto invalid_freq;
09813          }
09814 
09815          return DC_COMPLETE;
09816 
09817 invalid_freq:
09818          rpt_telemetry(myrpt,INVFREQ,NULL);
09819          return DC_ERROR; 
09820       
09821       case 3: /* set rx PL tone */
09822             for(i = 0, j = 0, k = 0, l = 0 ; digitbuf[i] ; i++){ /* look for N+*N */
09823             if(digitbuf[i] == '*'){
09824                j++;
09825                continue;
09826             }
09827             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
09828                return DC_ERROR;
09829             else{
09830                if(j)
09831                   l++;
09832                else
09833                   k++;
09834             }
09835          }
09836          if((j > 1) || (k > 3) || (l > 1))
09837             return DC_ERROR; /* &$@^! */
09838          i = strlen(digitbuf) - 1;
09839          if((j != 1) || (k < 2)|| (l != 1))
09840             break; /* Not yet */
09841          if(debug)
09842             printf("PL digits entered %s\n", digitbuf);
09843             
09844          strncpy(tmp, digitbuf, sizeof(tmp) - 1);
09845          /* see if we have at least 1 */
09846          s = strchr(tmp,'*');
09847          if(s)
09848             *s = '.';
09849          strncpy(savestr, myrpt->rxpl, sizeof(savestr) - 1);
09850          strncpy(myrpt->rxpl, tmp, sizeof(myrpt->rxpl) - 1);
09851          if(!strcmp(myrpt->remoterig, remote_rig_rbi))
09852          {
09853             strncpy(myrpt->txpl, tmp, sizeof(myrpt->txpl) - 1);
09854          }
09855          if (setrem(myrpt) == -1){
09856             strncpy(myrpt->rxpl, savestr, sizeof(myrpt->rxpl) - 1);
09857             return DC_ERROR;
09858          }
09859          return DC_COMPLETE;
09860       
09861       case 4: /* set tx PL tone */
09862          /* cant set tx tone on RBI (rx tone does both) */
09863          if(!strcmp(myrpt->remoterig, remote_rig_rbi))
09864             return DC_ERROR;
09865          /*  eventually for the ic706 instead of just throwing the exception
09866             we can check if we are in encode only mode and allow the tx
09867             ctcss code to be changed. but at least the warning message is
09868             issued for now.
09869          */
09870          if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09871          {
09872             if(debug)
09873                ast_log(LOG_WARNING,"Setting IC706 Tx CTCSS Code Not Supported. Set Rx Code for both.\n");
09874             return DC_ERROR;
09875          }
09876          for(i = 0, j = 0, k = 0, l = 0 ; digitbuf[i] ; i++){ /* look for N+*N */
09877             if(digitbuf[i] == '*'){
09878                j++;
09879                continue;
09880             }
09881             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
09882                return DC_ERROR;
09883             else{
09884                if(j)
09885                   l++;
09886                else
09887                   k++;
09888             }
09889          }
09890          if((j > 1) || (k > 3) || (l > 1))
09891             return DC_ERROR; /* &$@^! */
09892          i = strlen(digitbuf) - 1;
09893          if((j != 1) || (k < 2)|| (l != 1))
09894             break; /* Not yet */
09895          if(debug)
09896             printf("PL digits entered %s\n", digitbuf);
09897             
09898          strncpy(tmp, digitbuf, sizeof(tmp) - 1);
09899          /* see if we have at least 1 */
09900          s = strchr(tmp,'*');
09901          if(s)
09902             *s = '.';
09903          strncpy(savestr, myrpt->txpl, sizeof(savestr) - 1);
09904          strncpy(myrpt->txpl, tmp, sizeof(myrpt->txpl) - 1);
09905          
09906          if (setrem(myrpt) == -1){
09907             strncpy(myrpt->txpl, savestr, sizeof(myrpt->txpl) - 1);
09908             return DC_ERROR;
09909          }
09910          return DC_COMPLETE;
09911       
09912 
09913       case 6: /* MODE (FM,USB,LSB,AM) */
09914          if(strlen(digitbuf) < 1)
09915             break;
09916 
09917          if(!multimode)
09918             return DC_ERROR; /* Multimode radios only */
09919 
09920          switch(*digitbuf){
09921             case '1':
09922                split_freq(mhz, decimals, myrpt->freq); 
09923                m=atoi(mhz);
09924                if(m < 29) /* No FM allowed below 29MHz! */
09925                   return DC_ERROR;
09926                myrpt->remmode = REM_MODE_FM;
09927                
09928                rpt_telemetry(myrpt,REMMODE,NULL);
09929                break;
09930 
09931             case '2':
09932                myrpt->remmode = REM_MODE_USB;
09933                rpt_telemetry(myrpt,REMMODE,NULL);
09934                break;   
09935 
09936             case '3':
09937                myrpt->remmode = REM_MODE_LSB;
09938                rpt_telemetry(myrpt,REMMODE,NULL);
09939                break;
09940             
09941             case '4':
09942                myrpt->remmode = REM_MODE_AM;
09943                rpt_telemetry(myrpt,REMMODE,NULL);
09944                break;
09945       
09946             default:
09947                return DC_ERROR;
09948          }
09949 
09950          if(setrem(myrpt))
09951             return DC_ERROR;
09952          return DC_COMPLETEQUIET;
09953       case 99:
09954          /* cant log in when logged in */
09955          if (myrpt->loginlevel[0]) 
09956             return DC_ERROR;
09957          *myrpt->loginuser = 0;
09958          myrpt->loginlevel[0] = 0;
09959          cp = ast_strdup(param);
09960          cp1 = strchr(cp,',');
09961          ast_mutex_lock(&myrpt->lock);
09962          if (cp1) 
09963          {
09964             *cp1 = 0;
09965             cp2 = strchr(cp1 + 1,',');
09966             if (cp2) 
09967             {
09968                *cp2 = 0;
09969                strncpy(myrpt->loginlevel,cp2 + 1,
09970                   sizeof(myrpt->loginlevel) - 1);
09971             }
09972             strncpy(myrpt->loginuser,cp1 + 1,sizeof(myrpt->loginuser));
09973             ast_mutex_unlock(&myrpt->lock);
09974             if (myrpt->p.archivedir)
09975             {
09976                char str[100];
09977 
09978                sprintf(str,"LOGIN,%s,%s",
09979                    myrpt->loginuser,myrpt->loginlevel);
09980                donodelog(myrpt,str);
09981             }
09982             if (debug) 
09983                printf("loginuser %s level %s\n",myrpt->loginuser,myrpt->loginlevel);
09984             rpt_telemetry(myrpt,REMLOGIN,NULL);
09985          }
09986          ast_free(cp);
09987          return DC_COMPLETEQUIET;
09988       case 100: /* RX PL Off */
09989          myrpt->rxplon = 0;
09990          setrem(myrpt);
09991          rpt_telemetry(myrpt,REMXXX,(void *)p);
09992          return DC_COMPLETEQUIET;
09993       case 101: /* RX PL On */
09994          myrpt->rxplon = 1;
09995          setrem(myrpt);
09996          rpt_telemetry(myrpt,REMXXX,(void *)p);
09997          return DC_COMPLETEQUIET;
09998       case 102: /* TX PL Off */
09999          myrpt->txplon = 0;
10000          setrem(myrpt);
10001          rpt_telemetry(myrpt,REMXXX,(void *)p);
10002          return DC_COMPLETEQUIET;
10003       case 103: /* TX PL On */
10004          myrpt->txplon = 1;
10005          setrem(myrpt);
10006          rpt_telemetry(myrpt,REMXXX,(void *)p);
10007          return DC_COMPLETEQUIET;
10008       case 104: /* Low Power */
10009          if(!strcmp(myrpt->remoterig, remote_rig_ic706))
10010             return DC_ERROR;
10011          myrpt->powerlevel = REM_LOWPWR;
10012          setrem(myrpt);
10013          rpt_telemetry(myrpt,REMXXX,(void *)p);
10014          return DC_COMPLETEQUIET;
10015       case 105: /* Medium Power */
10016          if(!strcmp(myrpt->remoterig, remote_rig_ic706))
10017             return DC_ERROR;
10018          if (ISRIG_RTX(myrpt->remoterig)) return DC_ERROR;
10019          myrpt->powerlevel = REM_MEDPWR;
10020          setrem(myrpt);
10021          rpt_telemetry(myrpt,REMXXX,(void *)p);
10022          return DC_COMPLETEQUIET;
10023       case 106: /* Hi Power */
10024          if(!strcmp(myrpt->remoterig, remote_rig_ic706))
10025             return DC_ERROR;
10026          myrpt->powerlevel = REM_HIPWR;
10027          setrem(myrpt);
10028          rpt_telemetry(myrpt,REMXXX,(void *)p);
10029          return DC_COMPLETEQUIET;
10030       case 107: /* Bump down 20Hz */
10031          multimode_bump_freq(myrpt, -20);
10032          return DC_COMPLETE;
10033       case 108: /* Bump down 100Hz */
10034          multimode_bump_freq(myrpt, -100);
10035          return DC_COMPLETE;
10036       case 109: /* Bump down 500Hz */
10037          multimode_bump_freq(myrpt, -500);
10038          return DC_COMPLETE;
10039       case 110: /* Bump up 20Hz */
10040          multimode_bump_freq(myrpt, 20);
10041          return DC_COMPLETE;
10042       case 111: /* Bump up 100Hz */
10043          multimode_bump_freq(myrpt, 100);
10044          return DC_COMPLETE;
10045       case 112: /* Bump up 500Hz */
10046          multimode_bump_freq(myrpt, 500);
10047          return DC_COMPLETE;
10048       case 113: /* Scan down slow */
10049          myrpt->scantimer = REM_SCANTIME;
10050          myrpt->hfscanmode = HF_SCAN_DOWN_SLOW;
10051          rpt_telemetry(myrpt,REMXXX,(void *)p);
10052          return DC_COMPLETEQUIET;
10053       case 114: /* Scan down quick */
10054          myrpt->scantimer = REM_SCANTIME;
10055          myrpt->hfscanmode = HF_SCAN_DOWN_QUICK;
10056          rpt_telemetry(myrpt,REMXXX,(void *)p);
10057          return DC_COMPLETEQUIET;
10058       case 115: /* Scan down fast */
10059          myrpt->scantimer = REM_SCANTIME;
10060          myrpt->hfscanmode = HF_SCAN_DOWN_FAST;
10061          rpt_telemetry(myrpt,REMXXX,(void *)p);
10062          return DC_COMPLETEQUIET;
10063       case 116: /* Scan up slow */
10064          myrpt->scantimer = REM_SCANTIME;
10065          myrpt->hfscanmode = HF_SCAN_UP_SLOW;
10066          rpt_telemetry(myrpt,REMXXX,(void *)p);
10067          return DC_COMPLETEQUIET;
10068       case 117: /* Scan up quick */
10069          myrpt->scantimer = REM_SCANTIME;
10070          myrpt->hfscanmode = HF_SCAN_UP_QUICK;
10071          rpt_telemetry(myrpt,REMXXX,(void *)p);
10072          return DC_COMPLETEQUIET;
10073       case 118: /* Scan up fast */
10074          myrpt->scantimer = REM_SCANTIME;
10075          myrpt->hfscanmode = HF_SCAN_UP_FAST;
10076          rpt_telemetry(myrpt,REMXXX,(void *)p);
10077          return DC_COMPLETEQUIET;
10078       case 119: /* Tune Request */
10079          if(debug > 3)
10080             ast_log(LOG_NOTICE,"TUNE REQUEST\n");
10081          /* if not currently going, and valid to do */
10082          if((!myrpt->tunerequest) && 
10083              ((!strcmp(myrpt->remoterig, remote_rig_ft897) || 
10084             !strcmp(myrpt->remoterig, remote_rig_ic706)) )) { 
10085             myrpt->remotetx = 0;
10086             ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_UNKEY);
10087             myrpt->tunerequest = 1;
10088             rpt_telemetry(myrpt,TUNE,NULL);
10089             return DC_COMPLETEQUIET;
10090          }
10091          return DC_ERROR;        
10092       case 5: /* Long Status */
10093          rpt_telemetry(myrpt,REMLONGSTATUS,NULL);
10094          return DC_COMPLETEQUIET;
10095       case 140: /* Short Status */
10096          rpt_telemetry(myrpt,REMSHORTSTATUS,NULL);
10097          return DC_COMPLETEQUIET;
10098       case 200:
10099       case 201:
10100       case 202:
10101       case 203:
10102       case 204:
10103       case 205:
10104       case 206:
10105       case 207:
10106       case 208:
10107       case 209:
10108       case 210:
10109       case 211:
10110       case 212:
10111       case 213:
10112       case 214:
10113       case 215:
10114          do_dtmf_local(myrpt,remdtmfstr[p - 200]);
10115          return DC_COMPLETEQUIET;
10116       default:
10117          break;
10118    }
10119    return DC_INDETERMINATE;
10120 }
10121 
10122 
10123 static int handle_remote_dtmf_digit(struct rpt *myrpt,char c, char *keyed, int phonemode)
10124 {
10125 time_t   now;
10126 int   ret,res = 0,src;
10127 
10128    if(debug > 6)
10129       ast_log(LOG_NOTICE,"c=%c  phonemode=%i  dtmfidx=%i\n",c,phonemode,myrpt->dtmfidx);
10130 
10131    time(&myrpt->last_activity_time);
10132    /* Stop scan mode if in scan mode */
10133    if(myrpt->hfscanmode){
10134       stop_scan(myrpt);
10135       return 0;
10136    }
10137 
10138    time(&now);
10139    /* if timed-out */
10140    if ((myrpt->dtmf_time_rem + DTMF_TIMEOUT) < now)
10141    {
10142       myrpt->dtmfidx = -1;
10143       myrpt->dtmfbuf[0] = 0;
10144       myrpt->dtmf_time_rem = 0;
10145    }
10146    /* if decode not active */
10147    if (myrpt->dtmfidx == -1)
10148    {
10149       /* if not lead-in digit, don't worry */
10150       if (c != myrpt->p.funcchar)
10151       {
10152          if (!myrpt->p.propagate_dtmf)
10153          {
10154             rpt_mutex_lock(&myrpt->lock);
10155             do_dtmf_local(myrpt,c);
10156             rpt_mutex_unlock(&myrpt->lock);
10157          }
10158          return 0;
10159       }
10160       myrpt->dtmfidx = 0;
10161       myrpt->dtmfbuf[0] = 0;
10162       myrpt->dtmf_time_rem = now;
10163       return 0;
10164    }
10165    /* if too many in buffer, start over */
10166    if (myrpt->dtmfidx >= MAXDTMF)
10167    {
10168       myrpt->dtmfidx = 0;
10169       myrpt->dtmfbuf[0] = 0;
10170       myrpt->dtmf_time_rem = now;
10171    }
10172    if (c == myrpt->p.funcchar)
10173    {
10174       /* if star at beginning, or 2 together, erase buffer */
10175       if ((myrpt->dtmfidx < 1) || 
10176          (myrpt->dtmfbuf[myrpt->dtmfidx - 1] == myrpt->p.funcchar))
10177       {
10178          myrpt->dtmfidx = 0;
10179          myrpt->dtmfbuf[0] = 0;
10180          myrpt->dtmf_time_rem = now;
10181          return 0;
10182       }
10183    }
10184    myrpt->dtmfbuf[myrpt->dtmfidx++] = c;
10185    myrpt->dtmfbuf[myrpt->dtmfidx] = 0;
10186    myrpt->dtmf_time_rem = now;
10187    
10188    
10189    src = SOURCE_RMT;
10190    if (phonemode == 2) src = SOURCE_DPHONE;
10191    else if (phonemode) src = SOURCE_PHONE;
10192    else if (phonemode == 4) src = SOURCE_ALT;
10193    ret = collect_function_digits(myrpt, myrpt->dtmfbuf, src, NULL);
10194    
10195    switch(ret){
10196    
10197       case DC_INDETERMINATE:
10198          res = 0;
10199          break;
10200             
10201       case DC_DOKEY:
10202          if (keyed) *keyed = 1;
10203          res = 0;
10204          break;
10205             
10206       case DC_REQ_FLUSH:
10207          myrpt->dtmfidx = 0;
10208          myrpt->dtmfbuf[0] = 0;
10209          res = 0;
10210          break;
10211             
10212             
10213       case DC_COMPLETE:
10214          res = 1;
10215       case DC_COMPLETEQUIET:
10216          myrpt->totalexecdcommands++;
10217          myrpt->dailyexecdcommands++;
10218          strncpy(myrpt->lastdtmfcommand, myrpt->dtmfbuf, MAXDTMF-1);
10219          myrpt->lastdtmfcommand[MAXDTMF-1] = '\0';
10220          myrpt->dtmfbuf[0] = 0;
10221          myrpt->dtmfidx = -1;
10222          myrpt->dtmf_time_rem = 0;
10223          break;
10224             
10225       case DC_ERROR:
10226       default:
10227          myrpt->dtmfbuf[0] = 0;
10228          myrpt->dtmfidx = -1;
10229          myrpt->dtmf_time_rem = 0;
10230          res = 0;
10231          break;
10232    }
10233 
10234    return res;
10235 }
10236 
10237 static int handle_remote_data(struct rpt *myrpt, char *str)
10238 {
10239 /* XXX ATTENTION: if you change the size of these arrays you MUST
10240  * change the limits in corresponding sscanf() calls below. */
10241 char  tmp[300],cmd[300],dest[300],src[300],c;
10242 int   seq,res;
10243 
10244    /* put string in our buffer */
10245    strncpy(tmp,str,sizeof(tmp) - 1);
10246    if (!strcmp(tmp,discstr)) return 0;
10247         if (!strcmp(tmp,newkeystr))
10248         {
10249       myrpt->newkey = 1;
10250                 return 0;
10251         }
10252 
10253 #ifndef  DO_NOT_NOTIFY_MDC1200_ON_REMOTE_BASES
10254    if (tmp[0] == 'I')
10255    {
10256       /* XXX WARNING: be very careful with the limits on the folowing
10257        * sscanf() call, make sure they match the values defined above */
10258       if (sscanf(tmp,"%299s %299s %30x",cmd,src,&seq) != 3)
10259       {
10260          ast_log(LOG_WARNING, "Unable to parse ident string %s\n",str);
10261          return 0;
10262       }
10263       mdc1200_notify(myrpt,src,seq);
10264       return 0;
10265    }
10266 #endif
10267    /* XXX WARNING: be very careful with the limits on the folowing
10268     * sscanf() call, make sure they match the values defined above */
10269    if (sscanf(tmp,"%299s %299s %299s %30d %1c",cmd,dest,src,&seq,&c) != 5)
10270    {
10271       ast_log(LOG_WARNING, "Unable to parse link string %s\n",str);
10272       return 0;
10273    }
10274    if (strcmp(cmd,"D"))
10275    {
10276       ast_log(LOG_WARNING, "Unable to parse link string %s\n",str);
10277       return 0;
10278    }
10279    /* if not for me, ignore */
10280    if (strcmp(dest,myrpt->name)) return 0;
10281    if (myrpt->p.archivedir)
10282    {
10283       char dtmfstr[100];
10284 
10285       sprintf(dtmfstr,"DTMF,%c",c);
10286       donodelog(myrpt,dtmfstr);
10287    }
10288    c = func_xlat(myrpt,c,&myrpt->p.outxlat);
10289    if (!c) return(0);
10290    res = handle_remote_dtmf_digit(myrpt,c, NULL, 0);
10291    if (res != 1)
10292       return res;
10293    rpt_telemetry(myrpt,COMPLETE,NULL);
10294    return 0;
10295 }
10296 
10297 static int handle_remote_phone_dtmf(struct rpt *myrpt, char c, char *keyed, int phonemode)
10298 {
10299 int   res;
10300 
10301 
10302    if(phonemode == 3) /* simplex phonemode, funcchar key/unkey toggle */
10303    {
10304       if (keyed && *keyed && ((c == myrpt->p.funcchar) || (c == myrpt->p.endchar)))
10305       {
10306          *keyed = 0; /* UNKEY */
10307          return 0;
10308       }
10309       else if (keyed && !*keyed && (c = myrpt->p.funcchar))
10310       {
10311          *keyed = 1; /* KEY */
10312          return 0;
10313       }
10314    }
10315    else /* endchar unkey */
10316    {
10317 
10318       if (keyed && *keyed && (c == myrpt->p.endchar))
10319       {
10320          *keyed = 0;
10321          return DC_INDETERMINATE;
10322       }
10323    }
10324    if (myrpt->p.archivedir)
10325    {
10326       char str[100];
10327 
10328       sprintf(str,"DTMF(P),%c",c);
10329       donodelog(myrpt,str);
10330    }
10331    res = handle_remote_dtmf_digit(myrpt,c,keyed, phonemode);
10332    if (res != 1)
10333       return res;
10334    rpt_telemetry(myrpt,COMPLETE,NULL);
10335    return 0;
10336 }
10337 
10338 static int attempt_reconnect(struct rpt *myrpt, struct rpt_link *l)
10339 {
10340    char *val, *s, *s1, *s2, *tele;
10341    char tmp[300], deststr[300] = "";
10342    char sx[320],*sy;
10343 
10344 
10345    val = node_lookup(myrpt,l->name);
10346    if (!val)
10347    {
10348       fprintf(stderr,"attempt_reconnect: cannot find node %s\n",l->name);
10349       return -1;
10350    }
10351 
10352    rpt_mutex_lock(&myrpt->lock);
10353    /* remove from queue */
10354    remque((struct qelem *) l);
10355    rpt_mutex_unlock(&myrpt->lock);
10356    strncpy(tmp,val,sizeof(tmp) - 1);
10357    s = tmp;
10358    s1 = strsep(&s,",");
10359    if (!strchr(s1,':') && strchr(s1,'/') && strncasecmp(s1, "local/", 6))
10360    {
10361       sy = strchr(s1,'/');    
10362       *sy = 0;
10363       sprintf(sx,"%s:4569/%s",s1,sy + 1);
10364       s1 = sx;
10365    }
10366    s2 = strsep(&s,",");
10367    snprintf(deststr, sizeof(deststr), "IAX2/%s", s1);
10368    tele = strchr(deststr, '/');
10369    if (!tele) {
10370       fprintf(stderr,"attempt_reconnect:Dial number (%s) must be in format tech/number\n",deststr);
10371       return -1;
10372    }
10373    *tele++ = 0;
10374    l->elaptime = 0;
10375    l->connecttime = 0;
10376    l->thisconnected = 0;
10377    l->newkey = 0;
10378    l->chan = ast_request(deststr, AST_FORMAT_SLINEAR, NULL, tele, NULL);
10379    if (l->chan){
10380       ast_set_read_format(l->chan, AST_FORMAT_SLINEAR);
10381       ast_set_write_format(l->chan, AST_FORMAT_SLINEAR);
10382 #ifndef  NEW_ASTERISK
10383       l->chan->whentohangup = 0;
10384 #endif
10385       l->chan->appl = "Apprpt";
10386       l->chan->data = "(Remote Rx)";
10387       if (option_verbose > 2)
10388          ast_verbose(VERBOSE_PREFIX_3 "rpt (attempt_reconnect) initiating call to %s/%s on %s\n",
10389             deststr, tele, l->chan->name);
10390       l->chan->caller.id.number.valid = 1;
10391       ast_free(l->chan->caller.id.number.str);
10392       l->chan->caller.id.number.str = ast_strdup(myrpt->name);
10393                 ast_call(l->chan,tele,999); 
10394 
10395    }
10396    else 
10397    {
10398       if (option_verbose > 2)
10399          ast_verbose(VERBOSE_PREFIX_3 "Unable to place call to %s/%s on %s\n",
10400             deststr,tele,l->chan->name);
10401       return -1;
10402    }
10403    rpt_mutex_lock(&myrpt->lock);
10404    /* put back in queue */
10405    insque((struct qelem *)l,(struct qelem *)myrpt->links.next);
10406    rpt_mutex_unlock(&myrpt->lock);
10407    ast_log(LOG_WARNING,"Reconnect Attempt to %s in process\n",l->name);
10408    if (!l->phonemode) send_newkey(l->chan);
10409    return 0;
10410 }
10411 
10412 /* 0 return=continue, 1 return = break, -1 return = error */
10413 static void local_dtmf_helper(struct rpt *myrpt,char c_in)
10414 {
10415 int   res;
10416 pthread_attr_t attr;
10417 char  cmd[MAXDTMF+1] = "",c;
10418 
10419 
10420    c = c_in & 0x7f;
10421    if (myrpt->p.archivedir)
10422    {
10423       char str[100];
10424 
10425       sprintf(str,"DTMF,MAIN,%c",c);
10426       donodelog(myrpt,str);
10427    }
10428    if (c == myrpt->p.endchar)
10429    {
10430    /* if in simple mode, kill autopatch */
10431       if (myrpt->p.simple && myrpt->callmode)
10432       {   
10433          if(debug)
10434             ast_log(LOG_WARNING, "simple mode autopatch kill\n");
10435          rpt_mutex_lock(&myrpt->lock);
10436          myrpt->callmode = 0;
10437          myrpt->macropatch=0;
10438          channel_revert(myrpt);
10439          rpt_mutex_unlock(&myrpt->lock);
10440          rpt_telemetry(myrpt,TERM,NULL);
10441          return;
10442       }
10443       rpt_mutex_lock(&myrpt->lock);
10444       myrpt->stopgen = 1;
10445       if (myrpt->cmdnode[0])
10446       {
10447          myrpt->cmdnode[0] = 0;
10448          myrpt->dtmfidx = -1;
10449          myrpt->dtmfbuf[0] = 0;
10450          rpt_mutex_unlock(&myrpt->lock);
10451          rpt_telemetry(myrpt,COMPLETE,NULL);
10452          return;
10453       } 
10454       else if(!myrpt->inpadtest)
10455                 {
10456                         rpt_mutex_unlock(&myrpt->lock);
10457                         if (myrpt->p.propagate_phonedtmf)
10458                                do_dtmf_phone(myrpt,NULL,c);
10459          return;
10460                 }
10461       else
10462          rpt_mutex_unlock(&myrpt->lock);
10463    }
10464    rpt_mutex_lock(&myrpt->lock);
10465    if (myrpt->cmdnode[0])
10466    {
10467       rpt_mutex_unlock(&myrpt->lock);
10468       send_link_dtmf(myrpt,c);
10469       return;
10470    }
10471    if (!myrpt->p.simple)
10472    {
10473       if ((!myrpt->inpadtest)&&(c == myrpt->p.funcchar))
10474       {
10475          myrpt->dtmfidx = 0;
10476          myrpt->dtmfbuf[myrpt->dtmfidx] = 0;
10477          rpt_mutex_unlock(&myrpt->lock);
10478          time(&myrpt->dtmf_time);
10479          return;
10480       } 
10481       else if (((myrpt->inpadtest)||(c != myrpt->p.endchar)) && (myrpt->dtmfidx >= 0))
10482       {
10483          time(&myrpt->dtmf_time);
10484          
10485          if (myrpt->dtmfidx < MAXDTMF)
10486          {
10487             int src;
10488 
10489             myrpt->dtmfbuf[myrpt->dtmfidx++] = c;
10490             myrpt->dtmfbuf[myrpt->dtmfidx] = 0;
10491             
10492             strncpy(cmd, myrpt->dtmfbuf, sizeof(cmd) - 1);
10493             
10494             rpt_mutex_unlock(&myrpt->lock);
10495             src = SOURCE_RPT;
10496             if (c_in & 0x80) src = SOURCE_ALT;
10497             res = collect_function_digits(myrpt, cmd, src, NULL);
10498             rpt_mutex_lock(&myrpt->lock);
10499             switch(res){
10500                 case DC_INDETERMINATE:
10501                break;
10502                 case DC_REQ_FLUSH:
10503                myrpt->dtmfidx = 0;
10504                myrpt->dtmfbuf[0] = 0;
10505                break;
10506                 case DC_COMPLETE:
10507                 case DC_COMPLETEQUIET:
10508                myrpt->totalexecdcommands++;
10509                myrpt->dailyexecdcommands++;
10510                strncpy(myrpt->lastdtmfcommand, cmd, MAXDTMF-1);
10511                myrpt->lastdtmfcommand[MAXDTMF-1] = '\0';
10512                myrpt->dtmfbuf[0] = 0;
10513                myrpt->dtmfidx = -1;
10514                myrpt->dtmf_time = 0;
10515                break;
10516 
10517                 case DC_ERROR:
10518                 default:
10519                myrpt->dtmfbuf[0] = 0;
10520                myrpt->dtmfidx = -1;
10521                myrpt->dtmf_time = 0;
10522                break;
10523             }
10524             if(res != DC_INDETERMINATE) {
10525                rpt_mutex_unlock(&myrpt->lock);
10526                return;
10527             }
10528          } 
10529       }
10530    }
10531    else /* if simple */
10532    {
10533       if ((!myrpt->callmode) && (c == myrpt->p.funcchar))
10534       {
10535          myrpt->callmode = 1;
10536          myrpt->patchnoct = 0;
10537          myrpt->patchquiet = 0;
10538          myrpt->patchfarenddisconnect = 0;
10539          myrpt->patchdialtime = 0;
10540          strncpy(myrpt->patchcontext, myrpt->p.ourcontext, MAXPATCHCONTEXT);
10541          myrpt->cidx = 0;
10542          myrpt->exten[myrpt->cidx] = 0;
10543          rpt_mutex_unlock(&myrpt->lock);
10544               pthread_attr_init(&attr);
10545               pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
10546          ast_pthread_create(&myrpt->rpt_call_thread,&attr,rpt_call,(void *)myrpt);
10547          return;
10548       }
10549    }
10550    if (myrpt->callmode == 1)
10551    {
10552       myrpt->exten[myrpt->cidx++] = c;
10553       myrpt->exten[myrpt->cidx] = 0;
10554       /* if this exists */
10555       if (ast_exists_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
10556       {
10557          /* if this really it, end now */
10558          if (!ast_matchmore_extension(myrpt->pchannel,myrpt->patchcontext,
10559             myrpt->exten,1,NULL)) 
10560          {
10561             myrpt->callmode = 2;
10562             rpt_mutex_unlock(&myrpt->lock);
10563             if(!myrpt->patchquiet)
10564                rpt_telemetry(myrpt,PROC,NULL); 
10565             return;
10566          }
10567          else /* othewise, reset timer */
10568          {
10569             myrpt->calldigittimer = 1;
10570          }
10571       }
10572       /* if can continue, do so */
10573       if (!ast_canmatch_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
10574       {
10575          /* call has failed, inform user */
10576          myrpt->callmode = 4;
10577       }
10578       rpt_mutex_unlock(&myrpt->lock);
10579       return;
10580    }
10581    if ((myrpt->callmode == 2) || (myrpt->callmode == 3))
10582    {
10583       myrpt->mydtmf = c;
10584    }
10585    rpt_mutex_unlock(&myrpt->lock);
10586    if ((myrpt->dtmfidx < 0) && myrpt->p.propagate_phonedtmf)
10587       do_dtmf_phone(myrpt,NULL,c);
10588    return;
10589 }
10590 
10591 
10592 /* place an ID event in the telemetry queue */
10593 
10594 static void queue_id(struct rpt *myrpt)
10595 {
10596    if(myrpt->p.idtime){ /* ID time must be non-zero */
10597       myrpt->mustid = myrpt->tailid = 0;
10598       myrpt->idtimer = myrpt->p.idtime; /* Reset our ID timer */
10599       rpt_mutex_unlock(&myrpt->lock);
10600       rpt_telemetry(myrpt,ID,NULL);
10601       rpt_mutex_lock(&myrpt->lock);
10602    }
10603 }
10604 
10605 /* Scheduler */
10606 /* must be called locked */
10607 
10608 static void do_scheduler(struct rpt *myrpt)
10609 {
10610    int i,res;
10611 
10612 #ifdef   NEW_ASTERISK
10613    struct ast_tm tmnow;
10614 #else
10615    struct tm tmnow;
10616 #endif
10617    struct ast_variable *skedlist;
10618    char *strs[5],*vp,*val,value[100];
10619 
10620    memcpy(&myrpt->lasttv, &myrpt->curtv, sizeof(struct timeval));
10621    
10622    if( (res = gettimeofday(&myrpt->curtv, NULL)) < 0)
10623       ast_log(LOG_NOTICE, "Scheduler gettime of day returned: %s\n", strerror(res));
10624 
10625    /* Try to get close to a 1 second resolution */
10626    
10627    if(myrpt->lasttv.tv_sec == myrpt->curtv.tv_sec)
10628       return;
10629 
10630    rpt_localtime(&myrpt->curtv.tv_sec, &tmnow);
10631 
10632    /* If midnight, then reset all daily statistics */
10633    
10634    if((tmnow.tm_hour == 0)&&(tmnow.tm_min == 0)&&(tmnow.tm_sec == 0)){
10635       myrpt->dailykeyups = 0;
10636       myrpt->dailytxtime = 0;
10637       myrpt->dailykerchunks = 0;
10638       myrpt->dailyexecdcommands = 0;
10639    }
10640 
10641    if(tmnow.tm_sec != 0)
10642       return;
10643 
10644    /* Code below only executes once per minute */
10645 
10646 
10647    /* Don't schedule if remote */
10648 
10649         if (myrpt->remote)
10650                 return;
10651 
10652    /* Don't schedule if disabled */
10653 
10654         if(myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable){
10655       if(debug > 6)
10656          ast_log(LOG_NOTICE, "Scheduler disabled\n");
10657       return;
10658    }
10659 
10660    if(!myrpt->p.skedstanzaname){ /* No stanza means we do nothing */
10661       if(debug > 6)
10662          ast_log(LOG_NOTICE,"No stanza for scheduler in rpt.conf\n");
10663       return;
10664    }
10665 
10666     /* get pointer to linked list of scheduler entries */
10667     skedlist = ast_variable_browse(myrpt->cfg, myrpt->p.skedstanzaname);
10668 
10669    if(debug > 6){
10670       ast_log(LOG_NOTICE, "Time now: %02d:%02d %02d %02d %02d\n",
10671          tmnow.tm_hour,tmnow.tm_min,tmnow.tm_mday,tmnow.tm_mon + 1, tmnow.tm_wday); 
10672    }
10673    /* walk the list */
10674    for(; skedlist; skedlist = skedlist->next){
10675       if(debug > 6)
10676          ast_log(LOG_NOTICE, "Scheduler entry %s = %s being considered\n",skedlist->name, skedlist->value);
10677       strncpy(value,skedlist->value,99);
10678       value[99] = 0;
10679       /* point to the substrings for minute, hour, dom, month, and dow */
10680       for( i = 0, vp = value ; i < 5; i++){
10681          if(!*vp)
10682             break;
10683          while((*vp == ' ') || (*vp == 0x09)) /* get rid of any leading white space */
10684             vp++;
10685          strs[i] = vp; /* save pointer to beginning of substring */
10686          while((*vp != ' ') && (*vp != 0x09) && (*vp != 0)) /* skip over substring */
10687             vp++;
10688          if(*vp)
10689             *vp++ = 0; /* mark end of substring */
10690       }
10691       if(debug > 6)
10692          ast_log(LOG_NOTICE, "i = %d, min = %s, hour = %s, mday=%s, mon=%s, wday=%s\n",i,
10693             strs[0], strs[1], strs[2], strs[3], strs[4]); 
10694       if(i == 5){
10695          if((*strs[0] != '*')&&(atoi(strs[0]) != tmnow.tm_min))
10696             continue;
10697          if((*strs[1] != '*')&&(atoi(strs[1]) != tmnow.tm_hour))
10698             continue;
10699          if((*strs[2] != '*')&&(atoi(strs[2]) != tmnow.tm_mday))
10700             continue;
10701          if((*strs[3] != '*')&&(atoi(strs[3]) != tmnow.tm_mon + 1))
10702             continue;
10703          if(atoi(strs[4]) == 7)
10704             strs[4] = "0";
10705          if((*strs[4] != '*')&&(atoi(strs[4]) != tmnow.tm_wday))
10706             continue;
10707          if(debug)
10708             ast_log(LOG_NOTICE, "Executing scheduler entry %s = %s\n", skedlist->name, skedlist->value);
10709          if(atoi(skedlist->name) == 0)
10710             return; /* Zero is reserved for the startup macro */
10711          val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.macro, skedlist->name);
10712          if (!val){
10713             ast_log(LOG_WARNING,"Scheduler could not find macro %s\n",skedlist->name);
10714             return; /* Macro not found */
10715          }
10716          if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(val)){
10717             ast_log(LOG_WARNING, "Scheduler could not execute macro %s: Macro buffer full\n",
10718                skedlist->name);
10719             return; /* Macro buffer full */
10720          }
10721          myrpt->macrotimer = MACROTIME;
10722          strncat(myrpt->macrobuf,val,MAXMACRO - 1);
10723       }
10724       else{
10725          ast_log(LOG_WARNING,"Malformed scheduler entry in rpt.conf: %s = %s\n",
10726             skedlist->name, skedlist->value);
10727       }
10728    }
10729 
10730 }
10731 
10732 /* single thread with one file (request) to dial */
10733 static void *rpt(void *this)
10734 {
10735 struct   rpt *myrpt = (struct rpt *)this;
10736 char *tele,*idtalkover,c,myfirst,*p;
10737 int ms = MSWAIT,i,lasttx=0,val,remrx=0,identqueued,othertelemqueued;
10738 int tailmessagequeued,ctqueued,dtmfed,lastmyrx,localmsgqueued;
10739 struct ast_channel *who;
10740 struct dahdi_confinfo ci;  /* conference info */
10741 time_t   t;
10742 struct rpt_link *l,*m;
10743 struct rpt_tele *telem;
10744 char tmpstr[300],lstr[MAXLINKLIST];
10745 
10746 
10747    if (myrpt->p.archivedir) mkdir(myrpt->p.archivedir,0600);
10748    sprintf(tmpstr,"%s/%s",myrpt->p.archivedir,myrpt->name);
10749    mkdir(tmpstr,0600);
10750    rpt_mutex_lock(&myrpt->lock);
10751 
10752    telem = myrpt->tele.next;
10753    while(telem != &myrpt->tele)
10754    {
10755       ast_softhangup(telem->chan,AST_SOFTHANGUP_DEV);
10756       telem = telem->next;
10757    }
10758    rpt_mutex_unlock(&myrpt->lock);
10759    /* find our index, and load the vars initially */
10760    for(i = 0; i < nrpts; i++)
10761    {
10762       if (&rpt_vars[i] == myrpt)
10763       {
10764          load_rpt_vars(i,0);
10765          break;
10766       }
10767    }
10768 
10769    rpt_mutex_lock(&myrpt->lock);
10770    while(myrpt->xlink)
10771    {
10772       myrpt->xlink = 3;
10773       rpt_mutex_unlock(&myrpt->lock);
10774       usleep(100000);
10775       rpt_mutex_lock(&myrpt->lock);
10776    }
10777 #ifdef HAVE_IOPERM
10778    if ((!strcmp(myrpt->remoterig, remote_rig_rbi)) &&
10779      (ioperm(myrpt->p.iobase,1,1) == -1))
10780    {
10781       rpt_mutex_unlock(&myrpt->lock);
10782       ast_log(LOG_WARNING, "Cant get io permission on IO port %x hex\n",myrpt->p.iobase);
10783       myrpt->rpt_thread = AST_PTHREADT_STOP;
10784       pthread_exit(NULL);
10785    }
10786 #endif
10787    strncpy(tmpstr,myrpt->rxchanname,sizeof(tmpstr) - 1);
10788    tele = strchr(tmpstr,'/');
10789    if (!tele)
10790    {
10791       fprintf(stderr,"rpt:Rxchannel Dial number (%s) must be in format tech/number\n",myrpt->rxchanname);
10792       rpt_mutex_unlock(&myrpt->lock);
10793       myrpt->rpt_thread = AST_PTHREADT_STOP;
10794       pthread_exit(NULL);
10795    }
10796    *tele++ = 0;
10797    myrpt->rxchannel = ast_request(tmpstr, AST_FORMAT_SLINEAR, NULL, tele, NULL);
10798    myrpt->dahdirxchannel = NULL;
10799    if (!strcasecmp(tmpstr,"DAHDI"))
10800       myrpt->dahdirxchannel = myrpt->rxchannel;
10801    if (myrpt->rxchannel)
10802    {
10803       if (myrpt->rxchannel->_state == AST_STATE_BUSY)
10804       {
10805          fprintf(stderr,"rpt:Sorry unable to obtain Rx channel\n");
10806          rpt_mutex_unlock(&myrpt->lock);
10807          ast_hangup(myrpt->rxchannel);
10808          myrpt->rpt_thread = AST_PTHREADT_STOP;
10809          pthread_exit(NULL);
10810       }
10811       ast_set_read_format(myrpt->rxchannel,AST_FORMAT_SLINEAR);
10812       ast_set_write_format(myrpt->rxchannel,AST_FORMAT_SLINEAR);
10813 #ifdef   AST_CDR_FLAG_POST_DISABLED
10814       if (myrpt->rxchannel->cdr)
10815          ast_set_flag(myrpt->rxchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10816 #endif
10817 #ifndef  NEW_ASTERISK
10818       myrpt->rxchannel->whentohangup = 0;
10819 #endif
10820       myrpt->rxchannel->appl = "Apprpt";
10821       myrpt->rxchannel->data = "(Repeater Rx)";
10822       if (option_verbose > 2)
10823          ast_verbose(VERBOSE_PREFIX_3 "rpt (Rx) initiating call to %s/%s on %s\n",
10824             tmpstr,tele,myrpt->rxchannel->name);
10825       ast_call(myrpt->rxchannel,tele,999);
10826       if (myrpt->rxchannel->_state != AST_STATE_UP)
10827       {
10828          rpt_mutex_unlock(&myrpt->lock);
10829          ast_hangup(myrpt->rxchannel);
10830          myrpt->rpt_thread = AST_PTHREADT_STOP;
10831          pthread_exit(NULL);
10832       }
10833    }
10834    else
10835    {
10836       fprintf(stderr,"rpt:Sorry unable to obtain Rx channel\n");
10837       rpt_mutex_unlock(&myrpt->lock);
10838       myrpt->rpt_thread = AST_PTHREADT_STOP;
10839       pthread_exit(NULL);
10840    }
10841    myrpt->dahditxchannel = NULL;
10842    if (myrpt->txchanname)
10843    {
10844       strncpy(tmpstr,myrpt->txchanname,sizeof(tmpstr) - 1);
10845       tele = strchr(tmpstr,'/');
10846       if (!tele)
10847       {
10848          fprintf(stderr,"rpt:Txchannel Dial number (%s) must be in format tech/number\n",myrpt->txchanname);
10849          rpt_mutex_unlock(&myrpt->lock);
10850          ast_hangup(myrpt->rxchannel);
10851          myrpt->rpt_thread = AST_PTHREADT_STOP;
10852          pthread_exit(NULL);
10853       }
10854       *tele++ = 0;
10855       myrpt->txchannel = ast_request(tmpstr, AST_FORMAT_SLINEAR, NULL, tele, NULL);
10856       if (!strcasecmp(tmpstr,"DAHDI"))
10857          myrpt->dahditxchannel = myrpt->txchannel;
10858       if (myrpt->txchannel)
10859       {
10860          if (myrpt->txchannel->_state == AST_STATE_BUSY)
10861          {
10862             fprintf(stderr,"rpt:Sorry unable to obtain Tx channel\n");
10863             rpt_mutex_unlock(&myrpt->lock);
10864             ast_hangup(myrpt->txchannel);
10865             ast_hangup(myrpt->rxchannel);
10866             myrpt->rpt_thread = AST_PTHREADT_STOP;
10867             pthread_exit(NULL);
10868          }        
10869          ast_set_read_format(myrpt->txchannel,AST_FORMAT_SLINEAR);
10870          ast_set_write_format(myrpt->txchannel,AST_FORMAT_SLINEAR);
10871 #ifdef   AST_CDR_FLAG_POST_DISABLED
10872          if (myrpt->txchannel->cdr)
10873             ast_set_flag(myrpt->txchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10874 #endif
10875 #ifndef  NEW_ASTERISK
10876          myrpt->txchannel->whentohangup = 0;
10877 #endif
10878          myrpt->txchannel->appl = "Apprpt";
10879          myrpt->txchannel->data = "(Repeater Tx)";
10880          if (option_verbose > 2)
10881             ast_verbose(VERBOSE_PREFIX_3 "rpt (Tx) initiating call to %s/%s on %s\n",
10882                tmpstr,tele,myrpt->txchannel->name);
10883          ast_call(myrpt->txchannel,tele,999);
10884          if (myrpt->rxchannel->_state != AST_STATE_UP)
10885          {
10886             rpt_mutex_unlock(&myrpt->lock);
10887             ast_hangup(myrpt->rxchannel);
10888             ast_hangup(myrpt->txchannel);
10889             myrpt->rpt_thread = AST_PTHREADT_STOP;
10890             pthread_exit(NULL);
10891          }
10892       }
10893       else
10894       {
10895          fprintf(stderr,"rpt:Sorry unable to obtain Tx channel\n");
10896          rpt_mutex_unlock(&myrpt->lock);
10897          ast_hangup(myrpt->rxchannel);
10898          myrpt->rpt_thread = AST_PTHREADT_STOP;
10899          pthread_exit(NULL);
10900       }
10901    }
10902    else
10903    {
10904       myrpt->txchannel = myrpt->rxchannel;
10905       if (!strncasecmp(myrpt->rxchanname,"DAHDI",3))
10906          myrpt->dahditxchannel = myrpt->txchannel;
10907    }
10908    ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_KEY);
10909    ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_UNKEY);
10910    /* allocate a pseudo-channel thru asterisk */
10911    myrpt->pchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
10912    if (!myrpt->pchannel)
10913    {
10914       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
10915       rpt_mutex_unlock(&myrpt->lock);
10916       if (myrpt->txchannel != myrpt->rxchannel) 
10917          ast_hangup(myrpt->txchannel);
10918       ast_hangup(myrpt->rxchannel);
10919       myrpt->rpt_thread = AST_PTHREADT_STOP;
10920       pthread_exit(NULL);
10921    }
10922 #ifdef   AST_CDR_FLAG_POST_DISABLED
10923    if (myrpt->pchannel->cdr)
10924       ast_set_flag(myrpt->pchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10925 #endif
10926    if (!myrpt->dahdirxchannel) myrpt->dahdirxchannel = myrpt->pchannel;
10927    if (!myrpt->dahditxchannel)
10928    {
10929       /* allocate a pseudo-channel thru asterisk */
10930       myrpt->dahditxchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
10931       if (!myrpt->dahditxchannel)
10932       {
10933          fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
10934          rpt_mutex_unlock(&myrpt->lock);
10935          if (myrpt->txchannel != myrpt->rxchannel) 
10936             ast_hangup(myrpt->txchannel);
10937          ast_hangup(myrpt->rxchannel);
10938          myrpt->rpt_thread = AST_PTHREADT_STOP;
10939          pthread_exit(NULL);
10940       }
10941       ast_set_read_format(myrpt->dahditxchannel,AST_FORMAT_SLINEAR);
10942       ast_set_write_format(myrpt->dahditxchannel,AST_FORMAT_SLINEAR);
10943 #ifdef   AST_CDR_FLAG_POST_DISABLED
10944       if (myrpt->dahditxchannel->cdr)
10945          ast_set_flag(myrpt->dahditxchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10946 #endif
10947    }
10948    /* allocate a pseudo-channel thru asterisk */
10949    myrpt->monchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
10950    if (!myrpt->monchannel)
10951    {
10952       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
10953       rpt_mutex_unlock(&myrpt->lock);
10954       if (myrpt->txchannel != myrpt->rxchannel) 
10955          ast_hangup(myrpt->txchannel);
10956       ast_hangup(myrpt->rxchannel);
10957       myrpt->rpt_thread = AST_PTHREADT_STOP;
10958       pthread_exit(NULL);
10959    }
10960    ast_set_read_format(myrpt->monchannel,AST_FORMAT_SLINEAR);
10961    ast_set_write_format(myrpt->monchannel,AST_FORMAT_SLINEAR);
10962 #ifdef   AST_CDR_FLAG_POST_DISABLED
10963    if (myrpt->monchannel->cdr)
10964       ast_set_flag(myrpt->monchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10965 #endif
10966    /* make a conference for the tx */
10967    ci.chan = 0;
10968    ci.confno = -1; /* make a new conf */
10969    ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_LISTENER;
10970    /* first put the channel on the conference in proper mode */
10971    if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
10972    {
10973       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
10974       rpt_mutex_unlock(&myrpt->lock);
10975       ast_hangup(myrpt->pchannel);
10976       ast_hangup(myrpt->monchannel);
10977       if (myrpt->txchannel != myrpt->rxchannel) 
10978          ast_hangup(myrpt->txchannel);
10979       ast_hangup(myrpt->rxchannel);
10980       myrpt->rpt_thread = AST_PTHREADT_STOP;
10981       pthread_exit(NULL);
10982    }
10983    /* save tx conference number */
10984    myrpt->txconf = ci.confno;
10985    /* make a conference for the pseudo */
10986    ci.chan = 0;
10987    ci.confno = -1; /* make a new conf */
10988    ci.confmode = ((myrpt->p.duplex == 2) || (myrpt->p.duplex == 4)) ? DAHDI_CONF_CONFANNMON :
10989       (DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER);
10990    /* first put the channel on the conference in announce mode */
10991    if (ioctl(myrpt->pchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
10992    {
10993       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
10994       rpt_mutex_unlock(&myrpt->lock);
10995       ast_hangup(myrpt->pchannel);
10996       ast_hangup(myrpt->monchannel);
10997       if (myrpt->txchannel != myrpt->rxchannel) 
10998          ast_hangup(myrpt->txchannel);
10999       ast_hangup(myrpt->rxchannel);
11000       myrpt->rpt_thread = AST_PTHREADT_STOP;
11001       pthread_exit(NULL);
11002    }
11003    /* save pseudo channel conference number */
11004    myrpt->conf = ci.confno;
11005    /* make a conference for the pseudo */
11006    ci.chan = 0;
11007    if ((strstr(myrpt->txchannel->name,"pseudo") == NULL) &&
11008       (myrpt->dahditxchannel == myrpt->txchannel))
11009    {
11010       /* get tx channel's port number */
11011       if (ioctl(myrpt->txchannel->fds[0],DAHDI_CHANNO,&ci.confno) == -1)
11012       {
11013          ast_log(LOG_WARNING, "Unable to set tx channel's chan number\n");
11014          rpt_mutex_unlock(&myrpt->lock);
11015          ast_hangup(myrpt->pchannel);
11016          ast_hangup(myrpt->monchannel);
11017          if (myrpt->txchannel != myrpt->rxchannel) 
11018             ast_hangup(myrpt->txchannel);
11019          ast_hangup(myrpt->rxchannel);
11020          myrpt->rpt_thread = AST_PTHREADT_STOP;
11021          pthread_exit(NULL);
11022       }
11023       ci.confmode = DAHDI_CONF_MONITORTX;
11024    }
11025    else
11026    {
11027       ci.confno = myrpt->txconf;
11028       ci.confmode = DAHDI_CONF_CONFANNMON;
11029    }
11030    /* first put the channel on the conference in announce mode */
11031    if (ioctl(myrpt->monchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
11032    {
11033       ast_log(LOG_WARNING, "Unable to set conference mode for monitor\n");
11034       rpt_mutex_unlock(&myrpt->lock);
11035       ast_hangup(myrpt->pchannel);
11036       ast_hangup(myrpt->monchannel);
11037       if (myrpt->txchannel != myrpt->rxchannel) 
11038          ast_hangup(myrpt->txchannel);
11039       ast_hangup(myrpt->rxchannel);
11040       myrpt->rpt_thread = AST_PTHREADT_STOP;
11041       pthread_exit(NULL);
11042    }
11043    /* allocate a pseudo-channel thru asterisk */
11044    myrpt->parrotchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
11045    if (!myrpt->parrotchannel)
11046    {
11047       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
11048       rpt_mutex_unlock(&myrpt->lock);
11049       if (myrpt->txchannel != myrpt->rxchannel) 
11050          ast_hangup(myrpt->txchannel);
11051       ast_hangup(myrpt->rxchannel);
11052       myrpt->rpt_thread = AST_PTHREADT_STOP;
11053       pthread_exit(NULL);
11054    }
11055    ast_set_read_format(myrpt->parrotchannel,AST_FORMAT_SLINEAR);
11056    ast_set_write_format(myrpt->parrotchannel,AST_FORMAT_SLINEAR);
11057 #ifdef   AST_CDR_FLAG_POST_DISABLED
11058    if (myrpt->parrotchannel->cdr)
11059       ast_set_flag(myrpt->parrotchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
11060 #endif
11061    /* allocate a pseudo-channel thru asterisk */
11062    myrpt->voxchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
11063    if (!myrpt->voxchannel)
11064    {
11065       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
11066       rpt_mutex_unlock(&myrpt->lock);
11067       if (myrpt->txchannel != myrpt->rxchannel) 
11068          ast_hangup(myrpt->txchannel);
11069       ast_hangup(myrpt->rxchannel);
11070       myrpt->rpt_thread = AST_PTHREADT_STOP;
11071       pthread_exit(NULL);
11072    }
11073    ast_set_read_format(myrpt->voxchannel,AST_FORMAT_SLINEAR);
11074    ast_set_write_format(myrpt->voxchannel,AST_FORMAT_SLINEAR);
11075 #ifdef   AST_CDR_FLAG_POST_DISABLED
11076    if (myrpt->voxchannel->cdr)
11077       ast_set_flag(myrpt->voxchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
11078 #endif
11079    /* allocate a pseudo-channel thru asterisk */
11080    myrpt->txpchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
11081    if (!myrpt->txpchannel)
11082    {
11083       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
11084       rpt_mutex_unlock(&myrpt->lock);
11085       ast_hangup(myrpt->pchannel);
11086       ast_hangup(myrpt->monchannel);
11087       if (myrpt->txchannel != myrpt->rxchannel) 
11088          ast_hangup(myrpt->txchannel);
11089       ast_hangup(myrpt->rxchannel);
11090       myrpt->rpt_thread = AST_PTHREADT_STOP;
11091       pthread_exit(NULL);
11092    }
11093 #ifdef   AST_CDR_FLAG_POST_DISABLED
11094    if (myrpt->txpchannel->cdr)
11095       ast_set_flag(myrpt->txpchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
11096 #endif
11097    /* make a conference for the tx */
11098    ci.chan = 0;
11099    ci.confno = myrpt->txconf;
11100    ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER ;
11101    /* first put the channel on the conference in proper mode */
11102    if (ioctl(myrpt->txpchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
11103    {
11104       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
11105       rpt_mutex_unlock(&myrpt->lock);
11106       ast_hangup(myrpt->txpchannel);
11107       ast_hangup(myrpt->monchannel);
11108       if (myrpt->txchannel != myrpt->rxchannel) 
11109          ast_hangup(myrpt->txchannel);
11110       ast_hangup(myrpt->rxchannel);
11111       myrpt->rpt_thread = AST_PTHREADT_STOP;
11112       pthread_exit(NULL);
11113    }
11114    /* if serial io port, open it */
11115    myrpt->iofd = -1;
11116    if (myrpt->p.ioport && ((myrpt->iofd = openserial(myrpt,myrpt->p.ioport)) == -1))
11117    {
11118       ast_log(LOG_ERROR, "Unable to open %s\n",myrpt->p.ioport);
11119       rpt_mutex_unlock(&myrpt->lock);
11120       ast_hangup(myrpt->pchannel);
11121       if (myrpt->txchannel != myrpt->rxchannel) 
11122          ast_hangup(myrpt->txchannel);
11123       ast_hangup(myrpt->rxchannel);
11124       pthread_exit(NULL);
11125    }
11126    /* Now, the idea here is to copy from the physical rx channel buffer
11127       into the pseudo tx buffer, and from the pseudo rx buffer into the 
11128       tx channel buffer */
11129    myrpt->links.next = &myrpt->links;
11130    myrpt->links.prev = &myrpt->links;
11131    myrpt->tailtimer = 0;
11132    myrpt->totimer = 0;
11133    myrpt->tmsgtimer = myrpt->p.tailmessagetime;
11134    myrpt->idtimer = myrpt->p.politeid;
11135    myrpt->mustid = myrpt->tailid = 0;
11136    myrpt->callmode = 0;
11137    myrpt->tounkeyed = 0;
11138    myrpt->tonotify = 0;
11139    myrpt->retxtimer = 0;
11140    myrpt->rerxtimer = 0;
11141    myrpt->skedtimer = 0;
11142    myrpt->tailevent = 0;
11143    lasttx = 0;
11144    myrpt->keyed = 0;
11145    myrpt->txkeyed = 0;
11146    time(&myrpt->lastkeyedtime);
11147    myrpt->lastkeyedtime -= RPT_LOCKOUT_SECS;
11148    time(&myrpt->lasttxkeyedtime);
11149    myrpt->lasttxkeyedtime -= RPT_LOCKOUT_SECS;
11150    idtalkover = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, "idtalkover");
11151    myrpt->dtmfidx = -1;
11152    myrpt->dtmfbuf[0] = 0;
11153    myrpt->rem_dtmfidx = -1;
11154    myrpt->rem_dtmfbuf[0] = 0;
11155    myrpt->dtmf_time = 0;
11156    myrpt->rem_dtmf_time = 0;
11157    myrpt->inpadtest = 0;
11158    myrpt->disgorgetime = 0;
11159    myrpt->lastnodewhichkeyedusup[0] = '\0';
11160    myrpt->dailytxtime = 0;
11161    myrpt->totaltxtime = 0;
11162    myrpt->dailykeyups = 0;
11163    myrpt->totalkeyups = 0;
11164    myrpt->dailykerchunks = 0;
11165    myrpt->totalkerchunks = 0;
11166    myrpt->dailyexecdcommands = 0;
11167    myrpt->totalexecdcommands = 0;
11168    myrpt->timeouts = 0;
11169    myrpt->exten[0] = '\0';
11170    myrpt->lastdtmfcommand[0] = '\0';
11171    voxinit_rpt(myrpt,1);
11172    myrpt->wasvox = 0;
11173    if (myrpt->p.startupmacro)
11174    {
11175       snprintf(myrpt->macrobuf,MAXMACRO - 1,"PPPP%s",myrpt->p.startupmacro);
11176    }
11177    rpt_mutex_unlock(&myrpt->lock);
11178    val = 1;
11179    ast_channel_setoption(myrpt->rxchannel,AST_OPTION_RELAXDTMF,&val,sizeof(char),0);
11180    val = 1;
11181    ast_channel_setoption(myrpt->rxchannel,AST_OPTION_TONE_VERIFY,&val,sizeof(char),0);
11182    if (myrpt->p.archivedir) donodelog(myrpt,"STARTUP");
11183    dtmfed = 0;
11184    if (myrpt->remoterig && !ISRIG_RTX(myrpt->remoterig)) setrem(myrpt);
11185    lastmyrx = 0;
11186    myfirst = 0;
11187    while (ms >= 0)
11188    {
11189       struct ast_frame *f,*f1,*f2;
11190       struct ast_channel *cs[300],*cs1[300];
11191       int totx=0,elap=0,n,x,toexit=0;
11192 
11193       /* DEBUG Dump */
11194       if((myrpt->disgorgetime) && (time(NULL) >= myrpt->disgorgetime)){
11195          struct rpt_link *dl;
11196          struct rpt_tele *dt;
11197 
11198          myrpt->disgorgetime = 0;
11199          ast_log(LOG_NOTICE,"********** Variable Dump Start (app_rpt) **********\n");
11200          ast_log(LOG_NOTICE,"totx = %d\n",totx);
11201          ast_log(LOG_NOTICE,"remrx = %d\n",remrx);
11202          ast_log(LOG_NOTICE,"lasttx = %d\n",lasttx);
11203          ast_log(LOG_NOTICE,"elap = %d\n",elap);
11204          ast_log(LOG_NOTICE,"toexit = %d\n",toexit);
11205 
11206          ast_log(LOG_NOTICE,"myrpt->keyed = %d\n",myrpt->keyed);
11207          ast_log(LOG_NOTICE,"myrpt->localtx = %d\n",myrpt->localtx);
11208          ast_log(LOG_NOTICE,"myrpt->callmode = %d\n",myrpt->callmode);
11209          ast_log(LOG_NOTICE,"myrpt->mustid = %d\n",myrpt->mustid);
11210          ast_log(LOG_NOTICE,"myrpt->tounkeyed = %d\n",myrpt->tounkeyed);
11211          ast_log(LOG_NOTICE,"myrpt->tonotify = %d\n",myrpt->tonotify);
11212          ast_log(LOG_NOTICE,"myrpt->retxtimer = %ld\n",myrpt->retxtimer);
11213          ast_log(LOG_NOTICE,"myrpt->totimer = %d\n",myrpt->totimer);
11214          ast_log(LOG_NOTICE,"myrpt->tailtimer = %d\n",myrpt->tailtimer);
11215          ast_log(LOG_NOTICE,"myrpt->tailevent = %d\n",myrpt->tailevent);
11216 
11217          dl = myrpt->links.next;
11218                   while(dl != &myrpt->links){
11219             ast_log(LOG_NOTICE,"*** Link Name: %s ***\n",dl->name);
11220             ast_log(LOG_NOTICE,"        link->lasttx %d\n",dl->lasttx);
11221             ast_log(LOG_NOTICE,"        link->lastrx %d\n",dl->lastrx);
11222             ast_log(LOG_NOTICE,"        link->connected %d\n",dl->connected);
11223             ast_log(LOG_NOTICE,"        link->hasconnected %d\n",dl->hasconnected);
11224             ast_log(LOG_NOTICE,"        link->outbound %d\n",dl->outbound);
11225             ast_log(LOG_NOTICE,"        link->disced %d\n",dl->disced);
11226             ast_log(LOG_NOTICE,"        link->killme %d\n",dl->killme);
11227             ast_log(LOG_NOTICE,"        link->disctime %ld\n",dl->disctime);
11228             ast_log(LOG_NOTICE,"        link->retrytimer %ld\n",dl->retrytimer);
11229             ast_log(LOG_NOTICE,"        link->retries = %d\n",dl->retries);
11230             ast_log(LOG_NOTICE,"        link->reconnects = %d\n",dl->reconnects);
11231             ast_log(LOG_NOTICE,"        link->newkey = %d\n",dl->newkey);
11232                            dl = dl->next;
11233                   }
11234                                                                                                                                
11235          dt = myrpt->tele.next;
11236          if(dt != &myrpt->tele)
11237             ast_log(LOG_NOTICE,"*** Telemetry Queue ***\n");
11238                   while(dt != &myrpt->tele){
11239             ast_log(LOG_NOTICE,"        Telemetry mode: %d\n",dt->mode);
11240                            dt = dt->next;
11241                   }
11242          ast_log(LOG_NOTICE,"******* Variable Dump End (app_rpt) *******\n");
11243 
11244       }  
11245 
11246 
11247       if (myrpt->reload)
11248       {
11249          struct rpt_tele *inner_telem;
11250 
11251          rpt_mutex_lock(&myrpt->lock);
11252          inner_telem = myrpt->tele.next;
11253          while(inner_telem != &myrpt->tele)
11254          {
11255             ast_softhangup(inner_telem->chan,AST_SOFTHANGUP_DEV);
11256             inner_telem = inner_telem->next;
11257          }
11258          myrpt->reload = 0;
11259          rpt_mutex_unlock(&myrpt->lock);
11260          usleep(10000);
11261          /* find our index, and load the vars */
11262          for(i = 0; i < nrpts; i++)
11263          {
11264             if (&rpt_vars[i] == myrpt)
11265             {
11266                load_rpt_vars(i,0);
11267                break;
11268             }
11269          }
11270       }
11271 
11272       rpt_mutex_lock(&myrpt->lock);
11273       if (ast_check_hangup(myrpt->rxchannel)) break;
11274       if (ast_check_hangup(myrpt->txchannel)) break;
11275       if (ast_check_hangup(myrpt->pchannel)) break;
11276       if (ast_check_hangup(myrpt->monchannel)) break;
11277       if (myrpt->parrotchannel && 
11278          ast_check_hangup(myrpt->parrotchannel)) break;
11279       if (myrpt->voxchannel && 
11280          ast_check_hangup(myrpt->voxchannel)) break;
11281       if (ast_check_hangup(myrpt->txpchannel)) break;
11282       if (myrpt->dahditxchannel && ast_check_hangup(myrpt->dahditxchannel)) break;
11283 
11284       /* Set local tx with keyed */
11285       myrpt->localtx = myrpt->keyed;
11286       /* If someone's connected, and they're transmitting from their end to us, set remrx true */
11287       l = myrpt->links.next;
11288       remrx = 0;
11289       while(l != &myrpt->links)
11290       {
11291          if (l->lastrx){
11292             remrx = 1;
11293             if(l->name[0] != '0') /* Ignore '0' nodes */
11294                strcpy(myrpt->lastnodewhichkeyedusup, l->name); /* Note the node which is doing the key up */
11295          }
11296          l = l->next;
11297       }
11298       /* Create a "must_id" flag for the cleanup ID */      
11299       if(myrpt->p.idtime) /* ID time must be non-zero */
11300          myrpt->mustid |= (myrpt->idtimer) && (myrpt->keyed || remrx) ;
11301       /* Build a fresh totx from myrpt->keyed and autopatch activated */
11302       /* If full duplex, add local tx to totx */
11303       if (myrpt->p.duplex > 1) 
11304       {
11305          totx = myrpt->callmode;
11306          totx = totx || myrpt->localtx;
11307       }
11308       else
11309       {
11310          int myrx = myrpt->localtx || remrx || (!myrpt->callmode);
11311 
11312          if (lastmyrx != myrx)
11313          {
11314             voxinit_rpt(myrpt,!myrx);
11315             lastmyrx = myrx;
11316          }
11317          totx = 0;
11318          if (myrpt->callmode && (myrpt->voxtotimer <= 0))
11319          {
11320             if (myrpt->voxtostate)
11321             {
11322                myrpt->voxtotimer = myrpt->p.voxtimeout_ms;
11323                myrpt->voxtostate = 0;
11324             }           
11325             else
11326             {
11327                myrpt->voxtotimer = myrpt->p.voxrecover_ms;
11328                myrpt->voxtostate = 1;
11329             }
11330          }
11331          if (!myrpt->voxtostate)
11332             totx = myrpt->callmode && myrpt->wasvox;
11333       }
11334       /* Traverse the telemetry list to see what's queued */
11335       identqueued = 0;
11336       localmsgqueued = 0;
11337       othertelemqueued = 0;
11338       tailmessagequeued = 0;
11339       ctqueued = 0;
11340       telem = myrpt->tele.next;
11341       while(telem != &myrpt->tele)
11342       {
11343          if((telem->mode == ID) || (telem->mode == IDTALKOVER)){
11344             identqueued = 1; /* Identification telemetry */
11345          }
11346          else if(telem->mode == TAILMSG)
11347          {
11348             tailmessagequeued = 1; /* Tail message telemetry */
11349          }
11350          else if(telem->mode == STATS_TIME_LOCAL) 
11351          {
11352             localmsgqueued = 1; /* Local message */
11353          }
11354          else
11355          {
11356             if ((telem->mode != UNKEY) && (telem->mode != LINKUNKEY))
11357                othertelemqueued = 1;  /* Other telemetry */
11358             else
11359                ctqueued = 1; /* Courtesy tone telemetry */
11360          }
11361          telem = telem->next;
11362       }
11363    
11364       /* Add in any "other" telemetry, unless specified otherwise */
11365       if (!myrpt->p.notelemtx) totx = totx || othertelemqueued;
11366       /* Update external (to links) transmitter PTT state with everything but */
11367       /* ID, CT, local messages, and tailmessage telemetry */
11368       myrpt->exttx = totx;
11369       totx = totx || myrpt->dtmf_local_timer;
11370       /* If half or 3/4 duplex, add localtx to external link tx */
11371       if (myrpt->p.duplex < 2) myrpt->exttx = myrpt->exttx || myrpt->localtx;
11372       /* Add in ID telemetry to local transmitter */
11373       totx = totx || remrx;
11374       /* If 3/4 or full duplex, add in ident, CT telemetry, and local messages */
11375       if (myrpt->p.duplex > 0)
11376          totx = totx || identqueued || ctqueued || localmsgqueued;
11377       /* If full duplex, add local dtmf stuff active */
11378       if (myrpt->p.duplex > 1) 
11379       {
11380          totx = totx || (myrpt->dtmfidx > -1) ||
11381             myrpt->cmdnode[0];
11382       }
11383       /* add in parrot stuff */
11384       totx = totx || (myrpt->parrotstate > 1);
11385       /* Reset time out timer variables if there is no activity */
11386       if (!totx) 
11387       {
11388          myrpt->totimer = myrpt->p.totime;
11389          myrpt->tounkeyed = 0;
11390          myrpt->tonotify = 0;
11391       }
11392       else{
11393          myrpt->tailtimer = myrpt->p.s[myrpt->p.sysstate_cur].alternatetail ?
11394             myrpt->p.althangtime : /* Initialize tail timer */
11395             myrpt->p.hangtime;
11396       }
11397       /* Disable the local transmitter if we are timed out */
11398       totx = totx && myrpt->totimer;
11399       /* if timed-out and not said already, say it */
11400       if ((!myrpt->totimer) && (!myrpt->tonotify))
11401       {
11402          myrpt->tonotify = 1;
11403          myrpt->timeouts++;
11404          rpt_mutex_unlock(&myrpt->lock);
11405          rpt_telemetry(myrpt,TIMEOUT,NULL);
11406          rpt_mutex_lock(&myrpt->lock);
11407       }
11408 
11409       /* If unkey and re-key, reset time out timer */
11410       if ((!totx) && (!myrpt->totimer) && (!myrpt->tounkeyed) && (!myrpt->keyed))
11411       {
11412          myrpt->tounkeyed = 1;
11413       }
11414       if ((!totx) && (!myrpt->totimer) && myrpt->tounkeyed && myrpt->keyed)
11415       {
11416          myrpt->totimer = myrpt->p.totime;
11417          myrpt->tounkeyed = 0;
11418          myrpt->tonotify = 0;
11419          rpt_mutex_unlock(&myrpt->lock);
11420          continue;
11421       }
11422       /* if timed-out and in circuit busy after call */
11423       if ((!totx) && (!myrpt->totimer) && (myrpt->callmode == 4))
11424       {
11425           if(debug)
11426             ast_log(LOG_NOTICE, "timed-out and in circuit busy after call\n");
11427          myrpt->callmode = 0;
11428          myrpt->macropatch=0;
11429          channel_revert(myrpt);
11430       }
11431       /* get rid of tail if timed out */
11432       if (!myrpt->totimer) myrpt->tailtimer = 0;
11433       /* if not timed-out, add in tail */
11434       if (myrpt->totimer) totx = totx || myrpt->tailtimer;
11435       /* If user or links key up or are keyed up over standard ID, switch to talkover ID, if one is defined */
11436       /* If tail message, kill the message if someone keys up over it */ 
11437       if ((myrpt->keyed || remrx) && ((identqueued && idtalkover) || (tailmessagequeued))) {
11438          int hasid = 0,hastalkover = 0;
11439 
11440          telem = myrpt->tele.next;
11441          while(telem != &myrpt->tele){
11442             if(telem->mode == ID){
11443                if (telem->chan) ast_softhangup(telem->chan, AST_SOFTHANGUP_DEV); /* Whoosh! */
11444                hasid = 1;
11445             }
11446             if(telem->mode == TAILMSG){
11447                                         if (telem->chan) ast_softhangup(telem->chan, AST_SOFTHANGUP_DEV); /* Whoosh! */
11448                                 }
11449             if (telem->mode == IDTALKOVER) hastalkover = 1;
11450             telem = telem->next;
11451          }
11452          rpt_mutex_unlock(&myrpt->lock);
11453          if (hasid && (!hastalkover)) rpt_telemetry(myrpt, IDTALKOVER, NULL); /* Start Talkover ID */
11454          rpt_mutex_lock(&myrpt->lock);
11455       }
11456       /* Try to be polite */
11457       /* If the repeater has been inactive for longer than the ID time, do an initial ID in the tail*/
11458       /* If within 30 seconds of the time to ID, try do it in the tail */
11459       /* else if at ID time limit, do it right over the top of them */
11460       /* Lastly, if the repeater has been keyed, and the ID timer is expired, do a clean up ID */
11461       if(myrpt->mustid && (!myrpt->idtimer))
11462          queue_id(myrpt);
11463 
11464       if ((myrpt->p.idtime && totx && (!myrpt->exttx) &&
11465           (myrpt->idtimer <= myrpt->p.politeid) && myrpt->tailtimer)) /* ID time must be non-zero */ 
11466          {
11467             myrpt->tailid = 1;
11468          }
11469 
11470       /* If tail timer expires, then check for tail messages */
11471 
11472       if(myrpt->tailevent){
11473          myrpt->tailevent = 0;
11474          if(myrpt->tailid){
11475             totx = 1;
11476             queue_id(myrpt);
11477          }
11478          else if ((myrpt->p.tailmessages[0]) &&
11479             (myrpt->p.tailmessagetime) && (myrpt->tmsgtimer == 0)){
11480                totx = 1;
11481                myrpt->tmsgtimer = myrpt->p.tailmessagetime; 
11482                rpt_mutex_unlock(&myrpt->lock);
11483                rpt_telemetry(myrpt, TAILMSG, NULL);
11484                rpt_mutex_lock(&myrpt->lock);
11485          }  
11486       }
11487 
11488       /* Main TX control */
11489 
11490       /* let telemetry transmit anyway (regardless of timeout) */
11491       if (myrpt->p.duplex > 0) totx = totx || (myrpt->tele.next != &myrpt->tele);
11492       totx = totx && !myrpt->p.s[myrpt->p.sysstate_cur].txdisable;
11493       myrpt->txrealkeyed = totx;
11494       totx = totx || (!AST_LIST_EMPTY(&myrpt->txq));
11495       if (totx && (!lasttx))
11496       {
11497          char mydate[100],myfname[100];
11498          time_t myt;
11499 
11500          if (myrpt->monstream) ast_closestream(myrpt->monstream);
11501          if (myrpt->p.archivedir)
11502          {
11503             long blocksleft;
11504 
11505             time(&myt);
11506             strftime(mydate,sizeof(mydate) - 1,"%Y%m%d%H%M%S",
11507                localtime(&myt));
11508             sprintf(myfname,"%s/%s/%s",myrpt->p.archivedir,
11509                myrpt->name,mydate);
11510             myrpt->monstream = ast_writefile(myfname,"wav49",
11511                "app_rpt Air Archive",O_CREAT | O_APPEND,0,0600);
11512             if (myrpt->p.monminblocks)
11513             {
11514                blocksleft = diskavail(myrpt);
11515                if (blocksleft >= myrpt->p.monminblocks)
11516                   donodelog(myrpt,"TXKEY,MAIN");
11517             } else donodelog(myrpt,"TXKEY,MAIN");
11518          }
11519          lasttx = 1;
11520          myrpt->txkeyed = 1;
11521          time(&myrpt->lasttxkeyedtime);
11522          myrpt->dailykeyups++;
11523          myrpt->totalkeyups++;
11524          rpt_mutex_unlock(&myrpt->lock);
11525          ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_KEY);
11526          rpt_mutex_lock(&myrpt->lock);
11527       }
11528       if ((!totx) && lasttx)
11529       {
11530          if (myrpt->monstream) ast_closestream(myrpt->monstream);
11531          myrpt->monstream = NULL;
11532 
11533          lasttx = 0;
11534          myrpt->txkeyed = 0;
11535          time(&myrpt->lasttxkeyedtime);
11536          rpt_mutex_unlock(&myrpt->lock);
11537          ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_UNKEY);
11538          rpt_mutex_lock(&myrpt->lock);
11539          donodelog(myrpt,"TXUNKEY,MAIN");
11540       }
11541       time(&t);
11542       /* if DTMF timeout */
11543       if ((!myrpt->cmdnode[0]) && (myrpt->dtmfidx >= 0) && ((myrpt->dtmf_time + DTMF_TIMEOUT) < t))
11544       {
11545          myrpt->inpadtest = 0;
11546          myrpt->dtmfidx = -1;
11547          myrpt->dtmfbuf[0] = 0;
11548       }        
11549       /* if remote DTMF timeout */
11550       if ((myrpt->rem_dtmfidx >= 0) && ((myrpt->rem_dtmf_time + DTMF_TIMEOUT) < t))
11551       {
11552          myrpt->inpadtest = 0;
11553          myrpt->rem_dtmfidx = -1;
11554          myrpt->rem_dtmfbuf[0] = 0;
11555       }  
11556 
11557       if (myrpt->exttx && myrpt->parrotchannel && 
11558          myrpt->p.parrotmode && (!myrpt->parrotstate))
11559       {
11560          char myfname[300];
11561 
11562          ci.confno = myrpt->conf;
11563          ci.confmode = DAHDI_CONF_CONFANNMON;
11564          ci.chan = 0;
11565 
11566          /* first put the channel on the conference in announce mode */
11567          if (ioctl(myrpt->parrotchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
11568          {
11569             ast_log(LOG_WARNING, "Unable to set conference mode for parrot\n");
11570             break;
11571          }
11572 
11573          sprintf(myfname,PARROTFILE,myrpt->name,myrpt->parrotcnt);
11574          strcat(myfname,".wav");
11575          unlink(myfname);        
11576          sprintf(myfname,PARROTFILE,myrpt->name,myrpt->parrotcnt);
11577          myrpt->parrotstate = 1;
11578          myrpt->parrottimer = myrpt->p.parrottime;
11579          if (myrpt->parrotstream) 
11580             ast_closestream(myrpt->parrotstream);
11581          myrpt->parrotstream = NULL;
11582          myrpt->parrotstream = ast_writefile(myfname,"wav",
11583             "app_rpt Parrot",O_CREAT | O_TRUNC,0,0600);
11584       }
11585 
11586       /* Reconnect */
11587    
11588       l = myrpt->links.next;
11589       while(l != &myrpt->links)
11590       {
11591          if (l->killme)
11592          {
11593             /* remove from queue */
11594             remque((struct qelem *) l);
11595             if (!strcmp(myrpt->cmdnode,l->name))
11596                myrpt->cmdnode[0] = 0;
11597             rpt_mutex_unlock(&myrpt->lock);
11598             /* hang-up on call to device */
11599             if (l->chan) ast_hangup(l->chan);
11600             ast_hangup(l->pchan);
11601             ast_free(l);
11602             rpt_mutex_lock(&myrpt->lock);
11603             /* re-start link traversal */
11604             l = myrpt->links.next;
11605             continue;
11606          }
11607          l = l->next;
11608       }
11609       n = 0;
11610       cs[n++] = myrpt->rxchannel;
11611       cs[n++] = myrpt->pchannel;
11612       cs[n++] = myrpt->monchannel;
11613       if (myrpt->parrotchannel) cs[n++] = myrpt->parrotchannel;
11614       if (myrpt->voxchannel) cs[n++] = myrpt->voxchannel;
11615       cs[n++] = myrpt->txpchannel;
11616       if (myrpt->txchannel != myrpt->rxchannel) cs[n++] = myrpt->txchannel;
11617       if (myrpt->dahditxchannel != myrpt->txchannel)
11618          cs[n++] = myrpt->dahditxchannel;
11619       l = myrpt->links.next;
11620       while(l != &myrpt->links)
11621       {
11622          if ((!l->killme) && (!l->disctime) && l->chan)
11623          {
11624             cs[n++] = l->chan;
11625             cs[n++] = l->pchan;
11626          }
11627          l = l->next;
11628       }
11629       if ((myrpt->topkeystate == 1) && 
11630           ((t - myrpt->topkeytime) > TOPKEYWAIT))
11631       {
11632          myrpt->topkeystate = 2;
11633          qsort(myrpt->topkey,TOPKEYN,sizeof(struct rpt_topkey),
11634             topcompar);
11635       }
11636       rpt_mutex_unlock(&myrpt->lock);
11637 
11638       if (myrpt->topkeystate == 2)
11639       {
11640          rpt_telemetry(myrpt,TOPKEY,NULL);
11641          myrpt->topkeystate = 3;
11642       }
11643       ms = MSWAIT;
11644       for(x = 0; x < n; x++)
11645       {
11646          int s = -(-x - myrpt->scram - 1) % n;
11647          cs1[x] = cs[s];
11648       }
11649       myrpt->scram++;
11650       who = ast_waitfor_n(cs1,n,&ms);
11651       if (who == NULL) ms = 0;
11652       elap = MSWAIT - ms;
11653       rpt_mutex_lock(&myrpt->lock);
11654       l = myrpt->links.next;
11655       while(l != &myrpt->links)
11656       {
11657          int myrx;
11658 
11659          if (l->voxtotimer) l->voxtotimer -= elap;
11660          if (l->voxtotimer < 0) l->voxtotimer = 0;
11661 
11662          if (l->lasttx != l->lasttx1)
11663          {
11664             voxinit_link(l,!l->lasttx);
11665             l->lasttx1 = l->lasttx;
11666          }
11667          myrx = l->lastrealrx;
11668          if ((l->phonemode) && (l->phonevox))
11669          {
11670             myrx = myrx || (!AST_LIST_EMPTY(&l->rxq));
11671             if (l->voxtotimer <= 0)
11672             {
11673                if (l->voxtostate)
11674                {
11675                   l->voxtotimer = myrpt->p.voxtimeout_ms;
11676                   l->voxtostate = 0;
11677                }           
11678                else
11679                {
11680                   l->voxtotimer = myrpt->p.voxrecover_ms;
11681                   l->voxtostate = 1;
11682                }
11683             }
11684             if (!l->voxtostate)
11685                myrx = myrx || l->wasvox ;
11686          }
11687          l->lastrx = myrx;
11688          if (l->linklisttimer)
11689          {
11690             l->linklisttimer -= elap;
11691             if (l->linklisttimer < 0) l->linklisttimer = 0;
11692          }
11693          if ((!l->linklisttimer) && (l->name[0] != '0') && (!l->isremote))
11694          {
11695             struct   ast_frame lf;
11696 
11697             memset(&lf,0,sizeof(lf));
11698             lf.frametype = AST_FRAME_TEXT;
11699             lf.subclass.integer = 0;
11700             lf.offset = 0;
11701             lf.mallocd = 0;
11702             lf.samples = 0;
11703             l->linklisttimer = LINKLISTTIME;
11704             strcpy(lstr,"L ");
11705             __mklinklist(myrpt,l,lstr + 2);
11706             if (l->chan)
11707             {
11708                lf.datalen = strlen(lstr) + 1;
11709                lf.data.ptr = lstr;
11710                ast_write(l->chan,&lf);
11711                if (debug > 6) ast_log(LOG_NOTICE,
11712                   "@@@@ node %s sent node string %s to node %s\n",
11713                      myrpt->name,lstr,l->name);
11714             }
11715          }
11716          if (l->newkey)
11717          {
11718             if ((l->retxtimer += elap) >= REDUNDANT_TX_TIME)
11719             {
11720                l->retxtimer = 0;
11721                if (l->chan && l->phonemode == 0) 
11722                {
11723                   if (l->lasttx)
11724                      ast_indicate(l->chan,AST_CONTROL_RADIO_KEY);
11725                   else
11726                      ast_indicate(l->chan,AST_CONTROL_RADIO_UNKEY);
11727                }
11728             }
11729             if ((l->rerxtimer += elap) >= (REDUNDANT_TX_TIME * 5))
11730             {
11731                if (debug == 7) printf("@@@@ rx un-key\n");
11732                l->lastrealrx = 0;
11733                l->rerxtimer = 0;
11734                if (l->lastrx1)
11735                {
11736                   if (myrpt->p.archivedir)
11737                   {
11738                      char str[100];
11739    
11740                      sprintf(str,"RXUNKEY(T),%s",l->name);
11741                      donodelog(myrpt,str);
11742                   }
11743                   if(myrpt->p.duplex) 
11744                      rpt_telemetry(myrpt,LINKUNKEY,l);
11745                   l->lastrx1 = 0;
11746                }
11747             }
11748          }
11749          if (l->disctime) /* Disconnect timer active on a channel ? */
11750          {
11751             l->disctime -= elap;
11752             if (l->disctime <= 0) /* Disconnect timer expired on inbound channel ? */
11753                l->disctime = 0; /* Yep */
11754          }
11755 
11756          if (l->retrytimer)
11757          {
11758             l->retrytimer -= elap;
11759             if (l->retrytimer < 0) l->retrytimer = 0;
11760          }
11761 
11762          /* Tally connect time */
11763          l->connecttime += elap;
11764 
11765          /* ignore non-timing channels */
11766          if (l->elaptime < 0)
11767          {
11768             l = l->next;
11769             continue;
11770          }
11771          l->elaptime += elap;
11772          /* if connection has taken too long */
11773          if ((l->elaptime > MAXCONNECTTIME) && 
11774             ((!l->chan) || (l->chan->_state != AST_STATE_UP)))
11775          {
11776             l->elaptime = 0;
11777             rpt_mutex_unlock(&myrpt->lock);
11778             if (l->chan) ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
11779             rpt_mutex_lock(&myrpt->lock);
11780             break;
11781          }
11782          if ((!l->chan) && (!l->retrytimer) && l->outbound && 
11783             (l->retries++ < l->max_retries) && (l->hasconnected))
11784          {
11785             if (l->chan) ast_hangup(l->chan);
11786             l->chan = 0;
11787             rpt_mutex_unlock(&myrpt->lock);
11788             if ((l->name[0] != '0') && (!l->isremote))
11789             {
11790                if (attempt_reconnect(myrpt,l) == -1)
11791                {
11792                   l->retrytimer = RETRY_TIMER_MS;
11793                } 
11794             }
11795             else 
11796             {
11797                l->retrytimer = l->max_retries + 1;
11798             }
11799 
11800             rpt_mutex_lock(&myrpt->lock);
11801             break;
11802          }
11803          if ((!l->chan) && (!l->retrytimer) && l->outbound &&
11804             (l->retries >= l->max_retries))
11805          {
11806             /* remove from queue */
11807             remque((struct qelem *) l);
11808             if (!strcmp(myrpt->cmdnode,l->name))
11809                myrpt->cmdnode[0] = 0;
11810             rpt_mutex_unlock(&myrpt->lock);
11811             if (l->name[0] != '0')
11812             {
11813                if (!l->hasconnected)
11814                   rpt_telemetry(myrpt,CONNFAIL,l);
11815                else rpt_telemetry(myrpt,REMDISC,l);
11816             }
11817             if (myrpt->p.archivedir)
11818             {
11819                char str[100];
11820 
11821                if (!l->hasconnected)
11822                   sprintf(str,"LINKFAIL,%s",l->name);
11823                else
11824                   sprintf(str,"LINKDISC,%s",l->name);
11825                donodelog(myrpt,str);
11826             }
11827             /* hang-up on call to device */
11828             ast_hangup(l->pchan);
11829             ast_free(l);
11830                                 rpt_mutex_lock(&myrpt->lock);
11831             break;
11832          }
11833             if ((!l->chan) && (!l->disctime) && (!l->outbound))
11834             {
11835             if(debug)ast_log(LOG_NOTICE, "LINKDISC AA\n");
11836                 /* remove from queue */
11837                 remque((struct qelem *) l);
11838             if(myrpt->links.next==&myrpt->links)channel_revert(myrpt);
11839                 if (!strcmp(myrpt->cmdnode,l->name))myrpt->cmdnode[0] = 0;
11840                 rpt_mutex_unlock(&myrpt->lock);
11841             if (l->name[0] != '0') 
11842             {
11843                   rpt_telemetry(myrpt,REMDISC,l);
11844             }
11845             if (myrpt->p.archivedir)
11846             {
11847                char str[100];
11848                sprintf(str,"LINKDISC,%s",l->name);
11849                donodelog(myrpt,str);
11850             }
11851                 /* hang-up on call to device */
11852                 ast_hangup(l->pchan);
11853                 ast_free(l);
11854                 rpt_mutex_lock(&myrpt->lock);
11855                 break;
11856             }
11857          l = l->next;
11858       }
11859       if (myrpt->linkposttimer)
11860       {
11861          myrpt->linkposttimer -= elap;
11862          if (myrpt->linkposttimer < 0) myrpt->linkposttimer = 0;
11863       }
11864       if (myrpt->linkposttimer <= 0)
11865       {
11866          int nstr;
11867          char lst,*str;
11868          time_t now;
11869 
11870          myrpt->linkposttimer = LINKPOSTTIME;
11871          nstr = 0;
11872          for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
11873          {
11874             /* if is not a real link, ignore it */
11875             if (l->name[0] == '0') continue;
11876             nstr += strlen(l->name) + 1;
11877          }
11878          str = ast_malloc(nstr + 256);
11879          if (!str)
11880          {
11881             ast_log(LOG_NOTICE,"Cannot ast_malloc()\n");
11882             break;
11883          }
11884          nstr = 0;
11885          strcpy(str,"nodes=");
11886          for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
11887          {
11888             /* if is not a real link, ignore it */
11889             if (l->name[0] == '0') continue;
11890             lst = 'T';
11891             if (!l->mode) lst = 'R';
11892             if (!l->thisconnected) lst = 'C';
11893             if (nstr) strcat(str,",");
11894             sprintf(str + strlen(str),"%c%s",lst,l->name);
11895             nstr = 1;
11896          }
11897                   p = strstr(tdesc, "version");
11898                   if(p){
11899             int vmajor,vminor;
11900             if(sscanf(p, "version %30d.%30d", &vmajor, &vminor) == 2)
11901                sprintf(str + strlen(str),"&apprptvers=%d.%d",vmajor,vminor);
11902          }
11903          time(&now);
11904          sprintf(str + strlen(str),"&apprptuptime=%d",(int)(now-starttime));
11905          sprintf(str + strlen(str),
11906          "&totalkerchunks=%d&totalkeyups=%d&totaltxtime=%d&timeouts=%d&totalexecdcommands=%d",
11907          myrpt->totalkerchunks,myrpt->totalkeyups,(int) myrpt->totaltxtime/1000,
11908          myrpt->timeouts,myrpt->totalexecdcommands);
11909          rpt_mutex_unlock(&myrpt->lock);
11910          statpost(myrpt,str);
11911          rpt_mutex_lock(&myrpt->lock);
11912          ast_free(str);
11913       }
11914       if (myrpt->keyposttimer)
11915       {
11916          myrpt->keyposttimer -= elap;
11917          if (myrpt->keyposttimer < 0) myrpt->keyposttimer = 0;
11918       }
11919       if (myrpt->keyposttimer <= 0)
11920       {
11921          char str[100];
11922          int diff = 0;
11923          time_t now;
11924 
11925          myrpt->keyposttimer = KEYPOSTTIME;
11926          time(&now);
11927          if (myrpt->lastkeyedtime)
11928          {
11929             diff = (int)(now - myrpt->lastkeyedtime);
11930          }
11931          sprintf(str,"keyed=%d&keytime=%d",myrpt->keyed,diff);
11932          rpt_mutex_unlock(&myrpt->lock);
11933          statpost(myrpt,str);
11934          rpt_mutex_lock(&myrpt->lock);
11935       }
11936       if(totx){
11937          myrpt->dailytxtime += elap;
11938          myrpt->totaltxtime += elap;
11939       }
11940       i = myrpt->tailtimer;
11941       if (myrpt->tailtimer) myrpt->tailtimer -= elap;
11942       if (myrpt->tailtimer < 0) myrpt->tailtimer = 0;
11943       if((i) && (myrpt->tailtimer == 0))
11944          myrpt->tailevent = 1;
11945       if ((!myrpt->p.s[myrpt->p.sysstate_cur].totdisable) && myrpt->totimer) myrpt->totimer -= elap;
11946       if (myrpt->totimer < 0) myrpt->totimer = 0;
11947       if (myrpt->idtimer) myrpt->idtimer -= elap;
11948       if (myrpt->idtimer < 0) myrpt->idtimer = 0;
11949       if (myrpt->tmsgtimer) myrpt->tmsgtimer -= elap;
11950       if (myrpt->tmsgtimer < 0) myrpt->tmsgtimer = 0;
11951       if (myrpt->voxtotimer) myrpt->voxtotimer -= elap;
11952       if (myrpt->voxtotimer < 0) myrpt->voxtotimer = 0;
11953       if (myrpt->exttx)
11954       {
11955          myrpt->parrottimer = myrpt->p.parrottime;
11956       }
11957       else
11958       {
11959          if (myrpt->parrottimer) myrpt->parrottimer -= elap;
11960          if (myrpt->parrottimer < 0) myrpt->parrottimer = 0;
11961       }
11962       /* do macro timers */
11963       if (myrpt->macrotimer) myrpt->macrotimer -= elap;
11964       if (myrpt->macrotimer < 0) myrpt->macrotimer = 0;
11965       /* do local dtmf timer */
11966       if (myrpt->dtmf_local_timer)
11967       {
11968          if (myrpt->dtmf_local_timer > 1) myrpt->dtmf_local_timer -= elap;
11969          if (myrpt->dtmf_local_timer < 1) myrpt->dtmf_local_timer = 1;
11970       }
11971       do_dtmf_local(myrpt,0);
11972       /* Execute scheduler appx. every 2 tenths of a second */
11973       if (myrpt->skedtimer <= 0){
11974          myrpt->skedtimer = 200;
11975          do_scheduler(myrpt);
11976       }
11977       else
11978          myrpt->skedtimer -=elap;
11979       if (!ms) 
11980       {
11981          rpt_mutex_unlock(&myrpt->lock);
11982          continue;
11983       }
11984       if (myrpt->p.parrotmode && (myrpt->parrotstate == 1) &&
11985          (myrpt->parrottimer <= 0))
11986       {
11987 
11988          ci.confno = 0;
11989          ci.confmode = 0;
11990          ci.chan = 0;
11991 
11992          /* first put the channel on the conference in announce mode */
11993          if (ioctl(myrpt->parrotchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
11994          {
11995             ast_log(LOG_WARNING, "Unable to set conference mode for parrot\n");
11996             break;
11997          }
11998          if (myrpt->parrotstream) 
11999             ast_closestream(myrpt->parrotstream);
12000          myrpt->parrotstream = NULL;
12001          myrpt->parrotstate = 2;
12002          rpt_telemetry(myrpt,PARROT,(void *) ((intptr_t)myrpt->parrotcnt++)); 
12003       }        
12004       if (myrpt->cmdAction.state == CMD_STATE_READY)
12005       { /* there is a command waiting to be processed */
12006          int status;
12007          myrpt->cmdAction.state = CMD_STATE_EXECUTING;
12008          // lose the lock
12009          rpt_mutex_unlock(&myrpt->lock);
12010          // do the function
12011          status = (*function_table[myrpt->cmdAction.functionNumber].function)(myrpt,myrpt->cmdAction.param, myrpt->cmdAction.digits, myrpt->cmdAction.command_source, NULL);
12012          // get the lock again
12013          rpt_mutex_lock(&myrpt->lock);
12014          myrpt->cmdAction.state = CMD_STATE_IDLE;
12015       } /* if myrpt->cmdAction.state == CMD_STATE_READY */
12016       
12017       c = myrpt->macrobuf[0];
12018       time(&t);
12019       if (c && (!myrpt->macrotimer) && 
12020          starttime && (t > (starttime + START_DELAY)))
12021       {
12022          char cin = c & 0x7f;
12023          myrpt->macrotimer = MACROTIME;
12024          memmove(myrpt->macrobuf,myrpt->macrobuf + 1,MAXMACRO - 1);
12025          if ((cin == 'p') || (cin == 'P'))
12026             myrpt->macrotimer = MACROPTIME;
12027          rpt_mutex_unlock(&myrpt->lock);
12028          if (myrpt->p.archivedir)
12029          {
12030             char str[100];
12031 
12032             sprintf(str,"DTMF(M),MAIN,%c",cin);
12033             donodelog(myrpt,str);
12034          }
12035          local_dtmf_helper(myrpt,c);
12036       } else rpt_mutex_unlock(&myrpt->lock);
12037       if (who == myrpt->rxchannel) /* if it was a read from rx */
12038       {
12039          int ismuted;
12040 
12041          f = ast_read(myrpt->rxchannel);
12042          if (!f)
12043          {
12044             if (debug) printf("@@@@ rpt:Hung Up\n");
12045             break;
12046          }
12047          if (f->frametype == AST_FRAME_VOICE)
12048          {
12049 #ifdef   _MDC_DECODE_H_
12050             unsigned char ubuf[2560];
12051             short *sp;
12052             int n;
12053 #endif
12054 
12055             if ((!myrpt->localtx) && (!myrpt->p.linktolink)) {
12056                memset(f->data.ptr,0,f->datalen);
12057             }
12058 
12059 #ifdef   _MDC_DECODE_H_
12060             sp = (short *) f->data;
12061             /* convert block to unsigned char */
12062             for(n = 0; n < f->datalen / 2; n++)
12063             {
12064                ubuf[n] = (*sp++ >> 8) + 128;
12065             }
12066             n = mdc_decoder_process_samples(myrpt->mdc,ubuf,f->datalen / 2);
12067             if (n == 1)
12068             {
12069                   unsigned char op,arg;
12070                   unsigned short unitID;
12071 
12072                   mdc_decoder_get_packet(myrpt->mdc,&op,&arg,&unitID);
12073                   if (debug > 2)
12074                   {
12075                      ast_log(LOG_NOTICE,"Got (single-length) packet:\n");
12076                      ast_log(LOG_NOTICE,"op: %02x, arg: %02x, UnitID: %04x\n",
12077                         op & 255,arg & 255,unitID);
12078                   }
12079                   if ((op == 1) && (arg == 0))
12080                   {
12081                      myrpt->lastunit = unitID;
12082                      mdc1200_notify(myrpt,NULL,myrpt->lastunit);
12083                      mdc1200_send(myrpt,myrpt->lastunit);
12084                   }
12085             }
12086             if ((debug > 2) && (i == 2))
12087             {
12088                unsigned char op,arg,ex1,ex2,ex3,ex4;
12089                unsigned short unitID;
12090 
12091                mdc_decoder_get_double_packet(myrpt->mdc,&op,&arg,&unitID,
12092                   &ex1,&ex2,&ex3,&ex4);
12093                ast_log(LOG_NOTICE,"Got (double-length) packet:\n");
12094                ast_log(LOG_NOTICE,"op: %02x, arg: %02x, UnitID: %04x\n",
12095                   op & 255,arg & 255,unitID);
12096                ast_log(LOG_NOTICE,"ex1: %02x, ex2: %02x, ex3: %02x, ex4: %02x\n",
12097                   ex1 & 255, ex2 & 255, ex3 & 255, ex4 & 255);
12098             }
12099 #endif
12100 #ifdef   __RPT_NOTCH
12101             /* apply inbound filters, if any */
12102             rpt_filter(myrpt,f->data,f->datalen / 2);
12103 #endif
12104             if (ioctl(myrpt->dahdirxchannel->fds[0], DAHDI_GETCONFMUTE, &ismuted) == -1)
12105             {
12106                ismuted = 0;
12107             }
12108             if (dtmfed) ismuted = 1;
12109             dtmfed = 0;
12110             if (ismuted)
12111             {
12112                memset(f->data.ptr,0,f->datalen);
12113                if (myrpt->lastf1)
12114                   memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
12115                if (myrpt->lastf2)
12116                   memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
12117             } 
12118             if (f) f2 = ast_frdup(f);
12119             else f2 = NULL;
12120             f1 = myrpt->lastf2;
12121             myrpt->lastf2 = myrpt->lastf1;
12122             myrpt->lastf1 = f2;
12123             if (ismuted)
12124             {
12125                if (myrpt->lastf1)
12126                   memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
12127                if (myrpt->lastf2)
12128                   memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
12129             }
12130             if (f1)
12131             {
12132                ast_write(myrpt->pchannel,f1);
12133                ast_frfree(f1);
12134             }
12135          }
12136 #ifndef  OLD_ASTERISK
12137          else if (f->frametype == AST_FRAME_DTMF_BEGIN)
12138          {
12139             if (myrpt->lastf1)
12140                memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
12141             if (myrpt->lastf2)
12142                memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
12143             dtmfed = 1;
12144          }
12145 #endif
12146          else if (f->frametype == AST_FRAME_DTMF)
12147          {
12148             c = (char) f->subclass.integer; /* get DTMF char */
12149             ast_frfree(f);
12150             if (myrpt->lastf1)
12151                memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
12152             if (myrpt->lastf2)
12153                memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
12154             dtmfed = 1;
12155             if (!myrpt->keyed) continue;
12156             c = func_xlat(myrpt,c,&myrpt->p.inxlat);
12157             if (c) local_dtmf_helper(myrpt,c);
12158             continue;
12159          }                 
12160          else if (f->frametype == AST_FRAME_CONTROL)
12161          {
12162             if (f->subclass.integer == AST_CONTROL_HANGUP)
12163             {
12164                if (debug) printf("@@@@ rpt:Hung Up\n");
12165                ast_frfree(f);
12166                break;
12167             }
12168             /* if RX key */
12169             if (f->subclass.integer == AST_CONTROL_RADIO_KEY)
12170             {
12171                if ((!lasttx) || (myrpt->p.duplex > 1) || (myrpt->p.linktolink)) 
12172                {
12173                   if (debug == 7) printf("@@@@ rx key\n");
12174                   myrpt->keyed = 1;
12175                   time(&myrpt->lastkeyedtime);
12176                   myrpt->keyposttimer = KEYPOSTSHORTTIME;
12177                }
12178                if (myrpt->p.archivedir)
12179                {
12180                   donodelog(myrpt,"RXKEY,MAIN");
12181                }
12182                if (f->datalen && f->data.ptr)
12183                {
12184                   char busy = 0;
12185 
12186                   if (debug) ast_log(LOG_NOTICE,"Got PL %s on node %s\n",(char *)f->data.ptr,myrpt->name);
12187                   // ctcss code autopatch initiate
12188                   if (strstr((char *)f->data.ptr,"/M/")&& !myrpt->macropatch)
12189                   {
12190                       char value[16];
12191                      strcat(value,"*6");
12192                      myrpt->macropatch=1;
12193                      rpt_mutex_lock(&myrpt->lock);
12194                      if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(value)){
12195                         rpt_mutex_unlock(&myrpt->lock);
12196                         busy=1;
12197                      }
12198                      if(!busy){
12199                         myrpt->macrotimer = MACROTIME;
12200                         strncat(myrpt->macrobuf,value,MAXMACRO - 1);
12201                         if (!busy) strcpy(myrpt->lasttone,(char*)f->data.ptr);
12202                      }
12203                      rpt_mutex_unlock(&myrpt->lock);
12204                   }
12205                   else if (strcmp((char *)f->data.ptr,myrpt->lasttone))
12206                   {
12207                      char *value = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.tonemacro, (char *)f->data.ptr);
12208                      if (value)
12209                      {
12210                         if (debug) ast_log(LOG_NOTICE,"Tone %s doing %s on node %s\n",(char *) f->data.ptr,value,myrpt->name);
12211                         rpt_mutex_lock(&myrpt->lock);
12212                         if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(value)){
12213                            rpt_mutex_unlock(&myrpt->lock);
12214                            busy=1;
12215                         }
12216                         if(!busy){
12217                            myrpt->macrotimer = MACROTIME;
12218                            strncat(myrpt->macrobuf,value,MAXMACRO - 1);
12219                         }
12220                         rpt_mutex_unlock(&myrpt->lock);
12221                      }
12222                      if (!busy) strcpy(myrpt->lasttone,(char*)f->data.ptr);
12223                   }
12224                } else myrpt->lasttone[0] = 0;
12225             }
12226             /* if RX un-key */
12227             if (f->subclass.integer == AST_CONTROL_RADIO_UNKEY)
12228             {
12229                if ((!lasttx) || (myrpt->p.duplex > 1) || (myrpt->p.linktolink))
12230                {
12231                   if (debug == 7) printf("@@@@ rx un-key\n");
12232                   if(myrpt->p.duplex && myrpt->keyed) {
12233                      rpt_telemetry(myrpt,UNKEY,NULL);
12234                   }
12235                }
12236                myrpt->keyed = 0;
12237                time(&myrpt->lastkeyedtime);
12238                myrpt->keyposttimer = KEYPOSTSHORTTIME;
12239                if (myrpt->p.archivedir)
12240                {
12241                   donodelog(myrpt,"RXUNKEY,MAIN");
12242                }
12243             }
12244          }
12245          ast_frfree(f);
12246          continue;
12247       }
12248       if (who == myrpt->pchannel) /* if it was a read from pseudo */
12249       {
12250          f = ast_read(myrpt->pchannel);
12251          if (!f)
12252          {
12253             if (debug) printf("@@@@ rpt:Hung Up\n");
12254             break;
12255          }
12256          if (f->frametype == AST_FRAME_VOICE)
12257          {
12258             ast_write(myrpt->txpchannel,f);
12259          }
12260          if (f->frametype == AST_FRAME_CONTROL)
12261          {
12262             if (f->subclass.integer == AST_CONTROL_HANGUP)
12263             {
12264                if (debug) printf("@@@@ rpt:Hung Up\n");
12265                ast_frfree(f);
12266                break;
12267             }
12268          }
12269          ast_frfree(f);
12270          continue;
12271       }
12272       if (who == myrpt->txchannel) /* if it was a read from tx */
12273       {
12274          f = ast_read(myrpt->txchannel);
12275          if (!f)
12276          {
12277             if (debug) printf("@@@@ rpt:Hung Up\n");
12278             break;
12279          }
12280          if (f->frametype == AST_FRAME_CONTROL)
12281          {
12282             if (f->subclass.integer == AST_CONTROL_HANGUP)
12283             {
12284                if (debug) printf("@@@@ rpt:Hung Up\n");
12285                ast_frfree(f);
12286                break;
12287             }
12288          }
12289          ast_frfree(f);
12290          continue;
12291       }
12292       if (who == myrpt->dahditxchannel) /* if it was a read from pseudo-tx */
12293       {
12294          f = ast_read(myrpt->dahditxchannel);
12295          if (!f)
12296          {
12297             if (debug) printf("@@@@ rpt:Hung Up\n");
12298             break;
12299          }
12300          if (f->frametype == AST_FRAME_VOICE)
12301          {
12302             struct ast_frame *vframe;
12303 
12304             if (myrpt->p.duplex < 2)
12305             {
12306                if (myrpt->txrealkeyed) 
12307                {
12308                   if ((!myfirst) && myrpt->callmode)
12309                   {
12310                       x = 0;
12311                       AST_LIST_TRAVERSE(&myrpt->txq, vframe,
12312                      frame_list) x++;
12313                       for(;x < myrpt->p.simplexpatchdelay; x++)
12314                       {
12315                         vframe = ast_frdup(f);
12316                         memset(vframe->data.ptr,0,vframe->datalen);
12317                         AST_LIST_INSERT_TAIL(&myrpt->txq,vframe,frame_list);
12318                       }
12319                       myfirst = 1;
12320                   }
12321                   vframe = ast_frdup(f);
12322                   AST_LIST_INSERT_TAIL(&myrpt->txq,
12323                      vframe,frame_list);
12324                } else myfirst = 0;
12325                x = 0;
12326                AST_LIST_TRAVERSE(&myrpt->txq, vframe,
12327                   frame_list) x++;
12328                if (!x)
12329                {
12330                   memset(f->data.ptr,0,f->datalen);
12331                }
12332                else
12333                {
12334                   ast_frfree(f);
12335                   f = AST_LIST_REMOVE_HEAD(&myrpt->txq,
12336                      frame_list);
12337                }
12338             }
12339             else
12340             {
12341                while((vframe = AST_LIST_REMOVE_HEAD(&myrpt->txq,
12342                   frame_list))) ast_frfree(vframe);
12343             }
12344             ast_write(myrpt->txchannel,f);
12345          }
12346          if (f->frametype == AST_FRAME_CONTROL)
12347          {
12348             if (f->subclass.integer == AST_CONTROL_HANGUP)
12349             {
12350                if (debug) printf("@@@@ rpt:Hung Up\n");
12351                ast_frfree(f);
12352                break;
12353             }
12354          }
12355          ast_frfree(f);
12356          continue;
12357       }
12358       toexit = 0;
12359       rpt_mutex_lock(&myrpt->lock);
12360       l = myrpt->links.next;
12361       while(l != &myrpt->links)
12362       {
12363          int remnomute;
12364          struct timeval now;
12365 
12366          if (l->disctime)
12367          {
12368             l = l->next;
12369             continue;
12370          }
12371 
12372          remrx = 0;
12373          /* see if any other links are receiving */
12374          m = myrpt->links.next;
12375          while(m != &myrpt->links)
12376          {
12377             /* if not us, count it */
12378             if ((m != l) && (m->lastrx)) remrx = 1;
12379             m = m->next;
12380          }
12381          rpt_mutex_unlock(&myrpt->lock);
12382          now = ast_tvnow();
12383          if ((who == l->chan) || (!l->lastlinktv.tv_sec) ||
12384             (ast_tvdiff_ms(now,l->lastlinktv) >= 19))
12385          {
12386             l->lastlinktv = now;
12387             remnomute = myrpt->localtx && 
12388                 (!(myrpt->cmdnode[0] || 
12389                (myrpt->dtmfidx > -1)));
12390             totx = (((l->isremote) ? (remnomute) : 
12391                myrpt->exttx) || remrx) && l->mode;
12392             if (l->phonemode == 0 && l->chan && (l->lasttx != totx))
12393             {
12394                if (totx)
12395                {
12396                   ast_indicate(l->chan,AST_CONTROL_RADIO_KEY);
12397                }
12398                else
12399                {
12400                   ast_indicate(l->chan,AST_CONTROL_RADIO_UNKEY);
12401                }
12402                if (myrpt->p.archivedir)
12403                {
12404                   char str[100];
12405 
12406                   if (totx)
12407                      sprintf(str,"TXKEY,%s",l->name);
12408                   else
12409                      sprintf(str,"TXUNKEY,%s",l->name);
12410                   donodelog(myrpt,str);
12411                }
12412             }
12413             l->lasttx = totx;
12414          }
12415          rpt_mutex_lock(&myrpt->lock);
12416          if (who == l->chan) /* if it was a read from rx */
12417          {
12418             rpt_mutex_unlock(&myrpt->lock);
12419             f = ast_read(l->chan);
12420             if (!f)
12421             {
12422                rpt_mutex_lock(&myrpt->lock);
12423                __kickshort(myrpt);
12424                rpt_mutex_unlock(&myrpt->lock);
12425                if ((!l->disced) && (!l->outbound))
12426                {
12427                   if ((l->name[0] == '0') || l->isremote)
12428                      l->disctime = 1;
12429                   else
12430                      l->disctime = DISC_TIME;
12431                   rpt_mutex_lock(&myrpt->lock);
12432                   ast_hangup(l->chan);
12433                   l->chan = 0;
12434                   break;
12435                }
12436 
12437                if (l->retrytimer) 
12438                {
12439                   ast_hangup(l->chan);
12440                   l->chan = 0;
12441                   rpt_mutex_lock(&myrpt->lock);
12442                   break; 
12443                }
12444                if (l->outbound && (l->retries++ < l->max_retries) && (l->hasconnected))
12445                {
12446                   rpt_mutex_lock(&myrpt->lock);
12447                   if (l->chan) ast_hangup(l->chan);
12448                   l->chan = 0;
12449                   l->hasconnected = 1;
12450                   l->retrytimer = RETRY_TIMER_MS;
12451                   l->elaptime = 0;
12452                   l->connecttime = 0;
12453                   l->thisconnected = 0;
12454                   break;
12455                }
12456                rpt_mutex_lock(&myrpt->lock);
12457                /* remove from queue */
12458                remque((struct qelem *) l);
12459                if (!strcmp(myrpt->cmdnode,l->name))
12460                   myrpt->cmdnode[0] = 0;
12461                __kickshort(myrpt);
12462                rpt_mutex_unlock(&myrpt->lock);
12463                if (!l->hasconnected)
12464                   rpt_telemetry(myrpt,CONNFAIL,l);
12465                else if (l->disced != 2) rpt_telemetry(myrpt,REMDISC,l);
12466                if (myrpt->p.archivedir)
12467                {
12468                   char str[100];
12469 
12470                   if (!l->hasconnected)
12471                      sprintf(str,"LINKFAIL,%s",l->name);
12472                   else
12473                      sprintf(str,"LINKDISC,%s",l->name);
12474                   donodelog(myrpt,str);
12475                }
12476                if (l->lastf1) ast_frfree(l->lastf1);
12477                l->lastf1 = NULL;
12478                if (l->lastf2) ast_frfree(l->lastf2);
12479                l->lastf2 = NULL;
12480                /* hang-up on call to device */
12481                ast_hangup(l->chan);
12482                ast_hangup(l->pchan);
12483                ast_free(l);
12484                rpt_mutex_lock(&myrpt->lock);
12485                break;
12486             }
12487             if (f->frametype == AST_FRAME_VOICE)
12488             {
12489                int ismuted,n1;
12490 
12491                if ((l->phonemode) && (l->phonevox))
12492                {
12493                   n1 = dovox(&l->vox,
12494                      f->data.ptr,f->datalen / 2);
12495                   if (n1 != l->wasvox)
12496                   {
12497                      if (debug)ast_log(LOG_DEBUG,"Link Node %s, vox %d\n",l->name,n1);
12498                      l->wasvox = n1;
12499                      l->voxtostate = 0;
12500                      if (n1) l->voxtotimer = myrpt->p.voxtimeout_ms;
12501                      else l->voxtotimer = 0;
12502                   }
12503                   if (l->lastrealrx || n1)
12504                   {
12505                      if (!myfirst)
12506                      {
12507                          x = 0;
12508                          AST_LIST_TRAVERSE(&l->rxq, f1,
12509                         frame_list) x++;
12510                          for(;x < myrpt->p.simplexphonedelay; x++)
12511                         {
12512                            f1 = ast_frdup(f);
12513                            memset(f1->data.ptr,0,f1->datalen);
12514                            AST_LIST_INSERT_TAIL(&l->rxq,
12515                               f1,frame_list);
12516                          }
12517                          myfirst = 1;
12518                      }
12519                      f1 = ast_frdup(f);
12520                      AST_LIST_INSERT_TAIL(&l->rxq,f1,frame_list);
12521                   } else myfirst = 0; 
12522                   x = 0;
12523                   AST_LIST_TRAVERSE(&l->rxq, f1,frame_list) x++;
12524                   if (!x)
12525                   {
12526                      memset(f->data.ptr,0,f->datalen);
12527                   }
12528                   else
12529                   {
12530                      ast_frfree(f);
12531                      f = AST_LIST_REMOVE_HEAD(&l->rxq,frame_list);
12532                   }
12533                   if (ioctl(l->chan->fds[0], DAHDI_GETCONFMUTE, &ismuted) == -1)
12534                   {
12535                      ismuted = 0;
12536                   }
12537                   /* if not receiving, zero-out audio */
12538                   ismuted |= (!l->lastrx);
12539                   if (l->dtmfed && l->phonemode) ismuted = 1;
12540                   l->dtmfed = 0;
12541                   if (ismuted)
12542                   {
12543                      memset(f->data.ptr,0,f->datalen);
12544                      if (l->lastf1)
12545                         memset(l->lastf1->data.ptr,0,l->lastf1->datalen);
12546                      if (l->lastf2)
12547                         memset(l->lastf2->data.ptr,0,l->lastf2->datalen);
12548                   } 
12549                   if (f) f2 = ast_frdup(f);
12550                   else f2 = NULL;
12551                   f1 = l->lastf2;
12552                   l->lastf2 = l->lastf1;
12553                   l->lastf1 = f2;
12554                   if (ismuted)
12555                   {
12556                      if (l->lastf1)
12557                         memset(l->lastf1->data.ptr,0,l->lastf1->datalen);
12558                      if (l->lastf2)
12559                         memset(l->lastf2->data.ptr,0,l->lastf2->datalen);
12560                   }
12561                   if (f1)
12562                   {
12563                      ast_write(l->pchan,f1);
12564                      ast_frfree(f1);
12565                   }
12566                }
12567                else
12568                {
12569                   if (!l->lastrx)
12570                      memset(f->data.ptr,0,f->datalen);
12571                   ast_write(l->pchan,f);
12572                }
12573             }
12574 #ifndef  OLD_ASTERISK
12575             else if (f->frametype == AST_FRAME_DTMF_BEGIN)
12576             {
12577                if (l->lastf1)
12578                   memset(l->lastf1->data.ptr,0,l->lastf1->datalen);
12579                if (l->lastf2)
12580                   memset(l->lastf2->data.ptr,0,l->lastf2->datalen);
12581                l->dtmfed = 1;
12582             }
12583 #endif
12584             if (f->frametype == AST_FRAME_TEXT)
12585             {
12586                handle_link_data(myrpt,l,f->data.ptr);
12587             }
12588             if (f->frametype == AST_FRAME_DTMF)
12589             {
12590                if (l->lastf1)
12591                   memset(l->lastf1->data.ptr,0,l->lastf1->datalen);
12592                if (l->lastf2)
12593                   memset(l->lastf2->data.ptr,0,l->lastf2->datalen);
12594                l->dtmfed = 1;
12595                handle_link_phone_dtmf(myrpt,l,f->subclass.integer);
12596             }
12597             if (f->frametype == AST_FRAME_CONTROL)
12598             {
12599                if (f->subclass.integer == AST_CONTROL_ANSWER)
12600                {
12601                   char lconnected = l->connected;
12602 
12603                   __kickshort(myrpt);
12604                   l->connected = 1;
12605                   l->hasconnected = 1;
12606                   l->thisconnected = 1;
12607                   l->elaptime = -1;
12608                   if (!l->phonemode) send_newkey(l->chan);
12609                   if (!l->isremote) l->retries = 0;
12610                   if (!lconnected) 
12611                   {
12612                      rpt_telemetry(myrpt,CONNECTED,l);
12613                      if (myrpt->p.archivedir)
12614                      {
12615                         char str[100];
12616 
12617                         if (l->mode)
12618                            sprintf(str,"LINKTRX,%s",l->name);
12619                         else
12620                            sprintf(str,"LINKMONITOR,%s",l->name);
12621                         donodelog(myrpt,str);
12622                      }
12623                   }     
12624                   else
12625                      l->reconnects++;
12626                }
12627                /* if RX key */
12628                if (f->subclass.integer == AST_CONTROL_RADIO_KEY)
12629                {
12630                   if (debug == 7 ) printf("@@@@ rx key\n");
12631                   l->lastrealrx = 1;
12632                   l->rerxtimer = 0;
12633                   if (!l->lastrx1)
12634                   {
12635                      if (myrpt->p.archivedir)
12636                      {
12637                         char str[100];
12638 
12639                         sprintf(str,"RXKEY,%s",l->name);
12640                         donodelog(myrpt,str);
12641                      }
12642                      l->lastrx1 = 1;
12643                   }
12644                }
12645                /* if RX un-key */
12646                if (f->subclass.integer == AST_CONTROL_RADIO_UNKEY)
12647                {
12648                   if (debug == 7) printf("@@@@ rx un-key\n");
12649                   l->lastrealrx = 0;
12650                   l->rerxtimer = 0;
12651                   if (l->lastrx1)
12652                   {
12653                      if (myrpt->p.archivedir)
12654                      {
12655                         char str[100];
12656 
12657                         sprintf(str,"RXUNKEY,%s",l->name);
12658                         donodelog(myrpt,str);
12659                      }
12660                      l->lastrx1 = 0;
12661                      if(myrpt->p.duplex) 
12662                         rpt_telemetry(myrpt,LINKUNKEY,l);
12663                   }
12664                }
12665                if (f->subclass.integer == AST_CONTROL_HANGUP)
12666                {
12667                   ast_frfree(f);
12668                   rpt_mutex_lock(&myrpt->lock);
12669                   __kickshort(myrpt);
12670                   rpt_mutex_unlock(&myrpt->lock);
12671                   if ((!l->outbound) && (!l->disced))
12672                   {
12673                      if ((l->name[0] == '0') || l->isremote)
12674                         l->disctime = 1;
12675                      else
12676                         l->disctime = DISC_TIME;
12677                      rpt_mutex_lock(&myrpt->lock);
12678                      ast_hangup(l->chan);
12679                      l->chan = 0;
12680                      break;
12681                   }
12682                   if (l->retrytimer) 
12683                   {
12684                      if (l->chan) ast_hangup(l->chan);
12685                      l->chan = 0;
12686                      rpt_mutex_lock(&myrpt->lock);
12687                      break;
12688                   }
12689                   if (l->outbound && (l->retries++ < l->max_retries) && (l->hasconnected))
12690                   {
12691                      rpt_mutex_lock(&myrpt->lock);
12692                      if (l->chan) ast_hangup(l->chan);
12693                      l->chan = 0;
12694                      l->hasconnected = 1;
12695                      l->elaptime = 0;
12696                      l->retrytimer = RETRY_TIMER_MS;
12697                      l->connecttime = 0;
12698                      l->thisconnected = 0;
12699                      break;
12700                   }
12701                   rpt_mutex_lock(&myrpt->lock);
12702                   /* remove from queue */
12703                   remque((struct qelem *) l);
12704                   if (!strcmp(myrpt->cmdnode,l->name))
12705                      myrpt->cmdnode[0] = 0;
12706                   __kickshort(myrpt);
12707                   rpt_mutex_unlock(&myrpt->lock);
12708                   if (!l->hasconnected)
12709                      rpt_telemetry(myrpt,CONNFAIL,l);
12710                   else if (l->disced != 2) rpt_telemetry(myrpt,REMDISC,l);
12711                   if (myrpt->p.archivedir)
12712                   {
12713                      char str[100];
12714 
12715                      if (!l->hasconnected)
12716                         sprintf(str,"LINKFAIL,%s",l->name);
12717                      else
12718                         sprintf(str,"LINKDISC,%s",l->name);
12719                      donodelog(myrpt,str);
12720                   }
12721                   if (l->lastf1) ast_frfree(l->lastf1);
12722                   l->lastf1 = NULL;
12723                   if (l->lastf2) ast_frfree(l->lastf2);
12724                   l->lastf2 = NULL;
12725                   /* hang-up on call to device */
12726                   ast_hangup(l->chan);
12727                   ast_hangup(l->pchan);
12728                   ast_free(l);
12729                   rpt_mutex_lock(&myrpt->lock);
12730                   break;
12731                }
12732             }
12733             ast_frfree(f);
12734             rpt_mutex_lock(&myrpt->lock);
12735             break;
12736          }
12737          if (who == l->pchan) 
12738          {
12739             rpt_mutex_unlock(&myrpt->lock);
12740             f = ast_read(l->pchan);
12741             if (!f)
12742             {
12743                if (debug) printf("@@@@ rpt:Hung Up\n");
12744                toexit = 1;
12745                rpt_mutex_lock(&myrpt->lock);
12746                break;
12747             }
12748             if (f->frametype == AST_FRAME_VOICE)
12749             {
12750                if (l->chan) ast_write(l->chan,f);
12751             }
12752             if (f->frametype == AST_FRAME_CONTROL)
12753             {
12754                if (f->subclass.integer == AST_CONTROL_HANGUP)
12755                {
12756                   if (debug) printf("@@@@ rpt:Hung Up\n");
12757                   ast_frfree(f);
12758                   toexit = 1;
12759                   rpt_mutex_lock(&myrpt->lock);
12760                   break;
12761                }
12762             }
12763             ast_frfree(f);
12764             rpt_mutex_lock(&myrpt->lock);
12765             break;
12766          }
12767          l = l->next;
12768       }
12769       rpt_mutex_unlock(&myrpt->lock);
12770       if (toexit) break;
12771       if (who == myrpt->monchannel) 
12772       {
12773          f = ast_read(myrpt->monchannel);
12774          if (!f)
12775          {
12776             if (debug) printf("@@@@ rpt:Hung Up\n");
12777             break;
12778          }
12779          if (f->frametype == AST_FRAME_VOICE)
12780          {
12781             if (myrpt->monstream) 
12782                ast_writestream(myrpt->monstream,f);
12783          }
12784          if (f->frametype == AST_FRAME_CONTROL)
12785          {
12786             if (f->subclass.integer == AST_CONTROL_HANGUP)
12787             {
12788                if (debug) printf("@@@@ rpt:Hung Up\n");
12789                ast_frfree(f);
12790                break;
12791             }
12792          }
12793          ast_frfree(f);
12794          continue;
12795       }
12796       if (myrpt->parrotchannel && (who == myrpt->parrotchannel))
12797       {
12798          f = ast_read(myrpt->parrotchannel);
12799          if (!f)
12800          {
12801             if (debug) printf("@@@@ rpt:Hung Up\n");
12802             break;
12803          }
12804          if (!myrpt->p.parrotmode)
12805          {
12806             char myfname[300];
12807 
12808             if (myrpt->parrotstream)
12809             {
12810                ast_closestream(myrpt->parrotstream);
12811                myrpt->parrotstream = 0;
12812             }
12813             sprintf(myfname,PARROTFILE,myrpt->name,myrpt->parrotcnt);
12814             strcat(myfname,".wav");
12815             unlink(myfname);        
12816          } else if (f->frametype == AST_FRAME_VOICE)
12817          {
12818             if (myrpt->parrotstream) 
12819                ast_writestream(myrpt->parrotstream,f);
12820          }
12821          if (f->frametype == AST_FRAME_CONTROL)
12822          {
12823             if (f->subclass.integer == AST_CONTROL_HANGUP)
12824             {
12825                if (debug) printf("@@@@ rpt:Hung Up\n");
12826                ast_frfree(f);
12827                break;
12828             }
12829          }
12830          ast_frfree(f);
12831          continue;
12832       }
12833       if (myrpt->voxchannel && (who == myrpt->voxchannel))
12834       {
12835          f = ast_read(myrpt->voxchannel);
12836          if (!f)
12837          {
12838             if (debug) printf("@@@@ rpt:Hung Up\n");
12839             break;
12840          }
12841          if (f->frametype == AST_FRAME_VOICE)
12842          {
12843             n = dovox(&myrpt->vox,f->data.ptr,f->datalen / 2);
12844             if (n != myrpt->wasvox)
12845             {
12846                if (debug) ast_log(LOG_DEBUG,"Node %s, vox %d\n",myrpt->name,n);
12847                myrpt->wasvox = n;
12848                myrpt->voxtostate = 0;
12849                if (n) myrpt->voxtotimer = myrpt->p.voxtimeout_ms;
12850                else myrpt->voxtotimer = 0;
12851             }
12852          }
12853          if (f->frametype == AST_FRAME_CONTROL)
12854          {
12855             if (f->subclass.integer == AST_CONTROL_HANGUP)
12856             {
12857                if (debug) printf("@@@@ rpt:Hung Up\n");
12858                ast_frfree(f);
12859                break;
12860             }
12861          }
12862          ast_frfree(f);
12863          continue;
12864       }
12865       if (who == myrpt->txpchannel) /* if it was a read from remote tx */
12866       {
12867          f = ast_read(myrpt->txpchannel);
12868          if (!f)
12869          {
12870             if (debug) printf("@@@@ rpt:Hung Up\n");
12871             break;
12872          }
12873          if (f->frametype == AST_FRAME_CONTROL)
12874          {
12875             if (f->subclass.integer == AST_CONTROL_HANGUP)
12876             {
12877                if (debug) printf("@@@@ rpt:Hung Up\n");
12878                ast_frfree(f);
12879                break;
12880             }
12881          }
12882          ast_frfree(f);
12883          continue;
12884       }
12885    }
12886    usleep(100000);
12887    ast_hangup(myrpt->pchannel);
12888    ast_hangup(myrpt->monchannel);
12889    if (myrpt->parrotchannel) ast_hangup(myrpt->parrotchannel);
12890    myrpt->parrotstate = 0;
12891    if (myrpt->voxchannel) ast_hangup(myrpt->voxchannel);
12892    ast_hangup(myrpt->txpchannel);
12893    if (myrpt->txchannel != myrpt->rxchannel) ast_hangup(myrpt->txchannel);
12894    if (myrpt->dahditxchannel != myrpt->txchannel) ast_hangup(myrpt->dahditxchannel);
12895    if (myrpt->lastf1) ast_frfree(myrpt->lastf1);
12896    myrpt->lastf1 = NULL;
12897    if (myrpt->lastf2) ast_frfree(myrpt->lastf2);
12898    myrpt->lastf2 = NULL;
12899    ast_hangup(myrpt->rxchannel);
12900    rpt_mutex_lock(&myrpt->lock);
12901    l = myrpt->links.next;
12902    while(l != &myrpt->links)
12903    {
12904       struct rpt_link *ll = l;
12905       /* remove from queue */
12906       remque((struct qelem *) l);
12907       /* hang-up on call to device */
12908       if (l->chan) ast_hangup(l->chan);
12909       ast_hangup(l->pchan);
12910       l = l->next;
12911       ast_free(ll);
12912    }
12913    if (myrpt->xlink  == 1) myrpt->xlink = 2;
12914    rpt_mutex_unlock(&myrpt->lock);
12915    if (debug) printf("@@@@ rpt:Hung up channel\n");
12916    myrpt->rpt_thread = AST_PTHREADT_STOP;
12917    pthread_exit(NULL); 
12918    return NULL;
12919 }
12920 
12921    
12922 static void *rpt_master(void *ignore)
12923 {
12924 int   i,n;
12925 pthread_attr_t attr;
12926 struct ast_config *cfg;
12927 char *this,*val;
12928 
12929    /* init nodelog queue */
12930    nodelog.next = nodelog.prev = &nodelog;
12931    /* go thru all the specified repeaters */
12932    this = NULL;
12933    n = 0;
12934 #ifndef OLD_ASTERISK
12935    /* wait until asterisk starts */
12936         while(!ast_test_flag(&ast_options,AST_OPT_FLAG_FULLY_BOOTED))
12937                 usleep(250000);
12938 #endif
12939 #ifdef   NEW_ASTERISK
12940    rpt_vars[n].cfg = ast_config_load("rpt.conf",config_flags);
12941 #else
12942    rpt_vars[n].cfg = ast_config_load("rpt.conf");
12943 #endif
12944    cfg = rpt_vars[n].cfg;
12945    if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
12946       ast_log(LOG_NOTICE, "Unable to open radio repeater configuration rpt.conf.  Radio Repeater disabled.\n");
12947       pthread_exit(NULL);
12948    }
12949    while((this = ast_category_browse(cfg,this)) != NULL)
12950    {
12951       for(i = 0 ; i < strlen(this) ; i++){
12952          if((this[i] < '0') || (this[i] > '9'))
12953             break;
12954       }
12955       if(i != strlen(this)) continue; /* Not a node defn */
12956       memset(&rpt_vars[n],0,sizeof(rpt_vars[n]));
12957       rpt_vars[n].name = ast_strdup(this);
12958       val = (char *) ast_variable_retrieve(cfg,this,"rxchannel");
12959       if (val) rpt_vars[n].rxchanname = ast_strdup(val);
12960       val = (char *) ast_variable_retrieve(cfg,this,"txchannel");
12961       if (val) rpt_vars[n].txchanname = ast_strdup(val);
12962       rpt_vars[n].remote = 0;
12963       rpt_vars[n].remoterig = "";
12964       val = (char *) ast_variable_retrieve(cfg,this,"remote");
12965       if (val) 
12966       {
12967          rpt_vars[n].remoterig = ast_strdup(val);
12968          rpt_vars[n].remote = 1;
12969       }
12970       val = (char *) ast_variable_retrieve(cfg,this,"radiotype");
12971       if (val) rpt_vars[n].remoterig = ast_strdup(val);
12972       ast_mutex_init(&rpt_vars[n].lock);
12973       ast_mutex_init(&rpt_vars[n].remlock);
12974       ast_mutex_init(&rpt_vars[n].statpost_lock);
12975       rpt_vars[n].tele.next = &rpt_vars[n].tele;
12976       rpt_vars[n].tele.prev = &rpt_vars[n].tele;
12977       rpt_vars[n].rpt_thread = AST_PTHREADT_NULL;
12978       rpt_vars[n].tailmessagen = 0;
12979 #ifdef   _MDC_DECODE_H_
12980       rpt_vars[n].mdc = mdc_decoder_new(8000);
12981 #endif
12982       n++;
12983    }
12984    nrpts = n;
12985    ast_config_destroy(cfg);
12986 
12987    /* start em all */
12988    for(i = 0; i < n; i++)
12989    {
12990       load_rpt_vars(i,1);
12991 
12992       /* if is a remote, don't start one for it */
12993       if (rpt_vars[i].remote)
12994       {
12995          if(retreive_memory(&rpt_vars[i],"init")){ /* Try to retreive initial memory channel */
12996             if (!strcmp(rpt_vars[i].remoterig,remote_rig_rtx450))
12997                strncpy(rpt_vars[i].freq, "446.500", sizeof(rpt_vars[i].freq) - 1);
12998             else
12999                strncpy(rpt_vars[i].freq, "146.580", sizeof(rpt_vars[i].freq) - 1);
13000             strncpy(rpt_vars[i].rxpl, "100.0", sizeof(rpt_vars[i].rxpl) - 1);
13001 
13002             strncpy(rpt_vars[i].txpl, "100.0", sizeof(rpt_vars[i].txpl) - 1);
13003             rpt_vars[i].remmode = REM_MODE_FM;
13004             rpt_vars[i].offset = REM_SIMPLEX;
13005             rpt_vars[i].powerlevel = REM_LOWPWR;
13006          }
13007          continue;
13008       }
13009       else /* is a normal repeater */
13010       {
13011           rpt_vars[i].p.memory = rpt_vars[i].name;
13012          if(retreive_memory(&rpt_vars[i],"radiofreq")){ /* Try to retreive initial memory channel */
13013             if (!strcmp(rpt_vars[i].remoterig,remote_rig_rtx450))
13014                strncpy(rpt_vars[i].freq, "446.500", sizeof(rpt_vars[i].freq) - 1);
13015             else if (!strcmp(rpt_vars[i].remoterig,remote_rig_rtx150))
13016                strncpy(rpt_vars[i].freq, "146.580", sizeof(rpt_vars[i].freq) - 1);
13017             strncpy(rpt_vars[i].rxpl, "100.0", sizeof(rpt_vars[i].rxpl) - 1);
13018 
13019             strncpy(rpt_vars[i].txpl, "100.0", sizeof(rpt_vars[i].txpl) - 1);
13020             rpt_vars[i].remmode = REM_MODE_FM;
13021             rpt_vars[i].offset = REM_SIMPLEX;
13022             rpt_vars[i].powerlevel = REM_LOWPWR;
13023          }
13024          ast_log(LOG_NOTICE,"Normal Repeater Init  %s  %s  %s\n",rpt_vars[i].name, rpt_vars[i].remoterig, rpt_vars[i].freq);
13025       }
13026       if (!rpt_vars[i].p.ident)
13027       {
13028          ast_log(LOG_WARNING,"Did not specify ident for node %s\n",rpt_vars[i].name);
13029          ast_config_destroy(cfg);
13030          pthread_exit(NULL);
13031       }
13032            pthread_attr_init(&attr);
13033            pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13034       ast_pthread_create(&rpt_vars[i].rpt_thread,&attr,rpt,(void *) &rpt_vars[i]);
13035    }
13036    usleep(500000);
13037    time(&starttime);
13038    for(;;)
13039    {
13040       /* Now monitor each thread, and restart it if necessary */
13041       for(i = 0; i < n; i++)
13042       { 
13043          int rv;
13044          if (rpt_vars[i].remote) continue;
13045          if (rpt_vars[i].rpt_thread == AST_PTHREADT_STOP) 
13046             rv = -1;
13047          else
13048             rv = pthread_kill(rpt_vars[i].rpt_thread,0);
13049          if (rv)
13050          {
13051             if(time(NULL) - rpt_vars[i].lastthreadrestarttime <= 15)
13052             {
13053                if(rpt_vars[i].threadrestarts >= 5)
13054                {
13055                   ast_log(LOG_ERROR,"Continual RPT thread restarts, killing Asterisk\n");
13056                   exit(1); /* Stuck in a restart loop, kill Asterisk and start over */
13057                }
13058                else
13059                {
13060                   ast_log(LOG_NOTICE,"RPT thread restarted on %s\n",rpt_vars[i].name);
13061                   rpt_vars[i].threadrestarts++;
13062                }
13063             }
13064             else
13065                rpt_vars[i].threadrestarts = 0;
13066 
13067             rpt_vars[i].lastthreadrestarttime = time(NULL);
13068                  pthread_attr_init(&attr);
13069                  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13070             ast_pthread_create(&rpt_vars[i].rpt_thread,&attr,rpt,(void *) &rpt_vars[i]);
13071             /* if (!rpt_vars[i].xlink) */
13072                ast_log(LOG_WARNING, "rpt_thread restarted on node %s\n", rpt_vars[i].name);
13073          }
13074 
13075       }
13076       for(;;)
13077       {
13078          struct nodelog *nodep;
13079          char *space,datestr[100],fname[300];
13080          int fd;
13081 
13082          ast_mutex_lock(&nodeloglock);
13083          nodep = nodelog.next;
13084          if(nodep == &nodelog) /* if nothing in queue */
13085          {
13086             ast_mutex_unlock(&nodeloglock);
13087             break;
13088          }
13089          remque((struct qelem *)nodep);
13090          ast_mutex_unlock(&nodeloglock);
13091          space = strchr(nodep->str,' ');
13092          if (!space) 
13093          {
13094             ast_free(nodep);
13095             continue;
13096          }
13097          *space = 0;
13098          strftime(datestr,sizeof(datestr) - 1,"%Y%m%d",
13099             localtime(&nodep->timestamp));
13100          sprintf(fname,"%s/%s/%s.txt",nodep->archivedir,
13101             nodep->str,datestr);
13102          fd = open(fname,O_WRONLY | O_CREAT | O_APPEND,0600);
13103          if (fd == -1)
13104          {
13105             ast_log(LOG_ERROR,"Cannot open node log file %s for write",space + 1);
13106             ast_free(nodep);
13107             continue;
13108          }
13109          if (write(fd,space + 1,strlen(space + 1)) !=
13110             strlen(space + 1))
13111          {
13112             ast_log(LOG_ERROR,"Cannot write node log file %s for write",space + 1);
13113             ast_free(nodep);
13114             continue;
13115          }
13116          close(fd);
13117          ast_free(nodep);
13118       }
13119       sleep(2);
13120    }
13121    ast_config_destroy(cfg);
13122    pthread_exit(NULL);
13123 }
13124 
13125 static int rpt_exec(struct ast_channel *chan, const char *data)
13126 {
13127    int res=-1,i,rem_totx,rem_rx,remkeyed,n,phone_mode = 0;
13128    int iskenwood_pci4,authtold,authreq,setting,notremming,reming;
13129    int ismuted,dtmfed,phone_vox = 0;
13130 #ifdef   OLD_ASTERISK
13131    struct localuser *u;
13132 #endif
13133    char tmp[256], keyed = 0,keyed1 = 0;
13134    char *options,*stringp,*tele,c,*altp,*memp;
13135    char sx[320],*sy;
13136    struct   rpt *myrpt;
13137    struct ast_frame *f,*f1,*f2;
13138    struct ast_channel *who;
13139    struct ast_channel *cs[20];
13140    struct   rpt_link *l;
13141    struct dahdi_confinfo ci;  /* conference info */
13142    struct dahdi_params par;
13143    int ms,elap,nullfd;
13144    time_t t,last_timeout_warning;
13145    struct   dahdi_radio_param z;
13146    struct rpt_tele *telem;
13147    int   numlinks;
13148 
13149    nullfd = open("/dev/null",O_RDWR);
13150    if (ast_strlen_zero(data)) {
13151       ast_log(LOG_WARNING, "Rpt requires an argument (system node)\n");
13152       return -1;
13153    }
13154 
13155    strncpy(tmp, (char *)data, sizeof(tmp)-1);
13156    time(&t);
13157    /* if time has externally shifted negative, screw it */
13158    if (t < starttime) t = starttime + START_DELAY;
13159    if ((!starttime) || (t < (starttime + START_DELAY)))
13160    {
13161       ast_log(LOG_NOTICE,"Node %s rejecting call: too soon!\n",tmp);
13162       ast_safe_sleep(chan,3000);
13163       return -1;
13164    }
13165 
13166    ast_log(LOG_NOTICE,"parsing argument=%s \n",tmp);
13167 
13168    altp=strstr(tmp, "|*");
13169    if(altp){
13170       altp[0]=0;
13171       altp++;
13172     }
13173 
13174    memp=strstr(tmp, "|M");
13175    if(memp){
13176       memp[0]=0;
13177       memp+=2;
13178     }
13179 
13180    stringp=tmp;
13181    strsep(&stringp, "|");
13182    options = stringp;
13183 
13184    ast_log(LOG_NOTICE,"options=%s \n",options);
13185    if(memp>0)ast_log(LOG_NOTICE,"memp=%s \n",memp);
13186    if(altp>0)ast_log(LOG_NOTICE,"altp=%s \n",altp);
13187 
13188    myrpt = NULL;
13189    /* see if we can find our specified one */
13190    for(i = 0; i < nrpts; i++)
13191    {
13192       /* if name matches, assign it and exit loop */
13193       if (!strcmp(tmp,rpt_vars[i].name))
13194       {
13195          myrpt = &rpt_vars[i];
13196          break;
13197       }
13198    }
13199 
13200    pbx_builtin_setvar_helper(chan, "RPT_STAT_ERR", "");
13201 
13202    if (myrpt == NULL)
13203    {
13204       pbx_builtin_setvar_helper(chan, "RPT_STAT_ERR", "NODE_NOT_FOUND");
13205       ast_log(LOG_WARNING, "Cannot find specified system node %s\n",tmp);
13206       return (priority_jump(NULL,chan));
13207    }
13208 
13209    numlinks=linkcount(myrpt);
13210 
13211    if(options && *options == 'q')
13212    {
13213       char buf2[128];
13214 
13215       if(myrpt->keyed)
13216          pbx_builtin_setvar_helper(chan, "RPT_STAT_RXKEYED", "1");
13217       else
13218          pbx_builtin_setvar_helper(chan, "RPT_STAT_RXKEYED", "0");   
13219 
13220       if(myrpt->txkeyed)
13221          pbx_builtin_setvar_helper(chan, "RPT_STAT_TXKEYED", "1");
13222       else
13223          pbx_builtin_setvar_helper(chan, "RPT_STAT_TXKEYED", "0");   
13224 
13225       snprintf(buf2,sizeof(buf2),"%s=%i", "RPT_STAT_XLINK", myrpt->xlink);
13226       pbx_builtin_setvar(chan, buf2);
13227       snprintf(buf2,sizeof(buf2),"%s=%i", "RPT_STAT_LINKS", numlinks);
13228       pbx_builtin_setvar(chan, buf2);
13229       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_WASCHAN", myrpt->waschan);
13230       pbx_builtin_setvar(chan, buf2);
13231       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_NOWCHAN", myrpt->nowchan);
13232       pbx_builtin_setvar(chan, buf2);
13233       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_DUPLEX", myrpt->p.duplex);
13234       pbx_builtin_setvar(chan, buf2);
13235       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_PARROT", myrpt->p.parrotmode);
13236       pbx_builtin_setvar(chan, buf2);
13237       //snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_PHONEVOX", myrpt->phonevox);
13238       //pbx_builtin_setvar(chan, buf2);
13239       //snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_CONNECTED", myrpt->connected);
13240       //pbx_builtin_setvar(chan, buf2);
13241       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_CALLMODE", myrpt->callmode);
13242       pbx_builtin_setvar(chan, buf2);
13243       snprintf(buf2,sizeof(buf2),"%s=%s", "RPT_STAT_LASTTONE", myrpt->lasttone);
13244       pbx_builtin_setvar(chan, buf2);
13245 
13246       return priority_jump(myrpt,chan);
13247    }
13248 
13249    if(options && *options == 'o')
13250    {
13251       return(channel_revert(myrpt));
13252    }
13253 
13254    #if 0
13255    if((altp)&&(*options == 'Z'))
13256    {
13257       rpt_push_alt_macro(myrpt,altp);
13258       return 0;
13259    }
13260    #endif
13261 
13262 
13263    /* if not phone access, must be an IAX connection */
13264    if (options && ((*options == 'P') || (*options == 'D') || (*options == 'R') || (*options == 'S')))
13265    {
13266       int val;
13267 
13268       pbx_builtin_setvar_helper(chan, "RPT_STAT_BUSY", "0");
13269        
13270       myrpt->bargechan=0;
13271       if(options && strstr(options, "f")>0)
13272       {
13273          myrpt->bargechan=1;     
13274       }
13275 
13276       if(memp>0)
13277       {
13278          char radiochan;
13279          radiochan=strtod(data,NULL);
13280          // if(myrpt->nowchan!=0 && radiochan!=myrpt->nowchan && !myrpt->bargechan)
13281 
13282          if(numlinks>0 && radiochan!=myrpt->nowchan && !myrpt->bargechan)
13283          {
13284             pbx_builtin_setvar_helper(chan, "RPT_STAT_BUSY", "1");
13285             ast_log(LOG_NOTICE, "Radio Channel Busy.\n");
13286             return (priority_jump(myrpt,chan));
13287          }
13288          else if(radiochan!=myrpt->nowchan || myrpt->bargechan)
13289          {
13290             channel_steer(myrpt,memp); 
13291          }
13292       }
13293       if(altp)rpt_push_alt_macro(myrpt,altp);
13294       phone_mode = 1;
13295       if (*options == 'D') phone_mode = 2;
13296       if (*options == 'S') phone_mode = 3;
13297       ast_set_callerid(chan,"0","app_rpt user","0");
13298       val = 1;
13299       ast_channel_setoption(chan,AST_OPTION_TONE_VERIFY,&val,sizeof(char),0);
13300       if ((*(options + 1) == 'V') || (*(options + 1) == 'v')) phone_vox = 1;
13301    }
13302    else
13303    {
13304 #ifdef ALLOW_LOCAL_CHANNELS
13305            /* Check to insure the connection is IAX2 or Local*/
13306            if ( (strncmp(chan->name,"IAX2",4)) && (strncmp(chan->name,"Local",5)) ) {
13307                ast_log(LOG_WARNING, "We only accept links via IAX2 or Local!!\n");
13308                return -1;
13309            }
13310 #else
13311       if (strncmp(chan->name,"IAX2",4))
13312       {
13313          ast_log(LOG_WARNING, "We only accept links via IAX2!!\n");
13314          return -1;
13315       }
13316 #endif
13317            if(myrpt->p.s[myrpt->p.sysstate_cur].txdisable){ /* Do not allow incoming radio connections if disabled */
13318                  ast_log(LOG_NOTICE, "Connect attempt to node %s  with tx disabled", myrpt->name);
13319                   return -1;
13320          }  
13321    }
13322    if (options && (*options == 'R'))
13323    {
13324       /* Parts of this section taken from app_parkandannounce */
13325       char *return_context;
13326       int length, m, lot, timeout = 0;
13327       char buffer[256],*template;
13328       char *working, *context, *exten, *priority;
13329       char *s,*orig_s;
13330 
13331       rpt_mutex_lock(&myrpt->lock);
13332       m = myrpt->callmode;
13333       rpt_mutex_unlock(&myrpt->lock);
13334 
13335       if ((!myrpt->p.nobusyout) && m)
13336       {
13337          if (chan->_state != AST_STATE_UP)
13338          {
13339             ast_indicate(chan,AST_CONTROL_BUSY);
13340          }
13341          while(ast_safe_sleep(chan,10000) != -1);
13342          return -1;
13343       }
13344 
13345       if (chan->_state != AST_STATE_UP)
13346       {
13347          ast_answer(chan);
13348          if (!phone_mode) send_newkey(chan);
13349       }
13350 
13351       length=strlen(options)+2;
13352       orig_s=ast_malloc(length);
13353       if(!orig_s) {
13354          ast_log(LOG_WARNING, "Out of memory\n");
13355          return -1;
13356       }
13357       s=orig_s;
13358       strncpy(s,options,length);
13359 
13360       template=strsep(&s,"|");
13361       if(!template) {
13362          ast_log(LOG_WARNING, "An announce template must be defined\n");
13363          ast_free(orig_s);
13364          return -1;
13365       } 
13366   
13367       if(s) {
13368          timeout = atoi(strsep(&s, "|"));
13369          timeout *= 1000;
13370       }
13371    
13372       return_context = s;
13373   
13374       if(return_context != NULL) {
13375          /* set the return context. Code borrowed from the Goto builtin */
13376     
13377          working = return_context;
13378          context = strsep(&working, "|");
13379          exten = strsep(&working, "|");
13380          if(!exten) {
13381             /* Only a priority in this one */
13382             priority = context;
13383             exten = NULL;
13384             context = NULL;
13385          } else {
13386             priority = strsep(&working, "|");
13387             if(!priority) {
13388                /* Only an extension and priority in this one */
13389                priority = exten;
13390                exten = context;
13391                context = NULL;
13392          }
13393       }
13394       if(atoi(priority) < 0) {
13395          ast_log(LOG_WARNING, "Priority '%s' must be a number > 0\n", priority);
13396          ast_free(orig_s);
13397          return -1;
13398       }
13399       /* At this point we have a priority and maybe an extension and a context */
13400       chan->priority = atoi(priority);
13401 #ifdef OLD_ASTERISK
13402       if(exten && strcasecmp(exten, "BYEXTENSION"))
13403 #else
13404       if(exten)
13405 #endif
13406          strncpy(chan->exten, exten, sizeof(chan->exten)-1);
13407       if(context)
13408          strncpy(chan->context, context, sizeof(chan->context)-1);
13409       } else {  /* increment the priority by default*/
13410          chan->priority++;
13411       }
13412 
13413       if(option_verbose > 2) {
13414          ast_verbose(VERBOSE_PREFIX_3 "Return Context: (%s,%s,%d) ID: %s\n",
13415             chan->context, chan->exten, chan->priority,
13416             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, ""));
13417          if(!ast_exists_extension(chan, chan->context, chan->exten, chan->priority,
13418             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
13419             ast_verbose( VERBOSE_PREFIX_3 "Warning: Return Context Invalid, call will return to default|s\n");
13420          }
13421       }
13422   
13423       /* we are using masq_park here to protect * from touching the channel once we park it.  If the channel comes out of timeout
13424       before we are done announcing and the channel is messed with, Kablooeee.  So we use Masq to prevent this.  */
13425 
13426       ast_masq_park_call(chan, NULL, timeout, &lot);
13427 
13428       if (option_verbose > 2) ast_verbose( VERBOSE_PREFIX_3 "Call Parking Called, lot: %d, timeout: %d, context: %s\n", lot, timeout, return_context);
13429 
13430       snprintf(buffer, sizeof(buffer) - 1, "%d,%s", lot, template + 1);
13431 
13432       rpt_telemetry(myrpt,REV_PATCH,buffer);
13433 
13434       ast_free(orig_s);
13435 
13436       return 0;
13437 
13438    }
13439 
13440    if (!options)
13441    {
13442         struct ast_hostent ahp;
13443         struct hostent *hp;
13444         struct in_addr ia;
13445         char hisip[100],nodeip[100],*val, *s, *s1, *s2, *s3, *b,*b1;
13446 
13447       /* look at callerid to see what node this comes from */
13448       b = S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL);
13449       if (!b) /* if doesn't have caller id */
13450       {
13451          ast_log(LOG_WARNING, "Does not have callerid on %s\n",tmp);
13452          return -1;
13453       }
13454       /* get his IP from IAX2 module */
13455       memset(hisip,0,sizeof(hisip));
13456 #ifdef ALLOW_LOCAL_CHANNELS
13457         /* set IP address if this is a local connection*/
13458         if (strncmp(chan->name,"Local",5)==0) {
13459             strcpy(hisip,"127.0.0.1");
13460         } else {
13461          pbx_substitute_variables_helper(chan,"${IAXPEER(CURRENTCHANNEL)}",hisip,sizeof(hisip) - 1);
13462       }
13463 #else
13464       pbx_substitute_variables_helper(chan,"${IAXPEER(CURRENTCHANNEL)}",hisip,sizeof(hisip) - 1);
13465 #endif
13466 
13467       if (!hisip[0])
13468       {
13469          ast_log(LOG_WARNING, "Link IP address cannot be determined!!\n");
13470          return -1;
13471       }
13472       
13473       b1 = ast_strdupa(b);
13474       ast_shrink_phone_number(b1);
13475       if (!strcmp(myrpt->name,b1))
13476       {
13477          ast_log(LOG_WARNING, "Trying to link to self!!\n");
13478          return -1;
13479       }
13480 
13481       if (*b1 < '1')
13482       {
13483          ast_log(LOG_WARNING, "Node %s Invalid for connection here!!\n",b1);
13484          return -1;
13485       }
13486 
13487 
13488       /* look for his reported node string */
13489       val = node_lookup(myrpt,b1);
13490       if (!val)
13491       {
13492          ast_log(LOG_WARNING, "Reported node %s cannot be found!!\n",b1);
13493          return -1;
13494       }
13495       strncpy(tmp,val,sizeof(tmp) - 1);
13496       s = tmp;
13497       s1 = strsep(&s,",");
13498       if (!strchr(s1,':') && strchr(s1,'/') && strncasecmp(s1, "local/", 6))
13499       {
13500          sy = strchr(s1,'/');    
13501          *sy = 0;
13502          sprintf(sx,"%s:4569/%s",s1,sy + 1);
13503          s1 = sx;
13504       }
13505       s2 = strsep(&s,",");
13506       if (!s2)
13507       {
13508          ast_log(LOG_WARNING, "Reported node %s not in correct format!!\n",b1);
13509          return -1;
13510       }
13511                 if (strcmp(s2,"NONE")) {
13512          hp = ast_gethostbyname(s2, &ahp);
13513          if (!hp)
13514          {
13515             ast_log(LOG_WARNING, "Reported node %s, name %s cannot be found!!\n",b1,s2);
13516             return -1;
13517          }
13518          memcpy(&ia,hp->h_addr,sizeof(in_addr_t));
13519 #ifdef   OLD_ASTERISK
13520          ast_inet_ntoa(nodeip,sizeof(nodeip) - 1,ia);
13521 #else
13522          strncpy(nodeip,ast_inet_ntoa(ia),sizeof(nodeip) - 1);
13523 #endif
13524          s3 = strchr(hisip,':');
13525          if (s3) *s3 = 0;
13526          if (strcmp(hisip,nodeip))
13527          {
13528             s3 = strchr(s1,'@');
13529             if (s3) s1 = s3 + 1;
13530             s3 = strchr(s1,'/');
13531             if (s3) *s3 = 0;
13532             s3 = strchr(s1,':');
13533             if (s3) *s3 = 0;
13534             hp = ast_gethostbyname(s1, &ahp);
13535             if (!hp)
13536             {
13537                ast_log(LOG_WARNING, "Reported node %s, name %s cannot be found!!\n",b1,s1);
13538                return -1;
13539             }
13540             memcpy(&ia,hp->h_addr,sizeof(in_addr_t));
13541 #ifdef   OLD_ASTERISK
13542             ast_inet_ntoa(nodeip,sizeof(nodeip) - 1,ia);
13543 #else
13544             strncpy(nodeip,ast_inet_ntoa(ia),sizeof(nodeip) - 1);
13545 #endif
13546             if (strcmp(hisip,nodeip))
13547             {
13548                ast_log(LOG_WARNING, "Node %s IP %s does not match link IP %s!!\n",b1,nodeip,hisip);
13549                return -1;
13550             }
13551          }
13552       }
13553    }
13554 
13555    /* if is not a remote */
13556    if (!myrpt->remote)
13557    {
13558       char *b,*b1;
13559       int reconnects = 0;
13560 
13561       rpt_mutex_lock(&myrpt->lock);
13562       i = myrpt->xlink;
13563       rpt_mutex_unlock(&myrpt->lock);
13564       if (i)
13565       {
13566          ast_log(LOG_WARNING, "Cannot connect to node %s, system busy\n",myrpt->name);
13567          return -1;
13568       }
13569       /* look at callerid to see what node this comes from */
13570       b = S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL);
13571       if (!b) /* if doesn't have caller id */
13572       {
13573          ast_log(LOG_WARNING, "Doesnt have callerid on %s\n",tmp);
13574          return -1;
13575       }
13576 
13577       b1 = ast_strdupa(b);
13578       ast_shrink_phone_number(b1);
13579       if (!strcmp(myrpt->name,b1))
13580       {
13581          ast_log(LOG_WARNING, "Trying to link to self!!\n");
13582          return -1;
13583       }
13584       rpt_mutex_lock(&myrpt->lock);
13585       l = myrpt->links.next;
13586       /* try to find this one in queue */
13587       while(l != &myrpt->links)
13588       {
13589          if (l->name[0] == '0') 
13590          {
13591             l = l->next;
13592             continue;
13593          }
13594          /* if found matching string */
13595          if (!strcmp(l->name,b1)) break;
13596          l = l->next;
13597       }
13598       /* if found */
13599       if (l != &myrpt->links) 
13600       {
13601          l->killme = 1;
13602          l->retries = l->max_retries + 1;
13603          l->disced = 2;
13604          reconnects = l->reconnects;
13605          reconnects++;
13606                         rpt_mutex_unlock(&myrpt->lock);
13607          usleep(500000);   
13608       } else 
13609          rpt_mutex_unlock(&myrpt->lock);
13610       /* establish call in tranceive mode */
13611       l = ast_malloc(sizeof(struct rpt_link));
13612       if (!l)
13613       {
13614          ast_log(LOG_WARNING, "Unable to malloc\n");
13615          pthread_exit(NULL);
13616       }
13617       /* zero the silly thing */
13618       memset((char *)l,0,sizeof(struct rpt_link));
13619       l->mode = 1;
13620       strncpy(l->name,b1,MAXNODESTR - 1);
13621       l->isremote = 0;
13622       l->chan = chan;
13623       l->connected = 1;
13624       l->thisconnected = 1;
13625       l->hasconnected = 1;
13626       l->reconnects = reconnects;
13627       l->phonemode = phone_mode;
13628       l->phonevox = phone_vox;
13629       l->lastf1 = NULL;
13630       l->lastf2 = NULL;
13631       l->dtmfed = 0;
13632       voxinit_link(l,1);
13633       ast_set_read_format(l->chan,AST_FORMAT_SLINEAR);
13634       ast_set_write_format(l->chan,AST_FORMAT_SLINEAR);
13635       /* allocate a pseudo-channel thru asterisk */
13636       l->pchan = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
13637       if (!l->pchan)
13638       {
13639          fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
13640          pthread_exit(NULL);
13641       }
13642       ast_set_read_format(l->pchan,AST_FORMAT_SLINEAR);
13643       ast_set_write_format(l->pchan,AST_FORMAT_SLINEAR);
13644 #ifdef   AST_CDR_FLAG_POST_DISABLED
13645       if (l->pchan->cdr)
13646          ast_set_flag(l->pchan->cdr,AST_CDR_FLAG_POST_DISABLED);
13647 #endif
13648       /* make a conference for the tx */
13649       ci.chan = 0;
13650       ci.confno = myrpt->conf;
13651       ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER;
13652       /* first put the channel on the conference in proper mode */
13653       if (ioctl(l->pchan->fds[0],DAHDI_SETCONF,&ci) == -1)
13654       {
13655          ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
13656          pthread_exit(NULL);
13657       }
13658       rpt_mutex_lock(&myrpt->lock);
13659       if ((phone_mode == 2) && (!phone_vox)) l->lastrealrx = 1;
13660       l->max_retries = MAX_RETRIES;
13661       /* insert at end of queue */
13662       insque((struct qelem *)l,(struct qelem *)myrpt->links.next);
13663       __kickshort(myrpt);
13664       rpt_mutex_unlock(&myrpt->lock);
13665       if (chan->_state != AST_STATE_UP) {
13666          ast_answer(chan);
13667          if (!phone_mode) send_newkey(chan);
13668       }
13669       if (myrpt->p.archivedir)
13670       {
13671          char str[100];
13672 
13673          if (l->phonemode)
13674             sprintf(str,"LINK(P),%s",l->name);
13675          else
13676             sprintf(str,"LINK,%s",l->name);
13677          donodelog(myrpt,str);
13678       }
13679       if (!phone_mode) send_newkey(chan);
13680       return 0;
13681    }
13682    /* well, then it is a remote */
13683    rpt_mutex_lock(&myrpt->lock);
13684    /* if remote, error if anyone else already linked */
13685    if (myrpt->remoteon)
13686    {
13687       rpt_mutex_unlock(&myrpt->lock);
13688       usleep(500000);
13689       if (myrpt->remoteon)
13690       {
13691          ast_log(LOG_WARNING, "Trying to use busy link on %s\n",tmp);
13692 #ifdef   AST_CDR_FLAG_POST_DISABLED
13693          if (chan->cdr)
13694             ast_set_flag(chan->cdr,AST_CDR_FLAG_POST_DISABLED);
13695 #endif
13696          return -1;
13697       }     
13698       rpt_mutex_lock(&myrpt->lock);
13699    }
13700    if (myrpt->p.rptnode)
13701    {
13702       char killedit = 0;
13703       time_t now;
13704 
13705       time(&now);
13706       for(i = 0; i < nrpts; i++)
13707       {
13708          if (!strcasecmp(rpt_vars[i].name,myrpt->p.rptnode))
13709          {
13710             if ((rpt_vars[i].links.next != &rpt_vars[i].links) ||
13711                rpt_vars[i].keyed ||
13712                 ((rpt_vars[i].lastkeyedtime + RPT_LOCKOUT_SECS) > now) ||
13713                  rpt_vars[i].txkeyed ||
13714                   ((rpt_vars[i].lasttxkeyedtime + RPT_LOCKOUT_SECS) > now))
13715             {
13716                rpt_mutex_unlock(&myrpt->lock);
13717                ast_log(LOG_WARNING, "Trying to use busy link (repeater node %s) on %s\n",rpt_vars[i].name,tmp);
13718 #ifdef   AST_CDR_FLAG_POST_DISABLED
13719                if (chan->cdr)
13720                   ast_set_flag(chan->cdr,AST_CDR_FLAG_POST_DISABLED);
13721 #endif
13722                return -1;
13723             }
13724             while(rpt_vars[i].xlink != 3)
13725             {
13726                if (!killedit)
13727                {
13728                   ast_softhangup(rpt_vars[i].rxchannel,AST_SOFTHANGUP_DEV);
13729                   rpt_vars[i].xlink = 1;
13730                   killedit = 1;
13731                }
13732                rpt_mutex_unlock(&myrpt->lock);
13733                if (ast_safe_sleep(chan,500) == -1)
13734                {
13735 #ifdef   AST_CDR_FLAG_POST_DISABLED
13736                   if (chan->cdr)
13737                      ast_set_flag(chan->cdr,AST_CDR_FLAG_POST_DISABLED);
13738 #endif
13739                   return -1;
13740                }
13741                rpt_mutex_lock(&myrpt->lock);
13742             }
13743             break;
13744          }
13745       }
13746    }
13747 
13748 #ifdef HAVE_IOPERM
13749    if ( (!strcmp(myrpt->remoterig, remote_rig_rbi)||!strcmp(myrpt->remoterig, remote_rig_ppp16)) &&
13750      (ioperm(myrpt->p.iobase,1,1) == -1))
13751    {
13752       rpt_mutex_unlock(&myrpt->lock);
13753       ast_log(LOG_WARNING, "Can't get io permission on IO port %x hex\n",myrpt->p.iobase);
13754       return -1;
13755    }
13756 #endif
13757    myrpt->remoteon = 1;
13758 #ifdef   OLD_ASTERISK
13759    LOCAL_USER_ADD(u);
13760 #endif
13761    rpt_mutex_unlock(&myrpt->lock);
13762    /* find our index, and load the vars initially */
13763    for(i = 0; i < nrpts; i++)
13764    {
13765       if (&rpt_vars[i] == myrpt)
13766       {
13767          load_rpt_vars(i,0);
13768          break;
13769       }
13770    }
13771    rpt_mutex_lock(&myrpt->lock);
13772    tele = strchr(myrpt->rxchanname,'/');
13773    if (!tele)
13774    {
13775       fprintf(stderr,"rpt:Dial number must be in format tech/number\n");
13776       rpt_mutex_unlock(&myrpt->lock);
13777       pthread_exit(NULL);
13778    }
13779    *tele++ = 0;
13780    myrpt->rxchannel = ast_request(myrpt->rxchanname, AST_FORMAT_SLINEAR, NULL, tele, NULL);
13781    myrpt->dahdirxchannel = NULL;
13782    if (!strcasecmp(myrpt->rxchanname,"DAHDI"))
13783       myrpt->dahdirxchannel = myrpt->rxchannel;
13784    if (myrpt->rxchannel)
13785    {
13786       ast_set_read_format(myrpt->rxchannel,AST_FORMAT_SLINEAR);
13787       ast_set_write_format(myrpt->rxchannel,AST_FORMAT_SLINEAR);
13788 #ifdef   AST_CDR_FLAG_POST_DISABLED
13789       if (myrpt->rxchannel->cdr)
13790          ast_set_flag(myrpt->rxchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
13791 #endif
13792 #ifndef  NEW_ASTERISK
13793       myrpt->rxchannel->whentohangup = 0;
13794 #endif
13795       myrpt->rxchannel->appl = "Apprpt";
13796       myrpt->rxchannel->data = "(Link Rx)";
13797       if (option_verbose > 2)
13798          ast_verbose(VERBOSE_PREFIX_3 "rpt (Rx) initiating call to %s/%s on %s\n",
13799             myrpt->rxchanname,tele,myrpt->rxchannel->name);
13800       rpt_mutex_unlock(&myrpt->lock);
13801       ast_call(myrpt->rxchannel,tele,999);
13802       rpt_mutex_lock(&myrpt->lock);
13803    }
13804    else
13805    {
13806       fprintf(stderr,"rpt:Sorry unable to obtain Rx channel\n");
13807       rpt_mutex_unlock(&myrpt->lock);
13808       pthread_exit(NULL);
13809    }
13810    *--tele = '/';
13811    myrpt->dahditxchannel = NULL;
13812    if (myrpt->txchanname)
13813    {
13814       tele = strchr(myrpt->txchanname,'/');
13815       if (!tele)
13816       {
13817          fprintf(stderr,"rpt:Dial number must be in format tech/number\n");
13818          rpt_mutex_unlock(&myrpt->lock);
13819          ast_hangup(myrpt->rxchannel);
13820          pthread_exit(NULL);
13821       }
13822       *tele++ = 0;
13823       myrpt->txchannel = ast_request(myrpt->txchanname, AST_FORMAT_SLINEAR, NULL, tele, NULL);
13824       if (!strncasecmp(myrpt->txchanname,"DAHDI",3))
13825          myrpt->dahditxchannel = myrpt->txchannel;
13826       if (myrpt->txchannel)
13827       {
13828          ast_set_read_format(myrpt->txchannel,AST_FORMAT_SLINEAR);
13829          ast_set_write_format(myrpt->txchannel,AST_FORMAT_SLINEAR);
13830 #ifdef   AST_CDR_FLAG_POST_DISABLED
13831          if (myrpt->txchannel->cdr)
13832             ast_set_flag(myrpt->txchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
13833 #endif
13834 #ifndef  NEW_ASTERISK
13835          myrpt->txchannel->whentohangup = 0;
13836 #endif
13837          myrpt->txchannel->appl = "Apprpt";
13838          myrpt->txchannel->data = "(Link Tx)";
13839          if (option_verbose > 2)
13840             ast_verbose(VERBOSE_PREFIX_3 "rpt (Tx) initiating call to %s/%s on %s\n",
13841                myrpt->txchanname,tele,myrpt->txchannel->name);
13842          rpt_mutex_unlock(&myrpt->lock);
13843          ast_call(myrpt->txchannel,tele,999);
13844          rpt_mutex_lock(&myrpt->lock);
13845       }
13846       else
13847       {
13848          fprintf(stderr,"rpt:Sorry unable to obtain Tx channel\n");
13849          rpt_mutex_unlock(&myrpt->lock);
13850          ast_hangup(myrpt->rxchannel);
13851          pthread_exit(NULL);
13852       }
13853       *--tele = '/';
13854    }
13855    else
13856    {
13857       myrpt->txchannel = myrpt->rxchannel;
13858       if (!strncasecmp(myrpt->rxchanname,"DAHDI",3))
13859          myrpt->dahditxchannel = myrpt->rxchannel;
13860    }
13861    /* allocate a pseudo-channel thru asterisk */
13862    myrpt->pchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
13863    if (!myrpt->pchannel)
13864    {
13865       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
13866       rpt_mutex_unlock(&myrpt->lock);
13867       if (myrpt->txchannel != myrpt->rxchannel) 
13868          ast_hangup(myrpt->txchannel);
13869       ast_hangup(myrpt->rxchannel);
13870       pthread_exit(NULL);
13871    }
13872    ast_set_read_format(myrpt->pchannel,AST_FORMAT_SLINEAR);
13873    ast_set_write_format(myrpt->pchannel,AST_FORMAT_SLINEAR);
13874 #ifdef   AST_CDR_FLAG_POST_DISABLED
13875    if (myrpt->pchannel->cdr)
13876       ast_set_flag(myrpt->pchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
13877 #endif
13878    if (!myrpt->dahdirxchannel) myrpt->dahdirxchannel = myrpt->pchannel;
13879    if (!myrpt->dahditxchannel) myrpt->dahditxchannel = myrpt->pchannel;
13880    /* make a conference for the pseudo */
13881    ci.chan = 0;
13882    ci.confno = -1; /* make a new conf */
13883    ci.confmode = DAHDI_CONF_CONFANNMON ;
13884    /* first put the channel on the conference in announce/monitor mode */
13885    if (ioctl(myrpt->pchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
13886    {
13887       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
13888       rpt_mutex_unlock(&myrpt->lock);
13889       ast_hangup(myrpt->pchannel);
13890       if (myrpt->txchannel != myrpt->rxchannel) 
13891          ast_hangup(myrpt->txchannel);
13892       ast_hangup(myrpt->rxchannel);
13893       pthread_exit(NULL);
13894    }
13895    /* save pseudo channel conference number */
13896    myrpt->conf = myrpt->txconf = ci.confno;
13897    /* if serial io port, open it */
13898    myrpt->iofd = -1;
13899    if (myrpt->p.ioport && ((myrpt->iofd = openserial(myrpt,myrpt->p.ioport)) == -1))
13900    {
13901       rpt_mutex_unlock(&myrpt->lock);
13902       ast_hangup(myrpt->pchannel);
13903       if (myrpt->txchannel != myrpt->rxchannel) 
13904          ast_hangup(myrpt->txchannel);
13905       ast_hangup(myrpt->rxchannel);
13906       pthread_exit(NULL);
13907    }
13908    iskenwood_pci4 = 0;
13909    memset(&z,0,sizeof(z));
13910    if ((myrpt->iofd < 1) && (myrpt->txchannel == myrpt->dahditxchannel))
13911    {
13912       z.radpar = DAHDI_RADPAR_REMMODE;
13913       z.data = DAHDI_RADPAR_REM_NONE;
13914       res = ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z);
13915       /* if PCIRADIO and kenwood selected */
13916       if ((!res) && (!strcmp(myrpt->remoterig,remote_rig_kenwood)))
13917       {
13918          z.radpar = DAHDI_RADPAR_UIOMODE;
13919          z.data = 1;
13920          if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
13921          {
13922             ast_log(LOG_ERROR,"Cannot set UIOMODE\n");
13923             return -1;
13924          }
13925          z.radpar = DAHDI_RADPAR_UIODATA;
13926          z.data = 3;
13927          if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
13928          {
13929             ast_log(LOG_ERROR,"Cannot set UIODATA\n");
13930             return -1;
13931          }
13932          i = DAHDI_OFFHOOK;
13933          if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_HOOK,&i) == -1)
13934          {
13935             ast_log(LOG_ERROR,"Cannot set hook\n");
13936             return -1;
13937          }
13938          iskenwood_pci4 = 1;
13939       }
13940    }
13941    if (myrpt->txchannel == myrpt->dahditxchannel)
13942    {
13943       i = DAHDI_ONHOOK;
13944       ioctl(myrpt->dahditxchannel->fds[0],DAHDI_HOOK,&i);
13945       /* if PCIRADIO and Yaesu ft897/ICOM IC-706 selected */
13946       if ((myrpt->iofd < 1) && (!res) &&
13947          ((!strcmp(myrpt->remoterig,remote_rig_ft897)) ||
13948             (!strcmp(myrpt->remoterig,remote_rig_ic706)) ||
13949                (!strcmp(myrpt->remoterig,remote_rig_tm271))))
13950       {
13951          z.radpar = DAHDI_RADPAR_UIOMODE;
13952          z.data = 1;
13953          if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
13954          {
13955             ast_log(LOG_ERROR,"Cannot set UIOMODE\n");
13956             return -1;
13957          }
13958          z.radpar = DAHDI_RADPAR_UIODATA;
13959          z.data = 3;
13960          if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
13961          {
13962             ast_log(LOG_ERROR,"Cannot set UIODATA\n");
13963             return -1;
13964          }
13965       }
13966    }
13967    myrpt->remoterx = 0;
13968    myrpt->remotetx = 0;
13969    myrpt->retxtimer = 0;
13970    myrpt->rerxtimer = 0;
13971    myrpt->remoteon = 1;
13972    myrpt->dtmfidx = -1;
13973    myrpt->dtmfbuf[0] = 0;
13974    myrpt->dtmf_time_rem = 0;
13975    myrpt->hfscanmode = 0;
13976    myrpt->hfscanstatus = 0;
13977    if (myrpt->p.startupmacro)
13978    {
13979       snprintf(myrpt->macrobuf,MAXMACRO - 1,"PPPP%s",myrpt->p.startupmacro);
13980    }
13981    time(&myrpt->start_time);
13982    myrpt->last_activity_time = myrpt->start_time;
13983    last_timeout_warning = 0;
13984    myrpt->reload = 0;
13985    myrpt->tele.next = &myrpt->tele;
13986    myrpt->tele.prev = &myrpt->tele;
13987    myrpt->newkey = 0;
13988    rpt_mutex_unlock(&myrpt->lock);
13989    ast_set_write_format(chan, AST_FORMAT_SLINEAR);
13990    ast_set_read_format(chan, AST_FORMAT_SLINEAR);
13991    rem_rx = 0;
13992    remkeyed = 0;
13993    /* if we are on 2w loop and are a remote, turn EC on */
13994    if (myrpt->remote && (myrpt->rxchannel == myrpt->txchannel))
13995    {
13996       i = 128;
13997       ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_ECHOCANCEL,&i);
13998    }
13999    if (chan->_state != AST_STATE_UP) {
14000       ast_answer(chan);
14001       if (!phone_mode) send_newkey(chan);
14002    }
14003 
14004    if (myrpt->rxchannel == myrpt->dahdirxchannel)
14005    {
14006       if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_GET_PARAMS,&par) != -1)
14007       {
14008          if (par.rxisoffhook)
14009          {
14010             ast_indicate(chan,AST_CONTROL_RADIO_KEY);
14011             myrpt->remoterx = 1;
14012             remkeyed = 1;
14013          }
14014       }
14015    }
14016    if (myrpt->p.archivedir)
14017    {
14018       char mycmd[100],mydate[100],*b,*b1;
14019       time_t myt;
14020       long blocksleft;
14021 
14022 
14023       mkdir(myrpt->p.archivedir,0600);
14024       sprintf(mycmd,"%s/%s",myrpt->p.archivedir,myrpt->name);
14025       mkdir(mycmd,0600);
14026       time(&myt);
14027       strftime(mydate,sizeof(mydate) - 1,"%Y%m%d%H%M%S",
14028          localtime(&myt));
14029       sprintf(mycmd,"mixmonitor start %s %s/%s/%s.wav49 a",chan->name,
14030          myrpt->p.archivedir,myrpt->name,mydate);
14031       if (myrpt->p.monminblocks)
14032       {
14033          blocksleft = diskavail(myrpt);
14034          if (myrpt->p.remotetimeout)
14035          {
14036             blocksleft -= (myrpt->p.remotetimeout *
14037                MONITOR_DISK_BLOCKS_PER_MINUTE) / 60;
14038          }
14039          if (blocksleft >= myrpt->p.monminblocks)
14040             ast_cli_command(nullfd,mycmd);
14041       } else ast_cli_command(nullfd,mycmd);
14042       /* look at callerid to see what node this comes from */
14043       b = S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL);
14044       if (!b) /* if doesn't have caller id */
14045       {
14046          b1 = "0";
14047       } else {
14048          b1 = ast_strdupa(b);
14049          ast_shrink_phone_number(b1);
14050       }
14051       sprintf(mycmd,"CONNECT,%s",b1);
14052       donodelog(myrpt,mycmd);
14053    }
14054    myrpt->loginuser[0] = 0;
14055    myrpt->loginlevel[0] = 0;
14056    myrpt->authtelltimer = 0;
14057    myrpt->authtimer = 0;
14058    authtold = 0;
14059    authreq = 0;
14060    if (myrpt->p.authlevel > 1) authreq = 1;
14061    setrem(myrpt); 
14062    n = 0;
14063    dtmfed = 0;
14064    cs[n++] = chan;
14065    cs[n++] = myrpt->rxchannel;
14066    cs[n++] = myrpt->pchannel;
14067    if (myrpt->rxchannel != myrpt->txchannel)
14068       cs[n++] = myrpt->txchannel;
14069    if (!phone_mode) send_newkey(chan);
14070    /* start un-locked */
14071    for(;;) 
14072    {
14073       if (ast_check_hangup(chan)) break;
14074       if (ast_check_hangup(myrpt->rxchannel)) break;
14075       notremming = 0;
14076       setting = 0;
14077       reming = 0;
14078       telem = myrpt->tele.next;
14079       while(telem != &myrpt->tele)
14080       {
14081          if (telem->mode == SETREMOTE) setting = 1;
14082          if ((telem->mode == SETREMOTE) ||
14083              (telem->mode == SCAN) ||
14084             (telem->mode == TUNE))  reming = 1;
14085          else notremming = 1;
14086          telem = telem->next;
14087       }
14088       if (myrpt->reload)
14089       {
14090          myrpt->reload = 0;
14091          /* find our index, and load the vars */
14092          for(i = 0; i < nrpts; i++)
14093          {
14094             if (&rpt_vars[i] == myrpt)
14095             {
14096                load_rpt_vars(i,0);
14097                break;
14098             }
14099          }
14100       }
14101       time(&t);
14102       if (myrpt->p.remotetimeout)
14103       { 
14104          time_t r;
14105 
14106          r = (t - myrpt->start_time);
14107          if (r >= myrpt->p.remotetimeout)
14108          {
14109             saynode(myrpt,chan,myrpt->name);
14110             sayfile(chan,"rpt/timeout");
14111             ast_safe_sleep(chan,1000);
14112             break;
14113          }
14114          if ((myrpt->p.remotetimeoutwarning) && 
14115              (r >= (myrpt->p.remotetimeout -
14116             myrpt->p.remotetimeoutwarning)) &&
14117                 (r <= (myrpt->p.remotetimeout - 
14118                   myrpt->p.remotetimeoutwarningfreq)))
14119          {
14120             if (myrpt->p.remotetimeoutwarningfreq)
14121             {
14122                 if ((t - last_timeout_warning) >=
14123                myrpt->p.remotetimeoutwarningfreq)
14124                 {
14125                time(&last_timeout_warning);
14126                rpt_telemetry(myrpt,TIMEOUT_WARNING,0);
14127                 }
14128             }
14129             else
14130             {
14131                 if (!last_timeout_warning)
14132                 {
14133                time(&last_timeout_warning);
14134                rpt_telemetry(myrpt,TIMEOUT_WARNING,0);
14135                 }
14136             }
14137          }
14138       }
14139       if (myrpt->p.remoteinacttimeout && myrpt->last_activity_time)
14140       { 
14141          time_t r;
14142 
14143          r = (t - myrpt->last_activity_time);
14144          if (r >= myrpt->p.remoteinacttimeout)
14145          {
14146             saynode(myrpt,chan,myrpt->name);
14147             ast_safe_sleep(chan,1000);
14148             break;
14149          }
14150          if ((myrpt->p.remotetimeoutwarning) && 
14151              (r >= (myrpt->p.remoteinacttimeout -
14152             myrpt->p.remotetimeoutwarning)) &&
14153                 (r <= (myrpt->p.remoteinacttimeout - 
14154                   myrpt->p.remotetimeoutwarningfreq)))
14155          {
14156             if (myrpt->p.remotetimeoutwarningfreq)
14157             {
14158                 if ((t - last_timeout_warning) >=
14159                myrpt->p.remotetimeoutwarningfreq)
14160                 {
14161                time(&last_timeout_warning);
14162                rpt_telemetry(myrpt,ACT_TIMEOUT_WARNING,0);
14163                 }
14164             }
14165             else
14166             {
14167                 if (!last_timeout_warning)
14168                 {
14169                time(&last_timeout_warning);
14170                rpt_telemetry(myrpt,ACT_TIMEOUT_WARNING,0);
14171                 }
14172             }
14173          }
14174       }
14175       ms = MSWAIT;
14176       who = ast_waitfor_n(cs,n,&ms);
14177       if (who == NULL) ms = 0;
14178       elap = MSWAIT - ms;
14179       if (myrpt->macrotimer) myrpt->macrotimer -= elap;
14180       if (myrpt->macrotimer < 0) myrpt->macrotimer = 0;
14181       if (!ms) continue;
14182       /* do local dtmf timer */
14183       if (myrpt->dtmf_local_timer)
14184       {
14185          if (myrpt->dtmf_local_timer > 1) myrpt->dtmf_local_timer -= elap;
14186          if (myrpt->dtmf_local_timer < 1) myrpt->dtmf_local_timer = 1;
14187       }
14188       rpt_mutex_lock(&myrpt->lock);
14189       do_dtmf_local(myrpt,0);
14190       rpt_mutex_unlock(&myrpt->lock);
14191       //
14192       rem_totx =  myrpt->dtmf_local_timer && (!phone_mode);
14193       rem_totx |= keyed && (!myrpt->tunerequest);
14194       rem_rx = (remkeyed && (!setting)) || (myrpt->tele.next != &myrpt->tele);
14195       if(!strcmp(myrpt->remoterig, remote_rig_ic706))
14196          rem_totx |= myrpt->tunerequest;
14197       //
14198        if((debug > 6) && rem_totx) {
14199          ast_log(LOG_NOTICE,"Set rem_totx=%i.  dtmf_local_timer=%i phone_mode=%i keyed=%i tunerequest=%i\n",rem_totx,myrpt->dtmf_local_timer,phone_mode,keyed,myrpt->tunerequest);
14200       }
14201       if (keyed && (!keyed1))
14202       {
14203          keyed1 = 1;
14204       }
14205 
14206       if (!keyed && (keyed1))
14207       {
14208          time_t myt;
14209 
14210          keyed1 = 0;
14211          time(&myt);
14212          /* if login necessary, and not too soon */
14213          if ((myrpt->p.authlevel) && 
14214              (!myrpt->loginlevel[0]) &&
14215             (myt > (t + 3)))
14216          {
14217             authreq = 1;
14218             authtold = 0;
14219             myrpt->authtelltimer = AUTHTELLTIME - AUTHTXTIME;
14220          }
14221       }
14222 
14223       if (rem_rx && (!myrpt->remoterx))
14224       {
14225          myrpt->remoterx = 1;
14226          ast_indicate(chan,AST_CONTROL_RADIO_KEY);
14227       }
14228       if ((!rem_rx) && (myrpt->remoterx))
14229       {
14230          myrpt->remoterx = 0;
14231          ast_indicate(chan,AST_CONTROL_RADIO_UNKEY);
14232       }
14233       /* if auth requested, and not authed yet */
14234       if (authreq && (!myrpt->loginlevel[0]))
14235       {
14236          if ((!authtold) && ((myrpt->authtelltimer += elap)
14237              >= AUTHTELLTIME))
14238          {
14239             authtold = 1;
14240             rpt_telemetry(myrpt,LOGINREQ,NULL);
14241          }
14242          if ((myrpt->authtimer += elap) >= AUTHLOGOUTTIME)
14243          {
14244             break; /* if not logged in, hang up after a time */
14245          }
14246       }
14247       if (myrpt->newkey)
14248       {
14249          if ((myrpt->retxtimer += elap) >= REDUNDANT_TX_TIME)
14250          {
14251             myrpt->retxtimer = 0;
14252             if ((myrpt->remoterx) && (!myrpt->remotetx))
14253                ast_indicate(chan,AST_CONTROL_RADIO_KEY);
14254             else
14255                ast_indicate(chan,AST_CONTROL_RADIO_UNKEY);
14256          }
14257 
14258          if ((myrpt->rerxtimer += elap) >= (REDUNDANT_TX_TIME * 2))
14259          {
14260             keyed = 0;
14261             myrpt->rerxtimer = 0;
14262          }
14263       }
14264       if (rem_totx && (!myrpt->remotetx))
14265       {
14266          /* if not authed, and needed, do not transmit */
14267          if ((!myrpt->p.authlevel) || myrpt->loginlevel[0])
14268          {
14269             if(debug > 6)
14270                ast_log(LOG_NOTICE,"Handle rem_totx=%i.  dtmf_local_timer=%i  tunerequest=%i\n",rem_totx,myrpt->dtmf_local_timer,myrpt->tunerequest);
14271 
14272             myrpt->remotetx = 1;
14273             /* asdf maw ??? is this really what you want? Doesn't it always get executed? */
14274             if((myrpt->remtxfreqok = check_tx_freq(myrpt)))
14275             {
14276                time(&myrpt->last_activity_time);
14277                if ((iskenwood_pci4) && (myrpt->txchannel == myrpt->dahditxchannel))
14278                {
14279                   z.radpar = DAHDI_RADPAR_UIODATA;
14280                   z.data = 1;
14281                   if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
14282                   {
14283                      ast_log(LOG_ERROR,"Cannot set UIODATA\n");
14284                      return -1;
14285                   }
14286                }
14287                else
14288                {
14289                   ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_KEY);
14290                }
14291                if (myrpt->p.archivedir) donodelog(myrpt,"TXKEY");
14292             }
14293          }
14294       }
14295       if ((!rem_totx) && myrpt->remotetx) /* Remote base radio TX unkey */
14296       {
14297          myrpt->remotetx = 0;
14298          if(!myrpt->remtxfreqok){
14299             rpt_telemetry(myrpt,UNAUTHTX,NULL);
14300          }
14301          if ((iskenwood_pci4) && (myrpt->txchannel == myrpt->dahditxchannel))
14302          {
14303             z.radpar = DAHDI_RADPAR_UIODATA;
14304             z.data = 3;
14305             if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
14306             {
14307                ast_log(LOG_ERROR,"Cannot set UIODATA\n");
14308                return -1;
14309             }
14310          }
14311          else
14312          {
14313             ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_UNKEY);
14314          }
14315          if (myrpt->p.archivedir) donodelog(myrpt,"TXUNKEY");
14316       }
14317       if (myrpt->hfscanmode){
14318          myrpt->scantimer -= elap;
14319          if(myrpt->scantimer <= 0){
14320             if (!reming)
14321             {
14322                myrpt->scantimer = REM_SCANTIME;
14323                rpt_telemetry(myrpt,SCAN,0);
14324             } else myrpt->scantimer = 1;
14325          }
14326       }
14327       rpt_mutex_lock(&myrpt->lock);
14328       c = myrpt->macrobuf[0];
14329       if (c && (!myrpt->macrotimer))
14330       {
14331          myrpt->macrotimer = MACROTIME;
14332          memmove(myrpt->macrobuf,myrpt->macrobuf + 1,MAXMACRO - 1);
14333          if ((c == 'p') || (c == 'P'))
14334             myrpt->macrotimer = MACROPTIME;
14335          rpt_mutex_unlock(&myrpt->lock);
14336          if (myrpt->p.archivedir)
14337          {
14338             char str[100];
14339                sprintf(str,"DTMF(M),%c",c);
14340             donodelog(myrpt,str);
14341          }
14342          if (handle_remote_dtmf_digit(myrpt,c,&keyed,0) == -1) break;
14343          continue;
14344       } else rpt_mutex_unlock(&myrpt->lock);
14345       if (who == chan) /* if it was a read from incoming */
14346       {
14347          f = ast_read(chan);
14348          if (!f)
14349          {
14350             if (debug) printf("@@@@ link:Hung Up\n");
14351             break;
14352          }
14353          if (f->frametype == AST_FRAME_VOICE)
14354          {
14355             if (ioctl(chan->fds[0], DAHDI_GETCONFMUTE, &ismuted) == -1)
14356             {
14357                ismuted = 0;
14358             }
14359             /* if not transmitting, zero-out audio */
14360             ismuted |= (!myrpt->remotetx);
14361             if (dtmfed && phone_mode) ismuted = 1;
14362             dtmfed = 0;
14363             if (ismuted)
14364             {
14365                memset(f->data.ptr,0,f->datalen);
14366                if (myrpt->lastf1)
14367                   memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
14368                if (myrpt->lastf2)
14369                   memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
14370             } 
14371             if (f) f2 = ast_frdup(f);
14372             else f2 = NULL;
14373             f1 = myrpt->lastf2;
14374             myrpt->lastf2 = myrpt->lastf1;
14375             myrpt->lastf1 = f2;
14376             if (ismuted)
14377             {
14378                if (myrpt->lastf1)
14379                   memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
14380                if (myrpt->lastf2)
14381                   memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
14382             }
14383             if (f1)
14384             {
14385                if (phone_mode)
14386                   ast_write(myrpt->txchannel,f1);
14387                else
14388                   ast_write(myrpt->txchannel,f);
14389                ast_frfree(f1);
14390             }
14391          }
14392 #ifndef  OLD_ASTERISK
14393          else if (f->frametype == AST_FRAME_DTMF_BEGIN)
14394          {
14395             if (myrpt->lastf1)
14396                memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
14397             if (myrpt->lastf2)
14398                memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
14399             dtmfed = 1;
14400          }
14401 #endif
14402          if (f->frametype == AST_FRAME_DTMF)
14403          {
14404             if (myrpt->lastf1)
14405                memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
14406             if (myrpt->lastf2)
14407                memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
14408             dtmfed = 1;
14409             if (handle_remote_phone_dtmf(myrpt,f->subclass.integer,&keyed,phone_mode) == -1)
14410             {
14411                if (debug) printf("@@@@ rpt:Hung Up\n");
14412                ast_frfree(f);
14413                break;
14414             }
14415          }
14416          if (f->frametype == AST_FRAME_TEXT)
14417          {
14418             if (handle_remote_data(myrpt,f->data.ptr) == -1)
14419             {
14420                if (debug) printf("@@@@ rpt:Hung Up\n");
14421                ast_frfree(f);
14422                break;
14423             }
14424          }
14425          if (f->frametype == AST_FRAME_CONTROL)
14426          {
14427             if (f->subclass.integer == AST_CONTROL_HANGUP)
14428             {
14429                if (debug) printf("@@@@ rpt:Hung Up\n");
14430                ast_frfree(f);
14431                break;
14432             }
14433             /* if RX key */
14434             if (f->subclass.integer == AST_CONTROL_RADIO_KEY)
14435             {
14436                if (debug == 7) printf("@@@@ rx key\n");
14437                keyed = 1;
14438                myrpt->rerxtimer = 0;
14439             }
14440             /* if RX un-key */
14441             if (f->subclass.integer == AST_CONTROL_RADIO_UNKEY)
14442             {
14443                myrpt->rerxtimer = 0;
14444                if (debug == 7) printf("@@@@ rx un-key\n");
14445                keyed = 0;
14446             }
14447          }
14448          ast_frfree(f);
14449          continue;
14450       }
14451       if (who == myrpt->rxchannel) /* if it was a read from radio */
14452       {
14453          f = ast_read(myrpt->rxchannel);
14454          if (!f)
14455          {
14456             if (debug) printf("@@@@ link:Hung Up\n");
14457             break;
14458          }
14459          if (f->frametype == AST_FRAME_VOICE)
14460          {
14461             int myreming = 0;
14462 
14463             if(!strcmp(myrpt->remoterig, remote_rig_kenwood))
14464                myreming = reming;
14465 
14466             if (myreming || (!remkeyed) ||
14467             ((myrpt->remote) && (myrpt->remotetx)) ||
14468               ((myrpt->remmode != REM_MODE_FM) &&
14469                 notremming))
14470                memset(f->data.ptr,0,f->datalen); 
14471              ast_write(myrpt->pchannel,f);
14472          }
14473          else if (f->frametype == AST_FRAME_CONTROL)
14474          {
14475             if (f->subclass.integer == AST_CONTROL_HANGUP)
14476             {
14477                if (debug) printf("@@@@ rpt:Hung Up\n");
14478                ast_frfree(f);
14479                break;
14480             }
14481             /* if RX key */
14482             if (f->subclass.integer == AST_CONTROL_RADIO_KEY)
14483             {
14484                if (debug == 7) printf("@@@@ remote rx key\n");
14485                if (!myrpt->remotetx)
14486                {
14487                   remkeyed = 1;
14488                }
14489             }
14490             /* if RX un-key */
14491             if (f->subclass.integer == AST_CONTROL_RADIO_UNKEY)
14492             {
14493                if (debug == 7) printf("@@@@ remote rx un-key\n");
14494                if (!myrpt->remotetx) 
14495                {
14496                   remkeyed = 0;
14497                }
14498             }
14499          }
14500          ast_frfree(f);
14501          continue;
14502       }
14503       if (who == myrpt->pchannel) /* if is remote mix output */
14504       {
14505          f = ast_read(myrpt->pchannel);
14506          if (!f)
14507          {
14508             if (debug) printf("@@@@ link:Hung Up\n");
14509             break;
14510          }
14511          if (f->frametype == AST_FRAME_VOICE)
14512          {
14513             ast_write(chan,f);
14514          }
14515          if (f->frametype == AST_FRAME_CONTROL)
14516          {
14517             if (f->subclass.integer == AST_CONTROL_HANGUP)
14518             {
14519                if (debug) printf("@@@@ rpt:Hung Up\n");
14520                ast_frfree(f);
14521                break;
14522             }
14523          }
14524          ast_frfree(f);
14525          continue;
14526       }
14527       if ((myrpt->rxchannel != myrpt->txchannel) && 
14528          (who == myrpt->txchannel)) /* do this cuz you have to */
14529       {
14530          f = ast_read(myrpt->txchannel);
14531          if (!f)
14532          {
14533             if (debug) printf("@@@@ link:Hung Up\n");
14534             break;
14535          }
14536          if (f->frametype == AST_FRAME_CONTROL)
14537          {
14538             if (f->subclass.integer == AST_CONTROL_HANGUP)
14539             {
14540                if (debug) printf("@@@@ rpt:Hung Up\n");
14541                ast_frfree(f);
14542                break;
14543             }
14544          }
14545          ast_frfree(f);
14546          continue;
14547       }
14548    }
14549    if (myrpt->p.archivedir)
14550    {
14551       char mycmd[100],*b,*b1;
14552 
14553       /* look at callerid to see what node this comes from */
14554       b = S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL);
14555       if (!b) /* if doesn't have caller id */
14556       {
14557          b1 = "0";
14558       } else {
14559          b1 = ast_strdupa(b);
14560          ast_shrink_phone_number(b1);
14561       }
14562       sprintf(mycmd,"DISCONNECT,%s",b1);
14563       donodelog(myrpt,mycmd);
14564    }
14565    /* wait for telem to be done */
14566    while(myrpt->tele.next != &myrpt->tele) usleep(100000);
14567    sprintf(tmp,"mixmonitor stop %s",chan->name);
14568    ast_cli_command(nullfd,tmp);
14569    close(nullfd);
14570    rpt_mutex_lock(&myrpt->lock);
14571    myrpt->hfscanmode = 0;
14572    myrpt->hfscanstatus = 0;
14573    myrpt->remoteon = 0;
14574    rpt_mutex_unlock(&myrpt->lock);
14575    if (myrpt->lastf1) ast_frfree(myrpt->lastf1);
14576    myrpt->lastf1 = NULL;
14577    if (myrpt->lastf2) ast_frfree(myrpt->lastf2);
14578    myrpt->lastf2 = NULL;
14579    if ((iskenwood_pci4) && (myrpt->txchannel == myrpt->dahditxchannel))
14580    {
14581       z.radpar = DAHDI_RADPAR_UIOMODE;
14582       z.data = 3;
14583       if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
14584       {
14585          ast_log(LOG_ERROR,"Cannot set UIOMODE\n");
14586          return -1;
14587       }
14588       z.radpar = DAHDI_RADPAR_UIODATA;
14589       z.data = 3;
14590       if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
14591       {
14592          ast_log(LOG_ERROR,"Cannot set UIODATA\n");
14593          return -1;
14594       }
14595       i = DAHDI_OFFHOOK;
14596       if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_HOOK,&i) == -1)
14597       {
14598          ast_log(LOG_ERROR,"Cannot set hook\n");
14599          return -1;
14600       }
14601    }
14602    if (myrpt->iofd) close(myrpt->iofd);
14603    myrpt->iofd = -1;
14604    ast_hangup(myrpt->pchannel);
14605    if (myrpt->rxchannel != myrpt->txchannel) ast_hangup(myrpt->txchannel);
14606    ast_hangup(myrpt->rxchannel);
14607    closerem(myrpt);
14608    if (myrpt->p.rptnode)
14609    {
14610       rpt_mutex_lock(&myrpt->lock);
14611       for(i = 0; i < nrpts; i++)
14612       {
14613          if (!strcasecmp(rpt_vars[i].name,myrpt->p.rptnode))
14614          {
14615             rpt_vars[i].xlink = 0;
14616             break;
14617          }
14618       }
14619       rpt_mutex_unlock(&myrpt->lock);
14620    }
14621 #ifdef   OLD_ASTERISK
14622    LOCAL_USER_REMOVE(u);
14623 #endif
14624    return res;
14625 }
14626 
14627 #ifndef OLD_ASTERISK
14628 /*!\brief callback to display list of locally configured nodes
14629    \addtogroup Group_AMI
14630  */
14631 static int manager_rpt_local_nodes(struct mansession *s, const struct message *m)
14632 {
14633     int i;
14634     astman_append(s, "<?xml version=\"1.0\"?>\r\n");
14635     astman_append(s, "<nodes>\r\n");
14636     for (i=0; i< nrpts; i++)
14637     {
14638         astman_append(s, "  <node>%s</node>\r\n", rpt_vars[i].name);        
14639     } /* for i */
14640     astman_append(s, "</nodes>\r\n");
14641     astman_append(s, "\r\n"); /* Properly terminate Manager output */
14642     return RESULT_SUCCESS;
14643 } /* manager_rpt_local_nodes() */
14644 
14645 
14646 
14647 /*
14648  * Append Success and ActionID to manager response message
14649  */
14650 
14651 static void rpt_manager_success(struct mansession *s, const struct message *m)
14652 {
14653    const char *id = astman_get_header(m, "ActionID");
14654    if (!ast_strlen_zero(id))
14655       astman_append(s, "ActionID: %s\r\n", id);
14656    astman_append(s, "Response: Success\r\n");
14657 }
14658 
14659 /*
14660 * Dump statistics to manager session
14661 */
14662 
14663 static int rpt_manager_do_stats(struct mansession *s, const struct message *m, char *str)
14664 {
14665    int i,j,numoflinks;
14666    int dailytxtime, dailykerchunks;
14667    time_t now;
14668    int totalkerchunks, dailykeyups, totalkeyups, timeouts;
14669    int totalexecdcommands, dailyexecdcommands, hours, minutes, seconds;
14670    long long totaltxtime;
14671    struct   rpt_link *l;
14672    char *listoflinks[MAX_STAT_LINKS];  
14673    char *lastdtmfcommand,*parrot_ena;
14674    char *tot_state, *ider_state, *patch_state;
14675    char *reverse_patch_state, *sys_ena, *tot_ena, *link_ena, *patch_ena;
14676    char *sch_ena, *input_signal, *called_number, *user_funs, *tail_type;
14677    char *transmitterkeyed;
14678    const char *node = astman_get_header(m, "Node");
14679    struct rpt *myrpt;
14680 
14681    static char *not_applicable = "N/A";
14682 
14683    tot_state = ider_state = 
14684    patch_state = reverse_patch_state = 
14685    input_signal = not_applicable;
14686    called_number = lastdtmfcommand = transmitterkeyed = NULL;
14687 
14688    time(&now);
14689    for(i = 0; i < nrpts; i++)
14690    {
14691       if ((node)&&(!strcmp(node,rpt_vars[i].name))){
14692          rpt_manager_success(s,m);
14693 
14694          myrpt = &rpt_vars[i];
14695 
14696          if(myrpt->remote){ /* Remote base ? */
14697             char *loginuser, *loginlevel, *freq, *rxpl, *txpl, *modestr;
14698             char offset = 0, powerlevel = 0, rxplon = 0, txplon = 0, remoteon, remmode = 0, reportfmstuff;
14699             char offsetc,powerlevelc;
14700 
14701             loginuser = loginlevel = freq = rxpl = txpl = NULL;
14702             /* Make a copy of all stat variables while locked */
14703             rpt_mutex_lock(&myrpt->lock); /* LOCK */
14704             if((remoteon = myrpt->remoteon)){
14705                if(!ast_strlen_zero(myrpt->loginuser))
14706                   loginuser = ast_strdup(myrpt->loginuser);
14707                if(!ast_strlen_zero(myrpt->loginlevel))
14708                   loginlevel = ast_strdup(myrpt->loginlevel);
14709                if(!ast_strlen_zero(myrpt->freq))
14710                   freq = ast_strdup(myrpt->freq);
14711                if(!ast_strlen_zero(myrpt->rxpl))
14712                   rxpl = ast_strdup(myrpt->rxpl);
14713                if(!ast_strlen_zero(myrpt->txpl))
14714                   txpl = ast_strdup(myrpt->txpl);
14715                remmode = myrpt->remmode;
14716                offset = myrpt->offset;
14717                powerlevel = myrpt->powerlevel;
14718                rxplon = myrpt->rxplon;
14719                txplon = myrpt->txplon;       
14720             }
14721             rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
14722             astman_append(s, "IsRemoteBase: YES\r\n");
14723             astman_append(s, "RemoteOn: %s\r\n",(remoteon) ? "YES": "NO");
14724             if(remoteon){
14725                if(loginuser){
14726                   astman_append(s, "LogInUser: %s\r\n", loginuser);
14727                   ast_free(loginuser);
14728                }
14729                if(loginlevel){
14730                   astman_append(s, "LogInLevel: %s\r\n", loginlevel);
14731                   ast_free(loginlevel);
14732                }
14733                if(freq){
14734                   astman_append(s, "Freq: %s\r\n", freq);
14735                   ast_free(freq);
14736                }
14737                reportfmstuff = 0;
14738                switch(remmode){
14739                   case REM_MODE_FM:
14740                      modestr = "FM";   
14741                      reportfmstuff = 1;
14742                      break;
14743                   case REM_MODE_AM:
14744                      modestr = "AM";
14745                      break;
14746                   case REM_MODE_USB:
14747                      modestr = "USB";
14748                      break;
14749                   default:
14750                      modestr = "LSB";
14751                      break;
14752                }
14753                astman_append(s, "RemMode: %s\r\n", modestr);
14754                if(reportfmstuff){
14755                   switch(offset){
14756                      case REM_SIMPLEX:
14757                         offsetc = 'S';
14758                         break;
14759                      case REM_MINUS:
14760                         offsetc = '-';
14761                         break;
14762                      default:
14763                         offsetc = '+';
14764                         break;
14765                   }
14766                   astman_append(s, "RemOffset: %c\r\n", offsetc);
14767                   if(rxplon && rxpl){
14768                      astman_append(s, "RxPl: %s\r\n",rxpl);
14769                      ast_free(rxpl);
14770                   }
14771                   if(txplon && txpl){
14772                      astman_append(s, "TxPl: %s\r\n",txpl);
14773                      ast_free(txpl);
14774                   }
14775                }
14776                switch(powerlevel){
14777                   case REM_LOWPWR:
14778                      powerlevelc = 'L';
14779                      break;
14780                   case REM_MEDPWR:
14781                      powerlevelc = 'M';
14782                      break;
14783                   default:
14784                      powerlevelc = 'H';
14785                      break;
14786                }
14787                astman_append(s,"PowerLevel: %c\r\n", powerlevelc);
14788             }
14789             astman_append(s, "\r\n");
14790             return 0; /* End of remote base status reporting */
14791          }  
14792 
14793          /* ELSE Process as a repeater node */
14794          /* Make a copy of all stat variables while locked */
14795          rpt_mutex_lock(&myrpt->lock); /* LOCK */
14796          dailytxtime = myrpt->dailytxtime;
14797          totaltxtime = myrpt->totaltxtime;
14798          dailykeyups = myrpt->dailykeyups;
14799          totalkeyups = myrpt->totalkeyups;
14800          dailykerchunks = myrpt->dailykerchunks;
14801          totalkerchunks = myrpt->totalkerchunks;
14802          dailyexecdcommands = myrpt->dailyexecdcommands;
14803          totalexecdcommands = myrpt->totalexecdcommands;
14804          timeouts = myrpt->timeouts;
14805 
14806 
14807          /* Traverse the list of connected nodes */
14808          reverse_patch_state = "DOWN";
14809          numoflinks = 0;
14810          l = myrpt->links.next;
14811          while(l && (l != &myrpt->links)){
14812             if(numoflinks >= MAX_STAT_LINKS){
14813                ast_log(LOG_NOTICE,
14814                "maximum number of links exceeds %d in rpt_do_stats()!",MAX_STAT_LINKS);
14815                break;
14816             }
14817             if (l->name[0] == '0'){ /* Skip '0' nodes */
14818                reverse_patch_state = "UP";
14819                l = l->next;
14820                continue;
14821             }
14822             listoflinks[numoflinks] = ast_strdup(l->name);
14823             if(listoflinks[numoflinks] == NULL){
14824                break;
14825             }
14826             else{
14827                numoflinks++;
14828             }
14829             l = l->next;
14830          }
14831 
14832          if(myrpt->keyed)
14833             input_signal = "YES";
14834          else
14835             input_signal = "NO";
14836          
14837          if(myrpt->txkeyed)
14838             transmitterkeyed = "YES";
14839          else
14840             transmitterkeyed = "NO";
14841 
14842          if(myrpt->p.parrotmode)
14843             parrot_ena = "ENABLED";
14844          else
14845             parrot_ena = "DISABLED";
14846 
14847          if(myrpt->p.s[myrpt->p.sysstate_cur].txdisable)
14848             sys_ena = "DISABLED";
14849          else
14850             sys_ena = "ENABLED";
14851 
14852          if(myrpt->p.s[myrpt->p.sysstate_cur].totdisable)
14853             tot_ena = "DISABLED";
14854          else
14855             tot_ena = "ENABLED";
14856 
14857          if(myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable)
14858             link_ena = "DISABLED";
14859          else
14860             link_ena = "ENABLED";
14861 
14862          if(myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable)
14863             patch_ena = "DISABLED";
14864          else
14865             patch_ena = "ENABLED";
14866 
14867          if(myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable)
14868             sch_ena = "DISABLED";
14869          else
14870             sch_ena = "ENABLED";
14871 
14872          if(myrpt->p.s[myrpt->p.sysstate_cur].userfundisable)
14873             user_funs = "DISABLED";
14874          else
14875             user_funs = "ENABLED";
14876 
14877          if(myrpt->p.s[myrpt->p.sysstate_cur].alternatetail)
14878             tail_type = "ALTERNATE";
14879          else
14880             tail_type = "STANDARD";
14881 
14882          if(!myrpt->totimer)
14883             tot_state = "TIMED OUT!";
14884          else if(myrpt->totimer != myrpt->p.totime)
14885             tot_state = "ARMED";
14886          else
14887             tot_state = "RESET";
14888 
14889          if(myrpt->tailid)
14890             ider_state = "QUEUED IN TAIL";
14891          else if(myrpt->mustid)
14892             ider_state = "QUEUED FOR CLEANUP";
14893          else
14894             ider_state = "CLEAN";
14895 
14896          switch(myrpt->callmode){
14897             case 1:
14898                patch_state = "DIALING";
14899                break;
14900             case 2:
14901                patch_state = "CONNECTING";
14902                break;
14903             case 3:
14904                patch_state = "UP";
14905                break;
14906 
14907             case 4:
14908                patch_state = "CALL FAILED";
14909                break;
14910 
14911             default:
14912                patch_state = "DOWN";
14913          }
14914 
14915          if(strlen(myrpt->exten)){
14916             called_number = ast_strdup(myrpt->exten);
14917          }
14918 
14919          if(strlen(myrpt->lastdtmfcommand)){
14920             lastdtmfcommand = ast_strdup(myrpt->lastdtmfcommand);
14921          }
14922          rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
14923 
14924          astman_append(s, "IsRemoteBase: NO\r\n");
14925          astman_append(s, "NodeState: %d\r\n", myrpt->p.sysstate_cur);
14926          astman_append(s, "SignalOnInput: %s\r\n", input_signal);
14927          astman_append(s, "TransmitterKeyed: %s\r\n", transmitterkeyed);
14928          astman_append(s, "Transmitter: %s\r\n", sys_ena);
14929          astman_append(s, "Parrot: %s\r\n", parrot_ena);
14930          astman_append(s, "Scheduler: %s\r\n", sch_ena);
14931          astman_append(s, "TailLength: %s\r\n", tail_type);
14932          astman_append(s, "TimeOutTimer: %s\r\n", tot_ena);
14933          astman_append(s, "TimeOutTimerState: %s\r\n", tot_state);
14934          astman_append(s, "TimeOutsSinceSystemInitialization: %d\r\n", timeouts);
14935          astman_append(s, "IdentifierState: %s\r\n", ider_state);
14936          astman_append(s, "KerchunksToday: %d\r\n", dailykerchunks);
14937          astman_append(s, "KerchunksSinceSystemInitialization: %d\r\n", totalkerchunks);
14938          astman_append(s, "KeyupsToday: %d\r\n", dailykeyups);
14939          astman_append(s, "KeyupsSinceSystemInitialization: %d\r\n", totalkeyups);
14940          astman_append(s, "DtmfCommandsToday: %d\r\n", dailyexecdcommands);
14941          astman_append(s, "DtmfCommandsSinceSystemInitialization: %d\r\n", totalexecdcommands);
14942          astman_append(s, "LastDtmfCommandExecuted: %s\r\n", 
14943          (lastdtmfcommand && strlen(lastdtmfcommand)) ? lastdtmfcommand : not_applicable);
14944          hours = dailytxtime/3600000;
14945          dailytxtime %= 3600000;
14946          minutes = dailytxtime/60000;
14947          dailytxtime %= 60000;
14948          seconds = dailytxtime/1000;
14949          dailytxtime %= 1000;
14950 
14951          astman_append(s, "TxTimeToday: %02d:%02d:%02d.%d\r\n",
14952             hours, minutes, seconds, dailytxtime);
14953 
14954          hours = (int) totaltxtime/3600000;
14955          totaltxtime %= 3600000;
14956          minutes = (int) totaltxtime/60000;
14957          totaltxtime %= 60000;
14958          seconds = (int)  totaltxtime/1000;
14959          totaltxtime %= 1000;
14960 
14961          astman_append(s, "TxTimeSinceSystemInitialization: %02d:%02d:%02d.%d\r\n",
14962              hours, minutes, seconds, (int) totaltxtime);
14963 
14964          sprintf(str, "NodesCurrentlyConnectedToUs: ");
14965                         if(!numoflinks){
14966                          strcat(str,"<NONE>");
14967                         }
14968          else{
14969             for(j = 0 ;j < numoflinks; j++){
14970                sprintf(str+strlen(str), "%s", listoflinks[j]);
14971                if(j < numoflinks - 1)
14972                   strcat(str,",");
14973             }
14974          }
14975          astman_append(s,"%s\r\n", str);
14976 
14977          astman_append(s, "Autopatch: %s\r\n", patch_ena);
14978          astman_append(s, "AutopatchState: %s\r\n", patch_state);
14979          astman_append(s, "AutopatchCalledNumber: %s\r\n",
14980          (called_number && strlen(called_number)) ? called_number : not_applicable);
14981          astman_append(s, "ReversePatchIaxrptConnected: %s\r\n", reverse_patch_state);
14982          astman_append(s, "UserLinkingCommands: %s\r\n", link_ena);
14983          astman_append(s, "UserFunctions: %s\r\n", user_funs);
14984 
14985          for(j = 0; j < numoflinks; j++){ /* ast_free() all link names */
14986             ast_free(listoflinks[j]);
14987          }
14988          if(called_number){
14989             ast_free(called_number);
14990          }
14991          if(lastdtmfcommand){
14992             ast_free(lastdtmfcommand);
14993          }
14994          astman_append(s, "\r\n"); /* We're Done! */
14995               return 0;
14996       }
14997    }
14998    astman_send_error(s, m, "RptStatus unknown or missing node");
14999    return -1;
15000 }
15001 
15002 
15003 
15004 /*
15005  * Implement the RptStatus Manager Interface
15006  */
15007 
15008 static int manager_rpt_status(struct mansession *s, const struct message *m)
15009 {
15010    int i,res,len,idx;
15011    int uptime,hours,minutes;
15012    time_t now;
15013    const char *cmd = astman_get_header(m, "Command");
15014    char *str;
15015    enum {MGRCMD_RPTSTAT,MGRCMD_NODESTAT};
15016    struct mgrcmdtbl{
15017       const char *cmd;
15018       int index;
15019    };
15020    static struct mgrcmdtbl mct[] = {
15021       {"RptStat",MGRCMD_RPTSTAT},
15022       {"NodeStat",MGRCMD_NODESTAT},
15023       {NULL,0} /* NULL marks end of command table */
15024    };
15025 
15026    time(&now);
15027 
15028    len = 1024; /* Allocate a working buffer */
15029    if(!(str = ast_malloc(len)))
15030       return -1;
15031 
15032    /* Check for Command */
15033    if(ast_strlen_zero(cmd)){
15034       astman_send_error(s, m, "RptStatus missing command");
15035       ast_free(str);
15036       return 0;
15037    }
15038    /* Try to find the command in the table */
15039    for(i = 0 ; mct[i].cmd ; i++){
15040       if(!strcmp(mct[i].cmd, cmd))
15041          break;
15042    }
15043 
15044    if(!mct[i].cmd){ /* Found or not found ? */
15045       astman_send_error(s, m, "RptStatus unknown command");
15046       ast_free(str);
15047       return 0;
15048    }
15049    else
15050       idx = mct[i].index;
15051 
15052    switch(idx){ /* Use the index to go to the correct command */
15053 
15054       case MGRCMD_RPTSTAT:
15055          /* Return Nodes: and a comma separated list of nodes */
15056          if((res = snprintf(str, len, "Nodes: ")) > -1)
15057             len -= res;
15058          else{
15059             ast_free(str);
15060             return 0;
15061          }
15062          for(i = 0; i < nrpts; i++){
15063             if(i < nrpts - 1){
15064                if((res = snprintf(str+strlen(str), len, "%s,",rpt_vars[i].name)) < 0){
15065                   ast_free(str);
15066                   return 0;
15067                }
15068             }
15069             else{
15070                if((res = snprintf(str+strlen(str), len, "%s",rpt_vars[i].name)) < 0){
15071                   ast_free(str);
15072                   return 0;
15073                }
15074             }
15075             len -= res;
15076          }
15077 
15078          rpt_manager_success(s,m);
15079          
15080          if(!nrpts)
15081             astman_append(s, "<NONE>\r\n");
15082          else
15083             astman_append(s, "%s\r\n", str);
15084 
15085          uptime = (int)(now - starttime);
15086                         hours = uptime/3600;
15087                         uptime %= 3600;
15088                         minutes = uptime/60;
15089                         uptime %= 60;
15090 
15091                         astman_append(s, "RptUptime: %02d:%02d:%02d\r\n",
15092                                 hours, minutes, uptime);
15093 
15094          astman_append(s, "\r\n");
15095          break;      
15096 
15097       case  MGRCMD_NODESTAT:
15098          res = rpt_manager_do_stats(s,m,str);
15099          ast_free(str);
15100          return res;
15101 
15102       default:
15103          astman_send_error(s, m, "RptStatus invalid command");
15104          break;
15105    }
15106    ast_free(str);
15107    return 0;
15108 }
15109 
15110 #endif
15111 
15112 #ifdef   OLD_ASTERISK
15113 int unload_module()
15114 #else
15115 static int unload_module(void)
15116 #endif
15117 {
15118    int i, res;
15119 
15120 #ifdef   OLD_ASTERISK
15121    STANDARD_HANGUP_LOCALUSERS;
15122 #endif
15123    for(i = 0; i < nrpts; i++) {
15124       if (!strcmp(rpt_vars[i].name,rpt_vars[i].p.nodes)) continue;
15125                 ast_mutex_destroy(&rpt_vars[i].lock);
15126                 ast_mutex_destroy(&rpt_vars[i].remlock);
15127    }
15128    res = ast_unregister_application(app);
15129 
15130 #ifdef   NEW_ASTERISK
15131    ast_cli_unregister_multiple(rpt_cli, ARRAY_LEN(rpt_cli));
15132 #else
15133    /* Unregister cli extensions */
15134    ast_cli_unregister(&cli_debug);
15135    ast_cli_unregister(&cli_dump);
15136    ast_cli_unregister(&cli_stats);
15137    ast_cli_unregister(&cli_lstats);
15138    ast_cli_unregister(&cli_nodes);
15139    ast_cli_unregister(&cli_local_nodes);
15140    ast_cli_unregister(&cli_reload);
15141    ast_cli_unregister(&cli_restart);
15142    ast_cli_unregister(&cli_fun);
15143    ast_cli_unregister(&cli_fun1);
15144    res |= ast_cli_unregister(&cli_cmd);
15145 #endif
15146 #ifndef OLD_ASTERISK
15147    res |= ast_manager_unregister("RptLocalNodes");
15148    res |= ast_manager_unregister("RptStatus");
15149 #endif
15150    return res;
15151 }
15152 
15153 #ifdef   OLD_ASTERISK
15154 int load_module()
15155 #else
15156 static int load_module(void)
15157 #endif
15158 {
15159    int res;
15160    ast_pthread_create(&rpt_master_thread,NULL,rpt_master,NULL);
15161 
15162 #ifdef   NEW_ASTERISK
15163    ast_cli_register_multiple(rpt_cli, ARRAY_LEN(rpt_cli));
15164    res = 0;
15165 #else
15166    /* Register cli extensions */
15167    ast_cli_register(&cli_debug);
15168    ast_cli_register(&cli_dump);
15169    ast_cli_register(&cli_stats);
15170    ast_cli_register(&cli_lstats);
15171    ast_cli_register(&cli_nodes);
15172    ast_cli_register(&cli_local_nodes);
15173    ast_cli_register(&cli_reload);
15174    ast_cli_register(&cli_restart);
15175    ast_cli_register(&cli_fun);
15176    ast_cli_register(&cli_fun1);
15177    res = ast_cli_register(&cli_cmd);
15178 #endif
15179 #ifndef OLD_ASTERISK
15180    res |= ast_manager_register("RptLocalNodes", 0, manager_rpt_local_nodes, "List local node numbers");
15181    res |= ast_manager_register("RptStatus", 0, manager_rpt_status, "Return Rpt Status for CGI");
15182 
15183 #endif
15184    res |= ast_register_application(app, rpt_exec, synopsis, descrip);
15185    return res;
15186 }
15187 
15188 #ifdef   OLD_ASTERISK
15189 char *description()
15190 {
15191    return tdesc;
15192 }
15193 int usecount(void)
15194 {
15195    int res;
15196    STANDARD_USECOUNT(res);
15197    return res;
15198 }
15199 
15200 char *key()
15201 {
15202    return ASTERISK_GPL_KEY;
15203 }
15204 #endif
15205 
15206 #ifdef   OLD_ASTERISK
15207 int reload()
15208 #else
15209 static int reload(void)
15210 #endif
15211 {
15212 int   n;
15213 
15214    for(n = 0; n < nrpts; n++) rpt_vars[n].reload = 1;
15215    return(0);
15216 }
15217 
15218 
15219 #ifndef  OLD_ASTERISK
15220 /* STD_MOD(MOD_1, reload, NULL, NULL); */
15221 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Radio Repeater/Remote Base Application",
15222       .load = load_module,
15223       .unload = unload_module,
15224       .reload = reload,
15225           );
15226 #endif
15227 

Generated on Sat Mar 26 11:06:35 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9