Mon May 14 2012 03:42:20

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    <defaultenabled>no</defaultenabled>
00158    <support_level>extended</support_level>
00159  ***/
00160 
00161 /* Un-comment the following to include support for MDC-1200 digital tone
00162    signalling protocol (using KA6SQG's GPL'ed implementation) */
00163 /* #include "mdc_decode.c" */
00164 
00165 /* Un-comment the following to include support for notch filters in the
00166    rx audio stream (using Tony Fisher's mknotch (mkfilter) implementation) */
00167 /* #include "rpt_notch.c" */
00168 
00169 /* maximum digits in DTMF buffer, and seconds after * for DTMF command timeout */
00170 
00171 #ifdef OLD_ASTERISK
00172 #define ast_free free
00173 #define ast_malloc malloc
00174 #define ast_strdup strdup
00175 #endif
00176 
00177 
00178 #define  MAXDTMF 32
00179 #define  MAXMACRO 2048
00180 #define  MAXLINKLIST 512
00181 #define  LINKLISTTIME 10000
00182 #define  LINKLISTSHORTTIME 200
00183 #define  LINKPOSTTIME 30000
00184 #define  LINKPOSTSHORTTIME 200
00185 #define  KEYPOSTTIME 30000
00186 #define  KEYPOSTSHORTTIME 200
00187 #define  MACROTIME 100
00188 #define  MACROPTIME 500
00189 #define  DTMF_TIMEOUT 3
00190 #define  KENWOOD_RETRIES 5
00191 #define  TOPKEYN 32
00192 #define  TOPKEYWAIT 3
00193 #define  TOPKEYMAXSTR 30
00194 
00195 #define  AUTHTELLTIME 7000
00196 #define  AUTHTXTIME 1000
00197 #define  AUTHLOGOUTTIME 25000
00198 
00199 #ifdef   __RPT_NOTCH
00200 #define  MAXFILTERS 10
00201 #endif
00202 
00203 #define  DISC_TIME 10000  /* report disc after 10 seconds of no connect */
00204 #define  MAX_RETRIES 5
00205 #define  MAX_RETRIES_PERM 1000000000
00206 
00207 #define  REDUNDANT_TX_TIME 2000
00208 
00209 #define  RETRY_TIMER_MS 5000
00210 
00211 #define  PATCH_DIALPLAN_TIMEOUT 1500
00212 
00213 #ifdef OLD_ASTERISK
00214 #define  START_DELAY 10
00215 #else
00216 #define  START_DELAY 2
00217 #endif
00218 
00219 #define  RPT_LOCKOUT_SECS 10
00220 
00221 #define MAXPEERSTR 31
00222 #define  MAXREMSTR 15
00223 
00224 #define  DELIMCHR ','
00225 #define  QUOTECHR 34
00226 
00227 #define  MONITOR_DISK_BLOCKS_PER_MINUTE 38
00228 
00229 #define  DEFAULT_MONITOR_MIN_DISK_BLOCKS 10000
00230 #define  DEFAULT_REMOTE_INACT_TIMEOUT (15 * 60)
00231 #define  DEFAULT_REMOTE_TIMEOUT (60 * 60)
00232 #define  DEFAULT_REMOTE_TIMEOUT_WARNING (3 * 60)
00233 #define  DEFAULT_REMOTE_TIMEOUT_WARNING_FREQ 30
00234 
00235 #define  NODES "nodes"
00236 #define  EXTNODES "extnodes"
00237 #define MEMORY "memory"
00238 #define MACRO "macro"
00239 #define  FUNCTIONS "functions"
00240 #define TELEMETRY "telemetry"
00241 #define MORSE "morse"
00242 #define  TONEMACRO "tonemacro"
00243 #define  FUNCCHAR '*'
00244 #define  ENDCHAR '#'
00245 #define  EXTNODEFILE "/var/lib/asterisk/rpt_extnodes"
00246 #define  NODENAMES "rpt/nodenames"
00247 #define  PARROTFILE "/tmp/parrot_%s_%u"
00248 
00249 #define  PARROTTIME 1000
00250 
00251 #define  DEFAULT_IOBASE 0x378
00252 
00253 #define  DEFAULT_CIV_ADDR 0x58
00254 
00255 #define  MAXCONNECTTIME 5000
00256 
00257 #define MAXNODESTR 300
00258 
00259 #define MAXNODELEN 16
00260 
00261 #define MAXIDENTLEN 32
00262 
00263 #define MAXPATCHCONTEXT 100
00264 
00265 #define ACTIONSIZE 32
00266 
00267 #define TELEPARAMSIZE 256
00268 
00269 #define REM_SCANTIME 100
00270 
00271 #define  DTMF_LOCAL_TIME 250
00272 #define  DTMF_LOCAL_STARTTIME 500
00273 
00274 #define  IC706_PL_MEMORY_OFFSET 50
00275 
00276 #define  VOX_ON_DEBOUNCE_COUNT 3
00277 #define  VOX_OFF_DEBOUNCE_COUNT 20
00278 #define  VOX_MAX_THRESHOLD 10000.0
00279 #define  VOX_MIN_THRESHOLD 3000.0
00280 #define  VOX_TIMEOUT_MS 5000
00281 #define  VOX_RECOVER_MS 500
00282 #define  SIMPLEX_PATCH_DELAY 25
00283 #define  SIMPLEX_PHONE_DELAY 25
00284 
00285 #define  STATPOST_PROGRAM "/usr/bin/wget,-q,--output-document=/dev/null,--no-check-certificate"
00286 
00287 #define  ALLOW_LOCAL_CHANNELS
00288 
00289 enum {REM_OFF,REM_MONITOR,REM_TX};
00290 
00291 enum{ID,PROC,TERM,COMPLETE,UNKEY,REMDISC,REMALREADY,REMNOTFOUND,REMGO,
00292    CONNECTED,CONNFAIL,STATUS,TIMEOUT,ID1, STATS_TIME, PLAYBACK,
00293    STATS_VERSION, IDTALKOVER, ARB_ALPHA, TEST_TONE, REV_PATCH,
00294    TAILMSG, MACRO_NOTFOUND, MACRO_BUSY, LASTNODEKEY, FULLSTATUS,
00295    MEMNOTFOUND, INVFREQ, REMMODE, REMLOGIN, REMXXX, REMSHORTSTATUS,
00296    REMLONGSTATUS, LOGINREQ, SCAN, SCANSTAT, TUNE, SETREMOTE, TOPKEY,
00297    TIMEOUT_WARNING, ACT_TIMEOUT_WARNING, LINKUNKEY, UNAUTHTX, PARROT,
00298    STATS_TIME_LOCAL};
00299 
00300 
00301 enum {REM_SIMPLEX,REM_MINUS,REM_PLUS};
00302 
00303 enum {REM_LOWPWR,REM_MEDPWR,REM_HIPWR};
00304 
00305 enum {DC_INDETERMINATE, DC_REQ_FLUSH, DC_ERROR, DC_COMPLETE, DC_COMPLETEQUIET, DC_DOKEY};
00306 
00307 enum {SOURCE_RPT, SOURCE_LNK, SOURCE_RMT, SOURCE_PHONE, SOURCE_DPHONE, SOURCE_ALT};
00308 
00309 enum {DLY_TELEM, DLY_ID, DLY_UNKEY, DLY_CALLTERM, DLY_COMP, DLY_LINKUNKEY, DLY_PARROT};
00310 
00311 enum {REM_MODE_FM,REM_MODE_USB,REM_MODE_LSB,REM_MODE_AM};
00312 
00313 enum {HF_SCAN_OFF,HF_SCAN_DOWN_SLOW,HF_SCAN_DOWN_QUICK,
00314       HF_SCAN_DOWN_FAST,HF_SCAN_UP_SLOW,HF_SCAN_UP_QUICK,HF_SCAN_UP_FAST};
00315 
00316 #include "asterisk.h"
00317 
00318 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 356337 $")
00319 
00320 #include <signal.h>
00321 #include <stdio.h>
00322 #include <stdint.h>
00323 #include <unistd.h>
00324 #include <string.h>
00325 #include <stdlib.h>
00326 #include <search.h>
00327 #include <sys/types.h>
00328 #include <sys/stat.h>
00329 #include <errno.h>
00330 #include <dirent.h>
00331 #include <ctype.h>
00332 #include <sys/stat.h>
00333 #include <sys/time.h>
00334 #include <sys/file.h>
00335 #include <sys/ioctl.h>
00336 #ifdef HAVE_SYS_IO_H
00337 #include <sys/io.h>
00338 #endif
00339 #include <sys/vfs.h>
00340 #include <math.h>
00341 #include <dahdi/user.h>
00342 #include <dahdi/tonezone.h>
00343 #include <netinet/in.h>
00344 #include <arpa/inet.h>
00345 
00346 #include "asterisk/utils.h"
00347 #include "asterisk/lock.h"
00348 #include "asterisk/file.h"
00349 #include "asterisk/logger.h"
00350 #include "asterisk/channel.h"
00351 #include "asterisk/callerid.h"
00352 #include "asterisk/pbx.h"
00353 #include "asterisk/module.h"
00354 #include "asterisk/translate.h"
00355 #include "asterisk/features.h"
00356 #include "asterisk/options.h"
00357 #include "asterisk/cli.h"
00358 #include "asterisk/config.h"
00359 #include "asterisk/say.h"
00360 #include "asterisk/localtime.h"
00361 #include "asterisk/cdr.h"
00362 #include "asterisk/options.h"
00363 #include "asterisk/manager.h"
00364 #include "asterisk/app.h"
00365 
00366 #include <termios.h>
00367 
00368 #ifdef   NEW_ASTERISK
00369 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS };
00370 #endif
00371 
00372 
00373 /* Start a tone-list going */
00374 int ast_playtones_start(struct ast_channel *chan, int vol, const char* tonelist, int interruptible);
00375 /*! Stop the tones from playing */
00376 void ast_playtones_stop(struct ast_channel *chan);
00377 
00378 static  char *tdesc = "Radio Repeater / Remote Base  version 0.115  5/12/2008";
00379 
00380 static char *app = "Rpt";
00381 
00382 static char *synopsis = "Radio Repeater/Remote Base Control System";
00383 
00384 static char *descrip = 
00385 "  Rpt(nodename[|options][|M][|*]):  \n"
00386 "    Radio Remote Link or Remote Base Link Endpoint Process.\n"
00387 "\n"
00388 "    Not specifying an option puts it in normal endpoint mode (where source\n"
00389 "    IP and nodename are verified).\n"
00390 "\n"
00391 "    Options are as follows:\n"
00392 "\n"
00393 "        X - Normal endpoint mode WITHOUT security check. Only specify\n"
00394 "            this if you have checked security already (like with an IAX2\n"
00395 "            user/password or something).\n"
00396 "\n"
00397 "        Rannounce-string[|timeout[|timeout-destination]] - Amateur Radio\n"
00398 "            Reverse Autopatch. Caller is put on hold, and announcement (as\n"
00399 "            specified by the 'announce-string') is played on radio system.\n"
00400 "            Users of radio system can access autopatch, dial specified\n"
00401 "            code, and pick up call. Announce-string is list of names of\n"
00402 "            recordings, or \"PARKED\" to substitute code for un-parking,\n"
00403 "            or \"NODE\" to substitute node number.\n"
00404 "\n"
00405 "        P - Phone Control mode. This allows a regular phone user to have\n"
00406 "            full control and audio access to the radio system. For the\n"
00407 "            user to have DTMF control, the 'phone_functions' parameter\n"
00408 "            must be specified for the node in 'rpt.conf'. An additional\n"
00409 "            function (cop,6) must be listed so that PTT control is available.\n"
00410 "\n"
00411 "        D - Dumb Phone Control mode. This allows a regular phone user to\n"
00412 "            have full control and audio access to the radio system. In this\n"
00413 "            mode, the PTT is activated for the entire length of the call.\n"
00414 "            For the user to have DTMF control (not generally recomended in\n"
00415 "            this mode), the 'dphone_functions' parameter must be specified\n"
00416 "            for the node in 'rpt.conf'. Otherwise no DTMF control will be\n"
00417 "            available to the phone user.\n"
00418 "\n"
00419 "        S - Simplex Dumb Phone Control mode. This allows a regular phone user\n"
00420 "            audio-only access to the radio system. In this mode, the\n"
00421 "            transmitter is toggled on and off when the phone user presses the\n"
00422 "            funcchar (*) key on the telephone set. In addition, the transmitter\n"
00423 "            will turn off if the endchar (#) key is pressed. When a user first\n"
00424 "            calls in, the transmitter will be off, and the user can listen for\n"
00425 "            radio traffic. When the user wants to transmit, they press the *\n" 
00426 "            key, start talking, then press the * key again or the # key to turn\n"
00427 "            the transmitter off.  No other functions can be executed by the\n"
00428 "            user on the phone when this mode is selected. Note: If your\n"
00429 "            radio system is full-duplex, we recommend using either P or D\n"
00430 "            modes as they provide more flexibility.\n"
00431 "\n"
00432 "        q - Query Status. Sets channel variables and returns + 101 in plan.\n"
00433 "\n"
00434 "        M - Memory Channel Steer as MXX where XX is the memory channel number.\n"
00435 "\n"
00436 "        * - Alt Macro to execute (e.g. *7 for status)\n"
00437 "\n";
00438 ;
00439 
00440 static int debug = 0;  /* Set this >0 for extra debug output */
00441 static int nrpts = 0;
00442 
00443 static const char remdtmfstr[] = "0123456789*#ABCD";
00444 
00445 enum {TOP_TOP,TOP_WON,WON_BEFREAD,BEFREAD_AFTERREAD};
00446 
00447 int max_chan_stat [] = {22000,1000,22000,100,22000,2000,22000};
00448 
00449 #define NRPTSTAT 7
00450 
00451 struct rpt_chan_stat
00452 {
00453    struct timeval last;
00454    long long total;
00455    unsigned long count;
00456    unsigned long largest;
00457    struct timeval largest_time;
00458 };
00459 
00460 char *discstr = "!!DISCONNECT!!";
00461 char *newkeystr = "!NEWKEY!";
00462 static char *remote_rig_ft897="ft897";
00463 static char *remote_rig_rbi="rbi";
00464 static char *remote_rig_kenwood="kenwood";
00465 static char *remote_rig_tm271="tm271";
00466 static char *remote_rig_ic706="ic706";
00467 static char *remote_rig_rtx150="rtx150";
00468 static char *remote_rig_rtx450="rtx450";
00469 static char *remote_rig_ppp16="ppp16";       // parallel port programmable 16 channels
00470 
00471 #define ISRIG_RTX(x) ((!strcmp(x,remote_rig_rtx150)) || (!strcmp(x,remote_rig_rtx450)))
00472 #define  IS_XPMR(x) (!strncasecmp(x->rxchanname,"rad",3))
00473 
00474 #ifdef   OLD_ASTERISK
00475 STANDARD_LOCAL_USER;
00476 LOCAL_USER_DECL;
00477 #endif
00478 
00479 #define  MSWAIT 200
00480 #define  HANGTIME 5000
00481 #define  TOTIME 180000
00482 #define  IDTIME 300000
00483 #define  MAXRPTS 20
00484 #define MAX_STAT_LINKS 32
00485 #define POLITEID 30000
00486 #define FUNCTDELAY 1500
00487 
00488 #define  MAXXLAT 20
00489 #define  MAXXLATTIME 3
00490 
00491 #define MAX_SYSSTATES 10
00492 
00493 struct vox {
00494    float speech_energy;
00495    float noise_energy;
00496    int   enacount;
00497    char  voxena;
00498    char  lastvox;
00499    int   offdebcnt;
00500    int   ondebcnt;
00501 } ;
00502 
00503 #define  mymax(x,y) ((x > y) ? x : y)
00504 #define  mymin(x,y) ((x < y) ? x : y)
00505 
00506 struct rpt_topkey
00507 {
00508 char  node[TOPKEYMAXSTR];
00509 int   timesince;
00510 int   keyed;
00511 } ;
00512 
00513 struct rpt_xlat
00514 {
00515 char  funccharseq[MAXXLAT];
00516 char  endcharseq[MAXXLAT];
00517 char  passchars[MAXXLAT];
00518 int   funcindex;
00519 int   endindex;
00520 time_t   lastone;
00521 } ;
00522 
00523 static time_t  starttime = 0;
00524 
00525 static  pthread_t rpt_master_thread;
00526 
00527 struct rpt;
00528 
00529 struct rpt_link
00530 {
00531    struct rpt_link *next;
00532    struct rpt_link *prev;
00533    char  mode;       /* 1 if in tx mode */
00534    char  isremote;
00535    char  phonemode;
00536    char  phonevox;      /* vox the phone */
00537    char  name[MAXNODESTR]; /* identifier (routing) string */
00538    char  lasttx;
00539    char  lasttx1;
00540    char  lastrx;
00541    char  lastrealrx;
00542    char  lastrx1;
00543    char  connected;
00544    char  hasconnected;
00545    char  perma;
00546    char  thisconnected;
00547    char  outbound;
00548    char  disced;
00549    char  killme;
00550    long  elaptime;
00551    long  disctime;
00552    long  retrytimer;
00553    long  retxtimer;
00554    long  rerxtimer;
00555    int   retries;
00556    int   max_retries;
00557    int   reconnects;
00558    long long connecttime;
00559    struct ast_channel *chan;  
00560    struct ast_channel *pchan; 
00561    char  linklist[MAXLINKLIST];
00562    time_t   linklistreceived;
00563    long  linklisttimer;
00564    int   dtmfed;
00565    int linkunkeytocttimer;
00566    struct timeval lastlinktv;
00567    struct   ast_frame *lastf1,*lastf2;
00568    struct   rpt_chan_stat chan_stat[NRPTSTAT];
00569    struct vox vox;
00570    char wasvox;
00571    int voxtotimer;
00572    char voxtostate;
00573    char newkey;
00574 #ifdef OLD_ASTERISK
00575         AST_LIST_HEAD(, ast_frame) rxq;
00576 #else
00577    AST_LIST_HEAD_NOLOCK(, ast_frame) rxq;
00578 #endif
00579 } ;
00580 
00581 struct rpt_lstat
00582 {
00583    struct   rpt_lstat *next;
00584    struct   rpt_lstat *prev;
00585    char  peer[MAXPEERSTR];
00586    char  name[MAXNODESTR];
00587    char  mode;
00588    char  outbound;
00589    char  reconnects;
00590    char  thisconnected;
00591    long long   connecttime;
00592    struct   rpt_chan_stat chan_stat[NRPTSTAT];
00593 } ;
00594 
00595 struct rpt_tele
00596 {
00597    struct rpt_tele *next;
00598    struct rpt_tele *prev;
00599    struct rpt *rpt;
00600    struct ast_channel *chan;
00601    int   mode;
00602    struct rpt_link mylink;
00603    char param[TELEPARAMSIZE];
00604    intptr_t submode;
00605    uintptr_t  parrot;
00606    pthread_t threadid;
00607 } ;
00608 
00609 struct function_table_tag
00610 {
00611    char action[ACTIONSIZE];
00612    int (*function)(struct rpt *myrpt, char *param, char *digitbuf, 
00613       int command_source, struct rpt_link *mylink);
00614 } ;
00615 
00616 /* Used to store the morse code patterns */
00617 
00618 struct morse_bits
00619 {       
00620    int len;
00621    int ddcomb;
00622 } ;
00623 
00624 struct telem_defaults
00625 {
00626    char name[20];
00627    char value[80];
00628 } ;
00629 
00630 
00631 struct sysstate
00632 {
00633    char txdisable;
00634    char totdisable;
00635    char linkfundisable;
00636    char autopatchdisable;
00637    char schedulerdisable;
00638    char userfundisable;
00639    char alternatetail;
00640 };
00641 
00642 /* rpt cmd support */
00643 #define CMD_DEPTH 1
00644 #define CMD_STATE_IDLE 0
00645 #define CMD_STATE_BUSY 1
00646 #define CMD_STATE_READY 2
00647 #define CMD_STATE_EXECUTING 3
00648 
00649 struct rpt_cmd_struct
00650 {
00651     int state;
00652     int functionNumber;
00653     char param[MAXDTMF];
00654     char digits[MAXDTMF];
00655     int command_source;
00656 };
00657 
00658 static struct rpt
00659 {
00660    ast_mutex_t lock;
00661    ast_mutex_t remlock;
00662    ast_mutex_t statpost_lock;
00663    struct ast_config *cfg;
00664    char reload;
00665    char xlink;                         // cross link state of a share repeater/remote radio
00666    unsigned int statpost_seqno;
00667 
00668    char *name;
00669    char *rxchanname;
00670    char *txchanname;
00671    char remote;
00672    char *remoterig;
00673    struct   rpt_chan_stat chan_stat[NRPTSTAT];
00674    unsigned int scram;
00675 
00676    struct {
00677       char *ourcontext;
00678       char *ourcallerid;
00679       char *acctcode;
00680       char *ident;
00681       char *tonezone;
00682       char simple;
00683       char *functions;
00684       char *link_functions;
00685       char *phone_functions;
00686       char *dphone_functions;
00687       char *alt_functions;
00688       char *nodes;
00689       char *extnodes;
00690       char *extnodefile;
00691       int hangtime;
00692       int althangtime;
00693       int totime;
00694       int idtime;
00695       int tailmessagetime;
00696       int tailsquashedtime;
00697       int duplex;
00698       int politeid;
00699       char *tailmessages[500];
00700       int tailmessagemax;
00701       char  *memory;
00702       char  *macro;
00703       char  *tonemacro;
00704       char  *startupmacro;
00705       int iobase;
00706       char *ioport;
00707       char funcchar;
00708       char endchar;
00709       char nobusyout;
00710       char notelemtx;
00711       char propagate_dtmf;
00712       char propagate_phonedtmf;
00713       char linktolink;
00714       unsigned char civaddr;
00715       struct rpt_xlat inxlat;
00716       struct rpt_xlat outxlat;
00717       char *archivedir;
00718       int authlevel;
00719       char *csstanzaname;
00720       char *skedstanzaname;
00721       char *txlimitsstanzaname;
00722       long monminblocks;
00723       int remoteinacttimeout;
00724       int remotetimeout;
00725       int remotetimeoutwarning;
00726       int remotetimeoutwarningfreq;
00727       int sysstate_cur;
00728       struct sysstate s[MAX_SYSSTATES];
00729       char parrotmode;
00730       int parrottime;
00731       char *rptnode;
00732       char remote_mars;
00733       int voxtimeout_ms;
00734       int voxrecover_ms;
00735       int simplexpatchdelay;
00736       int simplexphonedelay;
00737       char *statpost_program;
00738       char *statpost_url;
00739    } p;
00740    struct rpt_link links;
00741    int unkeytocttimer;
00742    time_t lastkeyedtime;
00743    time_t lasttxkeyedtime;
00744    char keyed;
00745    char txkeyed;
00746    char exttx;
00747    char localtx;
00748    char remoterx;
00749    char remotetx;
00750    char remoteon;
00751    char remtxfreqok;
00752    char tounkeyed;
00753    char tonotify;
00754    char dtmfbuf[MAXDTMF];
00755    char macrobuf[MAXMACRO];
00756    char rem_dtmfbuf[MAXDTMF];
00757    char lastdtmfcommand[MAXDTMF];
00758    char cmdnode[50];
00759    char nowchan;                 // channel now
00760    char waschan;                 // channel selected initially or by command
00761    char bargechan;                  // barge in channel
00762    char macropatch;              // autopatch via tonemacro state
00763    char parrotstate;
00764    int  parrottimer;
00765    unsigned int parrotcnt;
00766    struct ast_channel *rxchannel,*txchannel, *monchannel, *parrotchannel;
00767    struct ast_channel *pchannel,*txpchannel, *dahdirxchannel, *dahditxchannel;
00768    struct ast_channel *voxchannel;
00769    struct ast_frame *lastf1,*lastf2;
00770    struct rpt_tele tele;
00771    struct timeval lasttv,curtv;
00772    pthread_t rpt_call_thread,rpt_thread;
00773    time_t dtmf_time,rem_dtmf_time,dtmf_time_rem;
00774    int calldigittimer;
00775    int tailtimer,totimer,idtimer,txconf,conf,callmode,cidx,scantimer,tmsgtimer,skedtimer;
00776    int mustid,tailid;
00777    int tailevent;
00778    int telemrefcount;
00779    int dtmfidx,rem_dtmfidx;
00780    int dailytxtime,dailykerchunks,totalkerchunks,dailykeyups,totalkeyups,timeouts;
00781    int totalexecdcommands, dailyexecdcommands;
00782    long  retxtimer;
00783    long  rerxtimer;
00784    long long totaltxtime;
00785    char mydtmf;
00786    char exten[AST_MAX_EXTENSION];
00787    char freq[MAXREMSTR],rxpl[MAXREMSTR],txpl[MAXREMSTR];
00788    char offset;
00789    char powerlevel;
00790    char txplon;
00791    char rxplon;
00792    char remmode;
00793    char tunerequest;
00794    char hfscanmode;
00795    int hfscanstatus;
00796    char hfscanstop;
00797    char lastlinknode[MAXNODESTR];
00798    char savednodes[MAXNODESTR];
00799    int stopgen;
00800    char patchfarenddisconnect;
00801    char patchnoct;
00802    char patchquiet;
00803    char patchcontext[MAXPATCHCONTEXT];
00804    int patchdialtime;
00805    int macro_longest;
00806    int phone_longestfunc;
00807    int alt_longestfunc;
00808    int dphone_longestfunc;
00809    int link_longestfunc;
00810    int longestfunc;
00811    int longestnode;
00812    int threadrestarts;     
00813    int tailmessagen;
00814    time_t disgorgetime;
00815    time_t lastthreadrestarttime;
00816    long  macrotimer;
00817    char  lastnodewhichkeyedusup[MAXNODESTR];
00818    int   dtmf_local_timer;
00819    char  dtmf_local_str[100];
00820    struct ast_filestream *monstream,*parrotstream;
00821    char  loginuser[50];
00822    char  loginlevel[10];
00823    long  authtelltimer;
00824    long  authtimer;
00825    int iofd;
00826    time_t start_time,last_activity_time;
00827    char  lasttone[32];
00828    struct rpt_tele *active_telem;
00829    struct   rpt_topkey topkey[TOPKEYN];
00830    int topkeystate;
00831    time_t topkeytime;
00832    int topkeylong;
00833    struct vox vox;
00834    char wasvox;
00835    int voxtotimer;
00836    char voxtostate;
00837    int linkposttimer;         
00838    int keyposttimer;       
00839    char newkey;
00840    char inpadtest;
00841 #ifdef OLD_ASTERISK
00842    AST_LIST_HEAD(, ast_frame) txq;
00843 #else
00844    AST_LIST_HEAD_NOLOCK(, ast_frame) txq;
00845 #endif
00846    char txrealkeyed;
00847 #ifdef   __RPT_NOTCH
00848    struct rptfilter
00849    {
00850       char  desc[100];
00851       float x0;
00852       float x1;
00853       float x2;
00854       float y0;
00855       float y1;
00856       float y2;
00857       float gain;
00858       float const0;
00859       float const1;
00860       float const2;
00861    } filters[MAXFILTERS];
00862 #endif
00863 #ifdef   _MDC_DECODE_H_
00864    mdc_decoder_t *mdc;
00865    unsigned short lastunit;
00866 #endif
00867    struct rpt_cmd_struct cmdAction;
00868 } rpt_vars[MAXRPTS]; 
00869 
00870 struct nodelog {
00871 struct nodelog *next;
00872 struct nodelog *prev;
00873 time_t   timestamp;
00874 char archivedir[MAXNODESTR];
00875 char str[MAXNODESTR * 2];
00876 } nodelog;
00877 
00878 static int service_scan(struct rpt *myrpt);
00879 static int set_mode_ft897(struct rpt *myrpt, char newmode);
00880 static int set_mode_ic706(struct rpt *myrpt, char newmode);
00881 static int simple_command_ft897(struct rpt *myrpt, char command);
00882 static int setrem(struct rpt *myrpt);
00883 static int setrtx_check(struct rpt *myrpt);
00884 static int channel_revert(struct rpt *myrpt);
00885 static int channel_steer(struct rpt *myrpt, char *data);
00886 
00887 AST_MUTEX_DEFINE_STATIC(nodeloglock);
00888 
00889 AST_MUTEX_DEFINE_STATIC(nodelookuplock);
00890 
00891 #ifdef   APP_RPT_LOCK_DEBUG
00892 
00893 #warning COMPILING WITH LOCK-DEBUGGING ENABLED!!
00894 
00895 #define  MAXLOCKTHREAD 100
00896 
00897 #define rpt_mutex_lock(x) _rpt_mutex_lock(x,myrpt,__LINE__)
00898 #define rpt_mutex_unlock(x) _rpt_mutex_unlock(x,myrpt,__LINE__)
00899 
00900 struct lockthread
00901 {
00902    pthread_t id;
00903    int lockcount;
00904    int lastlock;
00905    int lastunlock;
00906 } lockthreads[MAXLOCKTHREAD];
00907 
00908 
00909 struct by_lightning
00910 {
00911    int line;
00912    struct timeval tv;
00913    struct rpt *rpt;
00914    struct lockthread lockthread;
00915 } lock_ring[32];
00916 
00917 int lock_ring_index = 0;
00918 
00919 AST_MUTEX_DEFINE_STATIC(locklock);
00920 
00921 static struct lockthread *get_lockthread(pthread_t id)
00922 {
00923 int   i;
00924 
00925    for(i = 0; i < MAXLOCKTHREAD; i++)
00926    {
00927       if (lockthreads[i].id == id) return(&lockthreads[i]);
00928    }
00929    return(NULL);
00930 }
00931 
00932 static struct lockthread *put_lockthread(pthread_t id)
00933 {
00934 int   i;
00935 
00936    for(i = 0; i < MAXLOCKTHREAD; i++)
00937    {
00938       if (lockthreads[i].id == id)
00939          return(&lockthreads[i]);
00940    }
00941    for(i = 0; i < MAXLOCKTHREAD; i++)
00942    {
00943       if (!lockthreads[i].id)
00944       {
00945          lockthreads[i].lockcount = 0;
00946          lockthreads[i].lastlock = 0;
00947          lockthreads[i].lastunlock = 0;
00948          lockthreads[i].id = id;
00949          return(&lockthreads[i]);
00950       }
00951    }
00952    return(NULL);
00953 }
00954 
00955 
00956 static void rpt_mutex_spew(void)
00957 {
00958    struct by_lightning lock_ring_copy[32];
00959    int lock_ring_index_copy;
00960    int i,j;
00961    long long diff;
00962    char a[100];
00963    struct timeval lasttv;
00964 
00965    ast_mutex_lock(&locklock);
00966    memcpy(&lock_ring_copy, &lock_ring, sizeof(lock_ring_copy));
00967    lock_ring_index_copy = lock_ring_index;
00968    ast_mutex_unlock(&locklock);
00969 
00970    lasttv.tv_sec = lasttv.tv_usec = 0;
00971    for(i = 0 ; i < 32 ; i++)
00972    {
00973       j = (i + lock_ring_index_copy) % 32;
00974       strftime(a,sizeof(a) - 1,"%m/%d/%Y %H:%M:%S",
00975          localtime(&lock_ring_copy[j].tv.tv_sec));
00976       diff = 0;
00977       if(lasttv.tv_sec)
00978       {
00979          diff = (lock_ring_copy[j].tv.tv_sec - lasttv.tv_sec)
00980             * 1000000;
00981          diff += (lock_ring_copy[j].tv.tv_usec - lasttv.tv_usec);
00982       }
00983       lasttv.tv_sec = lock_ring_copy[j].tv.tv_sec;
00984       lasttv.tv_usec = lock_ring_copy[j].tv.tv_usec;
00985       if (!lock_ring_copy[j].tv.tv_sec) continue;
00986       if (lock_ring_copy[j].line < 0)
00987       {
00988          ast_log(LOG_NOTICE,"LOCKDEBUG [#%d] UNLOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
00989             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);
00990       }
00991       else
00992       {
00993          ast_log(LOG_NOTICE,"LOCKDEBUG [#%d] LOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
00994             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);
00995       }
00996    }
00997 }
00998 
00999 
01000 static void _rpt_mutex_lock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
01001 {
01002 struct lockthread *t;
01003 pthread_t id;
01004 
01005    id = pthread_self();
01006    ast_mutex_lock(&locklock);
01007    t = put_lockthread(id);
01008    if (!t)
01009    {
01010       ast_mutex_unlock(&locklock);
01011       return;
01012    }
01013    if (t->lockcount)
01014    {
01015       int lastline = t->lastlock;
01016       ast_mutex_unlock(&locklock);
01017       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);
01018       rpt_mutex_spew();
01019       return;
01020    }
01021    t->lastlock = line;
01022    t->lockcount = 1;
01023    gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
01024    lock_ring[lock_ring_index].rpt = myrpt;
01025    memcpy(&lock_ring[lock_ring_index].lockthread,t,sizeof(struct lockthread));
01026    lock_ring[lock_ring_index++].line = line;
01027    if(lock_ring_index == 32)
01028       lock_ring_index = 0;
01029    ast_mutex_unlock(&locklock);
01030    ast_mutex_lock(lockp);
01031 }
01032 
01033 
01034 static void _rpt_mutex_unlock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
01035 {
01036 struct lockthread *t;
01037 pthread_t id;
01038 
01039    id = pthread_self();
01040    ast_mutex_lock(&locklock);
01041    t = put_lockthread(id);
01042    if (!t)
01043    {
01044       ast_mutex_unlock(&locklock);
01045       return;
01046    }
01047    if (!t->lockcount)
01048    {
01049       int lastline = t->lastunlock;
01050       ast_mutex_unlock(&locklock);
01051       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);
01052       rpt_mutex_spew();
01053       return;
01054    }
01055    t->lastunlock = line;
01056    t->lockcount = 0;
01057    gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
01058    lock_ring[lock_ring_index].rpt = myrpt;
01059    memcpy(&lock_ring[lock_ring_index].lockthread,t,sizeof(struct lockthread));
01060    lock_ring[lock_ring_index++].line = -line;
01061    if(lock_ring_index == 32)
01062       lock_ring_index = 0;
01063    ast_mutex_unlock(&locklock);
01064    ast_mutex_unlock(lockp);
01065 }
01066 
01067 #else  /* APP_RPT_LOCK_DEBUG */
01068 
01069 #define rpt_mutex_lock(x) ast_mutex_lock(x)
01070 #define rpt_mutex_unlock(x) ast_mutex_unlock(x)
01071 
01072 #endif  /* APP_RPT_LOCK_DEBUG */
01073 
01074 /*
01075 * Return 1 if rig is multimode capable
01076 */
01077 
01078 static int multimode_capable(struct rpt *myrpt)
01079 {
01080    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
01081       return 1;
01082    if(!strcmp(myrpt->remoterig, remote_rig_ic706))
01083       return 1;
01084    return 0;
01085 }  
01086 
01087 static void voxinit_rpt(struct rpt *myrpt,char enable)
01088 {
01089 
01090    myrpt->vox.speech_energy = 0.0;
01091    myrpt->vox.noise_energy = 0.0;
01092    myrpt->vox.enacount = 0;
01093    myrpt->vox.voxena = 0;
01094    if (!enable) myrpt->vox.voxena = -1;
01095    myrpt->vox.lastvox = 0;
01096    myrpt->vox.ondebcnt = VOX_ON_DEBOUNCE_COUNT;
01097    myrpt->vox.offdebcnt = VOX_OFF_DEBOUNCE_COUNT;
01098    myrpt->wasvox = 0;
01099    myrpt->voxtotimer = 0;
01100    myrpt->voxtostate = 0;
01101 }
01102 
01103 static void voxinit_link(struct rpt_link *mylink,char enable)
01104 {
01105 
01106    mylink->vox.speech_energy = 0.0;
01107    mylink->vox.noise_energy = 0.0;
01108    mylink->vox.enacount = 0;
01109    mylink->vox.voxena = 0;
01110    if (!enable) mylink->vox.voxena = -1;
01111    mylink->vox.lastvox = 0;
01112    mylink->vox.ondebcnt = VOX_ON_DEBOUNCE_COUNT;
01113    mylink->vox.offdebcnt = VOX_OFF_DEBOUNCE_COUNT;
01114    mylink->wasvox = 0;
01115    mylink->voxtotimer = 0;
01116    mylink->voxtostate = 0;
01117 }
01118 
01119 static int dovox(struct vox *v,short *buf,int bs)
01120 {
01121 
01122    int i;
01123    float esquare = 0.0;
01124    float energy = 0.0;
01125    float threshold = 0.0;
01126    
01127    if (v->voxena < 0) return(v->lastvox);
01128    for(i = 0; i < bs; i++)
01129    {
01130       esquare += (float) buf[i] * (float) buf[i];
01131    }
01132    energy = sqrt(esquare);
01133 
01134    if (energy >= v->speech_energy)
01135       v->speech_energy += (energy - v->speech_energy) / 4;
01136    else
01137       v->speech_energy += (energy - v->speech_energy) / 64;
01138 
01139    if (energy >= v->noise_energy)
01140       v->noise_energy += (energy - v->noise_energy) / 64;
01141    else
01142       v->noise_energy += (energy - v->noise_energy) / 4;
01143    
01144    if (v->voxena) threshold = v->speech_energy / 8;
01145    else
01146    {
01147       threshold = mymax(v->speech_energy / 16,v->noise_energy * 2);
01148       threshold = mymin(threshold,VOX_MAX_THRESHOLD);
01149    }
01150    threshold = mymax(threshold,VOX_MIN_THRESHOLD);
01151    if (energy > threshold)
01152    {
01153       if (v->voxena) v->noise_energy *= 0.75;
01154       v->voxena = 1;
01155    } else   v->voxena = 0;
01156    if (v->lastvox != v->voxena)
01157    {
01158       if (v->enacount++ >= ((v->lastvox) ? v->offdebcnt : v->ondebcnt))
01159       {
01160          v->lastvox = v->voxena;
01161          v->enacount = 0;
01162       }
01163    } else v->enacount = 0;
01164    return(v->lastvox);
01165 }
01166 
01167 
01168 
01169 
01170 /*
01171 * CLI extensions
01172 */
01173 
01174 /* Debug mode */
01175 static int rpt_do_debug(int fd, int argc, const char * const *argv);
01176 static int rpt_do_dump(int fd, int argc, const char * const *argv);
01177 static int rpt_do_stats(int fd, int argc, const char * const *argv);
01178 static int rpt_do_lstats(int fd, int argc, const char * const *argv);
01179 static int rpt_do_nodes(int fd, int argc, const char * const *argv);
01180 static int rpt_do_local_nodes(int fd, int argc, const char * const *argv);
01181 static int rpt_do_reload(int fd, int argc, const char * const *argv);
01182 static int rpt_do_restart(int fd, int argc, const char * const *argv);
01183 static int rpt_do_fun(int fd, int argc, const char * const *argv);
01184 static int rpt_do_fun1(int fd, int argc, const char * const *argv);
01185 static int rpt_do_cmd(int fd, int argc, const char * const *argv);
01186 
01187 static char debug_usage[] =
01188 "Usage: rpt debug level {0-7}\n"
01189 "       Enables debug messages in app_rpt\n";
01190 
01191 static char dump_usage[] =
01192 "Usage: rpt dump <nodename>\n"
01193 "       Dumps struct debug info to log\n";
01194 
01195 static char dump_stats[] =
01196 "Usage: rpt stats <nodename>\n"
01197 "       Dumps node statistics to console\n";
01198 
01199 static char dump_lstats[] =
01200 "Usage: rpt lstats <nodename>\n"
01201 "       Dumps link statistics to console\n";
01202 
01203 static char dump_nodes[] =
01204 "Usage: rpt nodes <nodename>\n"
01205 "       Dumps a list of directly and indirectly connected nodes to the console\n";
01206 
01207 static char usage_local_nodes[] =
01208 "Usage: rpt localnodes\n"
01209 "       Dumps a list of the locally configured node numbers to the console.\n";
01210 
01211 static char reload_usage[] =
01212 "Usage: rpt reload\n"
01213 "       Reloads app_rpt running config parameters\n";
01214 
01215 static char restart_usage[] =
01216 "Usage: rpt restart\n"
01217 "       Restarts app_rpt\n";
01218 
01219 static char fun_usage[] =
01220 "Usage: rpt fun <nodename> <command>\n"
01221 "       Send a DTMF function to a node\n";
01222 
01223 static char cmd_usage[] =
01224 "Usage: rpt cmd <nodename> <cmd-name> <cmd-index> <cmd-args.\n"
01225 "       Send a command to a node.\n        i.e. rpt cmd 2000 ilink 3 2001\n";
01226 
01227 #ifndef  NEW_ASTERISK
01228 
01229 static struct ast_cli_entry  cli_debug =
01230         { { "rpt", "debug", "level" }, rpt_do_debug, 
01231       "Enable app_rpt debugging", debug_usage };
01232 
01233 static struct ast_cli_entry  cli_dump =
01234         { { "rpt", "dump" }, rpt_do_dump,
01235       "Dump app_rpt structs for debugging", dump_usage };
01236 
01237 static struct ast_cli_entry  cli_stats =
01238         { { "rpt", "stats" }, rpt_do_stats,
01239       "Dump node statistics", dump_stats };
01240 
01241 static struct ast_cli_entry  cli_nodes =
01242         { { "rpt", "nodes" }, rpt_do_nodes,
01243       "Dump node list", dump_nodes };
01244 
01245 static struct ast_cli_entry  cli_local_nodes =
01246         { { "rpt", "localnodes" }, rpt_do_local_nodes,
01247       "Dump list of local node numbers", usage_local_nodes };
01248 
01249 static struct ast_cli_entry  cli_lstats =
01250         { { "rpt", "lstats" }, rpt_do_lstats,
01251       "Dump link statistics", dump_lstats };
01252 
01253 static struct ast_cli_entry  cli_reload =
01254         { { "rpt", "reload" }, rpt_do_reload,
01255       "Reload app_rpt config", reload_usage };
01256 
01257 static struct ast_cli_entry  cli_restart =
01258         { { "rpt", "restart" }, rpt_do_restart,
01259       "Restart app_rpt", restart_usage };
01260 
01261 static struct ast_cli_entry  cli_fun =
01262         { { "rpt", "fun" }, rpt_do_fun,
01263       "Execute a DTMF function", fun_usage };
01264 
01265 static struct ast_cli_entry  cli_fun1 =
01266         { { "rpt", "fun1" }, rpt_do_fun1,
01267       "Execute a DTMF function", fun_usage };
01268 
01269 static struct ast_cli_entry  cli_cmd =
01270         { { "rpt", "cmd" }, rpt_do_cmd,
01271       "Execute a DTMF function", cmd_usage };
01272 
01273 #endif
01274 
01275 /*
01276 * Telemetry defaults
01277 */
01278 
01279 
01280 static struct telem_defaults tele_defs[] = {
01281    {"ct1","|t(350,0,100,3072)(500,0,100,3072)(660,0,100,3072)"},
01282    {"ct2","|t(660,880,150,3072)"},
01283    {"ct3","|t(440,0,150,3072)"},
01284    {"ct4","|t(550,0,150,3072)"},
01285    {"ct5","|t(660,0,150,3072)"},
01286    {"ct6","|t(880,0,150,3072)"},
01287    {"ct7","|t(660,440,150,3072)"},
01288    {"ct8","|t(700,1100,150,3072)"},
01289    {"remotemon","|t(1600,0,75,2048)"},
01290    {"remotetx","|t(2000,0,75,2048)(0,0,75,0)(1600,0,75,2048)"},
01291    {"cmdmode","|t(900,904,200,2048)"},
01292    {"functcomplete","|t(1000,0,100,2048)(0,0,100,0)(1000,0,100,2048)"}
01293 } ;
01294 
01295 /*
01296 * Forward decl's - these suppress compiler warnings when funcs coded further down the file than thier invokation
01297 */
01298 
01299 static int setrbi(struct rpt *myrpt);
01300 static int set_ft897(struct rpt *myrpt);
01301 static int set_ic706(struct rpt *myrpt);
01302 static int setkenwood(struct rpt *myrpt);
01303 static int set_tm271(struct rpt *myrpt);
01304 static int setrbi_check(struct rpt *myrpt);
01305 
01306 
01307 
01308 /*
01309 * Define function protos for function table here
01310 */
01311 
01312 static int function_ilink(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01313 static int function_autopatchup(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01314 static int function_autopatchdn(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01315 static int function_status(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01316 static int function_cop(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01317 static int function_remote(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01318 static int function_macro(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01319 static int function_playback(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
01320 /*
01321 * Function table
01322 */
01323 
01324 static struct function_table_tag function_table[] = {
01325    {"cop", function_cop},
01326    {"autopatchup", function_autopatchup},
01327    {"autopatchdn", function_autopatchdn},
01328    {"ilink", function_ilink},
01329    {"status", function_status},
01330    {"remote", function_remote},
01331    {"macro", function_macro},
01332    {"playback", function_playback}
01333 } ;
01334 
01335 static long diskavail(struct rpt *myrpt)
01336 {
01337 struct   statfs statfsbuf;
01338 
01339    if (!myrpt->p.archivedir) return(0);
01340    if (statfs(myrpt->p.archivedir,&statfsbuf) == -1)
01341    {
01342       ast_log(LOG_WARNING,"Cannot get filesystem size for %s node %s\n",
01343          myrpt->p.archivedir,myrpt->name);
01344       return(-1);
01345    }
01346    return(statfsbuf.f_bavail);
01347 }
01348 
01349 static void flush_telem(struct rpt *myrpt)
01350 {
01351    struct rpt_tele *telem;
01352    if(debug > 2)
01353       ast_log(LOG_NOTICE, "flush_telem()!!");
01354    rpt_mutex_lock(&myrpt->lock);
01355    telem = myrpt->tele.next;
01356    while(telem != &myrpt->tele)
01357    {
01358       if (telem->mode != SETREMOTE) ast_softhangup(telem->chan,AST_SOFTHANGUP_DEV);
01359       telem = telem->next;
01360    }
01361    rpt_mutex_unlock(&myrpt->lock);
01362 }
01363 /*
01364    return via error priority
01365 */
01366 static int priority_jump(struct rpt *myrpt, struct ast_channel *chan)
01367 {
01368    int res=0;
01369 
01370    // if (ast_test_flag(&flags,OPT_JUMP) && ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101) == 0){
01371    if (ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101) == 0){
01372       res = 0;
01373    } else {
01374       res = -1;
01375    }
01376    return res;
01377 }
01378 /*
01379 */
01380 static int linkcount(struct rpt *myrpt)
01381 {
01382    struct   rpt_link *l;
01383    int numoflinks;
01384 
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       numoflinks++;
01394 
01395       l = l->next;
01396    }
01397    ast_log(LOG_NOTICE, "numoflinks=%i\n",numoflinks);
01398    return numoflinks;
01399 }
01400 /*
01401  * Retrieve a memory channel
01402  * Return 0 if sucessful,
01403  * -1 if channel not found,
01404  *  1 if parse error
01405  */
01406 static int retreive_memory(struct rpt *myrpt, char *memory)
01407 {
01408    char tmp[30], *s, *s1, *val;
01409 
01410    if (debug)ast_log(LOG_NOTICE, "memory=%s block=%s\n",memory,myrpt->p.memory);
01411 
01412    val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.memory, memory);
01413    if (!val){
01414       return -1;
01415    }        
01416    strncpy(tmp,val,sizeof(tmp) - 1);
01417    tmp[sizeof(tmp)-1] = 0;
01418 
01419    s = strchr(tmp,',');
01420    if (!s)
01421       return 1; 
01422    *s++ = 0;
01423    s1 = strchr(s,',');
01424    if (!s1)
01425       return 1;
01426    *s1++ = 0;
01427    strncpy(myrpt->freq, tmp, sizeof(myrpt->freq) - 1);
01428    strncpy(myrpt->rxpl, s, sizeof(myrpt->rxpl) - 1);
01429    strncpy(myrpt->txpl, s, sizeof(myrpt->rxpl) - 1);
01430    myrpt->remmode = REM_MODE_FM;
01431    myrpt->offset = REM_SIMPLEX;
01432    myrpt->powerlevel = REM_MEDPWR;
01433    myrpt->txplon = myrpt->rxplon = 0;
01434    while(*s1){
01435       switch(*s1++){
01436          case 'A':
01437          case 'a':
01438             strcpy(myrpt->rxpl, "100.0");
01439             strcpy(myrpt->txpl, "100.0");
01440             myrpt->remmode = REM_MODE_AM; 
01441             break;
01442          case 'B':
01443          case 'b':
01444             strcpy(myrpt->rxpl, "100.0");
01445             strcpy(myrpt->txpl, "100.0");
01446             myrpt->remmode = REM_MODE_LSB;
01447             break;
01448          case 'F':
01449             myrpt->remmode = REM_MODE_FM;
01450             break;
01451          case 'L':
01452          case 'l':
01453             myrpt->powerlevel = REM_LOWPWR;
01454             break;               
01455          case 'H':
01456          case 'h':
01457             myrpt->powerlevel = REM_HIPWR;
01458             break;
01459                
01460          case 'M':
01461          case 'm':
01462             myrpt->powerlevel = REM_MEDPWR;
01463             break;
01464                   
01465          case '-':
01466             myrpt->offset = REM_MINUS;
01467             break;
01468                   
01469          case '+':
01470             myrpt->offset = REM_PLUS;
01471             break;
01472                   
01473          case 'S':
01474          case 's':
01475             myrpt->offset = REM_SIMPLEX;
01476             break;
01477                   
01478          case 'T':
01479          case 't':
01480             myrpt->txplon = 1;
01481             break;
01482                   
01483          case 'R':
01484          case 'r':
01485             myrpt->rxplon = 1;
01486             break;
01487 
01488          case 'U':
01489          case 'u':
01490             strcpy(myrpt->rxpl, "100.0");
01491             strcpy(myrpt->txpl, "100.0");
01492             myrpt->remmode = REM_MODE_USB;
01493             break;
01494          default:
01495             return 1;
01496       }
01497    }
01498    return 0;
01499 }
01500 /*
01501 
01502 */
01503 static void birdbath(struct rpt *myrpt)
01504 {
01505    struct rpt_tele *telem;
01506    if(debug > 2)
01507       ast_log(LOG_NOTICE, "birdbath!!");
01508    rpt_mutex_lock(&myrpt->lock);
01509    telem = myrpt->tele.next;
01510    while(telem != &myrpt->tele)
01511    {
01512       if (telem->mode == PARROT) ast_softhangup(telem->chan,AST_SOFTHANGUP_DEV);
01513       telem = telem->next;
01514    }
01515    rpt_mutex_unlock(&myrpt->lock);
01516 }
01517 
01518 static void do_dtmf_phone(struct rpt *myrpt, struct rpt_link *mylink, char c)
01519 {
01520 struct        rpt_link *l;
01521 
01522        l = myrpt->links.next;
01523        /* go thru all the links */
01524        while(l != &myrpt->links)
01525        {
01526                if (!l->phonemode)
01527                {
01528                        l = l->next;
01529                        continue;
01530                }
01531                /* don't send to self */
01532                if (mylink && (l == mylink))
01533                {
01534                        l = l->next;
01535                        continue;
01536                }
01537 #ifdef   NEW_ASTERISK
01538                if (l->chan) ast_senddigit(l->chan,c,0);
01539 #else
01540                if (l->chan) ast_senddigit(l->chan,c);
01541 #endif
01542                l = l->next;
01543        }
01544        return;
01545 }
01546 
01547 /* node logging function */
01548 static void donodelog(struct rpt *myrpt,char *str)
01549 {
01550 struct nodelog *nodep;
01551 char  datestr[100];
01552 
01553    if (!myrpt->p.archivedir) return;
01554    nodep = (struct nodelog *)ast_malloc(sizeof(struct nodelog));
01555    if (nodep == NULL)
01556    {
01557       ast_log(LOG_ERROR,"Cannot get memory for node log");
01558       return;
01559    }
01560    time(&nodep->timestamp);
01561    strncpy(nodep->archivedir,myrpt->p.archivedir,
01562       sizeof(nodep->archivedir) - 1);
01563    strftime(datestr,sizeof(datestr) - 1,"%Y%m%d%H%M%S",
01564       localtime(&nodep->timestamp));
01565    snprintf(nodep->str,sizeof(nodep->str) - 1,"%s %s,%s\n",
01566       myrpt->name,datestr,str);
01567    ast_mutex_lock(&nodeloglock);
01568    insque((struct qelem *) nodep, (struct qelem *) nodelog.prev);
01569    ast_mutex_unlock(&nodeloglock);
01570 }
01571 
01572 /* must be called locked */
01573 static void do_dtmf_local(struct rpt *myrpt, char c)
01574 {
01575 int   i;
01576 char  digit;
01577 static const char* dtmf_tones[] = {
01578    "!941+1336/200,!0/200", /* 0 */
01579    "!697+1209/200,!0/200", /* 1 */
01580    "!697+1336/200,!0/200", /* 2 */
01581    "!697+1477/200,!0/200", /* 3 */
01582    "!770+1209/200,!0/200", /* 4 */
01583    "!770+1336/200,!0/200", /* 5 */
01584    "!770+1477/200,!0/200", /* 6 */
01585    "!852+1209/200,!0/200", /* 7 */
01586    "!852+1336/200,!0/200", /* 8 */
01587    "!852+1477/200,!0/200", /* 9 */
01588    "!697+1633/200,!0/200", /* A */
01589    "!770+1633/200,!0/200", /* B */
01590    "!852+1633/200,!0/200", /* C */
01591    "!941+1633/200,!0/200", /* D */
01592    "!941+1209/200,!0/200", /* * */
01593    "!941+1477/200,!0/200" };  /* # */
01594 
01595 
01596    if (c)
01597    {
01598       snprintf(myrpt->dtmf_local_str + strlen(myrpt->dtmf_local_str),sizeof(myrpt->dtmf_local_str) - 1,"%c",c);
01599       if (!myrpt->dtmf_local_timer) 
01600           myrpt->dtmf_local_timer = DTMF_LOCAL_STARTTIME;
01601    }
01602    /* if at timeout */
01603    if (myrpt->dtmf_local_timer == 1)
01604    {
01605       if(debug > 6)
01606          ast_log(LOG_NOTICE,"time out dtmf_local_timer=%i\n",myrpt->dtmf_local_timer);
01607 
01608       /* if anything in the string */
01609       if (myrpt->dtmf_local_str[0])
01610       {
01611          digit = myrpt->dtmf_local_str[0];
01612          myrpt->dtmf_local_str[0] = 0;
01613          for(i = 1; myrpt->dtmf_local_str[i]; i++)
01614          {
01615             myrpt->dtmf_local_str[i - 1] =
01616                myrpt->dtmf_local_str[i];
01617          }
01618          myrpt->dtmf_local_str[i - 1] = 0;
01619          myrpt->dtmf_local_timer = DTMF_LOCAL_TIME;
01620          rpt_mutex_unlock(&myrpt->lock);
01621          if (digit >= '0' && digit <='9')
01622             ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[digit-'0'], 0);
01623          else if (digit >= 'A' && digit <= 'D')
01624             ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[digit-'A'+10], 0);
01625          else if (digit == '*')
01626             ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[14], 0);
01627          else if (digit == '#')
01628             ast_playtones_start(myrpt->txchannel, 0, dtmf_tones[15], 0);
01629          else {
01630             /* not handled */
01631             ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, myrpt->txchannel->name);
01632          }
01633          rpt_mutex_lock(&myrpt->lock);
01634       }
01635       else
01636       {
01637          myrpt->dtmf_local_timer = 0;
01638       }
01639    }
01640 }
01641 
01642 static int setdtr(int fd, int enable)
01643 {
01644 struct termios mode;
01645 
01646    if (fd < 0) return -1;
01647    if (tcgetattr(fd, &mode)) {
01648       ast_log(LOG_WARNING, "Unable to get serial parameters for dtr: %s\n", strerror(errno));
01649       return -1;
01650    }
01651    if (enable)
01652    {
01653       cfsetspeed(&mode, B9600);
01654    }
01655    else
01656    {
01657       cfsetspeed(&mode, B0);
01658       usleep(100000);
01659    }
01660    if (tcsetattr(fd, TCSADRAIN, &mode)) {
01661       ast_log(LOG_WARNING, "Unable to set serial parameters for dtr: %s\n", strerror(errno));
01662       return -1;
01663    }
01664    if (enable) usleep(100000);
01665    return 0;
01666 }
01667 
01668 static int openserial(struct rpt *myrpt,char *fname)
01669 {
01670    struct termios mode;
01671    int fd;
01672 
01673    fd = open(fname,O_RDWR);
01674    if (fd == -1)
01675    {
01676       ast_log(LOG_WARNING,"Cannot open serial port %s\n",fname);
01677       return -1;
01678    }
01679    memset(&mode, 0, sizeof(mode));
01680    if (tcgetattr(fd, &mode)) {
01681       ast_log(LOG_WARNING, "Unable to get serial parameters on %s: %s\n", fname, strerror(errno));
01682       return -1;
01683    }
01684 #ifndef  SOLARIS
01685    cfmakeraw(&mode);
01686 #else
01687         mode.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
01688                         |INLCR|IGNCR|ICRNL|IXON);
01689         mode.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
01690         mode.c_cflag &= ~(CSIZE|PARENB|CRTSCTS);
01691         mode.c_cflag |= CS8;
01692    mode.c_cc[VTIME] = 3;
01693    mode.c_cc[VMIN] = 1; 
01694 #endif
01695 
01696    cfsetispeed(&mode, B9600);
01697    cfsetospeed(&mode, B9600);
01698    if (tcsetattr(fd, TCSANOW, &mode)) 
01699       ast_log(LOG_WARNING, "Unable to set serial parameters on %s: %s\n", fname, strerror(errno));
01700    if(!strcmp(myrpt->remoterig, remote_rig_kenwood)) setdtr(fd,0); 
01701    usleep(100000);
01702    if (debug)ast_log(LOG_NOTICE,"Opened serial port %s\n",fname);
01703    return(fd); 
01704 }
01705 
01706 static void mdc1200_notify(struct rpt *myrpt,char *fromnode, unsigned int unit)
01707 {
01708    if (!fromnode)
01709    {
01710       ast_verbose("Got MDC-1200 ID %04X from local system (%s)\n",
01711          unit,myrpt->name);
01712    }
01713    else
01714    {
01715       ast_verbose("Got MDC-1200 ID %04X from node %s (%s)\n",
01716          unit,fromnode,myrpt->name);
01717    }
01718 }
01719 
01720 #ifdef   _MDC_DECODE_H_
01721 
01722 static void mdc1200_send(struct rpt *myrpt, unsigned int unit)
01723 {
01724 struct rpt_link *l;
01725 struct   ast_frame wf;
01726 char  str[200];
01727 
01728 
01729    sprintf(str,"I %s %04X",myrpt->name,unit);
01730 
01731    wf.frametype = AST_FRAME_TEXT;
01732    wf.subclass.integer = 0;
01733    wf.offset = 0;
01734    wf.mallocd = 0;
01735    wf.datalen = strlen(str) + 1;
01736    wf.samples = 0;
01737 
01738 
01739    l = myrpt->links.next;
01740    /* otherwise, send it to all of em */
01741    while(l != &myrpt->links)
01742    {
01743       if (l->name[0] == '0') 
01744       {
01745          l = l->next;
01746          continue;
01747       }
01748       wf.data = str;
01749       if (l->chan) ast_write(l->chan,&wf); 
01750       l = l->next;
01751    }
01752    return;
01753 }
01754 
01755 #endif
01756 
01757 static char func_xlat(struct rpt *myrpt,char c,struct rpt_xlat *xlat)
01758 {
01759 time_t   now;
01760 int   gotone;
01761 
01762    time(&now);
01763    gotone = 0;
01764    /* if too much time, reset the skate machine */
01765    if ((now - xlat->lastone) > MAXXLATTIME)
01766    {
01767       xlat->funcindex = xlat->endindex = 0;
01768    }
01769    if (xlat->funccharseq[0] && (c == xlat->funccharseq[xlat->funcindex++]))
01770    {
01771       time(&xlat->lastone);
01772       gotone = 1;
01773       if (!xlat->funccharseq[xlat->funcindex])
01774       {
01775          xlat->funcindex = xlat->endindex = 0;
01776          return(myrpt->p.funcchar);
01777       }
01778    } else xlat->funcindex = 0;
01779    if (xlat->endcharseq[0] && (c == xlat->endcharseq[xlat->endindex++]))
01780    {
01781       time(&xlat->lastone);
01782       gotone = 1;
01783       if (!xlat->endcharseq[xlat->endindex])
01784       {
01785          xlat->funcindex = xlat->endindex = 0;
01786          return(myrpt->p.endchar);
01787       }
01788    } else xlat->endindex = 0;
01789    /* if in middle of decode seq, send nothing back */
01790    if (gotone) return(0);
01791    /* if no pass chars specified, return em all */
01792    if (!xlat->passchars[0]) return(c);
01793    /* if a "pass char", pass it */
01794    if (strchr(xlat->passchars,c)) return(c);
01795    return(0);
01796 }
01797 
01798 /*
01799  * Return a pointer to the first non-whitespace character
01800  */
01801 
01802 static char *eatwhite(char *s)
01803 {
01804    while((*s == ' ') || (*s == 0x09)){ /* get rid of any leading white space */
01805       if(!*s)
01806          break;
01807       s++;
01808    }
01809    return s;
01810 }
01811 
01812 /*
01813 * Break up a delimited string into a table of substrings
01814 *
01815 * str - delimited string ( will be modified )
01816 * strp- list of pointers to substrings (this is built by this function), NULL will be placed at end of list
01817 * limit- maximum number of substrings to process
01818 */
01819    
01820 
01821 
01822 static int finddelim(char *str, char *strp[], int limit)
01823 {
01824 int     i,l,inquo;
01825 
01826         inquo = 0;
01827         i = 0;
01828         strp[i++] = str;
01829         if (!*str)
01830            {
01831                 strp[0] = 0;
01832                 return(0);
01833            }
01834         for(l = 0; *str && (l < limit) ; str++)
01835            {
01836                 if (*str == QUOTECHR)
01837                    {
01838                         if (inquo)
01839                            {
01840                                 *str = 0;
01841                                 inquo = 0;
01842                            }
01843                         else
01844                            {
01845                                 strp[i - 1] = str + 1;
01846                                 inquo = 1;
01847                            }
01848       }
01849                 if ((*str == DELIMCHR) && (!inquo))
01850                 {
01851                         *str = 0;
01852          l++;
01853                         strp[i++] = str + 1;
01854                 }
01855            }
01856         strp[i] = 0;
01857         return(i);
01858 
01859 }
01860 /*
01861    send asterisk frame text message on the current tx channel
01862 */
01863 static int send_usb_txt(struct rpt *myrpt, char *txt) 
01864 {
01865    struct ast_frame wf;
01866  
01867    if (debug)ast_log(LOG_NOTICE, "send_usb_txt %s\n",txt);
01868    wf.frametype = AST_FRAME_TEXT;
01869    wf.subclass.integer = 0;
01870    wf.offset = 0;
01871    wf.mallocd = 0;
01872    wf.datalen = strlen(txt) + 1;
01873    wf.data.ptr = txt;
01874    wf.samples = 0;
01875    ast_write(myrpt->txchannel,&wf); 
01876    return 0;
01877 }
01878 /* must be called locked */
01879 static void __mklinklist(struct rpt *myrpt, struct rpt_link *mylink, char *buf)
01880 {
01881 struct rpt_link *l;
01882 char mode;
01883 int   i,spos;
01884 
01885    buf[0] = 0; /* clear output buffer */
01886    if (myrpt->remote) return;
01887    /* go thru all links */
01888    for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
01889    {
01890       /* if is not a real link, ignore it */
01891       if (l->name[0] == '0') continue;
01892       /* don't count our stuff */
01893       if (l == mylink) continue;
01894       if (mylink && (!strcmp(l->name,mylink->name))) continue;
01895       /* figure out mode to report */
01896       mode = 'T'; /* use Tranceive by default */
01897       if (!l->mode) mode = 'R'; /* indicate RX for our mode */
01898       if (!l->thisconnected)  mode = 'C'; /* indicate connecting */
01899       spos = strlen(buf); /* current buf size (b4 we add our stuff) */
01900       if (spos)
01901       {
01902          strcat(buf,",");
01903          spos++;
01904       }
01905       /* add nodes into buffer */
01906       if (l->linklist[0])
01907       {
01908          snprintf(buf + spos,MAXLINKLIST - spos,
01909             "%c%s,%s",mode,l->name,l->linklist);
01910       }
01911       else /* if no nodes, add this node into buffer */
01912       {
01913          snprintf(buf + spos,MAXLINKLIST - spos,
01914             "%c%s",mode,l->name);
01915       }
01916       /* if we are in tranceive mode, let all modes stand */
01917       if (mode == 'T') continue;
01918       /* downgrade everyone on this node if appropriate */
01919       for(i = spos; buf[i]; i++)
01920       {
01921          if (buf[i] == 'T') buf[i] = mode;
01922          if ((buf[i] == 'R') && (mode == 'C')) buf[i] = mode;
01923       }
01924    }
01925    return;
01926 }
01927 
01928 /* must be called locked */
01929 static void __kickshort(struct rpt *myrpt)
01930 {
01931 struct rpt_link *l;
01932 
01933    for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
01934    {
01935       /* if is not a real link, ignore it */
01936       if (l->name[0] == '0') continue;
01937       l->linklisttimer = LINKLISTSHORTTIME;
01938    }
01939    myrpt->linkposttimer = LINKPOSTSHORTTIME;
01940    return;
01941 }
01942 
01943 static void statpost(struct rpt *myrpt,char *pairs)
01944 {
01945 char *str,*astr;
01946 char *astrs[100];
01947 int   n,pid;
01948 time_t   now;
01949 unsigned int seq;
01950 
01951    if (!myrpt->p.statpost_url) return;
01952    str = ast_malloc(strlen(pairs) + strlen(myrpt->p.statpost_url) + 200);
01953    astr = ast_strdup(myrpt->p.statpost_program);
01954    if ((!str) || (!astr)) {
01955       ast_free(str);
01956       ast_free(astr);
01957       return;
01958    }
01959    n = finddelim(astr,astrs,100);
01960    if (n < 1) {
01961       ast_free(str);
01962       ast_free(astr);
01963       return;
01964    }
01965    ast_mutex_lock(&myrpt->statpost_lock);
01966    seq = ++myrpt->statpost_seqno;
01967    ast_mutex_unlock(&myrpt->statpost_lock);
01968    astrs[n++] = str;
01969    astrs[n] = NULL;
01970    time(&now);
01971    sprintf(str,"%s?node=%s&time=%u&seqno=%u",myrpt->p.statpost_url,
01972       myrpt->name,(unsigned int) now,seq);
01973    if (pairs) sprintf(str + strlen(str),"&%s",pairs);
01974    if (!(pid = ast_safe_fork(0)))
01975    {
01976       execv(astrs[0],astrs);
01977       ast_log(LOG_ERROR, "exec of %s failed.\n", astrs[0]);
01978       perror("asterisk");
01979       exit(0);
01980    }
01981    ast_free(astr);
01982    ast_free(str);
01983    return;
01984 }
01985 
01986 static char *node_lookup(struct rpt *myrpt,char *digitbuf)
01987 {
01988 
01989 char *val;
01990 int longestnode,j;
01991 struct stat mystat;
01992 static time_t last = 0;
01993 static struct ast_config *ourcfg = NULL;
01994 struct ast_variable *vp;
01995 
01996    /* try to look it up locally first */
01997    val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.nodes, digitbuf);
01998    if (val) return(val);
01999    ast_mutex_lock(&nodelookuplock);
02000    /* if file does not exist */
02001    if (stat(myrpt->p.extnodefile,&mystat) == -1)
02002    {
02003       if (ourcfg) ast_config_destroy(ourcfg);
02004       ourcfg = NULL;
02005       ast_mutex_unlock(&nodelookuplock);
02006       return(NULL);
02007    }
02008    /* if we need to reload */
02009    if (mystat.st_mtime > last)
02010    {
02011       if (ourcfg) ast_config_destroy(ourcfg);
02012 #ifdef   NEW_ASTERISK
02013       ourcfg = ast_config_load(myrpt->p.extnodefile,config_flags);
02014 #else
02015       ourcfg = ast_config_load(myrpt->p.extnodefile);
02016 #endif
02017       /* if file not there, just bail */
02018       if (!ourcfg || ourcfg == CONFIG_STATUS_FILEINVALID)
02019       {
02020          ast_mutex_unlock(&nodelookuplock);
02021          return(NULL);
02022       }
02023       /* reset "last" time */
02024       last = mystat.st_mtime;
02025 
02026       /* determine longest node length again */    
02027       longestnode = 0;
02028       vp = ast_variable_browse(myrpt->cfg, myrpt->p.nodes);
02029       while(vp){
02030          j = strlen(vp->name);
02031          if (j > longestnode)
02032             longestnode = j;
02033          vp = vp->next;
02034       }
02035 
02036       vp = ast_variable_browse(ourcfg, myrpt->p.extnodes);
02037       while(vp){
02038          j = strlen(vp->name);
02039          if (j > longestnode)
02040             longestnode = j;
02041          vp = vp->next;
02042       }
02043 
02044       myrpt->longestnode = longestnode;
02045    }
02046    val = NULL;
02047    if (ourcfg)
02048       val = (char *) ast_variable_retrieve(ourcfg, myrpt->p.extnodes, digitbuf);
02049    ast_mutex_unlock(&nodelookuplock);
02050    return(val);
02051 }
02052 
02053 /*
02054 * Match a keyword in a list, and return index of string plus 1 if there was a match,* else return 0.
02055 * If param is passed in non-null, then it will be set to the first character past the match
02056 */
02057 
02058 static int matchkeyword(char *string, char **param, char *keywords[])
02059 {
02060 int   i,ls;
02061    for( i = 0 ; keywords[i] ; i++){
02062       ls = strlen(keywords[i]);
02063       if(!ls){
02064          *param = NULL;
02065          return 0;
02066       }
02067       if(!strncmp(string, keywords[i], ls)){
02068          if(param)
02069             *param = string + ls;
02070          return i + 1; 
02071       }
02072    }
02073    *param = NULL;
02074    return 0;
02075 }
02076 
02077 /*
02078 * Skip characters in string which are in charlist, and return a pointer to the
02079 * first non-matching character
02080 */
02081 
02082 static char *skipchars(char *string, char *charlist)
02083 {
02084 int i;   
02085    while(*string){
02086       for(i = 0; charlist[i] ; i++){
02087          if(*string == charlist[i]){
02088             string++;
02089             break;
02090          }
02091       }
02092       if(!charlist[i])
02093          return string;
02094    }
02095    return string;
02096 }
02097 
02098 static int myatoi(const char *str)
02099 {
02100    int   ret;
02101 
02102    if (!str) {
02103       return -1;
02104    }
02105 
02106    /* leave this %i alone, non-base-10 input is useful here */
02107    if (sscanf(str, "%30i", &ret) != 1) {
02108       return -1;
02109    }
02110 
02111    return ret;
02112 }
02113 
02114 static int mycompar(const void *a, const void *b)
02115 {
02116 char  **x = (char **) a;
02117 char  **y = (char **) b;
02118 int   xoff,yoff;
02119 
02120    if ((**x < '0') || (**x > '9')) xoff = 1; else xoff = 0;
02121    if ((**y < '0') || (**y > '9')) yoff = 1; else yoff = 0;
02122    return(strcmp((*x) + xoff,(*y) + yoff));
02123 }
02124 
02125 static int topcompar(const void *a, const void *b)
02126 {
02127 struct rpt_topkey *x = (struct rpt_topkey *) a;
02128 struct rpt_topkey *y = (struct rpt_topkey *) b;
02129 
02130    return(x->timesince - y->timesince);
02131 }
02132 
02133 #ifdef   __RPT_NOTCH
02134 
02135 /* rpt filter routine */
02136 static void rpt_filter(struct rpt *myrpt, volatile short *buf, int len)
02137 {
02138 int   i,j;
02139 struct   rptfilter *f;
02140 
02141    for(i = 0; i < len; i++)
02142    {
02143       for(j = 0; j < MAXFILTERS; j++)
02144       {
02145          f = &myrpt->filters[j];
02146          if (!*f->desc) continue;
02147          f->x0 = f->x1; f->x1 = f->x2;
02148               f->x2 = ((float)buf[i]) / f->gain;
02149               f->y0 = f->y1; f->y1 = f->y2;
02150               f->y2 =   (f->x0 + f->x2) +   f->const0 * f->x1
02151                            + (f->const1 * f->y0) + (f->const2 * f->y1);
02152          buf[i] = (short)f->y2;
02153       }
02154    }
02155 }
02156 
02157 #endif
02158 
02159 
02160 /*
02161  Get the time for the machine's time zone
02162  Note: Asterisk requires a copy of localtime
02163  in the /etc directory for this to work properly.
02164  If /etc/localtime is not present, you will get
02165  GMT time! This is especially important on systems
02166  running embedded linux distributions as they don't usually
02167  have support for locales. 
02168 
02169  If OLD_ASTERISK is defined, then the older localtime_r
02170  function will be used. The /etc/localtime file is not
02171  required in this case. This provides backward compatibility
02172  with Asterisk 1.2 systems.
02173 
02174 */
02175 
02176 #ifdef   NEW_ASTERISK
02177 static void rpt_localtime( time_t * t, struct ast_tm *lt)
02178 {
02179    struct timeval when;
02180 
02181    when.tv_sec = *t;
02182    when.tv_usec = 0;
02183    ast_localtime(&when, lt, NULL);
02184 }
02185 
02186 #else
02187 static void rpt_localtime( time_t * t, struct tm *lt)
02188 {
02189 #ifdef OLD_ASTERISK
02190    localtime_r(t, lt);
02191 #else
02192    ast_localtime(t, lt, NULL);
02193 #endif
02194 }
02195 #endif
02196 
02197 
02198 /* Retrieve an int from a config file */
02199                                                                                 
02200 static int retrieve_astcfgint(struct rpt *myrpt,char *category, char *name, int min, int max, int defl)
02201 {
02202         char *var;
02203         int ret;
02204    char include_zero = 0;
02205 
02206    if(min < 0){ /* If min is negative, this means include 0 as a valid entry */
02207       min = -min;
02208       include_zero = 1;
02209    }           
02210                                                                      
02211         var = (char *) ast_variable_retrieve(myrpt->cfg, category, name);
02212         if(var){
02213                 ret = myatoi(var);
02214       if(include_zero && !ret)
02215          return 0;
02216                 if(ret < min)
02217                         ret = min;
02218                 if(ret > max)
02219                         ret = max;
02220         }
02221         else
02222                 ret = defl;
02223         return ret;
02224 }
02225 
02226 
02227 static void load_rpt_vars(int n,int init)
02228 {
02229 char *this,*val;
02230 int   i,j,longestnode;
02231 struct ast_variable *vp;
02232 struct ast_config *cfg;
02233 char *strs[100];
02234 char s1[256];
02235 static char *cs_keywords[] = {"rptena","rptdis","apena","apdis","lnkena","lnkdis","totena","totdis","skena","skdis",
02236             "ufena","ufdis","atena","atdis",NULL};
02237 
02238    if (option_verbose > 2)
02239       ast_verbose(VERBOSE_PREFIX_3 "%s config for repeater %s\n",
02240          (init) ? "Loading initial" : "Re-Loading",rpt_vars[n].name);
02241    ast_mutex_lock(&rpt_vars[n].lock);
02242    if (rpt_vars[n].cfg) ast_config_destroy(rpt_vars[n].cfg);
02243 #ifdef   NEW_ASTERISK
02244    cfg = ast_config_load("rpt.conf",config_flags);
02245 #else
02246    cfg = ast_config_load("rpt.conf");
02247 #endif
02248    if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
02249       ast_mutex_unlock(&rpt_vars[n].lock);
02250       ast_log(LOG_NOTICE, "Unable to open radio repeater configuration rpt.conf.  Radio Repeater disabled.\n");
02251       pthread_exit(NULL);
02252    }
02253    rpt_vars[n].cfg = cfg; 
02254    this = rpt_vars[n].name;
02255    memset(&rpt_vars[n].p,0,sizeof(rpt_vars[n].p));
02256    if (init)
02257    {
02258       char *cp;
02259       int savearea = (char *)&rpt_vars[n].p - (char *)&rpt_vars[n];
02260 
02261       cp = (char *) &rpt_vars[n].p;
02262       memset(cp + sizeof(rpt_vars[n].p),0,
02263          sizeof(rpt_vars[n]) - (sizeof(rpt_vars[n].p) + savearea));
02264       rpt_vars[n].tele.next = &rpt_vars[n].tele;
02265       rpt_vars[n].tele.prev = &rpt_vars[n].tele;
02266       rpt_vars[n].rpt_thread = AST_PTHREADT_NULL;
02267       rpt_vars[n].tailmessagen = 0;
02268    }
02269 #ifdef   __RPT_NOTCH
02270    /* zot out filters stuff */
02271    memset(&rpt_vars[n].filters,0,sizeof(rpt_vars[n].filters));
02272 #endif
02273    val = (char *) ast_variable_retrieve(cfg,this,"context");
02274    if (val) rpt_vars[n].p.ourcontext = val;
02275    else rpt_vars[n].p.ourcontext = this;
02276    val = (char *) ast_variable_retrieve(cfg,this,"callerid");
02277    if (val) rpt_vars[n].p.ourcallerid = val;
02278    val = (char *) ast_variable_retrieve(cfg,this,"accountcode");
02279    if (val) rpt_vars[n].p.acctcode = val;
02280    val = (char *) ast_variable_retrieve(cfg,this,"idrecording");
02281    if (val) rpt_vars[n].p.ident = val;
02282    val = (char *) ast_variable_retrieve(cfg,this,"hangtime");
02283    if (val) rpt_vars[n].p.hangtime = atoi(val);
02284       else rpt_vars[n].p.hangtime = HANGTIME;
02285    val = (char *) ast_variable_retrieve(cfg,this,"althangtime");
02286    if (val) rpt_vars[n].p.althangtime = atoi(val);
02287       else rpt_vars[n].p.althangtime = HANGTIME;
02288    val = (char *) ast_variable_retrieve(cfg,this,"totime");
02289    if (val) rpt_vars[n].p.totime = atoi(val);
02290       else rpt_vars[n].p.totime = TOTIME;
02291    val = (char *) ast_variable_retrieve(cfg,this,"voxtimeout");
02292    if (val) rpt_vars[n].p.voxtimeout_ms = atoi(val);
02293       else rpt_vars[n].p.voxtimeout_ms = VOX_TIMEOUT_MS;
02294    val = (char *) ast_variable_retrieve(cfg,this,"voxrecover");
02295    if (val) rpt_vars[n].p.voxrecover_ms = atoi(val);
02296       else rpt_vars[n].p.voxrecover_ms = VOX_RECOVER_MS;
02297    val = (char *) ast_variable_retrieve(cfg,this,"simplexpatchdelay");
02298    if (val) rpt_vars[n].p.simplexpatchdelay = atoi(val);
02299       else rpt_vars[n].p.simplexpatchdelay = SIMPLEX_PATCH_DELAY;
02300    val = (char *) ast_variable_retrieve(cfg,this,"simplexphonedelay");
02301    if (val) rpt_vars[n].p.simplexphonedelay = atoi(val);
02302       else rpt_vars[n].p.simplexphonedelay = SIMPLEX_PHONE_DELAY;
02303    val = (char *) ast_variable_retrieve(cfg,this,"statpost_program");
02304    if (val) rpt_vars[n].p.statpost_program = val;
02305       else rpt_vars[n].p.statpost_program = STATPOST_PROGRAM;
02306    rpt_vars[n].p.statpost_url = 
02307       (char *) ast_variable_retrieve(cfg,this,"statpost_url");
02308    rpt_vars[n].p.tailmessagetime = retrieve_astcfgint(&rpt_vars[n],this, "tailmessagetime", 0, 2400000, 0);    
02309    rpt_vars[n].p.tailsquashedtime = retrieve_astcfgint(&rpt_vars[n],this, "tailsquashedtime", 0, 2400000, 0);     
02310    rpt_vars[n].p.duplex = retrieve_astcfgint(&rpt_vars[n],this,"duplex",0,4,2);
02311    rpt_vars[n].p.idtime = retrieve_astcfgint(&rpt_vars[n],this, "idtime", -60000, 2400000, IDTIME);   /* Enforce a min max including zero */
02312    rpt_vars[n].p.politeid = retrieve_astcfgint(&rpt_vars[n],this, "politeid", 30000, 300000, POLITEID); /* Enforce a min max */
02313    val = (char *) ast_variable_retrieve(cfg,this,"tonezone");
02314    if (val) rpt_vars[n].p.tonezone = val;
02315    rpt_vars[n].p.tailmessages[0] = 0;
02316    rpt_vars[n].p.tailmessagemax = 0;
02317    val = (char *) ast_variable_retrieve(cfg,this,"tailmessagelist");
02318    if (val) rpt_vars[n].p.tailmessagemax = finddelim(val, rpt_vars[n].p.tailmessages, 500);
02319    val = (char *) ast_variable_retrieve(cfg,this,"memory");
02320    if (!val) val = MEMORY;
02321    rpt_vars[n].p.memory = val;
02322    val = (char *) ast_variable_retrieve(cfg,this,"macro");
02323    if (!val) val = MACRO;
02324    rpt_vars[n].p.macro = val;
02325    val = (char *) ast_variable_retrieve(cfg,this,"tonemacro");
02326    if (!val) val = TONEMACRO;
02327    rpt_vars[n].p.tonemacro = val;
02328    val = (char *) ast_variable_retrieve(cfg,this,"startup_macro");
02329    if (val) rpt_vars[n].p.startupmacro = val;
02330    val = (char *) ast_variable_retrieve(cfg,this,"iobase");
02331    /* do not use atoi() here, we need to be able to have
02332       the input specified in hex or decimal so we use
02333       sscanf with a %i */
02334    if ((!val) || (sscanf(val,"%30i",&rpt_vars[n].p.iobase) != 1))
02335       rpt_vars[n].p.iobase = DEFAULT_IOBASE;
02336    val = (char *) ast_variable_retrieve(cfg,this,"ioport");
02337    rpt_vars[n].p.ioport = val;
02338    val = (char *) ast_variable_retrieve(cfg,this,"functions");
02339    if (!val)
02340       {
02341          val = FUNCTIONS;
02342          rpt_vars[n].p.simple = 1;
02343       } 
02344    rpt_vars[n].p.functions = val;
02345    val =  (char *) ast_variable_retrieve(cfg,this,"link_functions");
02346    if (val) rpt_vars[n].p.link_functions = val;
02347    else 
02348       rpt_vars[n].p.link_functions = rpt_vars[n].p.functions;
02349    val = (char *) ast_variable_retrieve(cfg,this,"phone_functions");
02350    if (val) rpt_vars[n].p.phone_functions = val;
02351    val = (char *) ast_variable_retrieve(cfg,this,"dphone_functions");
02352    if (val) rpt_vars[n].p.dphone_functions = val;
02353    val = (char *) ast_variable_retrieve(cfg,this,"alt_functions");
02354    if (val) rpt_vars[n].p.alt_functions = val;
02355    val = (char *) ast_variable_retrieve(cfg,this,"funcchar");
02356    if (!val) rpt_vars[n].p.funcchar = FUNCCHAR; else 
02357       rpt_vars[n].p.funcchar = *val;      
02358    val = (char *) ast_variable_retrieve(cfg,this,"endchar");
02359    if (!val) rpt_vars[n].p.endchar = ENDCHAR; else 
02360       rpt_vars[n].p.endchar = *val;    
02361    val = (char *) ast_variable_retrieve(cfg,this,"nobusyout");
02362    if (val) rpt_vars[n].p.nobusyout = ast_true(val);
02363    val = (char *) ast_variable_retrieve(cfg,this,"notelemtx");
02364    if (val) rpt_vars[n].p.notelemtx = ast_true(val);
02365    val = (char *) ast_variable_retrieve(cfg,this,"propagate_dtmf");
02366    if (val) rpt_vars[n].p.propagate_dtmf = ast_true(val);
02367    val = (char *) ast_variable_retrieve(cfg,this,"propagate_phonedtmf");
02368    if (val) rpt_vars[n].p.propagate_phonedtmf = ast_true(val);
02369    val = (char *) ast_variable_retrieve(cfg,this,"linktolink");
02370    if (val) rpt_vars[n].p.linktolink = ast_true(val);
02371    val = (char *) ast_variable_retrieve(cfg,this,"nodes");
02372    if (!val) val = NODES;
02373    rpt_vars[n].p.nodes = val;
02374    val = (char *) ast_variable_retrieve(cfg,this,"extnodes");
02375    if (!val) val = EXTNODES;
02376    rpt_vars[n].p.extnodes = val;
02377    val = (char *) ast_variable_retrieve(cfg,this,"extnodefile");
02378    if (!val) val = EXTNODEFILE;
02379    rpt_vars[n].p.extnodefile = val;
02380    val = (char *) ast_variable_retrieve(cfg,this,"archivedir");
02381    if (val) rpt_vars[n].p.archivedir = val;
02382    val = (char *) ast_variable_retrieve(cfg,this,"authlevel");
02383    if (val) rpt_vars[n].p.authlevel = atoi(val); 
02384    else rpt_vars[n].p.authlevel = 0;
02385    val = (char *) ast_variable_retrieve(cfg,this,"parrot");
02386    if (val) rpt_vars[n].p.parrotmode = ast_true(val) * 2;
02387    else rpt_vars[n].p.parrotmode = 0;
02388    val = (char *) ast_variable_retrieve(cfg,this,"parrottime");
02389    if (val) rpt_vars[n].p.parrottime = atoi(val); 
02390    else rpt_vars[n].p.parrottime = PARROTTIME;
02391    val = (char *) ast_variable_retrieve(cfg,this,"rptnode");
02392    rpt_vars[n].p.rptnode = val;
02393    val = (char *) ast_variable_retrieve(cfg,this,"mars");
02394    if (val) rpt_vars[n].p.remote_mars = atoi(val); 
02395    else rpt_vars[n].p.remote_mars = 0;
02396    val = (char *) ast_variable_retrieve(cfg,this,"monminblocks");
02397    if (val) rpt_vars[n].p.monminblocks = atol(val); 
02398    else rpt_vars[n].p.monminblocks = DEFAULT_MONITOR_MIN_DISK_BLOCKS;
02399    val = (char *) ast_variable_retrieve(cfg,this,"remote_inact_timeout");
02400    if (val) rpt_vars[n].p.remoteinacttimeout = atoi(val); 
02401    else rpt_vars[n].p.remoteinacttimeout = DEFAULT_REMOTE_INACT_TIMEOUT;
02402    val = (char *) ast_variable_retrieve(cfg,this,"civaddr");
02403    if (val) rpt_vars[n].p.civaddr = atoi(val); 
02404    else rpt_vars[n].p.civaddr = DEFAULT_CIV_ADDR;
02405    val = (char *) ast_variable_retrieve(cfg,this,"remote_timeout");
02406    if (val) rpt_vars[n].p.remotetimeout = atoi(val); 
02407    else rpt_vars[n].p.remotetimeout = DEFAULT_REMOTE_TIMEOUT;
02408    val = (char *) ast_variable_retrieve(cfg,this,"remote_timeout_warning");
02409    if (val) rpt_vars[n].p.remotetimeoutwarning = atoi(val); 
02410    else rpt_vars[n].p.remotetimeoutwarning = DEFAULT_REMOTE_TIMEOUT_WARNING;
02411    val = (char *) ast_variable_retrieve(cfg,this,"remote_timeout_warning_freq");
02412    if (val) rpt_vars[n].p.remotetimeoutwarningfreq = atoi(val); 
02413    else rpt_vars[n].p.remotetimeoutwarningfreq = DEFAULT_REMOTE_TIMEOUT_WARNING_FREQ;
02414 #ifdef   __RPT_NOTCH
02415    val = (char *) ast_variable_retrieve(cfg,this,"rxnotch");
02416    if (val) {
02417       i = finddelim(val,strs,MAXFILTERS * 2);
02418       i &= ~1; /* force an even number, rounded down */
02419       if (i >= 2) for(j = 0; j < i; j += 2)
02420       {
02421          rpt_mknotch(atof(strs[j]),atof(strs[j + 1]),
02422            &rpt_vars[n].filters[j >> 1].gain,
02423              &rpt_vars[n].filters[j >> 1].const0,
02424             &rpt_vars[n].filters[j >> 1].const1,
02425                 &rpt_vars[n].filters[j >> 1].const2);
02426          sprintf(rpt_vars[n].filters[j >> 1].desc,"%s Hz, BW = %s",
02427             strs[j],strs[j + 1]);
02428       }
02429 
02430    }
02431 #endif
02432    val = (char *) ast_variable_retrieve(cfg,this,"inxlat");
02433    if (val) {
02434       memset(&rpt_vars[n].p.inxlat,0,sizeof(struct rpt_xlat));
02435       i = finddelim(val,strs,3);
02436       if (i) strncpy(rpt_vars[n].p.inxlat.funccharseq,strs[0],MAXXLAT - 1);
02437       if (i > 1) strncpy(rpt_vars[n].p.inxlat.endcharseq,strs[1],MAXXLAT - 1);
02438       if (i > 2) strncpy(rpt_vars[n].p.inxlat.passchars,strs[2],MAXXLAT - 1);
02439    }
02440    val = (char *) ast_variable_retrieve(cfg,this,"outxlat");
02441    if (val) {
02442       memset(&rpt_vars[n].p.outxlat,0,sizeof(struct rpt_xlat));
02443       i = finddelim(val,strs,3);
02444       if (i) strncpy(rpt_vars[n].p.outxlat.funccharseq,strs[0],MAXXLAT - 1);
02445       if (i > 1) strncpy(rpt_vars[n].p.outxlat.endcharseq,strs[1],MAXXLAT - 1);
02446       if (i > 2) strncpy(rpt_vars[n].p.outxlat.passchars,strs[2],MAXXLAT - 1);
02447    }
02448    /* retreive the stanza name for the control states if there is one */
02449    val = (char *) ast_variable_retrieve(cfg,this,"controlstates");
02450    rpt_vars[n].p.csstanzaname = val;
02451       
02452    /* retreive the stanza name for the scheduler if there is one */
02453    val = (char *) ast_variable_retrieve(cfg,this,"scheduler");
02454    rpt_vars[n].p.skedstanzaname = val;
02455 
02456    /* retreive the stanza name for the txlimits */
02457    val = (char *) ast_variable_retrieve(cfg,this,"txlimits");
02458    rpt_vars[n].p.txlimitsstanzaname = val;
02459 
02460    longestnode = 0;
02461 
02462    vp = ast_variable_browse(cfg, rpt_vars[n].p.nodes);
02463       
02464    while(vp){
02465       j = strlen(vp->name);
02466       if (j > longestnode)
02467          longestnode = j;
02468       vp = vp->next;
02469    }
02470 
02471    rpt_vars[n].longestnode = longestnode;
02472       
02473    /*
02474    * For this repeater, Determine the length of the longest function 
02475    */
02476    rpt_vars[n].longestfunc = 0;
02477    vp = ast_variable_browse(cfg, rpt_vars[n].p.functions);
02478    while(vp){
02479       j = strlen(vp->name);
02480       if (j > rpt_vars[n].longestfunc)
02481          rpt_vars[n].longestfunc = j;
02482       vp = vp->next;
02483    }
02484    /*
02485    * For this repeater, Determine the length of the longest function 
02486    */
02487    rpt_vars[n].link_longestfunc = 0;
02488    vp = ast_variable_browse(cfg, rpt_vars[n].p.link_functions);
02489    while(vp){
02490       j = strlen(vp->name);
02491       if (j > rpt_vars[n].link_longestfunc)
02492          rpt_vars[n].link_longestfunc = j;
02493       vp = vp->next;
02494    }
02495    rpt_vars[n].phone_longestfunc = 0;
02496    if (rpt_vars[n].p.phone_functions)
02497    {
02498       vp = ast_variable_browse(cfg, rpt_vars[n].p.phone_functions);
02499       while(vp){
02500          j = strlen(vp->name);
02501          if (j > rpt_vars[n].phone_longestfunc)
02502             rpt_vars[n].phone_longestfunc = j;
02503          vp = vp->next;
02504       }
02505    }
02506    rpt_vars[n].dphone_longestfunc = 0;
02507    if (rpt_vars[n].p.dphone_functions)
02508    {
02509       vp = ast_variable_browse(cfg, rpt_vars[n].p.dphone_functions);
02510       while(vp){
02511          j = strlen(vp->name);
02512          if (j > rpt_vars[n].dphone_longestfunc)
02513             rpt_vars[n].dphone_longestfunc = j;
02514          vp = vp->next;
02515       }
02516    }
02517    rpt_vars[n].alt_longestfunc = 0;
02518    if (rpt_vars[n].p.alt_functions)
02519    {
02520       vp = ast_variable_browse(cfg, rpt_vars[n].p.alt_functions);
02521       while(vp){
02522          j = strlen(vp->name);
02523          if (j > rpt_vars[n].alt_longestfunc)
02524             rpt_vars[n].alt_longestfunc = j;
02525          vp = vp->next;
02526       }
02527    }
02528    rpt_vars[n].macro_longest = 1;
02529    vp = ast_variable_browse(cfg, rpt_vars[n].p.macro);
02530    while(vp){
02531       j = strlen(vp->name);
02532       if (j > rpt_vars[n].macro_longest)
02533          rpt_vars[n].macro_longest = j;
02534       vp = vp->next;
02535    }
02536    
02537    /* Browse for control states */
02538    if(rpt_vars[n].p.csstanzaname)
02539       vp = ast_variable_browse(cfg, rpt_vars[n].p.csstanzaname);
02540    else
02541       vp = NULL;
02542    for( i = 0 ; vp && (i < MAX_SYSSTATES) ; i++){ /* Iterate over the number of control state lines in the stanza */
02543       int k,nukw,statenum;
02544       statenum=atoi(vp->name);
02545       strncpy(s1, vp->value, 255);
02546       s1[255] = 0;
02547       nukw  = finddelim(s1,strs,32);
02548       
02549       for (k = 0 ; k < nukw ; k++){ /* for each user specified keyword */  
02550          for(j = 0 ; cs_keywords[j] != NULL ; j++){ /* try to match to one in our internal table */
02551             if(!strcmp(strs[k],cs_keywords[j])){
02552                switch(j){
02553                   case 0: /* rptena */
02554                      rpt_vars[n].p.s[statenum].txdisable = 0;
02555                      break;
02556                   case 1: /* rptdis */
02557                      rpt_vars[n].p.s[statenum].txdisable = 1;
02558                      break;
02559          
02560                   case 2: /* apena */
02561                      rpt_vars[n].p.s[statenum].autopatchdisable = 0;
02562                      break;
02563 
02564                   case 3: /* apdis */
02565                      rpt_vars[n].p.s[statenum].autopatchdisable = 1;
02566                      break;
02567 
02568                   case 4: /* lnkena */
02569                      rpt_vars[n].p.s[statenum].linkfundisable = 0;
02570                      break;
02571    
02572                   case 5: /* lnkdis */
02573                      rpt_vars[n].p.s[statenum].linkfundisable = 1;
02574                      break;
02575 
02576                   case 6: /* totena */
02577                      rpt_vars[n].p.s[statenum].totdisable = 0;
02578                      break;
02579                
02580                   case 7: /* totdis */
02581                      rpt_vars[n].p.s[statenum].totdisable = 1;
02582                      break;
02583 
02584                   case 8: /* skena */
02585                      rpt_vars[n].p.s[statenum].schedulerdisable = 0;
02586                      break;
02587 
02588                   case 9: /* skdis */
02589                      rpt_vars[n].p.s[statenum].schedulerdisable = 1;
02590                      break;
02591 
02592                   case 10: /* ufena */
02593                      rpt_vars[n].p.s[statenum].userfundisable = 0;
02594                      break;
02595 
02596                   case 11: /* ufdis */
02597                      rpt_vars[n].p.s[statenum].userfundisable = 1;
02598                      break;
02599 
02600                   case 12: /* atena */
02601                      rpt_vars[n].p.s[statenum].alternatetail = 1;
02602                      break;
02603 
02604                   case 13: /* atdis */
02605                      rpt_vars[n].p.s[statenum].alternatetail = 0;
02606                      break;
02607          
02608                   default:
02609                      ast_log(LOG_WARNING,
02610                         "Unhandled control state keyword %s", cs_keywords[i]);
02611                      break;
02612                }
02613             }
02614          }
02615       }
02616       vp = vp->next;
02617    }
02618    ast_mutex_unlock(&rpt_vars[n].lock);
02619 }
02620 
02621 /*
02622 * Enable or disable debug output at a given level at the console
02623 */
02624 static int rpt_do_debug(int fd, int argc, const char * const *argv)
02625 {
02626    int newlevel;
02627 
02628    if (argc != 4) {
02629       return RESULT_SHOWUSAGE;
02630    }
02631 
02632    newlevel = myatoi(argv[3]);
02633 
02634    if (newlevel < 0 || newlevel > 7) {
02635       return RESULT_SHOWUSAGE;
02636    }
02637 
02638    if (newlevel) {
02639       ast_cli(fd, "app_rpt Debugging enabled, previous level: %d, new level: %d\n", debug, newlevel);
02640    } else {
02641       ast_cli(fd, "app_rpt Debugging disabled\n");
02642    }
02643 
02644    debug = newlevel;
02645 
02646    return RESULT_SUCCESS;
02647 }
02648 
02649 /*
02650 * Dump rpt struct debugging onto console
02651 */
02652                                                                                                                                  
02653 static int rpt_do_dump(int fd, int argc, const char * const *argv)
02654 {
02655    int i;
02656 
02657         if (argc != 3)
02658                 return RESULT_SHOWUSAGE;
02659 
02660    for(i = 0; i < nrpts; i++)
02661    {
02662       if (!strcmp(argv[2],rpt_vars[i].name))
02663       {
02664          rpt_vars[i].disgorgetime = time(NULL) + 10; /* Do it 10 seconds later */
02665               ast_cli(fd, "app_rpt struct dump requested for node %s\n",argv[2]);
02666               return RESULT_SUCCESS;
02667       }
02668    }
02669    return RESULT_FAILURE;
02670 }
02671 
02672 /*
02673 * Dump statistics onto console
02674 */
02675 
02676 static int rpt_do_stats(int fd, int argc, const char * const *argv)
02677 {
02678    int i,j,numoflinks;
02679    int dailytxtime, dailykerchunks;
02680    time_t now;
02681    int totalkerchunks, dailykeyups, totalkeyups, timeouts;
02682    int totalexecdcommands, dailyexecdcommands, hours, minutes, seconds;
02683    int uptime;
02684    long long totaltxtime;
02685    struct   rpt_link *l;
02686    char *listoflinks[MAX_STAT_LINKS];  
02687    char *lastdtmfcommand,*parrot_ena;
02688    char *tot_state, *ider_state, *patch_state;
02689    char *reverse_patch_state, *sys_ena, *tot_ena, *link_ena, *patch_ena;
02690    char *sch_ena, *input_signal, *called_number, *user_funs, *tail_type;
02691    struct rpt *myrpt;
02692 
02693    static char *not_applicable = "N/A";
02694 
02695    if(argc != 3)
02696       return RESULT_SHOWUSAGE;
02697 
02698    tot_state = ider_state = 
02699    patch_state = reverse_patch_state = 
02700    input_signal = not_applicable;
02701    called_number = lastdtmfcommand = NULL;
02702 
02703    time(&now);
02704    for(i = 0; i < nrpts; i++)
02705    {
02706       if (!strcmp(argv[2],rpt_vars[i].name)){
02707          /* Make a copy of all stat variables while locked */
02708          myrpt = &rpt_vars[i];
02709          rpt_mutex_lock(&myrpt->lock); /* LOCK */
02710          uptime = (int)(now - starttime);
02711          dailytxtime = myrpt->dailytxtime;
02712          totaltxtime = myrpt->totaltxtime;
02713          dailykeyups = myrpt->dailykeyups;
02714          totalkeyups = myrpt->totalkeyups;
02715          dailykerchunks = myrpt->dailykerchunks;
02716          totalkerchunks = myrpt->totalkerchunks;
02717          dailyexecdcommands = myrpt->dailyexecdcommands;
02718          totalexecdcommands = myrpt->totalexecdcommands;
02719          timeouts = myrpt->timeouts;
02720 
02721          /* Traverse the list of connected nodes */
02722          reverse_patch_state = "DOWN";
02723          numoflinks = 0;
02724          l = myrpt->links.next;
02725          while(l && (l != &myrpt->links)){
02726             if(numoflinks >= MAX_STAT_LINKS){
02727                ast_log(LOG_NOTICE,
02728                "maximum number of links exceeds %d in rpt_do_stats()!",MAX_STAT_LINKS);
02729                break;
02730             }
02731             if (l->name[0] == '0'){ /* Skip '0' nodes */
02732                reverse_patch_state = "UP";
02733                l = l->next;
02734                continue;
02735             }
02736             listoflinks[numoflinks] = ast_strdup(l->name);
02737             if(listoflinks[numoflinks] == NULL){
02738                break;
02739             }
02740             else{
02741                numoflinks++;
02742             }
02743             l = l->next;
02744          }
02745 
02746          if(myrpt->keyed)
02747             input_signal = "YES";
02748          else
02749             input_signal = "NO";
02750 
02751          if(myrpt->p.parrotmode)
02752             parrot_ena = "ENABLED";
02753          else
02754             parrot_ena = "DISABLED";
02755 
02756          if(myrpt->p.s[myrpt->p.sysstate_cur].txdisable)
02757             sys_ena = "DISABLED";
02758          else
02759             sys_ena = "ENABLED";
02760 
02761          if(myrpt->p.s[myrpt->p.sysstate_cur].totdisable)
02762             tot_ena = "DISABLED";
02763          else
02764             tot_ena = "ENABLED";
02765 
02766          if(myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable)
02767             link_ena = "DISABLED";
02768          else
02769             link_ena = "ENABLED";
02770 
02771          if(myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable)
02772             patch_ena = "DISABLED";
02773          else
02774             patch_ena = "ENABLED";
02775 
02776          if(myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable)
02777             sch_ena = "DISABLED";
02778          else
02779             sch_ena = "ENABLED";
02780 
02781          if(myrpt->p.s[myrpt->p.sysstate_cur].userfundisable)
02782             user_funs = "DISABLED";
02783          else
02784             user_funs = "ENABLED";
02785 
02786          if(myrpt->p.s[myrpt->p.sysstate_cur].alternatetail)
02787             tail_type = "ALTERNATE";
02788          else
02789             tail_type = "STANDARD";
02790 
02791          if(!myrpt->totimer)
02792             tot_state = "TIMED OUT!";
02793          else if(myrpt->totimer != myrpt->p.totime)
02794             tot_state = "ARMED";
02795          else
02796             tot_state = "RESET";
02797 
02798          if(myrpt->tailid)
02799             ider_state = "QUEUED IN TAIL";
02800          else if(myrpt->mustid)
02801             ider_state = "QUEUED FOR CLEANUP";
02802          else
02803             ider_state = "CLEAN";
02804 
02805          switch(myrpt->callmode){
02806             case 1:
02807                patch_state = "DIALING";
02808                break;
02809             case 2:
02810                patch_state = "CONNECTING";
02811                break;
02812             case 3:
02813                patch_state = "UP";
02814                break;
02815 
02816             case 4:
02817                patch_state = "CALL FAILED";
02818                break;
02819 
02820             default:
02821                patch_state = "DOWN";
02822          }
02823 
02824          if(strlen(myrpt->exten)){
02825             called_number = ast_strdup(myrpt->exten);
02826          }
02827 
02828          if(strlen(myrpt->lastdtmfcommand)){
02829             lastdtmfcommand = ast_strdup(myrpt->lastdtmfcommand);
02830          }
02831          rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
02832 
02833          ast_cli(fd, "************************ NODE %s STATISTICS *************************\n\n", myrpt->name);
02834          ast_cli(fd, "Selected system state............................: %d\n", myrpt->p.sysstate_cur);
02835          ast_cli(fd, "Signal on input..................................: %s\n", input_signal);
02836          ast_cli(fd, "System...........................................: %s\n", sys_ena);
02837          ast_cli(fd, "Parrot Mode......................................: %s\n", parrot_ena);
02838          ast_cli(fd, "Scheduler........................................: %s\n", sch_ena);
02839          ast_cli(fd, "Tail Time........................................: %s\n", tail_type);
02840          ast_cli(fd, "Time out timer...................................: %s\n", tot_ena);
02841          ast_cli(fd, "Time out timer state.............................: %s\n", tot_state);
02842          ast_cli(fd, "Time outs since system initialization............: %d\n", timeouts);
02843          ast_cli(fd, "Identifier state.................................: %s\n", ider_state);
02844          ast_cli(fd, "Kerchunks today..................................: %d\n", dailykerchunks);
02845          ast_cli(fd, "Kerchunks since system initialization............: %d\n", totalkerchunks);
02846          ast_cli(fd, "Keyups today.....................................: %d\n", dailykeyups);
02847          ast_cli(fd, "Keyups since system initialization...............: %d\n", totalkeyups);
02848          ast_cli(fd, "DTMF commands today..............................: %d\n", dailyexecdcommands);
02849          ast_cli(fd, "DTMF commands since system initialization........: %d\n", totalexecdcommands);
02850          ast_cli(fd, "Last DTMF command executed.......................: %s\n", 
02851          (lastdtmfcommand && strlen(lastdtmfcommand)) ? lastdtmfcommand : not_applicable);
02852          hours = dailytxtime/3600000;
02853          dailytxtime %= 3600000;
02854          minutes = dailytxtime/60000;
02855          dailytxtime %= 60000;
02856          seconds = dailytxtime/1000;
02857          dailytxtime %= 1000;
02858 
02859          ast_cli(fd, "TX time today....................................: %02d:%02d:%02d.%d\n",
02860             hours, minutes, seconds, dailytxtime);
02861 
02862          hours = (int) totaltxtime/3600000;
02863          totaltxtime %= 3600000;
02864          minutes = (int) totaltxtime/60000;
02865          totaltxtime %= 60000;
02866          seconds = (int)  totaltxtime/1000;
02867          totaltxtime %= 1000;
02868 
02869          ast_cli(fd, "TX time since system initialization..............: %02d:%02d:%02d.%d\n",
02870              hours, minutes, seconds, (int) totaltxtime);
02871 
02872                         hours = uptime/3600;
02873                         uptime %= 3600;
02874                         minutes = uptime/60;
02875                         uptime %= 60;
02876 
02877                         ast_cli(fd, "Uptime...........................................: %02d:%02d:%02d\n",
02878                                 hours, minutes, uptime);
02879 
02880          ast_cli(fd, "Nodes currently connected to us..................: ");
02881                         if(!numoflinks){
02882                          ast_cli(fd,"<NONE>");
02883                         }
02884          else{
02885             for(j = 0 ;j < numoflinks; j++){
02886                ast_cli(fd, "%s", listoflinks[j]);
02887                if(j % 4 == 3){
02888                   ast_cli(fd, "\n");
02889                   ast_cli(fd, "                                                 : ");
02890                }  
02891                else{
02892                   if((numoflinks - 1) - j  > 0)
02893                      ast_cli(fd, ", ");
02894                }
02895             }
02896          }
02897          ast_cli(fd,"\n");
02898 
02899          ast_cli(fd, "Autopatch........................................: %s\n", patch_ena);
02900          ast_cli(fd, "Autopatch state..................................: %s\n", patch_state);
02901          ast_cli(fd, "Autopatch called number..........................: %s\n",
02902          (called_number && strlen(called_number)) ? called_number : not_applicable);
02903          ast_cli(fd, "Reverse patch/IAXRPT connected...................: %s\n", reverse_patch_state);
02904          ast_cli(fd, "User linking commands............................: %s\n", link_ena);
02905          ast_cli(fd, "User functions...................................: %s\n\n", user_funs);
02906 
02907          for(j = 0; j < numoflinks; j++){ /* ast_free() all link names */
02908             ast_free(listoflinks[j]);
02909          }
02910          ast_free(called_number);
02911          ast_free(lastdtmfcommand);
02912               return RESULT_SUCCESS;
02913       }
02914    }
02915    return RESULT_FAILURE;
02916 }
02917 
02918 /*
02919 * Link stats function
02920 */
02921 
02922 static int rpt_do_lstats(int fd, int argc, const char * const *argv)
02923 {
02924    int i;
02925    char *connstate;
02926    struct rpt *myrpt;
02927    struct rpt_link *l;
02928    struct rpt_lstat *s,*t;
02929    struct rpt_lstat s_head;
02930    if(argc != 3)
02931       return RESULT_SHOWUSAGE;
02932 
02933    s = NULL;
02934    s_head.next = &s_head;
02935    s_head.prev = &s_head;
02936 
02937    for(i = 0; i < nrpts; i++)
02938    {
02939       if (!strcmp(argv[2],rpt_vars[i].name)){
02940          /* Make a copy of all stat variables while locked */
02941          myrpt = &rpt_vars[i];
02942          rpt_mutex_lock(&myrpt->lock); /* LOCK */
02943          /* Traverse the list of connected nodes */
02944          l = myrpt->links.next;
02945          while(l && (l != &myrpt->links)){
02946             if (l->name[0] == '0'){ /* Skip '0' nodes */
02947                l = l->next;
02948                continue;
02949             }
02950             if((s = (struct rpt_lstat *) ast_malloc(sizeof(struct rpt_lstat))) == NULL){
02951                ast_log(LOG_ERROR, "Malloc failed in rpt_do_lstats\n");
02952                rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
02953                return RESULT_FAILURE;
02954             }
02955             memset(s, 0, sizeof(struct rpt_lstat));
02956             strncpy(s->name, l->name, MAXREMSTR - 1);
02957             if (l->chan) pbx_substitute_variables_helper(l->chan, "${IAXPEER(CURRENTCHANNEL)}", s->peer, MAXPEERSTR - 1);
02958             else strcpy(s->peer,"(none)");
02959             s->mode = l->mode;
02960             s->outbound = l->outbound;
02961             s->reconnects = l->reconnects;
02962             s->connecttime = l->connecttime;
02963             s->thisconnected = l->thisconnected;
02964             memcpy(s->chan_stat,l->chan_stat,NRPTSTAT * sizeof(struct rpt_chan_stat));
02965             insque((struct qelem *) s, (struct qelem *) s_head.next);
02966             memset(l->chan_stat,0,NRPTSTAT * sizeof(struct rpt_chan_stat));
02967             l = l->next;
02968          }
02969          rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
02970          ast_cli(fd, "NODE      PEER                RECONNECTS  DIRECTION  CONNECT TIME        CONNECT STATE\n");
02971          ast_cli(fd, "----      ----                ----------  ---------  ------------        -------------\n");
02972 
02973          for(s = s_head.next; s != &s_head; s = s->next){
02974             int hours, minutes, seconds;
02975             long long connecttime = s->connecttime;
02976             char conntime[21];
02977             hours = (int) connecttime/3600000;
02978             connecttime %= 3600000;
02979             minutes = (int) connecttime/60000;
02980             connecttime %= 60000;
02981             seconds = (int)  connecttime/1000;
02982             connecttime %= 1000;
02983             snprintf(conntime, 20, "%02d:%02d:%02d.%d",
02984                hours, minutes, seconds, (int) connecttime);
02985             conntime[20] = 0;
02986             if(s->thisconnected)
02987                connstate  = "ESTABLISHED";
02988             else
02989                connstate = "CONNECTING";
02990             ast_cli(fd, "%-10s%-20s%-12d%-11s%-20s%-20s\n",
02991                s->name, s->peer, s->reconnects, (s->outbound)? "OUT":"IN", conntime, connstate);
02992          }  
02993          /* destroy our local link queue */
02994          s = s_head.next;
02995          while(s != &s_head){
02996             t = s;
02997             s = s->next;
02998             remque((struct qelem *)t);
02999             ast_free(t);
03000          }        
03001          return RESULT_SUCCESS;
03002       }
03003    }
03004    return RESULT_FAILURE;
03005 }
03006 
03007 /*
03008 * List all nodes connected, directly or indirectly
03009 */
03010 
03011 static int rpt_do_nodes(int fd, int argc, const char * const *argv)
03012 {
03013    int i,j;
03014    char ns;
03015    char lbuf[MAXLINKLIST],*strs[MAXLINKLIST];
03016    struct rpt *myrpt;
03017    if(argc != 3)
03018       return RESULT_SHOWUSAGE;
03019 
03020    for(i = 0; i < nrpts; i++)
03021    {
03022       if (!strcmp(argv[2],rpt_vars[i].name)){
03023          /* Make a copy of all stat variables while locked */
03024          myrpt = &rpt_vars[i];
03025          rpt_mutex_lock(&myrpt->lock); /* LOCK */
03026          __mklinklist(myrpt,NULL,lbuf);
03027          rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
03028          /* parse em */
03029          ns = finddelim(lbuf,strs,MAXLINKLIST);
03030          /* sort em */
03031          if (ns) qsort((void *)strs,ns,sizeof(char *),mycompar);
03032          ast_cli(fd,"\n");
03033          ast_cli(fd, "************************* CONNECTED NODES *************************\n\n");
03034          for(j = 0 ;; j++){
03035             if(!strs[j]){
03036                if(!j){
03037                   ast_cli(fd,"<NONE>");
03038                }
03039                break;
03040             }
03041             ast_cli(fd, "%s", strs[j]);
03042             if(j % 8 == 7){
03043                ast_cli(fd, "\n");
03044             }
03045             else{
03046                if(strs[j + 1])
03047                   ast_cli(fd, ", ");
03048             }
03049          }
03050          ast_cli(fd,"\n\n");
03051          return RESULT_SUCCESS;
03052       }
03053    }
03054    return RESULT_FAILURE;
03055 }
03056 
03057 /*
03058 * List all locally configured nodes
03059 */
03060 
03061 static int rpt_do_local_nodes(int fd, int argc, const char * const *argv)
03062 {
03063 
03064     int i;
03065     ast_cli(fd, "\nNode\n----\n");
03066     for (i=0; i< nrpts; i++)
03067     {
03068         ast_cli(fd, "%s\n", rpt_vars[i].name);        
03069     } /* for i */
03070     ast_cli(fd,"\n");
03071     return RESULT_SUCCESS;
03072 } 
03073 
03074 
03075 /*
03076 * reload vars 
03077 */
03078 
03079 static int rpt_do_reload(int fd, int argc, const char * const *argv)
03080 {
03081 int   n;
03082 
03083         if (argc > 2) return RESULT_SHOWUSAGE;
03084 
03085    for(n = 0; n < nrpts; n++) rpt_vars[n].reload = 1;
03086 
03087    return RESULT_FAILURE;
03088 }
03089 
03090 /*
03091 * restart app_rpt
03092 */
03093                                                                                                                                  
03094 static int rpt_do_restart(int fd, int argc, const char * const *argv)
03095 {
03096 int   i;
03097 
03098         if (argc > 2) return RESULT_SHOWUSAGE;
03099    for(i = 0; i < nrpts; i++)
03100    {
03101       if (rpt_vars[i].rxchannel) ast_softhangup(rpt_vars[i].rxchannel,AST_SOFTHANGUP_DEV);
03102    }
03103    return RESULT_FAILURE;
03104 }
03105 
03106 
03107 /*
03108 * send an app_rpt DTMF function from the CLI
03109 */
03110                                                                                                                                  
03111 static int rpt_do_fun(int fd, int argc, const char * const *argv)
03112 {
03113    int   i,busy=0;
03114 
03115         if (argc != 4) return RESULT_SHOWUSAGE;
03116 
03117    for(i = 0; i < nrpts; i++){
03118       if(!strcmp(argv[2], rpt_vars[i].name)){
03119          struct rpt *myrpt = &rpt_vars[i];
03120          rpt_mutex_lock(&myrpt->lock);
03121          if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(argv[3])){
03122             rpt_mutex_unlock(&myrpt->lock);
03123             busy=1;
03124          }
03125          if(!busy){
03126             myrpt->macrotimer = MACROTIME;
03127             strncat(myrpt->macrobuf,argv[3],MAXMACRO - 1);
03128          }
03129          rpt_mutex_unlock(&myrpt->lock);
03130       }
03131    }
03132    if(busy){
03133       ast_cli(fd, "Function decoder busy");
03134    }
03135    return RESULT_FAILURE;
03136 }
03137 /*
03138    the convention is that macros in the data from the rpt() application
03139    are all at the end of the data, separated by the | and start with a *
03140    when put into the macro buffer, the characters have their high bit
03141    set so the macro processor knows they came from the application data
03142    and to use the alt-functions table.
03143    sph:
03144 */
03145 static int rpt_push_alt_macro(struct rpt *myrpt, char *sptr)
03146 {
03147    int   busy=0;
03148 
03149    rpt_mutex_lock(&myrpt->lock);
03150    if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(sptr)){
03151       rpt_mutex_unlock(&myrpt->lock);
03152       busy=1;
03153    }
03154    if(!busy){
03155       int x;
03156       if (debug)ast_log(LOG_NOTICE, "rpt_push_alt_macro %s\n",sptr);
03157       myrpt->macrotimer = MACROTIME;
03158       for(x = 0; *(sptr + x); x++)
03159           myrpt->macrobuf[x] = *(sptr + x) | 0x80;
03160       *(sptr + x) = 0;
03161    }
03162    rpt_mutex_unlock(&myrpt->lock);
03163 
03164    if(busy)ast_log(LOG_WARNING, "Function decoder busy on app_rpt command macro.\n");
03165 
03166    return busy;
03167 }
03168 /*
03169    allows us to test rpt() application data commands
03170 */
03171 static int rpt_do_fun1(int fd, int argc, const char * const *argv)
03172 {
03173    int   i;
03174 
03175     if (argc != 4) return RESULT_SHOWUSAGE;
03176 
03177    for(i = 0; i < nrpts; i++){
03178       if(!strcmp(argv[2], rpt_vars[i].name)){
03179          struct rpt *myrpt = &rpt_vars[i];
03180          rpt_push_alt_macro(myrpt, (char *) argv[3]);
03181       }
03182    }
03183    return RESULT_FAILURE;
03184 }
03185 /*
03186 * send an app_rpt **command** from the CLI
03187 */
03188 
03189 static int rpt_do_cmd(int fd, int argc, const char * const *argv)
03190 {
03191    int i, l;
03192    int busy=0;
03193    int maxActions = sizeof(function_table)/sizeof(struct function_table_tag);
03194 
03195    int thisRpt = -1;
03196    int thisAction = -1;
03197    struct rpt *myrpt = NULL;
03198    if (argc != 6) return RESULT_SHOWUSAGE;
03199    
03200    for(i = 0; i < nrpts; i++)
03201    {
03202       if(!strcmp(argv[2], rpt_vars[i].name))
03203       {
03204          thisRpt = i;
03205          myrpt = &rpt_vars[i];
03206          break;
03207       } /* if !strcmp... */
03208    } /* for i */
03209 
03210    if (thisRpt < 0)
03211    {
03212       ast_cli(fd, "Unknown node number %s.\n", argv[2]);
03213       return RESULT_FAILURE;
03214    } /* if thisRpt < 0 */
03215    
03216    /* Look up the action */
03217    l = strlen(argv[3]);
03218    for(i = 0 ; i < maxActions; i++)
03219    {
03220       if(!strncasecmp(argv[3], function_table[i].action, l))
03221       {
03222          thisAction = i;
03223          break;
03224       } /* if !strncasecmp... */
03225    } /* for i */
03226    
03227    if (thisAction < 0)
03228    {
03229       ast_cli(fd, "Unknown action name %s.\n", argv[3]);
03230       return RESULT_FAILURE;
03231    } /* if thisAction < 0 */
03232 
03233    /* at this point, it looks like all the arguments make sense... */
03234 
03235    rpt_mutex_lock(&myrpt->lock);
03236 
03237    if (rpt_vars[thisRpt].cmdAction.state == CMD_STATE_IDLE)
03238    {
03239       rpt_vars[thisRpt].cmdAction.state = CMD_STATE_BUSY;
03240       rpt_vars[thisRpt].cmdAction.functionNumber = thisAction;
03241       strncpy(rpt_vars[thisRpt].cmdAction.param, argv[4], MAXDTMF);
03242       strncpy(rpt_vars[thisRpt].cmdAction.digits, argv[5], MAXDTMF);
03243       rpt_vars[thisRpt].cmdAction.command_source = SOURCE_RPT;
03244       rpt_vars[thisRpt].cmdAction.state = CMD_STATE_READY;
03245    } /* if (rpt_vars[thisRpt].cmdAction.state == CMD_STATE_IDLE */
03246    else
03247    {
03248       busy = 1;
03249    } /* if (rpt_vars[thisRpt].cmdAction.state == CMD_STATE_IDLE */
03250    rpt_mutex_unlock(&myrpt->lock);
03251 
03252    return (busy ? RESULT_FAILURE : RESULT_SUCCESS);
03253 } /* rpt_do_cmd() */
03254 
03255 static int play_tone_pair(struct ast_channel *chan, int f1, int f2, int duration, int amplitude)
03256 {
03257    int res;
03258 
03259         if ((res = ast_tonepair_start(chan, f1, f2, duration, amplitude)))
03260                 return res;
03261                                                                                                                                             
03262         while(chan->generatordata) {
03263       if (ast_safe_sleep(chan,1)) return -1;
03264    }
03265 
03266         return 0;
03267 }
03268 
03269 static int play_tone(struct ast_channel *chan, int freq, int duration, int amplitude)
03270 {
03271    return play_tone_pair(chan, freq, 0, duration, amplitude);
03272 }
03273 
03274 static int play_silence(struct ast_channel *chan, int duration)
03275 {
03276    return play_tone_pair(chan, 0, 0, duration, 0);
03277 }
03278 
03279 #ifdef   NEW_ASTERISK
03280 
03281 static char *res2cli(int r)
03282 
03283 {
03284    switch (r)
03285    {
03286        case RESULT_SUCCESS:
03287       return(CLI_SUCCESS);
03288        case RESULT_SHOWUSAGE:
03289       return(CLI_SHOWUSAGE);
03290        default:
03291       return(CLI_FAILURE);
03292    }
03293 }
03294 
03295 static char *handle_cli_debug(struct ast_cli_entry *e,
03296    int cmd, struct ast_cli_args *a)
03297 {
03298         switch (cmd) {
03299         case CLI_INIT:
03300                 e->command = "rpt debug level";
03301                 e->usage = debug_usage;
03302                 return NULL;
03303         case CLI_GENERATE:
03304                 return NULL;
03305    }
03306    return res2cli(rpt_do_debug(a->fd, a->argc, a->argv));
03307 }
03308 
03309 static char *handle_cli_dump(struct ast_cli_entry *e,
03310    int cmd, struct ast_cli_args *a)
03311 {
03312         switch (cmd) {
03313         case CLI_INIT:
03314                 e->command = "rpt dump level";
03315                 e->usage = dump_usage;
03316                 return NULL;
03317         case CLI_GENERATE:
03318                 return NULL;
03319    }
03320    return res2cli(rpt_do_dump(a->fd,a->argc,a->argv));
03321 }
03322 
03323 
03324 static char *handle_cli_stats(struct ast_cli_entry *e,
03325    int cmd, struct ast_cli_args *a)
03326 {
03327         switch (cmd) {
03328         case CLI_INIT:
03329                 e->command = "rpt stats";
03330                 e->usage = dump_stats;
03331                 return NULL;
03332         case CLI_GENERATE:
03333                 return NULL;
03334    }
03335    return res2cli(rpt_do_stats(a->fd,a->argc,a->argv));
03336 }
03337 
03338 static char *handle_cli_nodes(struct ast_cli_entry *e,
03339    int cmd, struct ast_cli_args *a)
03340 {
03341         switch (cmd) {
03342         case CLI_INIT:
03343                 e->command = "rpt nodes";
03344                 e->usage = dump_nodes;
03345                 return NULL;
03346         case CLI_GENERATE:
03347                 return NULL;
03348    }
03349    return res2cli(rpt_do_nodes(a->fd,a->argc,a->argv));
03350 }
03351 
03352 static char *handle_cli_local_nodes(struct ast_cli_entry *e,
03353    int cmd, struct ast_cli_args *a)
03354 {
03355         switch (cmd) {
03356         case CLI_INIT:
03357                 e->command = "rpt localnodes";
03358                 e->usage = usage_local_nodes;
03359                 return NULL;
03360         case CLI_GENERATE:
03361                 return NULL;
03362    }
03363    return res2cli(rpt_do_local_nodes(a->fd,a->argc,a->argv));
03364 }
03365 
03366 static char *handle_cli_lstats(struct ast_cli_entry *e,
03367    int cmd, struct ast_cli_args *a)
03368 {
03369         switch (cmd) {
03370         case CLI_INIT:
03371                 e->command = "rpt lstats";
03372                 e->usage = dump_lstats;
03373                 return NULL;
03374         case CLI_GENERATE:
03375                 return NULL;
03376    }
03377    return res2cli(rpt_do_lstats(a->fd,a->argc,a->argv));
03378 }
03379 
03380 static char *handle_cli_reload(struct ast_cli_entry *e,
03381    int cmd, struct ast_cli_args *a)
03382 {
03383         switch (cmd) {
03384         case CLI_INIT:
03385                 e->command = "rpt reload";
03386                 e->usage = reload_usage;
03387                 return NULL;
03388         case CLI_GENERATE:
03389                 return NULL;
03390    }
03391    return res2cli(rpt_do_reload(a->fd,a->argc,a->argv));
03392 }
03393 
03394 static char *handle_cli_restart(struct ast_cli_entry *e,
03395    int cmd, struct ast_cli_args *a)
03396 {
03397         switch (cmd) {
03398         case CLI_INIT:
03399                 e->command = "rpt restart";
03400                 e->usage = restart_usage;
03401                 return NULL;
03402         case CLI_GENERATE:
03403                 return NULL;
03404    }
03405    return res2cli(rpt_do_restart(a->fd,a->argc,a->argv));
03406 }
03407 
03408 static char *handle_cli_fun(struct ast_cli_entry *e,
03409    int cmd, struct ast_cli_args *a)
03410 {
03411         switch (cmd) {
03412         case CLI_INIT:
03413                 e->command = "rpt fun";
03414                 e->usage = fun_usage;
03415                 return NULL;
03416         case CLI_GENERATE:
03417                 return NULL;
03418    }
03419    return res2cli(rpt_do_fun(a->fd,a->argc,a->argv));
03420 }
03421 
03422 static char *handle_cli_fun1(struct ast_cli_entry *e,
03423    int cmd, struct ast_cli_args *a)
03424 {
03425         switch (cmd) {
03426         case CLI_INIT:
03427                 e->command = "rpt fun1";
03428                 e->usage = fun_usage;
03429                 return NULL;
03430         case CLI_GENERATE:
03431                 return NULL;
03432    }
03433    return res2cli(rpt_do_fun1(a->fd,a->argc,a->argv));
03434 }
03435 
03436 static char *handle_cli_cmd(struct ast_cli_entry *e,
03437    int cmd, struct ast_cli_args *a)
03438 {
03439         switch (cmd) {
03440         case CLI_INIT:
03441                 e->command = "rpt cmd";
03442                 e->usage = cmd_usage;
03443                 return NULL;
03444         case CLI_GENERATE:
03445                 return NULL;
03446    }
03447    return res2cli(rpt_do_cmd(a->fd,a->argc,a->argv));
03448 }
03449 
03450 static struct ast_cli_entry rpt_cli[] = {
03451    AST_CLI_DEFINE(handle_cli_debug,"Enable app_rpt debugging"),
03452    AST_CLI_DEFINE(handle_cli_dump,"Dump app_rpt structs for debugging"),
03453    AST_CLI_DEFINE(handle_cli_stats,"Dump node statistics"),
03454    AST_CLI_DEFINE(handle_cli_nodes,"Dump node list"),
03455    AST_CLI_DEFINE(handle_cli_local_nodes, "Dump list of local node numbers"),
03456    AST_CLI_DEFINE(handle_cli_lstats,"Dump link statistics"),
03457    AST_CLI_DEFINE(handle_cli_reload,"Reload app_rpt config"),
03458    AST_CLI_DEFINE(handle_cli_restart,"Restart app_rpt"),
03459    AST_CLI_DEFINE(handle_cli_fun,"Execute a DTMF function"),
03460    AST_CLI_DEFINE(handle_cli_fun1,"Execute a DTMF function"),
03461    AST_CLI_DEFINE(handle_cli_cmd,"Execute a DTMF function")
03462 };
03463 
03464 #endif
03465 
03466 static int send_morse(struct ast_channel *chan, char *string, int speed, int freq, int amplitude)
03467 {
03468 
03469 static struct morse_bits mbits[] = {
03470       {0, 0}, /* SPACE */
03471       {0, 0}, 
03472       {6, 18},/* " */
03473       {0, 0},
03474       {7, 72},/* $ */
03475       {0, 0},
03476       {0, 0},
03477       {6, 30},/* ' */
03478       {5, 13},/* ( */
03479       {6, 29},/* ) */
03480       {0, 0},
03481       {5, 10},/* + */
03482       {6, 51},/* , */
03483       {6, 33},/* - */
03484       {6, 42},/* . */
03485       {5, 9}, /* / */
03486       {5, 31},/* 0 */
03487       {5, 30},/* 1 */
03488       {5, 28},/* 2 */
03489       {5, 24},/* 3 */
03490       {5, 16},/* 4 */
03491       {5, 0}, /* 5 */
03492       {5, 1}, /* 6 */
03493       {5, 3}, /* 7 */
03494       {5, 7}, /* 8 */
03495       {5, 15},/* 9 */
03496       {6, 7}, /* : */
03497       {6, 21},/* ; */
03498       {0, 0},
03499       {5, 33},/* = */
03500       {0, 0},
03501       {6, 12},/* ? */
03502       {0, 0},
03503          {2, 2}, /* A */
03504       {4, 1}, /* B */
03505       {4, 5}, /* C */
03506       {3, 1}, /* D */
03507       {1, 0}, /* E */
03508       {4, 4}, /* F */
03509       {3, 3}, /* G */
03510       {4, 0}, /* H */
03511       {2, 0}, /* I */
03512       {4, 14},/* J */
03513       {3, 5}, /* K */
03514       {4, 2}, /* L */
03515       {2, 3}, /* M */
03516       {2, 1}, /* N */
03517       {3, 7}, /* O */
03518       {4, 6}, /* P */
03519       {4, 11},/* Q */
03520       {3, 2}, /* R */
03521       {3, 0}, /* S */
03522       {1, 1}, /* T */
03523       {3, 4}, /* U */
03524       {4, 8}, /* V */
03525       {3, 6}, /* W */
03526       {4, 9}, /* X */
03527       {4, 13},/* Y */
03528       {4, 3}  /* Z */
03529    };
03530 
03531 
03532    int dottime;
03533    int dashtime;
03534    int intralettertime;
03535    int interlettertime;
03536    int interwordtime;
03537    int len, ddcomb;
03538    int res;
03539    int c;
03540    int i;
03541    int flags;
03542          
03543    res = 0;
03544    
03545    /* Approximate the dot time from the speed arg. */
03546    
03547    dottime = 900/speed;
03548    
03549    /* Establish timing releationships */
03550    
03551    dashtime = 3 * dottime;
03552    intralettertime = dottime;
03553    interlettertime = dottime * 4 ;
03554    interwordtime = dottime * 7;
03555    
03556    for(;(*string) && (!res); string++){
03557    
03558       c = *string;
03559       
03560       /* Convert lower case to upper case */
03561       
03562       if((c >= 'a') && (c <= 'z'))
03563          c -= 0x20;
03564       
03565       /* Can't deal with any char code greater than Z, skip it */
03566       
03567       if(c  > 'Z')
03568          continue;
03569       
03570       /* If space char, wait the inter word time */
03571                
03572       if(c == ' '){
03573          if(!res)
03574             res = play_silence(chan, interwordtime);
03575          continue;
03576       }
03577       
03578       /* Subtract out control char offset to match our table */
03579       
03580       c -= 0x20;
03581       
03582       /* Get the character data */
03583       
03584       len = mbits[c].len;
03585       ddcomb = mbits[c].ddcomb;
03586       
03587       /* Send the character */
03588       
03589       for(; len ; len--){
03590          if(!res)
03591             res = play_tone(chan, freq, (ddcomb & 1) ? dashtime : dottime, amplitude);
03592          if(!res)
03593             res = play_silence(chan, intralettertime);
03594          ddcomb >>= 1;
03595       }
03596       
03597       /* Wait the interletter time */
03598       
03599       if(!res)
03600          res = play_silence(chan, interlettertime - intralettertime);
03601    }
03602    
03603    /* Wait for all the frames to be sent */
03604    
03605    if (!res) 
03606       res = ast_waitstream(chan, "");
03607    ast_stopstream(chan);
03608    
03609    /*
03610    * Wait for the DAHDI driver to physically write the tone blocks to the hardware
03611    */
03612 
03613    for(i = 0; i < 20 ; i++){
03614       flags =  DAHDI_IOMUX_WRITEEMPTY | DAHDI_IOMUX_NOWAIT; 
03615       res = ioctl(chan->fds[0], DAHDI_IOMUX, &flags);
03616       if(flags & DAHDI_IOMUX_WRITEEMPTY)
03617          break;
03618       if( ast_safe_sleep(chan, 50)){
03619          res = -1;
03620          break;
03621       }
03622    }
03623 
03624    
03625    return res;
03626 }
03627 
03628 static int send_tone_telemetry(struct ast_channel *chan, char *tonestring)
03629 {
03630    char *p,*stringp;
03631    char *tonesubset;
03632    int f1,f2;
03633    int duration;
03634    int amplitude;
03635    int res;
03636    int i;
03637    int flags;
03638    
03639    res = 0;
03640 
03641    if(!tonestring)
03642       return res;
03643    
03644    p = stringp = ast_strdup(tonestring);
03645 
03646    for(;tonestring;){
03647       tonesubset = strsep(&stringp,")");
03648       if(!tonesubset)
03649          break;
03650       if(sscanf(tonesubset,"(%30d,%30d,%30d,%30d", &f1, &f2, &duration, &amplitude) != 4)
03651          break;
03652       res = play_tone_pair(chan, f1, f2, duration, amplitude);
03653       if(res)
03654          break;
03655    }
03656    ast_free(p);
03657    if(!res)
03658       res = play_tone_pair(chan, 0, 0, 100, 0); /* This is needed to ensure the last tone segment is timed correctly */
03659    
03660    if (!res) 
03661       res = ast_waitstream(chan, "");
03662 
03663    ast_stopstream(chan);
03664 
03665    /*
03666    * Wait for the DAHDI driver to physically write the tone blocks to the hardware
03667    */
03668 
03669    for(i = 0; i < 20 ; i++){
03670       flags =  DAHDI_IOMUX_WRITEEMPTY | DAHDI_IOMUX_NOWAIT; 
03671       res = ioctl(chan->fds[0], DAHDI_IOMUX, &flags);
03672       if(flags & DAHDI_IOMUX_WRITEEMPTY)
03673          break;
03674       if( ast_safe_sleep(chan, 50)){
03675          res = -1;
03676          break;
03677       }
03678    }
03679       
03680    return res;
03681       
03682 }
03683 
03684 static int sayfile(struct ast_channel *mychannel,char *fname)
03685 {
03686 int   res;
03687 
03688    res = ast_streamfile(mychannel, fname, mychannel->language);
03689    if (!res) 
03690       res = ast_waitstream(mychannel, "");
03691    else
03692        ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
03693    ast_stopstream(mychannel);
03694    return res;
03695 }
03696 
03697 static int saycharstr(struct ast_channel *mychannel,char *str)
03698 {
03699 int   res;
03700 
03701    res = ast_say_character_str(mychannel,str,NULL,mychannel->language);
03702    if (!res) 
03703       res = ast_waitstream(mychannel, "");
03704    else
03705        ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
03706    ast_stopstream(mychannel);
03707    return res;
03708 }
03709 
03710 static int saynum(struct ast_channel *mychannel, int num)
03711 {
03712    int res;
03713    res = ast_say_number(mychannel, num, NULL, mychannel->language, NULL);
03714    if(!res)
03715       res = ast_waitstream(mychannel, "");
03716    else
03717       ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
03718    ast_stopstream(mychannel);
03719    return res;
03720 }
03721 
03722 /* say a node and nodename. Try to look in dir referred to by nodenames in
03723 config, and see if there's a custom node file to play, and if so, play it */
03724 
03725 static int saynode(struct rpt *myrpt, struct ast_channel *mychannel, char *name)
03726 {
03727 int   res;
03728 char  *val,fname[300];
03729 
03730    val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, "nodenames");
03731    if (!val) val = NODENAMES;
03732    snprintf(fname,sizeof(fname) - 1,"%s/%s",val,name);
03733    if (ast_fileexists(fname,NULL,mychannel->language) > 0)
03734       return(sayfile(mychannel,fname));
03735    res = sayfile(mychannel,"rpt/node");
03736    if (!res) 
03737       res = ast_say_character_str(mychannel,name,NULL,mychannel->language);
03738    return res;
03739 }
03740 
03741 static int telem_any(struct rpt *myrpt,struct ast_channel *chan, char *entry)
03742 {
03743    int res;
03744    char c;
03745    
03746    static int morsespeed;
03747    static int morsefreq;
03748    static int morseampl;
03749    static int morseidfreq = 0;
03750    static int morseidampl;
03751    static char mcat[] = MORSE;
03752    
03753    res = 0;
03754    
03755    if(!morseidfreq){ /* Get the morse parameters if not already loaded */
03756       morsespeed = retrieve_astcfgint(myrpt, mcat, "speed", 5, 20, 20);
03757          morsefreq = retrieve_astcfgint(myrpt, mcat, "frequency", 300, 3000, 800);
03758          morseampl = retrieve_astcfgint(myrpt, mcat, "amplitude", 200, 8192, 4096);
03759       morseidampl = retrieve_astcfgint(myrpt, mcat, "idamplitude", 200, 8192, 2048);
03760       morseidfreq = retrieve_astcfgint(myrpt, mcat, "idfrequency", 300, 3000, 330); 
03761    }
03762    
03763    /* Is it a file, or a tone sequence? */
03764          
03765    if(entry[0] == '|'){
03766       c = entry[1];
03767       if((c >= 'a')&&(c <= 'z'))
03768          c -= 0x20;
03769    
03770       switch(c){
03771          case 'I': /* Morse ID */
03772             res = send_morse(chan, entry + 2, morsespeed, morseidfreq, morseidampl);
03773             break;
03774          
03775          case 'M': /* Morse Message */
03776             res = send_morse(chan, entry + 2, morsespeed, morsefreq, morseampl);
03777             break;
03778          
03779          case 'T': /* Tone sequence */
03780             res = send_tone_telemetry(chan, entry + 2);
03781             break;
03782          default:
03783             res = -1;
03784       }
03785    }
03786    else
03787       res = sayfile(chan, entry); /* File */
03788    return res;
03789 }
03790 
03791 /*
03792 * This function looks up a telemetry name in the config file, and does a telemetry response as configured.
03793 *
03794 * 4 types of telemtry are handled: Morse ID, Morse Message, Tone Sequence, and a File containing a recording.
03795 */
03796 
03797 static int telem_lookup(struct rpt *myrpt,struct ast_channel *chan, char *node, char *name)
03798 {
03799    
03800    int res;
03801    int i;
03802    char *entry;
03803    char *telemetry;
03804    char *telemetry_save;
03805 
03806    res = 0;
03807    telemetry_save = NULL;
03808    entry = NULL;
03809    
03810    /* Retrieve the section name for telemetry from the node section */
03811    telemetry = (char *) ast_variable_retrieve(myrpt->cfg, node, TELEMETRY);
03812    if(telemetry ){
03813       telemetry_save = ast_strdup(telemetry);
03814       if(!telemetry_save){
03815          ast_log(LOG_WARNING,"ast_strdup() failed in telem_lookup()\n");
03816          return res;
03817       }
03818       entry = (char *) ast_variable_retrieve(myrpt->cfg, telemetry_save, name);
03819    }
03820    
03821    /* Try to look up the telemetry name */   
03822 
03823    if(!entry){
03824       /* Telemetry name wasn't found in the config file, use the default */
03825       for(i = 0; i < sizeof(tele_defs)/sizeof(struct telem_defaults) ; i++){
03826          if(!strcasecmp(tele_defs[i].name, name))
03827             entry = tele_defs[i].value;
03828       }
03829    }
03830    if(entry){  
03831       if(strlen(entry))
03832          if (chan) telem_any(myrpt,chan, entry);
03833    }
03834    else{
03835       res = -1;
03836    }
03837    ast_free(telemetry_save);
03838    return res;
03839 }
03840 
03841 /*
03842 * Retrieve a wait interval
03843 */
03844 
03845 static int get_wait_interval(struct rpt *myrpt, int type)
03846 {
03847         int interval;
03848         char *wait_times;
03849         char *wait_times_save;
03850                                                                                                                   
03851         wait_times_save = NULL;
03852         wait_times = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, "wait_times");
03853                                                                                                                   
03854         if(wait_times){
03855                 wait_times_save = ast_strdup(wait_times);
03856                 if(!wait_times_save)
03857          return 0;
03858                 
03859         }
03860                                                                                                                   
03861         switch(type){
03862                 case DLY_TELEM:
03863                         if(wait_times)
03864                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "telemwait", 500, 5000, 1000);
03865                         else
03866                                 interval = 1000;
03867                         break;
03868                                                                                                                   
03869                 case DLY_ID:
03870                         if(wait_times)
03871                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "idwait",250,5000,500);
03872                         else
03873                                 interval = 500;
03874                         break;
03875                                                                                                                   
03876                 case DLY_UNKEY:
03877                         if(wait_times)
03878                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "unkeywait",50,5000,1000);
03879                         else
03880                                 interval = 1000;
03881                         break;
03882                                                                                                                   
03883                 case DLY_LINKUNKEY:
03884                         if(wait_times)
03885                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "linkunkeywait",500,5000,1000);
03886                         else
03887                                 interval = 1000;
03888                         break;
03889                                                                                                                   
03890                 case DLY_CALLTERM:
03891                         if(wait_times)
03892                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "calltermwait",500,5000,1500);
03893                         else
03894                                 interval = 1500;
03895                         break;
03896                                                                                                                   
03897                 case DLY_COMP:
03898                         if(wait_times)
03899                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "compwait",500,5000,200);
03900                         else
03901                                 interval = 200;
03902                         break;
03903                                                                                                                   
03904                 case DLY_PARROT:
03905                         if(wait_times)
03906                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "parrotwait",500,5000,200);
03907                         else
03908                                 interval = 200;
03909                         break;
03910                                                                                                                   
03911                 default:
03912          interval = 0;
03913          break;
03914         }
03915    ast_free(wait_times_save);
03916    return interval;
03917 }                                                                                                                  
03918 
03919 
03920 /*
03921 * Wait a configurable interval of time 
03922 */
03923 static void wait_interval(struct rpt *myrpt, int type, struct ast_channel *chan)
03924 {
03925    int interval;
03926    interval = get_wait_interval(myrpt, type);
03927    if(debug)
03928       ast_log(LOG_NOTICE,"Delay interval = %d\n", interval);
03929    if(interval)
03930       ast_safe_sleep(chan,interval);
03931    if(debug)
03932       ast_log(LOG_NOTICE,"Delay complete\n");
03933    return;
03934 }
03935 
03936 static int split_freq(char *mhz, char *decimals, char *freq);
03937 
03938 static void *rpt_tele_thread(void *this)
03939 {
03940 struct dahdi_confinfo ci;  /* conference info */
03941 int   res = 0,haslink,hastx,hasremote,imdone = 0, unkeys_queued, x;
03942 struct   rpt_tele *mytele = (struct rpt_tele *)this;
03943 struct  rpt_tele *tlist;
03944 struct   rpt *myrpt;
03945 struct   rpt_link *l,*l1,linkbase;
03946 struct   ast_channel *mychannel;
03947 int vmajor, vminor, m;
03948 char *p,*ct,*ct_copy,*ident, *nodename;
03949 time_t t;
03950 #ifdef   NEW_ASTERISK
03951 struct ast_tm localtm;
03952 #else
03953 struct tm localtm;
03954 #endif
03955 char lbuf[MAXLINKLIST],*strs[MAXLINKLIST];
03956 int   i,ns,rbimode;
03957 char mhz[MAXREMSTR];
03958 char decimals[MAXREMSTR];
03959 char  mystr[200];
03960 struct dahdi_params par;
03961 
03962 
03963    /* get a pointer to myrpt */
03964    myrpt = mytele->rpt;
03965 
03966    /* Snag copies of a few key myrpt variables */
03967    rpt_mutex_lock(&myrpt->lock);
03968    nodename = ast_strdup(myrpt->name);
03969    if(!nodename)
03970    {
03971        fprintf(stderr,"rpt:Sorry unable strdup nodename\n");
03972        rpt_mutex_lock(&myrpt->lock);
03973        remque((struct qelem *)mytele);
03974        ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
03975        rpt_mutex_unlock(&myrpt->lock);
03976        ast_free(mytele);
03977        pthread_exit(NULL);
03978    }
03979 
03980    if (myrpt->p.ident){
03981       ident = ast_strdup(myrpt->p.ident);
03982          if(!ident)
03983       {
03984                  fprintf(stderr,"rpt:Sorry unable strdup ident\n");
03985          rpt_mutex_lock(&myrpt->lock);
03986                   remque((struct qelem *)mytele);
03987                   ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",
03988          __LINE__, mytele->mode); /*@@@@@@@@@@@*/
03989                   rpt_mutex_unlock(&myrpt->lock);
03990          ast_free(nodename);
03991                   ast_free(mytele);
03992                   pthread_exit(NULL);
03993          }
03994    }
03995    else
03996    {
03997       ident = "";
03998    }
03999    rpt_mutex_unlock(&myrpt->lock);
04000       
04001 
04002 
04003    /* allocate a pseudo-channel thru asterisk */
04004    mychannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
04005    if (!mychannel)
04006    {
04007       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
04008       rpt_mutex_lock(&myrpt->lock);
04009       remque((struct qelem *)mytele);
04010       ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04011       rpt_mutex_unlock(&myrpt->lock);
04012       ast_free(nodename);
04013       ast_free(ident);
04014       ast_free(mytele);    
04015       pthread_exit(NULL);
04016    }
04017 #ifdef   AST_CDR_FLAG_POST_DISABLED
04018    if (mychannel->cdr) 
04019       ast_set_flag(mychannel->cdr,AST_CDR_FLAG_POST_DISABLED);
04020 #endif
04021    rpt_mutex_lock(&myrpt->lock);
04022    mytele->chan = mychannel;
04023    rpt_mutex_unlock(&myrpt->lock);
04024 
04025    while((mytele->mode != SETREMOTE) && (mytele->mode != UNKEY) &&
04026       (mytele->mode != LINKUNKEY))
04027    {  
04028                 rpt_mutex_lock(&myrpt->lock);
04029       if (!myrpt->active_telem)
04030       {
04031          myrpt->active_telem = mytele;
04032                    rpt_mutex_unlock(&myrpt->lock);
04033          break;
04034       }
04035                 rpt_mutex_unlock(&myrpt->lock);
04036       usleep(100000);
04037    }
04038 
04039    /* make a conference for the tx */
04040    ci.chan = 0;
04041    /* If the telemetry is only intended for a local audience, */
04042    /* only connect the ID audio to the local tx conference so */
04043    /* linked systems can't hear it */
04044    ci.confno = (((mytele->mode == ID) || (mytele->mode == IDTALKOVER) || (mytele->mode == UNKEY) || 
04045       (mytele->mode == TAILMSG) || (mytele->mode == LINKUNKEY) || (mytele->mode == TIMEOUT) || 
04046       (mytele->mode == PARROT) || (mytele->mode == STATS_TIME_LOCAL)) ? 
04047          myrpt->txconf : myrpt->conf);
04048    ci.confmode = DAHDI_CONF_CONFANN;
04049    /* first put the channel on the conference in announce mode */
04050    if (ioctl(mychannel->fds[0],DAHDI_SETCONF,&ci) == -1)
04051    {
04052       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
04053       rpt_mutex_lock(&myrpt->lock);
04054       myrpt->active_telem = NULL;
04055       remque((struct qelem *)mytele);
04056       rpt_mutex_unlock(&myrpt->lock);
04057       ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04058       ast_free(nodename);
04059       ast_free(ident);
04060       ast_free(mytele);    
04061       ast_hangup(mychannel);
04062       pthread_exit(NULL);
04063    }
04064    ast_stopstream(mychannel);
04065    switch(mytele->mode)
04066    {
04067        case ID:
04068        case ID1:
04069       /* wait a bit */
04070       wait_interval(myrpt, (mytele->mode == ID) ? DLY_ID : DLY_TELEM,mychannel);
04071       res = telem_any(myrpt,mychannel, ident); 
04072       imdone=1;   
04073       break;
04074       
04075        case TAILMSG:
04076       res = ast_streamfile(mychannel, myrpt->p.tailmessages[myrpt->tailmessagen], mychannel->language); 
04077       break;
04078       
04079        case IDTALKOVER:
04080          p = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "idtalkover");
04081          if(p)
04082          res = telem_any(myrpt,mychannel, p); 
04083       imdone=1;   
04084          break;
04085             
04086        case PROC:
04087       /* wait a little bit longer */
04088       wait_interval(myrpt, DLY_TELEM, mychannel);
04089       res = telem_lookup(myrpt, mychannel, myrpt->name, "patchup");
04090       if(res < 0){ /* Then default message */
04091          res = ast_streamfile(mychannel, "rpt/callproceeding", mychannel->language);
04092       }
04093       break;
04094        case TERM:
04095       /* wait a little bit longer */
04096       wait_interval(myrpt, DLY_CALLTERM, mychannel);
04097       res = telem_lookup(myrpt, mychannel, myrpt->name, "patchdown");
04098       if(res < 0){ /* Then default message */
04099          res = ast_streamfile(mychannel, "rpt/callterminated", mychannel->language);
04100       }
04101       break;
04102        case COMPLETE:
04103       /* wait a little bit */
04104       wait_interval(myrpt, DLY_TELEM, mychannel);
04105       res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04106       break;
04107        case MACRO_NOTFOUND:
04108       /* wait a little bit */
04109       wait_interval(myrpt, DLY_TELEM, mychannel);
04110       res = ast_streamfile(mychannel, "rpt/macro_notfound", mychannel->language);
04111       break;
04112        case MACRO_BUSY:
04113       /* wait a little bit */
04114       wait_interval(myrpt, DLY_TELEM, mychannel);
04115       res = ast_streamfile(mychannel, "rpt/macro_busy", mychannel->language);
04116       break;
04117        case UNKEY:
04118       if(myrpt->patchnoct && myrpt->callmode){ /* If no CT during patch configured, then don't send one */
04119          imdone = 1;
04120          break;
04121       }
04122          
04123       /*
04124       * Reset the Unkey to CT timer
04125       */
04126 
04127       x = get_wait_interval(myrpt, DLY_UNKEY);
04128       rpt_mutex_lock(&myrpt->lock);
04129       myrpt->unkeytocttimer = x; /* Must be protected as it is changed below */
04130       rpt_mutex_unlock(&myrpt->lock);
04131 
04132       /*
04133       * If there's one already queued, don't do another
04134       */
04135 
04136       tlist = myrpt->tele.next;
04137       unkeys_queued = 0;
04138                 if (tlist != &myrpt->tele)
04139                 {
04140                         rpt_mutex_lock(&myrpt->lock);
04141                         while(tlist != &myrpt->tele){
04142                                 if (tlist->mode == UNKEY) unkeys_queued++;
04143                                 tlist = tlist->next;
04144                         }
04145                         rpt_mutex_unlock(&myrpt->lock);
04146       }
04147       if( unkeys_queued > 1){
04148          imdone = 1;
04149          break;
04150       }
04151 
04152       /* Wait for the telemetry timer to expire */
04153       /* Periodically check the timer since it can be re-initialized above */
04154       while(myrpt->unkeytocttimer)
04155       {
04156          int ctint;
04157          if(myrpt->unkeytocttimer > 100)
04158             ctint = 100;
04159          else
04160             ctint = myrpt->unkeytocttimer;
04161          ast_safe_sleep(mychannel, ctint);
04162          rpt_mutex_lock(&myrpt->lock);
04163          if(myrpt->unkeytocttimer < ctint)
04164             myrpt->unkeytocttimer = 0;
04165          else
04166             myrpt->unkeytocttimer -= ctint;
04167          rpt_mutex_unlock(&myrpt->lock);
04168       }
04169    
04170       /*
04171       * Now, the carrier on the rptr rx should be gone. 
04172       * If it re-appeared, then forget about sending the CT
04173       */
04174       if(myrpt->keyed){
04175          imdone = 1;
04176          break;
04177       }
04178       
04179       rpt_mutex_lock(&myrpt->lock); /* Update the kerchunk counters */
04180       myrpt->dailykerchunks++;
04181       myrpt->totalkerchunks++;
04182       rpt_mutex_unlock(&myrpt->lock);
04183    
04184       haslink = 0;
04185       hastx = 0;
04186       hasremote = 0;    
04187       l = myrpt->links.next;
04188       if (l != &myrpt->links)
04189       {
04190          rpt_mutex_lock(&myrpt->lock);
04191          while(l != &myrpt->links)
04192          {
04193             if (l->name[0] == '0')
04194             {
04195                l = l->next;
04196                continue;
04197             }
04198             haslink = 1;
04199             if (l->mode) {
04200                hastx++;
04201                if (l->isremote) hasremote++;
04202             }
04203             l = l->next;
04204          }
04205          rpt_mutex_unlock(&myrpt->lock);
04206       }
04207       if (haslink)
04208       {
04209 
04210          res = telem_lookup(myrpt,mychannel, myrpt->name, (!hastx) ? "remotemon" : "remotetx");
04211          if(res)
04212             ast_log(LOG_WARNING, "telem_lookup:remotexx failed on %s\n", mychannel->name);
04213          
04214       
04215          /* if in remote cmd mode, indicate it */
04216          if (myrpt->cmdnode[0])
04217          {
04218             ast_safe_sleep(mychannel,200);
04219             res = telem_lookup(myrpt,mychannel, myrpt->name, "cmdmode");
04220             if(res)
04221                ast_log(LOG_WARNING, "telem_lookup:cmdmode failed on %s\n", mychannel->name);
04222             ast_stopstream(mychannel);
04223          }
04224       }
04225       else if((ct = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "unlinkedct"))){ /* Unlinked Courtesy Tone */
04226          ct_copy = ast_strdup(ct);
04227          if(ct_copy)
04228          {
04229             res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
04230             ast_free(ct_copy);
04231          }
04232          else
04233             res = -1;
04234          if(res)
04235             ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);     
04236       }  
04237       if (hasremote && (!myrpt->cmdnode[0]))
04238       {
04239          /* set for all to hear */
04240          ci.chan = 0;
04241          ci.confno = myrpt->conf;
04242          ci.confmode = DAHDI_CONF_CONFANN;
04243          /* first put the channel on the conference in announce mode */
04244          if (ioctl(mychannel->fds[0],DAHDI_SETCONF,&ci) == -1)
04245          {
04246             ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
04247             rpt_mutex_lock(&myrpt->lock);
04248             myrpt->active_telem = NULL;
04249             remque((struct qelem *)mytele);
04250             rpt_mutex_unlock(&myrpt->lock);
04251             ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04252             ast_free(nodename);
04253             ast_free(ident);
04254             ast_free(mytele);    
04255             ast_hangup(mychannel);
04256             pthread_exit(NULL);
04257          }
04258          if((ct = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "remotect"))){ /* Unlinked Courtesy Tone */
04259             ast_safe_sleep(mychannel,200);
04260             ct_copy = ast_strdup(ct);
04261             if(ct_copy)
04262             {
04263                res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
04264                ast_free(ct_copy);
04265             }
04266             else
04267                res = -1;
04268       
04269             if(res)
04270                ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);     
04271          }  
04272       }
04273 #if   defined(_MDC_DECODE_H_) && defined(MDC_SAY_WHEN_DOING_CT)
04274       if (myrpt->lastunit)
04275       {
04276          char mystr[10];
04277 
04278          ast_safe_sleep(mychannel,200);
04279          /* set for all to hear */
04280          ci.chan = 0;
04281          ci.confno = myrpt->txconf;
04282          ci.confmode = DAHDI_CONF_CONFANN;
04283          /* first put the channel on the conference in announce mode */
04284          if (ioctl(mychannel->fds[0],DAHDI_SETCONF,&ci) == -1)
04285          {
04286             ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
04287             rpt_mutex_lock(&myrpt->lock);
04288             myrpt->active_telem = NULL;
04289             remque((struct qelem *)mytele);
04290             rpt_mutex_unlock(&myrpt->lock);
04291             ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04292             ast_free(nodename);
04293             ast_free(ident);
04294             ast_free(mytele);    
04295             ast_hangup(mychannel);
04296             pthread_exit(NULL);
04297          }
04298          sprintf(mystr,"%04x",myrpt->lastunit);
04299          myrpt->lastunit = 0;
04300          ast_say_character_str(mychannel,mystr,NULL,mychannel->language);
04301          break;
04302       }
04303 #endif
04304       imdone = 1;
04305       break;
04306        case LINKUNKEY:
04307       if(myrpt->patchnoct && myrpt->callmode){ /* If no CT during patch configured, then don't send one */
04308          imdone = 1;
04309          break;
04310       }
04311          
04312       /*
04313       * Reset the Unkey to CT timer
04314       */
04315 
04316       x = get_wait_interval(myrpt, DLY_LINKUNKEY);
04317       mytele->mylink.linkunkeytocttimer = x; /* Must be protected as it is changed below */
04318 
04319       /*
04320       * If there's one already queued, don't do another
04321       */
04322 
04323       tlist = myrpt->tele.next;
04324       unkeys_queued = 0;
04325                 if (tlist != &myrpt->tele)
04326                 {
04327                         rpt_mutex_lock(&myrpt->lock);
04328                         while(tlist != &myrpt->tele){
04329                                 if (tlist->mode == LINKUNKEY) unkeys_queued++;
04330                                 tlist = tlist->next;
04331                         }
04332                         rpt_mutex_unlock(&myrpt->lock);
04333       }
04334       if( unkeys_queued > 1){
04335          imdone = 1;
04336          break;
04337       }
04338 
04339       /* Wait for the telemetry timer to expire */
04340       /* Periodically check the timer since it can be re-initialized above */
04341       while(mytele->mylink.linkunkeytocttimer)
04342       {
04343          int ctint;
04344          if(mytele->mylink.linkunkeytocttimer > 100)
04345             ctint = 100;
04346          else
04347             ctint = mytele->mylink.linkunkeytocttimer;
04348          ast_safe_sleep(mychannel, ctint);
04349          rpt_mutex_lock(&myrpt->lock);
04350          if(mytele->mylink.linkunkeytocttimer < ctint)
04351             mytele->mylink.linkunkeytocttimer = 0;
04352          else
04353             mytele->mylink.linkunkeytocttimer -= ctint;
04354          rpt_mutex_unlock(&myrpt->lock);
04355       }
04356    
04357       if((ct = (char *) ast_variable_retrieve(myrpt->cfg, nodename, "linkunkeyct"))){ /* Unlinked Courtesy Tone */
04358          ct_copy = ast_strdup(ct);
04359          if(ct_copy){
04360             res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
04361             ast_free(ct_copy);
04362          }
04363          else
04364             res = -1;
04365          if(res)
04366             ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);     
04367       }  
04368       imdone = 1;
04369       break;
04370        case REMDISC:
04371       /* wait a little bit */
04372       wait_interval(myrpt, DLY_TELEM, mychannel);
04373       l = myrpt->links.next;
04374       haslink = 0;
04375       /* don't report if a link for this one still on system */
04376       if (l != &myrpt->links)
04377       {
04378          rpt_mutex_lock(&myrpt->lock);
04379          while(l != &myrpt->links)
04380          {
04381             if (l->name[0] == '0')
04382             {
04383                l = l->next;
04384                continue;
04385             }
04386             if (!strcmp(l->name,mytele->mylink.name))
04387             {
04388                haslink = 1;
04389                break;
04390             }
04391             l = l->next;
04392          }
04393          rpt_mutex_unlock(&myrpt->lock);
04394       }
04395       if (haslink)
04396       {
04397          imdone = 1;
04398          break;
04399       }
04400       res = saynode(myrpt,mychannel,mytele->mylink.name);
04401       if (!res) 
04402           res = ast_streamfile(mychannel, ((mytele->mylink.hasconnected) ? 
04403          "rpt/remote_disc" : "rpt/remote_busy"), mychannel->language);
04404       break;
04405        case REMALREADY:
04406       /* wait a little bit */
04407       wait_interval(myrpt, DLY_TELEM, mychannel);
04408       res = ast_streamfile(mychannel, "rpt/remote_already", mychannel->language);
04409       break;
04410        case REMNOTFOUND:
04411       /* wait a little bit */
04412       wait_interval(myrpt, DLY_TELEM, mychannel);
04413       res = ast_streamfile(mychannel, "rpt/remote_notfound", mychannel->language);
04414       break;
04415        case REMGO:
04416       /* wait a little bit */
04417       wait_interval(myrpt, DLY_TELEM, mychannel);
04418       res = ast_streamfile(mychannel, "rpt/remote_go", mychannel->language);
04419       break;
04420        case CONNECTED:
04421       /* wait a little bit */
04422       wait_interval(myrpt, DLY_TELEM,  mychannel);
04423       res = saynode(myrpt,mychannel,mytele->mylink.name);
04424       if (!res)
04425           res = ast_streamfile(mychannel, "rpt/connected", mychannel->language);
04426       if (!res) 
04427          res = ast_waitstream(mychannel, "");
04428       else
04429           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04430       ast_stopstream(mychannel);
04431       res = ast_streamfile(mychannel, "digits/2", mychannel->language);
04432       if (!res) 
04433          res = ast_waitstream(mychannel, "");
04434       else
04435           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04436       ast_stopstream(mychannel);
04437       res = saynode(myrpt,mychannel,myrpt->name);
04438       imdone = 1;
04439       break;
04440        case CONNFAIL:
04441       res = saynode(myrpt,mychannel,mytele->mylink.name);
04442       if (!res) 
04443           res = ast_streamfile(mychannel, "rpt/connection_failed", mychannel->language);
04444       break;
04445        case MEMNOTFOUND:
04446       /* wait a little bit */
04447       wait_interval(myrpt, DLY_TELEM, mychannel);
04448       res = ast_streamfile(mychannel, "rpt/memory_notfound", mychannel->language);
04449       break;
04450        case PLAYBACK:
04451       /* wait a little bit */
04452       wait_interval(myrpt, DLY_TELEM, mychannel);
04453       res = ast_streamfile(mychannel, mytele->param, mychannel->language);
04454       break;
04455        case TOPKEY:
04456       /* wait a little bit */
04457       wait_interval(myrpt, DLY_TELEM, mychannel);
04458       for(i = 0; i < TOPKEYN; i++)
04459       {
04460          if (!myrpt->topkey[i].node[0]) continue;
04461          if ((!myrpt->topkeylong) && (myrpt->topkey[i].keyed)) continue;
04462          res = saynode(myrpt, mychannel,  myrpt->topkey[i].node);
04463          if (!res) res = sayfile(mychannel,(myrpt->topkey[i].keyed) ?
04464             "rpt/keyedfor" : "rpt/unkeyedfor");
04465          if (!res) res = saynum(mychannel,
04466             myrpt->topkey[i].timesince);
04467          if (!res) res = sayfile(mychannel,"rpt/seconds");
04468          if (!myrpt->topkeylong) break;
04469       }
04470       imdone = 1;
04471       break;
04472        case SETREMOTE:
04473       ast_mutex_lock(&myrpt->remlock);
04474       res = 0;
04475       if(!strcmp(myrpt->remoterig, remote_rig_ft897))
04476       {
04477          res = set_ft897(myrpt);
04478       }
04479       else if(!strcmp(myrpt->remoterig, remote_rig_tm271))
04480       {
04481          res = set_tm271(myrpt);
04482       }
04483       else if(!strcmp(myrpt->remoterig, remote_rig_ic706))
04484       {
04485          res = set_ic706(myrpt);
04486       }
04487 #ifdef HAVE_IOPERM
04488       else if(!strcmp(myrpt->remoterig, remote_rig_rbi)||!strcmp(myrpt->remoterig, remote_rig_ppp16))
04489       {
04490          if (ioperm(myrpt->p.iobase,1,1) == -1)
04491          {
04492             rpt_mutex_unlock(&myrpt->lock);
04493             ast_log(LOG_WARNING, "Cant get io permission on IO port %x hex\n",myrpt->p.iobase);
04494             res = -1;
04495          }
04496          else res = setrbi(myrpt);
04497       }
04498 #endif
04499       else if(!strcmp(myrpt->remoterig, remote_rig_kenwood))
04500       {
04501          if (myrpt->iofd >= 0) setdtr(myrpt->iofd,1);
04502          res = setkenwood(myrpt);
04503          if (myrpt->iofd >= 0) setdtr(myrpt->iofd,0);
04504          if (ast_safe_sleep(mychannel,200) == -1)
04505          {
04506             ast_mutex_unlock(&myrpt->remlock);
04507             res = -1;
04508             break;
04509          }
04510          if (myrpt->iofd < 0)
04511          {
04512             i = DAHDI_FLUSH_EVENT;
04513             if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_FLUSH,&i) == -1)
04514             {
04515                ast_mutex_unlock(&myrpt->remlock);
04516                ast_log(LOG_ERROR,"Cant flush events");
04517                res = -1;
04518                break;
04519             }
04520             if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_GET_PARAMS,&par) == -1)
04521             {
04522                ast_mutex_unlock(&myrpt->remlock);
04523                ast_log(LOG_ERROR,"Cant get params");
04524                res = -1;
04525                break;
04526             }
04527             myrpt->remoterx = 
04528                (par.rxisoffhook || (myrpt->tele.next != &myrpt->tele));
04529          }
04530       }
04531 
04532       ast_mutex_unlock(&myrpt->remlock);
04533       if (!res)
04534       {
04535          imdone = 1;
04536          break;
04537       }
04538       /* fall thru to invalid freq */
04539        case INVFREQ:
04540       /* wait a little bit */
04541       wait_interval(myrpt, DLY_TELEM, mychannel);
04542       res = ast_streamfile(mychannel, "rpt/invalid-freq", mychannel->language);
04543       break;
04544        case REMMODE:
04545       wait_interval(myrpt, DLY_TELEM, mychannel);
04546       switch(myrpt->remmode)
04547       {
04548           case REM_MODE_FM:
04549          saycharstr(mychannel,"FM");
04550          break;
04551           case REM_MODE_USB:
04552          saycharstr(mychannel,"USB");
04553          break;
04554           case REM_MODE_LSB:
04555          saycharstr(mychannel,"LSB");
04556          break;
04557           case REM_MODE_AM:
04558          saycharstr(mychannel,"AM");
04559          break;
04560       }
04561       wait_interval(myrpt, DLY_COMP, mychannel);
04562       if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04563       break;
04564        case LOGINREQ:
04565       wait_interval(myrpt, DLY_TELEM, mychannel);
04566       sayfile(mychannel,"rpt/login");
04567       saycharstr(mychannel,myrpt->name);
04568       break;
04569        case REMLOGIN:
04570       wait_interval(myrpt, DLY_TELEM, mychannel);
04571       saycharstr(mychannel,myrpt->loginuser);
04572       saynode(myrpt,mychannel,myrpt->name);
04573       wait_interval(myrpt, DLY_COMP, mychannel);
04574       if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04575       break;
04576        case REMXXX:
04577       wait_interval(myrpt, DLY_TELEM, mychannel);
04578       res = 0;
04579       switch(mytele->submode)
04580       {
04581           case 100: /* RX PL Off */
04582          sayfile(mychannel, "rpt/rxpl");
04583          sayfile(mychannel, "rpt/off");
04584          break;
04585           case 101: /* RX PL On */
04586          sayfile(mychannel, "rpt/rxpl");
04587          sayfile(mychannel, "rpt/on");
04588          break;
04589           case 102: /* TX PL Off */
04590          sayfile(mychannel, "rpt/txpl");
04591          sayfile(mychannel, "rpt/off");
04592          break;
04593           case 103: /* TX PL On */
04594          sayfile(mychannel, "rpt/txpl");
04595          sayfile(mychannel, "rpt/on");
04596          break;
04597           case 104: /* Low Power */
04598          sayfile(mychannel, "rpt/lopwr");
04599          break;
04600           case 105: /* Medium Power */
04601          sayfile(mychannel, "rpt/medpwr");
04602          break;
04603           case 106: /* Hi Power */
04604          sayfile(mychannel, "rpt/hipwr");
04605          break;
04606           case 113: /* Scan down slow */
04607          sayfile(mychannel,"rpt/down");
04608          sayfile(mychannel, "rpt/slow");
04609          break;
04610           case 114: /* Scan down quick */
04611          sayfile(mychannel,"rpt/down");
04612          sayfile(mychannel, "rpt/quick");
04613          break;
04614           case 115: /* Scan down fast */
04615          sayfile(mychannel,"rpt/down");
04616          sayfile(mychannel, "rpt/fast");
04617          break;
04618           case 116: /* Scan up slow */
04619          sayfile(mychannel,"rpt/up");
04620          sayfile(mychannel, "rpt/slow");
04621          break;
04622           case 117: /* Scan up quick */
04623          sayfile(mychannel,"rpt/up");
04624          sayfile(mychannel, "rpt/quick");
04625          break;
04626           case 118: /* Scan up fast */
04627          sayfile(mychannel,"rpt/up");
04628          sayfile(mychannel, "rpt/fast");
04629          break;
04630           default:
04631          res = -1;
04632       }
04633       wait_interval(myrpt, DLY_COMP, mychannel);
04634       if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04635       break;
04636        case SCAN:
04637       ast_mutex_lock(&myrpt->remlock);
04638       if (myrpt->hfscanstop)
04639       {
04640          myrpt->hfscanstatus = 0;
04641          myrpt->hfscanmode = 0;
04642          myrpt->hfscanstop = 0;
04643          mytele->mode = SCANSTAT;
04644          ast_mutex_unlock(&myrpt->remlock);
04645          if (ast_safe_sleep(mychannel,1000) == -1) break;
04646          sayfile(mychannel, "rpt/stop"); 
04647          imdone = 1;
04648          break;
04649       }
04650       if (myrpt->hfscanstatus > -2) service_scan(myrpt);
04651       i = myrpt->hfscanstatus;
04652       myrpt->hfscanstatus = 0;
04653       if (i) mytele->mode = SCANSTAT;
04654       ast_mutex_unlock(&myrpt->remlock);
04655       if (i < 0) sayfile(mychannel, "rpt/stop"); 
04656       else if (i > 0) saynum(mychannel,i);
04657       imdone = 1;
04658       break;
04659        case TUNE:
04660       ast_mutex_lock(&myrpt->remlock);
04661       if (!strcmp(myrpt->remoterig,remote_rig_ic706))
04662       {
04663          set_mode_ic706(myrpt, REM_MODE_AM);
04664          if(play_tone(mychannel, 800, 6000, 8192) == -1) break;
04665          ast_safe_sleep(mychannel,500);
04666          set_mode_ic706(myrpt, myrpt->remmode);
04667          myrpt->tunerequest = 0;
04668          ast_mutex_unlock(&myrpt->remlock);
04669          imdone = 1;
04670          break;
04671       }
04672       set_mode_ft897(myrpt, REM_MODE_AM);
04673       simple_command_ft897(myrpt, 8);
04674       if(play_tone(mychannel, 800, 6000, 8192) == -1) break;
04675       simple_command_ft897(myrpt, 0x88);
04676       ast_safe_sleep(mychannel,500);
04677       set_mode_ft897(myrpt, myrpt->remmode);
04678       myrpt->tunerequest = 0;
04679       ast_mutex_unlock(&myrpt->remlock);
04680       imdone = 1;
04681       break;
04682        case REMSHORTSTATUS:
04683        case REMLONGSTATUS: 
04684       wait_interval(myrpt, DLY_TELEM, mychannel);
04685       res = saynode(myrpt,mychannel,myrpt->name);
04686       if(!res)
04687          res = sayfile(mychannel,"rpt/frequency");
04688       if(!res)
04689          res = split_freq(mhz, decimals, myrpt->freq);
04690       if (!multimode_capable(myrpt)) decimals[3] = 0;
04691       if(!res){
04692          m = atoi(mhz);
04693          if(m < 100)
04694             res = saynum(mychannel, m);
04695          else
04696             res = saycharstr(mychannel, mhz);
04697       }
04698       if(!res)
04699          res = sayfile(mychannel, "letters/dot");
04700       if(!res)
04701          res = saycharstr(mychannel, decimals);
04702    
04703       if(res)  break;
04704       if(myrpt->remmode == REM_MODE_FM){ /* Mode FM? */
04705          switch(myrpt->offset){
04706    
04707             case REM_MINUS:
04708                res = sayfile(mychannel,"rpt/minus");
04709                break;
04710             
04711             case REM_SIMPLEX:
04712                res = sayfile(mychannel,"rpt/simplex");
04713                break;
04714                
04715             case REM_PLUS:
04716                res = sayfile(mychannel,"rpt/plus");
04717                break;
04718                
04719             default:
04720                break;
04721          }
04722       }
04723       else{ /* Must be USB, LSB, or AM */
04724          switch(myrpt->remmode){
04725 
04726             case REM_MODE_USB:
04727                res = saycharstr(mychannel, "USB");
04728                break;
04729 
04730             case REM_MODE_LSB:
04731                res = saycharstr(mychannel, "LSB");
04732                break;
04733 
04734             case REM_MODE_AM:
04735                res = saycharstr(mychannel, "AM");
04736                break;
04737 
04738 
04739             default:
04740                break;
04741          }
04742       }
04743 
04744       if (res == -1) break;
04745 
04746       if(mytele->mode == REMSHORTSTATUS){ /* Short status? */
04747          wait_interval(myrpt, DLY_COMP, mychannel);
04748          if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04749          break;
04750       }
04751 
04752       if (strcmp(myrpt->remoterig,remote_rig_ic706))
04753       {
04754          switch(myrpt->powerlevel){
04755 
04756             case REM_LOWPWR:
04757                res = sayfile(mychannel,"rpt/lopwr") ;
04758                break;
04759             case REM_MEDPWR:
04760                res = sayfile(mychannel,"rpt/medpwr");
04761                break;
04762             case REM_HIPWR:
04763                res = sayfile(mychannel,"rpt/hipwr"); 
04764                break;
04765             }
04766       }
04767 
04768       rbimode = ((!strncmp(myrpt->remoterig,remote_rig_rbi,3))
04769         || (!strncmp(myrpt->remoterig,remote_rig_ic706,3)));
04770       if (res || (sayfile(mychannel,"rpt/rxpl") == -1)) break;
04771       if (rbimode && (sayfile(mychannel,"rpt/txpl") == -1)) break;
04772       if ((sayfile(mychannel,"rpt/frequency") == -1) ||
04773          (saycharstr(mychannel,myrpt->rxpl) == -1)) break;
04774       if ((!rbimode) && ((sayfile(mychannel,"rpt/txpl") == -1) ||
04775          (sayfile(mychannel,"rpt/frequency") == -1) ||
04776          (saycharstr(mychannel,myrpt->txpl) == -1))) break;
04777       if(myrpt->remmode == REM_MODE_FM){ /* Mode FM? */
04778          if ((sayfile(mychannel,"rpt/rxpl") == -1) ||
04779             (sayfile(mychannel,((myrpt->rxplon) ? "rpt/on" : "rpt/off")) == -1) ||
04780             (sayfile(mychannel,"rpt/txpl") == -1) ||
04781             (sayfile(mychannel,((myrpt->txplon) ? "rpt/on" : "rpt/off")) == -1))
04782             {
04783                break;
04784             }
04785       }
04786       wait_interval(myrpt, DLY_COMP, mychannel);
04787       if (!res) res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
04788       break;
04789        case STATUS:
04790       /* wait a little bit */
04791       wait_interval(myrpt, DLY_TELEM, mychannel);
04792       hastx = 0;
04793       linkbase.next = &linkbase;
04794       linkbase.prev = &linkbase;
04795       rpt_mutex_lock(&myrpt->lock);
04796       /* make our own list of links */
04797       l = myrpt->links.next;
04798       while(l != &myrpt->links)
04799       {
04800          if (l->name[0] == '0')
04801          {
04802             l = l->next;
04803             continue;
04804          }
04805          l1 = ast_malloc(sizeof(struct rpt_link));
04806          if (!l1)
04807          {
04808             ast_log(LOG_WARNING, "Cannot alloc memory on %s\n", mychannel->name);
04809             remque((struct qelem *)mytele);
04810             myrpt->active_telem = NULL;
04811             rpt_mutex_unlock(&myrpt->lock);
04812             ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
04813             ast_free(nodename);
04814             ast_free(ident);
04815             ast_free(mytele);    
04816             ast_hangup(mychannel);
04817             pthread_exit(NULL);
04818          }
04819          memcpy(l1,l,sizeof(struct rpt_link));
04820          l1->next = l1->prev = NULL;
04821          insque((struct qelem *)l1,(struct qelem *)linkbase.next);
04822          l = l->next;
04823       }
04824       rpt_mutex_unlock(&myrpt->lock);
04825       res = saynode(myrpt,mychannel,myrpt->name);
04826       if (myrpt->callmode)
04827       {
04828          hastx = 1;
04829          res = ast_streamfile(mychannel, "rpt/autopatch_on", mychannel->language);
04830          if (!res) 
04831             res = ast_waitstream(mychannel, "");
04832          else
04833              ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04834          ast_stopstream(mychannel);
04835       }
04836       l = linkbase.next;
04837       while(l != &linkbase)
04838       {
04839          char *s;
04840 
04841          hastx = 1;
04842          res = saynode(myrpt,mychannel,l->name);
04843          s = "rpt/tranceive";
04844          if (!l->mode) s = "rpt/monitor";
04845          if (!l->thisconnected) s = "rpt/connecting";
04846          res = ast_streamfile(mychannel, s, mychannel->language);
04847          if (!res) 
04848             res = ast_waitstream(mychannel, "");
04849          else
04850             ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04851          ast_stopstream(mychannel);
04852          l = l->next;
04853       }        
04854       if (!hastx)
04855       {
04856          res = ast_streamfile(mychannel, "rpt/repeat_only", mychannel->language);
04857          if (!res) 
04858             res = ast_waitstream(mychannel, "");
04859          else
04860              ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04861          ast_stopstream(mychannel);
04862       }
04863       /* destroy our local link queue */
04864       l = linkbase.next;
04865       while(l != &linkbase)
04866       {
04867          l1 = l;
04868          l = l->next;
04869          remque((struct qelem *)l1);
04870          ast_free(l1);
04871       }        
04872       imdone = 1;
04873       break;
04874        case FULLSTATUS:
04875       rpt_mutex_lock(&myrpt->lock);
04876       /* get all the nodes */
04877       __mklinklist(myrpt,NULL,lbuf);
04878       rpt_mutex_unlock(&myrpt->lock);
04879       /* parse em */
04880       ns = finddelim(lbuf,strs,MAXLINKLIST);
04881       /* sort em */
04882       if (ns) qsort((void *)strs,ns,sizeof(char *),mycompar);
04883       /* wait a little bit */
04884       wait_interval(myrpt, DLY_TELEM, mychannel);
04885       hastx = 0;
04886       res = saynode(myrpt,mychannel,myrpt->name);
04887       if (myrpt->callmode)
04888       {
04889          hastx = 1;
04890          res = ast_streamfile(mychannel, "rpt/autopatch_on", mychannel->language);
04891          if (!res) 
04892             res = ast_waitstream(mychannel, "");
04893          else
04894              ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04895          ast_stopstream(mychannel);
04896       }
04897       /* go thru all the nodes in list */
04898       for(i = 0; i < ns; i++)
04899       {
04900          char *s,mode = 'T';
04901 
04902          /* if a mode spec at first, handle it */
04903          if ((*strs[i] < '0') || (*strs[i] > '9'))
04904          {
04905             mode = *strs[i];
04906             strs[i]++;
04907          }
04908 
04909          hastx = 1;
04910          res = saynode(myrpt,mychannel,strs[i]);
04911          s = "rpt/tranceive";
04912          if (mode == 'R') s = "rpt/monitor";
04913          if (mode == 'C') s = "rpt/connecting";
04914          res = ast_streamfile(mychannel, s, mychannel->language);
04915          if (!res) 
04916             res = ast_waitstream(mychannel, "");
04917          else
04918             ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04919          ast_stopstream(mychannel);
04920       }        
04921       if (!hastx)
04922       {
04923          res = ast_streamfile(mychannel, "rpt/repeat_only", mychannel->language);
04924          if (!res) 
04925             res = ast_waitstream(mychannel, "");
04926          else
04927              ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04928          ast_stopstream(mychannel);
04929       }
04930       imdone = 1;
04931       break;
04932 
04933        case LASTNODEKEY: /* Identify last node which keyed us up */
04934       rpt_mutex_lock(&myrpt->lock);
04935       if(myrpt->lastnodewhichkeyedusup){
04936          p = ast_strdup(myrpt->lastnodewhichkeyedusup); /* Make a local copy of the node name */
04937          if(!p){
04938             ast_log(LOG_WARNING, "ast_strdup failed in telemetery LASTNODEKEY");
04939             imdone = 1;
04940             break;
04941          }
04942       }
04943       else
04944          p = NULL;
04945       rpt_mutex_unlock(&myrpt->lock);
04946       if(!p){
04947          imdone = 1; /* no node previously keyed us up, or the node which did has been disconnected */
04948          break;
04949       }
04950       wait_interval(myrpt, DLY_TELEM, mychannel);
04951       res = saynode(myrpt,mychannel,p);
04952       ast_free(p);
04953       imdone = 1;
04954       break;      
04955 
04956        case UNAUTHTX: /* Say unauthorized transmit frequency */
04957       wait_interval(myrpt, DLY_TELEM, mychannel);
04958       res = ast_streamfile(mychannel, "rpt/unauthtx", mychannel->language);
04959       if (!res) 
04960          res = ast_waitstream(mychannel, "");
04961       else
04962           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04963       ast_stopstream(mychannel);
04964       imdone = 1;
04965       break;
04966 
04967        case PARROT: /* Repeat stuff */
04968 
04969       sprintf(mystr,PARROTFILE,myrpt->name,(unsigned int)mytele->parrot);
04970       if (ast_fileexists(mystr,NULL,mychannel->language) <= 0)
04971       {
04972          imdone = 1;
04973          myrpt->parrotstate = 0;
04974          break;
04975       }
04976       wait_interval(myrpt, DLY_PARROT, mychannel);
04977       sprintf(mystr,PARROTFILE,myrpt->name,(unsigned int)mytele->parrot);
04978       res = ast_streamfile(mychannel, mystr, mychannel->language);
04979       if (!res) 
04980          res = ast_waitstream(mychannel, "");
04981       else
04982           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
04983       ast_stopstream(mychannel);
04984       sprintf(mystr,PARROTFILE,myrpt->name,(unsigned int)mytele->parrot);
04985       strcat(mystr,".wav");
04986       unlink(mystr);       
04987       imdone = 1;
04988       myrpt->parrotstate = 0;
04989       break;
04990 
04991        case TIMEOUT:
04992       res = saynode(myrpt,mychannel,myrpt->name);
04993       if (!res)
04994          res = ast_streamfile(mychannel, "rpt/timeout", mychannel->language);
04995       break;
04996       
04997        case TIMEOUT_WARNING:
04998       time(&t);
04999       res = saynode(myrpt,mychannel,myrpt->name);
05000       if (!res)
05001          res = ast_streamfile(mychannel, "rpt/timeout-warning", mychannel->language);
05002       if (!res) 
05003          res = ast_waitstream(mychannel, "");
05004       else
05005           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
05006       ast_stopstream(mychannel);
05007       if(!res) /* Say number of seconds */
05008          ast_say_number(mychannel, myrpt->p.remotetimeout - 
05009              (t - myrpt->last_activity_time), 
05010             "", mychannel->language, (char *) NULL);
05011       if (!res) 
05012          res = ast_waitstream(mychannel, "");
05013       ast_stopstream(mychannel); 
05014       res = ast_streamfile(mychannel, "queue-seconds", mychannel->language);
05015       break;
05016 
05017        case ACT_TIMEOUT_WARNING:
05018       time(&t);
05019       res = saynode(myrpt,mychannel,myrpt->name);
05020       if (!res)
05021           res = ast_streamfile(mychannel, "rpt/act-timeout-warning", mychannel->language);
05022       if (!res) 
05023          res = ast_waitstream(mychannel, "");
05024       else
05025           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
05026       ast_stopstream(mychannel);
05027       if(!res) /* Say number of seconds */
05028          ast_say_number(mychannel, myrpt->p.remoteinacttimeout - 
05029              (t - myrpt->last_activity_time), 
05030             "", mychannel->language, (char *) NULL);
05031       if (!res) 
05032          res = ast_waitstream(mychannel, "");
05033       ast_stopstream(mychannel); 
05034       res = ast_streamfile(mychannel, "queue-seconds", mychannel->language);
05035       break;
05036       
05037        case STATS_TIME:
05038             case STATS_TIME_LOCAL:
05039          wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
05040       t = time(NULL);
05041       rpt_localtime(&t, &localtm);
05042       /* Say the phase of the day is before the time */
05043       if((localtm.tm_hour >= 0) && (localtm.tm_hour < 12))
05044          p = "rpt/goodmorning";
05045       else if((localtm.tm_hour >= 12) && (localtm.tm_hour < 18))
05046          p = "rpt/goodafternoon";
05047       else
05048          p = "rpt/goodevening";
05049       if (sayfile(mychannel,p) == -1)
05050       {
05051          imdone = 1;
05052          break;
05053       }
05054       /* Say the time is ... */     
05055       if (sayfile(mychannel,"rpt/thetimeis") == -1)
05056       {
05057          imdone = 1;
05058          break;
05059       }
05060       /* Say the time */            
05061          res = ast_say_time(mychannel, t, "", mychannel->language);
05062       if (!res) 
05063          res = ast_waitstream(mychannel, "");
05064       ast_stopstream(mychannel);    
05065       imdone = 1;
05066          break;
05067        case STATS_VERSION:
05068       p = strstr(tdesc, "version"); 
05069       if(!p)
05070          break;   
05071       if(sscanf(p, "version %30d.%30d", &vmajor, &vminor) != 2)
05072          break;
05073          wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
05074       /* Say "version" */
05075       if (sayfile(mychannel,"rpt/version") == -1)
05076       {
05077          imdone = 1;
05078          break;
05079       }
05080       if(!res) /* Say "X" */
05081          ast_say_number(mychannel, vmajor, "", mychannel->language, (char *) NULL);
05082       if (!res) 
05083          res = ast_waitstream(mychannel, "");
05084       ast_stopstream(mychannel); 
05085       if (saycharstr(mychannel,".") == -1)
05086       {
05087          imdone = 1;
05088          break;
05089       }
05090       if(!res) /* Say "Y" */
05091          ast_say_number(mychannel, vminor, "", mychannel->language, (char *) NULL);
05092       if (!res){
05093          res = ast_waitstream(mychannel, "");
05094          ast_stopstream(mychannel);
05095       }  
05096       else
05097           ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
05098       imdone = 1;
05099          break;
05100        case ARB_ALPHA:
05101          wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
05102          if(mytele->param)
05103             saycharstr(mychannel, mytele->param);
05104          imdone = 1;
05105       break;
05106        case REV_PATCH:
05107          wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
05108          if(mytele->param) {
05109 
05110          /* Parts of this section taken from app_parkandannounce */
05111          char *tpl_working, *tpl_current;
05112          char *tmp[100], *myparm;
05113          int looptemp=0,idx=0, dres = 0;
05114    
05115 
05116          tpl_working = ast_strdup(mytele->param);
05117          myparm = strsep(&tpl_working,",");
05118          tpl_current=strsep(&tpl_working, ":");
05119 
05120          while(tpl_current && looptemp < sizeof(tmp)) {
05121             tmp[looptemp]=tpl_current;
05122             looptemp++;
05123             tpl_current=strsep(&tpl_working,":");
05124          }
05125 
05126          for(idx=0; idx<looptemp; idx++) {
05127             if(!strcmp(tmp[idx], "PARKED")) {
05128                ast_say_digits(mychannel, atoi(myparm), "", mychannel->language);
05129             } else if(!strcmp(tmp[idx], "NODE")) {
05130                ast_say_digits(mychannel, atoi(myrpt->name), "", mychannel->language);
05131             } else {
05132                dres = ast_streamfile(mychannel, tmp[idx], mychannel->language);
05133                if(!dres) {
05134                   dres = ast_waitstream(mychannel, "");
05135                } else {
05136                   ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", tmp[idx], mychannel->name);
05137                   dres = 0;
05138                }
05139             }
05140          }
05141          ast_free(tpl_working);
05142       }
05143          imdone = 1;
05144       break;
05145        case TEST_TONE:
05146       imdone = 1;
05147       if (myrpt->stopgen) break;
05148       myrpt->stopgen = -1;
05149            if ((res = ast_tonepair_start(mychannel, 1004.0, 0, 99999999, 7200.0))) 
05150       {
05151          myrpt->stopgen = 0;
05152          break;
05153       }
05154            while(mychannel->generatordata && (myrpt->stopgen <= 0)) {
05155          if (ast_safe_sleep(mychannel,1)) break;
05156             imdone = 1;
05157          }
05158       myrpt->stopgen = 0;
05159       break;
05160        default:
05161          break;
05162    }
05163    if (!imdone)
05164    {
05165       if (!res) 
05166          res = ast_waitstream(mychannel, "");
05167       else {
05168          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
05169          res = 0;
05170       }
05171    }
05172    ast_stopstream(mychannel);
05173    rpt_mutex_lock(&myrpt->lock);
05174    if (mytele->mode == TAILMSG)
05175    {
05176       if (!res)
05177       {
05178          myrpt->tailmessagen++;
05179          if(myrpt->tailmessagen >= myrpt->p.tailmessagemax) myrpt->tailmessagen = 0;
05180       }
05181       else
05182       {
05183          myrpt->tmsgtimer = myrpt->p.tailsquashedtime;
05184       }
05185    }
05186    remque((struct qelem *)mytele);
05187    myrpt->active_telem = NULL;
05188    rpt_mutex_unlock(&myrpt->lock);
05189    ast_free(nodename);
05190    ast_free(ident);
05191    ast_free(mytele);    
05192    ast_hangup(mychannel);
05193 #ifdef  APP_RPT_LOCK_DEBUG
05194    {
05195       struct lockthread *t;
05196 
05197       sleep(5);
05198       ast_mutex_lock(&locklock);
05199       t = get_lockthread(pthread_self());
05200       if (t) memset(t,0,sizeof(struct lockthread));
05201       ast_mutex_unlock(&locklock);
05202    }        
05203 #endif
05204    pthread_exit(NULL);
05205 }
05206 
05207 static void rpt_telemetry(struct rpt *myrpt,int mode, void *data)
05208 {
05209 struct rpt_tele *tele;
05210 struct rpt_link *mylink = NULL;
05211 int res;
05212 pthread_attr_t attr;
05213 char *v1, *v2;
05214 
05215    if(debug > 6)
05216       ast_log(LOG_NOTICE,"mode=%i  data=%s\n",mode, (char *)data);
05217 
05218    switch(mode)
05219    {
05220        case UNKEY:
05221       /* if any of the following are defined, go ahead and do it,
05222          otherwise, don't bother */
05223       v1 = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, 
05224          "unlinkedct");
05225       v2 = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, 
05226          "remotect");
05227       if (telem_lookup(myrpt,NULL, myrpt->name, "remotemon") &&
05228         telem_lookup(myrpt,NULL, myrpt->name, "remotetx") &&
05229         telem_lookup(myrpt,NULL, myrpt->name, "cmdmode") &&
05230         (!(v1 && telem_lookup(myrpt,NULL, myrpt->name, v1))) && 
05231         (!(v2 && telem_lookup(myrpt,NULL, myrpt->name, v2)))) return;
05232       break;
05233        case LINKUNKEY:
05234       if (!ast_variable_retrieve(myrpt->cfg, myrpt->name, "linkunkeyct"))
05235          return;
05236       break;
05237        default:
05238       break;
05239    }
05240    tele = ast_malloc(sizeof(struct rpt_tele));
05241    if (!tele)
05242    {
05243       ast_log(LOG_WARNING, "Unable to allocate memory\n");
05244       pthread_exit(NULL);
05245       return;
05246    }
05247    /* zero it out */
05248    memset((char *)tele,0,sizeof(struct rpt_tele));
05249    tele->rpt = myrpt;
05250    tele->mode = mode;
05251    if (mode == PARROT) tele->parrot = (uintptr_t) data;
05252    else mylink = (struct rpt_link *) data;
05253    rpt_mutex_lock(&myrpt->lock);
05254    if((mode == CONNFAIL) || (mode == REMDISC) || (mode == CONNECTED) ||
05255        (mode == LINKUNKEY)){
05256       memset(&tele->mylink,0,sizeof(struct rpt_link));
05257       if (mylink){
05258          memcpy(&tele->mylink,mylink,sizeof(struct rpt_link));
05259       }
05260    }
05261    else if ((mode == ARB_ALPHA) || (mode == REV_PATCH) || (mode == PLAYBACK)) {
05262       strncpy(tele->param, (char *) data, TELEPARAMSIZE - 1);
05263       tele->param[TELEPARAMSIZE - 1] = 0;
05264    }
05265    if (mode == REMXXX) tele->submode = (intptr_t) data;
05266    insque((struct qelem *)tele, (struct qelem *)myrpt->tele.next);
05267    rpt_mutex_unlock(&myrpt->lock);
05268         pthread_attr_init(&attr);
05269         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
05270    res = ast_pthread_create(&tele->threadid,&attr,rpt_tele_thread,(void *) tele);
05271    if(res < 0){
05272       rpt_mutex_lock(&myrpt->lock);
05273       remque((struct qlem *) tele); /* We don't like stuck transmitters, remove it from the queue */
05274       rpt_mutex_unlock(&myrpt->lock);  
05275       ast_log(LOG_WARNING, "Could not create telemetry thread: %s",strerror(res));
05276    }
05277    return;
05278 }
05279 
05280 static void *rpt_call(void *this)
05281 {
05282 struct dahdi_confinfo ci;  /* conference info */
05283 struct   rpt *myrpt = (struct rpt *)this;
05284 int   res;
05285 int stopped,congstarted,dialtimer,lastcidx,aborted;
05286 struct ast_channel *mychannel,*genchannel;
05287 
05288    myrpt->mydtmf = 0;
05289    /* allocate a pseudo-channel thru asterisk */
05290    mychannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
05291    if (!mychannel)
05292    {
05293       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
05294       pthread_exit(NULL);
05295    }
05296 #ifdef   AST_CDR_FLAG_POST_DISABLED
05297    if (mychannel->cdr)
05298       ast_set_flag(mychannel->cdr,AST_CDR_FLAG_POST_DISABLED);
05299 #endif
05300    ci.chan = 0;
05301    ci.confno = myrpt->conf; /* use the pseudo conference */
05302 #if   0
05303    ci.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER
05304       | DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER; 
05305 #endif
05306    ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
05307    /* first put the channel on the conference */
05308    if (ioctl(mychannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05309    {
05310       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05311       ast_hangup(mychannel);
05312       myrpt->callmode = 0;
05313       pthread_exit(NULL);
05314    }
05315    /* allocate a pseudo-channel thru asterisk */
05316    genchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
05317    if (!genchannel)
05318    {
05319       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
05320       ast_hangup(mychannel);
05321       pthread_exit(NULL);
05322    }
05323 #ifdef   AST_CDR_FLAG_POST_DISABLED
05324    if (genchannel->cdr)
05325       ast_set_flag(genchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
05326 #endif
05327    ci.chan = 0;
05328    ci.confno = myrpt->conf;
05329    ci.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER
05330       | DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER; 
05331    /* first put the channel on the conference */
05332    if (ioctl(genchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05333    {
05334       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05335       ast_hangup(mychannel);
05336       ast_hangup(genchannel);
05337       myrpt->callmode = 0;
05338       pthread_exit(NULL);
05339    }
05340    if (myrpt->p.tonezone && (tone_zone_set_zone(mychannel->fds[0],myrpt->p.tonezone) == -1))
05341    {
05342       ast_log(LOG_WARNING, "Unable to set tone zone %s\n",myrpt->p.tonezone);
05343       ast_hangup(mychannel);
05344       ast_hangup(genchannel);
05345       myrpt->callmode = 0;
05346       pthread_exit(NULL);
05347    }
05348    if (myrpt->p.tonezone && (tone_zone_set_zone(genchannel->fds[0],myrpt->p.tonezone) == -1))
05349    {
05350       ast_log(LOG_WARNING, "Unable to set tone zone %s\n",myrpt->p.tonezone);
05351       ast_hangup(mychannel);
05352       ast_hangup(genchannel);
05353       myrpt->callmode = 0;
05354       pthread_exit(NULL);
05355    }
05356    /* start dialtone if patchquiet is 0. Special patch modes don't send dial tone */
05357    if ((!myrpt->patchquiet) && (tone_zone_play_tone(genchannel->fds[0],DAHDI_TONE_DIALTONE) < 0))
05358    {
05359       ast_log(LOG_WARNING, "Cannot start dialtone\n");
05360       ast_hangup(mychannel);
05361       ast_hangup(genchannel);
05362       myrpt->callmode = 0;
05363       pthread_exit(NULL);
05364    }
05365    stopped = 0;
05366    congstarted = 0;
05367    dialtimer = 0;
05368    lastcidx = 0;
05369    myrpt->calldigittimer = 0;
05370    aborted = 0;
05371 
05372    while ((myrpt->callmode == 1) || (myrpt->callmode == 4))
05373    {
05374       if((myrpt->patchdialtime)&&(myrpt->callmode == 1)&&(myrpt->cidx != lastcidx)){
05375          dialtimer = 0;
05376          lastcidx = myrpt->cidx;
05377       }     
05378 
05379       if((myrpt->patchdialtime)&&(dialtimer >= myrpt->patchdialtime)){ 
05380           if(debug)
05381             ast_log(LOG_NOTICE, "dialtimer %i > patchdialtime %i\n", dialtimer,myrpt->patchdialtime);
05382          rpt_mutex_lock(&myrpt->lock);
05383          aborted = 1;
05384          myrpt->callmode = 0;
05385          rpt_mutex_unlock(&myrpt->lock);
05386          break;
05387       }
05388    
05389       if ((!myrpt->patchquiet) && (!stopped) && (myrpt->callmode == 1) && (myrpt->cidx > 0))
05390       {
05391          stopped = 1;
05392          /* stop dial tone */
05393          tone_zone_play_tone(genchannel->fds[0],-1);
05394       }
05395       if (myrpt->callmode == 1)
05396       {
05397          if(myrpt->calldigittimer > PATCH_DIALPLAN_TIMEOUT)
05398          {
05399             myrpt->callmode = 2;
05400             break;
05401          }
05402          /* bump timer if active */
05403          if (myrpt->calldigittimer) 
05404             myrpt->calldigittimer += MSWAIT;
05405       }
05406       if (myrpt->callmode == 4)
05407       {
05408          if(!congstarted){
05409             congstarted = 1;
05410             /* start congestion tone */
05411             tone_zone_play_tone(genchannel->fds[0],DAHDI_TONE_CONGESTION);
05412          }
05413       }
05414       res = ast_safe_sleep(mychannel, MSWAIT);
05415       if (res < 0)
05416       {
05417           if(debug)
05418             ast_log(LOG_NOTICE, "ast_safe_sleep=%i\n", res);
05419          ast_hangup(mychannel);
05420          ast_hangup(genchannel);
05421          rpt_mutex_lock(&myrpt->lock);
05422          myrpt->callmode = 0;
05423          rpt_mutex_unlock(&myrpt->lock);
05424          pthread_exit(NULL);
05425       }
05426       dialtimer += MSWAIT;
05427    }
05428    /* stop any tone generation */
05429    tone_zone_play_tone(genchannel->fds[0],-1);
05430    /* end if done */
05431    if (!myrpt->callmode)
05432    {
05433       if(debug)
05434          ast_log(LOG_NOTICE, "callmode==0\n");
05435       ast_hangup(mychannel);
05436       ast_hangup(genchannel);
05437       rpt_mutex_lock(&myrpt->lock);
05438       myrpt->callmode = 0;
05439       myrpt->macropatch=0;
05440       channel_revert(myrpt);
05441       rpt_mutex_unlock(&myrpt->lock);
05442       if((!myrpt->patchquiet) && aborted)
05443          rpt_telemetry(myrpt, TERM, NULL);
05444       pthread_exit(NULL);        
05445    }
05446 
05447    if (myrpt->p.ourcallerid && *myrpt->p.ourcallerid){
05448       char *name, *loc, *instr;
05449       instr = ast_strdup(myrpt->p.ourcallerid);
05450       if(instr){
05451          ast_callerid_parse(instr, &name, &loc);
05452          if(loc){
05453             mychannel->caller.id.number.valid = 1;
05454             ast_free(mychannel->caller.id.number.str);
05455             mychannel->caller.id.number.str = ast_strdup(loc);
05456          }
05457          if(name){
05458             mychannel->caller.id.name.valid = 1;
05459             ast_free(mychannel->caller.id.name.str);
05460             mychannel->caller.id.name.str = ast_strdup(name);
05461          }
05462          ast_free(instr);
05463       }
05464    }
05465 
05466    ast_copy_string(mychannel->exten, myrpt->exten, sizeof(mychannel->exten) - 1);
05467    ast_copy_string(mychannel->context, myrpt->patchcontext, sizeof(mychannel->context) - 1);
05468    
05469    if (myrpt->p.acctcode)
05470       ast_cdr_setaccount(mychannel,myrpt->p.acctcode);
05471    mychannel->priority = 1;
05472    ast_channel_undefer_dtmf(mychannel);
05473    if (ast_pbx_start(mychannel) < 0)
05474    {
05475       ast_log(LOG_WARNING, "Unable to start PBX!!\n");
05476       ast_hangup(mychannel);
05477       ast_hangup(genchannel);
05478       rpt_mutex_lock(&myrpt->lock);
05479       myrpt->callmode = 0;
05480       rpt_mutex_unlock(&myrpt->lock);
05481       pthread_exit(NULL);
05482    }
05483    usleep(10000);
05484    rpt_mutex_lock(&myrpt->lock);
05485    myrpt->callmode = 3;
05486    /* set appropriate conference for the pseudo */
05487    ci.chan = 0;
05488    ci.confno = myrpt->conf;
05489    ci.confmode = (myrpt->p.duplex == 2) ? DAHDI_CONF_CONFANNMON :
05490       (DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER);
05491    /* first put the channel on the conference in announce mode */
05492    if (ioctl(myrpt->pchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05493    {
05494       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05495       ast_hangup(mychannel);
05496       ast_hangup(genchannel);
05497       myrpt->callmode = 0;
05498       pthread_exit(NULL);
05499    }
05500    /* get its channel number */
05501    if (ioctl(mychannel->fds[0],DAHDI_CHANNO,&res) == -1)
05502    {
05503       ast_log(LOG_WARNING, "Unable to get autopatch channel number\n");
05504       ast_hangup(mychannel);
05505       myrpt->callmode = 0;
05506       pthread_exit(NULL);
05507    }
05508    ci.chan = 0;
05509    ci.confno = res;
05510    ci.confmode = DAHDI_CONF_MONITOR;
05511    /* put vox channel monitoring on the channel  */
05512    if (ioctl(myrpt->voxchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05513    {
05514       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05515       ast_hangup(mychannel);
05516       myrpt->callmode = 0;
05517       pthread_exit(NULL);
05518    }
05519    while(myrpt->callmode)
05520    {
05521       if ((!mychannel->pbx) && (myrpt->callmode != 4))
05522       {
05523           /* If patch is setup for far end disconnect */
05524          if(myrpt->patchfarenddisconnect || (myrpt->p.duplex < 2)){ 
05525             if(debug)ast_log(LOG_NOTICE,"callmode=%i, patchfarenddisconnect=%i, duplex=%i\n",\
05526                   myrpt->callmode,myrpt->patchfarenddisconnect,myrpt->p.duplex);
05527             myrpt->callmode = 0;
05528             myrpt->macropatch=0;
05529             if(!myrpt->patchquiet){
05530                rpt_mutex_unlock(&myrpt->lock);
05531                rpt_telemetry(myrpt, TERM, NULL);
05532                rpt_mutex_lock(&myrpt->lock);
05533             }
05534          }
05535          else{ /* Send congestion until patch is downed by command */
05536             myrpt->callmode = 4;
05537             rpt_mutex_unlock(&myrpt->lock);
05538             /* start congestion tone */
05539             tone_zone_play_tone(genchannel->fds[0],DAHDI_TONE_CONGESTION);
05540             rpt_mutex_lock(&myrpt->lock);
05541          }
05542       }
05543       if (myrpt->mydtmf)
05544       {
05545          struct ast_frame wf = {AST_FRAME_DTMF, } ;
05546          wf.subclass.integer = myrpt->mydtmf;
05547          rpt_mutex_unlock(&myrpt->lock);
05548          ast_queue_frame(mychannel,&wf);
05549 #ifdef   NEW_ASTERISK
05550          ast_senddigit(genchannel,myrpt->mydtmf,0);
05551 #else
05552          ast_senddigit(genchannel,myrpt->mydtmf);
05553 #endif
05554          rpt_mutex_lock(&myrpt->lock);
05555          myrpt->mydtmf = 0;
05556       }
05557       rpt_mutex_unlock(&myrpt->lock);
05558       usleep(MSWAIT * 1000);
05559       rpt_mutex_lock(&myrpt->lock);
05560    }
05561    if(debug)
05562       ast_log(LOG_NOTICE, "exit channel loop\n");
05563    rpt_mutex_unlock(&myrpt->lock);
05564    tone_zone_play_tone(genchannel->fds[0],-1);
05565    if (mychannel->pbx) ast_softhangup(mychannel,AST_SOFTHANGUP_DEV);
05566    ast_hangup(genchannel);
05567    rpt_mutex_lock(&myrpt->lock);
05568    myrpt->callmode = 0;
05569    myrpt->macropatch=0;
05570    channel_revert(myrpt);
05571    rpt_mutex_unlock(&myrpt->lock);
05572    /* set appropriate conference for the pseudo */
05573    ci.chan = 0;
05574    ci.confno = myrpt->conf;
05575    ci.confmode = ((myrpt->p.duplex == 2) || (myrpt->p.duplex == 4)) ? DAHDI_CONF_CONFANNMON :
05576       (DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER);
05577    /* first put the channel on the conference in announce mode */
05578    if (ioctl(myrpt->pchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
05579    {
05580       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05581    }
05582    pthread_exit(NULL);
05583 }
05584 
05585 static void send_link_dtmf(struct rpt *myrpt,char c)
05586 {
05587 char  str[300];
05588 struct   ast_frame wf;
05589 struct   rpt_link *l;
05590 
05591    snprintf(str, sizeof(str), "D %s %s %d %c", myrpt->cmdnode, myrpt->name, ++(myrpt->dtmfidx), c);
05592    wf.frametype = AST_FRAME_TEXT;
05593    wf.subclass.integer = 0;
05594    wf.offset = 0;
05595    wf.mallocd = 0;
05596    wf.datalen = strlen(str) + 1;
05597    wf.samples = 0;
05598    l = myrpt->links.next;
05599    /* first, see if our dude is there */
05600    while(l != &myrpt->links)
05601    {
05602       if (l->name[0] == '0') 
05603       {
05604          l = l->next;
05605          continue;
05606       }
05607       /* if we found it, write it and were done */
05608       if (!strcmp(l->name,myrpt->cmdnode))
05609       {
05610          wf.data.ptr = str;
05611          if (l->chan) ast_write(l->chan,&wf);
05612          return;
05613       }
05614       l = l->next;
05615    }
05616    l = myrpt->links.next;
05617    /* if not, give it to everyone */
05618    while(l != &myrpt->links)
05619    {
05620       wf.data.ptr = str;
05621       if (l->chan) ast_write(l->chan,&wf);
05622       l = l->next;
05623    }
05624    return;
05625 }
05626 
05627 static void send_link_keyquery(struct rpt *myrpt)
05628 {
05629 char  str[300];
05630 struct   ast_frame wf;
05631 struct   rpt_link *l;
05632 
05633    rpt_mutex_lock(&myrpt->lock);
05634    memset(myrpt->topkey,0,sizeof(myrpt->topkey));
05635    myrpt->topkeystate = 1;
05636    time(&myrpt->topkeytime);
05637    rpt_mutex_unlock(&myrpt->lock);
05638    snprintf(str, sizeof(str), "K? * %s 0 0", myrpt->name);
05639    wf.frametype = AST_FRAME_TEXT;
05640    wf.subclass.integer = 0;
05641    wf.offset = 0;
05642    wf.mallocd = 0;
05643    wf.datalen = strlen(str) + 1;
05644    wf.samples = 0;
05645    l = myrpt->links.next;
05646    /* give it to everyone */
05647    while(l != &myrpt->links)
05648    {
05649       wf.data.ptr = str;
05650       if (l->chan) ast_write(l->chan,&wf);
05651       l = l->next;
05652    }
05653    return;
05654 }
05655 
05656 /* send newkey request */
05657 
05658 static void send_newkey(struct ast_channel *chan)
05659 {
05660 
05661    /* ast_safe_sleep(chan,10); */
05662    ast_sendtext(chan,newkeystr);
05663    return;
05664 }
05665 
05666 
05667 /* 
05668  * Connect a link 
05669  *
05670  * Return values:
05671  * -2: Attempt to connect to self 
05672  * -1: No such node
05673  *  0: Success
05674  *  1: No match yet
05675  *  2: Already connected to this node
05676  */
05677 
05678 static int connect_link(struct rpt *myrpt, char* node, int mode, int perma)
05679 {
05680    char *val, *s, *s1, *tele;
05681    char lstr[MAXLINKLIST],*strs[MAXLINKLIST];
05682    char tmp[300], deststr[300] = "",modechange = 0;
05683    char sx[320],*sy;
05684    struct rpt_link *l;
05685    int reconnects = 0;
05686    int i,n;
05687    struct dahdi_confinfo ci;  /* conference info */
05688 
05689    val = node_lookup(myrpt,node);
05690    if (!val){
05691       if(strlen(node) >= myrpt->longestnode)
05692          return -1; /* No such node */
05693       return 1; /* No match yet */
05694    }
05695 
05696    if(!strcmp(myrpt->name,node)) /* Do not allow connections to self */
05697       return -2;
05698       
05699    if(debug > 3){
05700       ast_log(LOG_NOTICE,"Connect attempt to node %s\n", node);
05701       ast_log(LOG_NOTICE,"Mode: %s\n",(mode)?"Transceive":"Monitor");
05702       ast_log(LOG_NOTICE,"Connection type: %s\n",(perma)?"Permalink":"Normal");
05703    }
05704 
05705    strncpy(tmp,val,sizeof(tmp) - 1);
05706    s = tmp;
05707    s1 = strsep(&s,",");
05708    if (!strchr(s1,':') && strchr(s1,'/') && strncasecmp(s1, "local/", 6))
05709    {
05710       sy = strchr(s1,'/');    
05711       *sy = 0;
05712       sprintf(sx,"%s:4569/%s",s1,sy + 1);
05713       s1 = sx;
05714    }
05715    strsep(&s,",");
05716    rpt_mutex_lock(&myrpt->lock);
05717    l = myrpt->links.next;
05718    /* try to find this one in queue */
05719    while(l != &myrpt->links){
05720       if (l->name[0] == '0') 
05721       {
05722          l = l->next;
05723          continue;
05724       }
05725    /* if found matching string */
05726       if (!strcmp(l->name, node))
05727          break;
05728       l = l->next;
05729    }
05730    /* if found */
05731    if (l != &myrpt->links){ 
05732    /* if already in this mode, just ignore */
05733       if ((l->mode) || (!l->chan)) {
05734          rpt_mutex_unlock(&myrpt->lock);
05735          return 2; /* Already linked */
05736       }
05737       reconnects = l->reconnects;
05738       rpt_mutex_unlock(&myrpt->lock);
05739       if (l->chan) ast_softhangup(l->chan, AST_SOFTHANGUP_DEV);
05740       l->retries = l->max_retries + 1;
05741       l->disced = 2;
05742       modechange = 1;
05743    } else
05744    {
05745       __mklinklist(myrpt,NULL,lstr);
05746       rpt_mutex_unlock(&myrpt->lock);
05747       n = finddelim(lstr,strs,MAXLINKLIST);
05748       for(i = 0; i < n; i++)
05749       {
05750          if ((*strs[i] < '0') || 
05751              (*strs[i] > '9')) strs[i]++;
05752          if (!strcmp(strs[i],node))
05753          {
05754             return 2; /* Already linked */
05755          }
05756       }
05757    }
05758    strncpy(myrpt->lastlinknode,node,MAXNODESTR - 1);
05759    /* establish call */
05760    l = ast_malloc(sizeof(struct rpt_link));
05761    if (!l)
05762    {
05763       ast_log(LOG_WARNING, "Unable to malloc\n");
05764       return -1;
05765    }
05766    /* zero the silly thing */
05767    memset((char *)l,0,sizeof(struct rpt_link));
05768    l->mode = mode;
05769    l->outbound = 1;
05770    l->thisconnected = 0;
05771    voxinit_link(l,1);
05772    strncpy(l->name, node, MAXNODESTR - 1);
05773    l->isremote = (s && ast_true(s));
05774    if (modechange) l->connected = 1;
05775    l->hasconnected = l->perma = perma;
05776 #ifdef ALLOW_LOCAL_CHANNELS
05777    if ((strncasecmp(s1,"iax2/", 5) == 0) || (strncasecmp(s1, "local/", 6) == 0))
05778          strncpy(deststr, s1, sizeof(deststr));
05779    else
05780            snprintf(deststr, sizeof(deststr), "IAX2/%s", s1);
05781 #else
05782    snprintf(deststr, sizeof(deststr), "IAX2/%s", s1);
05783 #endif
05784    tele = strchr(deststr, '/');
05785    if (!tele){
05786       ast_log(LOG_WARNING,"link3:Dial number (%s) must be in format tech/number\n",deststr);
05787       ast_free(l);
05788       return -1;
05789    }
05790    *tele++ = 0;
05791    l->chan = ast_request(deststr, AST_FORMAT_SLINEAR, NULL, tele, NULL);
05792    if (l->chan){
05793       ast_set_read_format(l->chan, AST_FORMAT_SLINEAR);
05794       ast_set_write_format(l->chan, AST_FORMAT_SLINEAR);
05795 #ifdef   AST_CDR_FLAG_POST_DISABLED
05796       if (l->chan->cdr)
05797          ast_set_flag(l->chan->cdr,AST_CDR_FLAG_POST_DISABLED);
05798 #endif
05799 #ifndef  NEW_ASTERISK
05800       l->chan->whentohangup = 0;
05801 #endif
05802       l->chan->appl = "Apprpt";
05803       l->chan->data = "(Remote Rx)";
05804       if (debug > 3)
05805          ast_log(LOG_NOTICE, "rpt (remote) initiating call to %s/%s on %s\n",
05806       deststr, tele, l->chan->name);
05807       l->chan->caller.id.number.valid = 1;
05808       ast_free(l->chan->caller.id.number.str);
05809       l->chan->caller.id.number.str = ast_strdup(myrpt->name);
05810       ast_call(l->chan,tele,999);
05811    }
05812    else {
05813       if(debug > 3) 
05814          ast_log(LOG_NOTICE, "Unable to place call to %s/%s on %s\n",
05815       deststr,tele,l->chan->name);
05816       if (myrpt->p.archivedir)
05817       {
05818          char str[100];
05819          sprintf(str,"LINKFAIL,%s",l->name);
05820          donodelog(myrpt,str);
05821       }
05822       ast_free(l);
05823       return -1;
05824    }
05825    /* allocate a pseudo-channel thru asterisk */
05826    l->pchan = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
05827    if (!l->pchan){
05828       ast_log(LOG_WARNING,"rpt connect: Sorry unable to obtain pseudo channel\n");
05829       ast_hangup(l->chan);
05830       ast_free(l);
05831       return -1;
05832    }
05833    ast_set_read_format(l->pchan, AST_FORMAT_SLINEAR);
05834    ast_set_write_format(l->pchan, AST_FORMAT_SLINEAR);
05835 #ifdef   AST_CDR_FLAG_POST_DISABLED
05836    if (l->pchan->cdr)
05837       ast_set_flag(l->pchan->cdr,AST_CDR_FLAG_POST_DISABLED);
05838 #endif
05839    /* make a conference for the tx */
05840    ci.chan = 0;
05841    ci.confno = myrpt->conf;
05842    ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER;
05843    /* first put the channel on the conference in proper mode */
05844    if (ioctl(l->pchan->fds[0], DAHDI_SETCONF, &ci) == -1)
05845    {
05846       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
05847       ast_hangup(l->chan);
05848       ast_hangup(l->pchan);
05849       ast_free(l);
05850       return -1;
05851    }
05852    rpt_mutex_lock(&myrpt->lock);
05853    l->reconnects = reconnects;
05854    /* insert at end of queue */
05855    l->max_retries = MAX_RETRIES;
05856    if (perma)
05857       l->max_retries = MAX_RETRIES_PERM;
05858    if (l->isremote) l->retries = l->max_retries + 1;
05859    insque((struct qelem *)l,(struct qelem *)myrpt->links.next);
05860    __kickshort(myrpt);
05861    rpt_mutex_unlock(&myrpt->lock);
05862    if (!l->phonemode) send_newkey(l->chan);
05863    return 0;
05864 }
05865 
05866 
05867 
05868 /*
05869 * Internet linking function 
05870 */
05871 
05872 static int function_ilink(struct rpt *myrpt, char *param, char *digits, int command_source, struct rpt_link *mylink)
05873 {
05874 
05875    char *val, *s, *s1;
05876    char tmp[300];
05877    char digitbuf[MAXNODESTR],*strs[MAXLINKLIST];
05878    char mode,perma;
05879    char sx[320],*sy;
05880    struct rpt_link *l;
05881    int i,r;
05882 
05883    if(!param)
05884       return DC_ERROR;
05885       
05886          
05887    if (myrpt->p.s[myrpt->p.sysstate_cur].txdisable || myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable )
05888       return DC_ERROR;
05889 
05890    strncpy(digitbuf,digits,MAXNODESTR - 1);
05891 
05892    if(debug > 6)
05893       printf("@@@@ ilink param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
05894       
05895    switch(myatoi(param)){
05896       case 11: /* Perm Link off */
05897       case 1: /* Link off */
05898          if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
05899             strcpy(digitbuf,myrpt->lastlinknode);
05900          val = node_lookup(myrpt,digitbuf);
05901          if (!val){
05902             if(strlen(digitbuf) >= myrpt->longestnode)
05903                return DC_ERROR;
05904             break;
05905          }
05906          strncpy(tmp,val,sizeof(tmp) - 1);
05907          s = tmp;
05908          s1 = strsep(&s,",");
05909          if (!strchr(s1,':') && strchr(s1,'/') && strncasecmp(s1, "local/", 6))
05910          {
05911             sy = strchr(s1,'/');    
05912             *sy = 0;
05913             sprintf(sx,"%s:4569/%s",s1,sy + 1);
05914             s1 = sx;
05915          }
05916          strsep(&s,",");
05917          rpt_mutex_lock(&myrpt->lock);
05918          l = myrpt->links.next;
05919          /* try to find this one in queue */
05920          while(l != &myrpt->links){
05921             if (l->name[0] == '0') 
05922             {
05923                l = l->next;
05924                continue;
05925             }
05926             /* if found matching string */
05927             if (!strcmp(l->name, digitbuf))
05928                break;
05929             l = l->next;
05930          }
05931          if (l != &myrpt->links){ /* if found */
05932             struct   ast_frame wf;
05933 
05934             /* must use perm command on perm link */
05935             if ((myatoi(param) < 10) && 
05936                 (l->max_retries > MAX_RETRIES))
05937             {
05938                rpt_mutex_unlock(&myrpt->lock);
05939                return DC_COMPLETE;
05940             }
05941             strncpy(myrpt->lastlinknode,digitbuf,MAXNODESTR - 1);
05942             l->retries = l->max_retries + 1;
05943             l->disced = 1;
05944             rpt_mutex_unlock(&myrpt->lock);
05945             wf.frametype = AST_FRAME_TEXT;
05946             wf.subclass.integer = 0;
05947             wf.offset = 0;
05948             wf.mallocd = 0;
05949             wf.datalen = strlen(discstr) + 1;
05950             wf.samples = 0;
05951             wf.data.ptr = discstr;
05952             if (l->chan)
05953             {
05954                ast_write(l->chan,&wf);
05955                if (ast_safe_sleep(l->chan,250) == -1) return DC_ERROR;
05956                ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
05957             }
05958             rpt_telemetry(myrpt, COMPLETE, NULL);
05959             return DC_COMPLETE;
05960          }
05961          rpt_mutex_unlock(&myrpt->lock);  
05962          return DC_COMPLETE;
05963       case 2: /* Link Monitor */
05964       case 3: /* Link transceive */
05965       case 12: /* Link Monitor permanent */
05966       case 13: /* Link transceive permanent */
05967          if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
05968             strcpy(digitbuf,myrpt->lastlinknode);
05969          /* Attempt connection  */
05970          perma = (atoi(param) > 10) ? 1 : 0;
05971          mode = (atoi(param) & 1) ? 1 : 0;
05972          r = connect_link(myrpt, digitbuf, mode, perma);
05973          switch(r){
05974             case -2: /* Attempt to connect to self */
05975                return DC_COMPLETE; /* Silent error */
05976 
05977             case 0:
05978                rpt_telemetry(myrpt, COMPLETE, NULL);
05979                return DC_COMPLETE;
05980 
05981             case 1:
05982                break;
05983             
05984             case 2:
05985                rpt_telemetry(myrpt, REMALREADY, NULL);
05986                return DC_COMPLETE;
05987             
05988             default:
05989                rpt_telemetry(myrpt, CONNFAIL, NULL);
05990                return DC_COMPLETE;
05991          }
05992          break;
05993 
05994       case 4: /* Enter Command Mode */
05995       
05996          /* if doesnt allow link cmd, or no links active, return */
05997          if (((command_source != SOURCE_RPT) && 
05998             (command_source != SOURCE_PHONE) &&
05999             (command_source != SOURCE_ALT) &&
06000             (command_source != SOURCE_DPHONE)) ||
06001              (myrpt->links.next == &myrpt->links))
06002             return DC_COMPLETE;
06003          
06004          /* if already in cmd mode, or selected self, fughetabahtit */
06005          if ((myrpt->cmdnode[0]) || (!strcmp(myrpt->name, digitbuf))){
06006          
06007             rpt_telemetry(myrpt, REMALREADY, NULL);
06008             return DC_COMPLETE;
06009          }
06010          if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
06011             strcpy(digitbuf,myrpt->lastlinknode);
06012          /* node must at least exist in list */
06013          val = node_lookup(myrpt,digitbuf);
06014          if (!val){
06015             if(strlen(digitbuf) >= myrpt->longestnode)
06016                return DC_ERROR;
06017             break;
06018          
06019          }
06020          rpt_mutex_lock(&myrpt->lock);
06021          strcpy(myrpt->lastlinknode,digitbuf);
06022          strncpy(myrpt->cmdnode, digitbuf, sizeof(myrpt->cmdnode) - 1);
06023          rpt_mutex_unlock(&myrpt->lock);
06024          rpt_telemetry(myrpt, REMGO, NULL);  
06025          return DC_COMPLETE;
06026          
06027       case 5: /* Status */
06028          rpt_telemetry(myrpt, STATUS, NULL);
06029          return DC_COMPLETE;
06030 
06031       case 15: /* Full Status */
06032          rpt_telemetry(myrpt, FULLSTATUS, NULL);
06033          return DC_COMPLETE;
06034          
06035          
06036       case 6: /* All Links Off, including permalinks */
06037                        rpt_mutex_lock(&myrpt->lock);
06038          myrpt->savednodes[0] = 0;
06039                         l = myrpt->links.next;
06040                         /* loop through all links */
06041                         while(l != &myrpt->links){
06042             struct   ast_frame wf;
06043                                 if (l->name[0] == '0') /* Skip any IAXRPT monitoring */
06044                                 {
06045                                         l = l->next;
06046                                         continue;
06047                                 }
06048             /* Make a string of disconnected nodes for possible restoration */
06049             sprintf(tmp,"%c%c%s",(l->mode) ? 'X' : 'M',(l->perma) ? 'P':'T',l->name);
06050             if(strlen(tmp) + strlen(myrpt->savednodes) + 1 < MAXNODESTR){ 
06051                if(myrpt->savednodes[0])
06052                   strcat(myrpt->savednodes, ",");
06053                strcat(myrpt->savednodes, tmp);
06054             }
06055                               l->retries = l->max_retries + 1;
06056                                 l->disced = 2; /* Silently disconnect */
06057                                 rpt_mutex_unlock(&myrpt->lock);
06058             /* ast_log(LOG_NOTICE,"dumping link %s\n",l->name); */
06059                                 
06060                                 wf.frametype = AST_FRAME_TEXT;
06061                                 wf.subclass.integer = 0;
06062                                 wf.offset = 0;
06063                                 wf.mallocd = 0;
06064                                 wf.datalen = strlen(discstr) + 1;
06065                                 wf.samples = 0;
06066                                 wf.data.ptr = discstr;
06067                                 if (l->chan)
06068                                 {
06069                                         ast_write(l->chan,&wf);
06070                                         ast_safe_sleep(l->chan,250); /* It's dead already, why check the return value? */
06071                                         ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
06072                                 }
06073             rpt_mutex_lock(&myrpt->lock);
06074                                 l = l->next;
06075                         }
06076          rpt_mutex_unlock(&myrpt->lock);
06077          if(debug > 3)
06078             ast_log(LOG_NOTICE,"Nodes disconnected: %s\n",myrpt->savednodes);
06079                         rpt_telemetry(myrpt, COMPLETE, NULL);
06080          return DC_COMPLETE;
06081 
06082       case 7: /* Identify last node which keyed us up */
06083          rpt_telemetry(myrpt, LASTNODEKEY, NULL);
06084          break;
06085 
06086 
06087 #ifdef   _MDC_DECODE_H_
06088       case 8:
06089          myrpt->lastunit = 0xd00d; 
06090          mdc1200_notify(myrpt,NULL,myrpt->lastunit);
06091          mdc1200_send(myrpt,myrpt->lastunit);
06092          break;
06093 #endif
06094 
06095       case 16: /* Restore links disconnected with "disconnect all links" command */
06096          strcpy(tmp, myrpt->savednodes); /* Make a copy */
06097          finddelim(tmp, strs, MAXLINKLIST); /* convert into substrings */
06098          for(i = 0; tmp[0] && strs[i] != NULL && i < MAXLINKLIST; i++){
06099             s1 = strs[i];
06100             mode = (s1[0] == 'X') ? 1 : 0;
06101             perma = (s1[1] == 'P') ? 1 : 0;
06102             connect_link(myrpt, s1 + 2, mode, perma); /* Try to reconnect */
06103          }
06104                         rpt_telemetry(myrpt, COMPLETE, NULL);
06105          break;
06106    
06107       case 200:
06108       case 201:
06109       case 202:
06110       case 203:
06111       case 204:
06112       case 205:
06113       case 206:
06114       case 207:
06115       case 208:
06116       case 209:
06117       case 210:
06118       case 211:
06119       case 212:
06120       case 213:
06121       case 214:
06122       case 215:
06123          if (((myrpt->p.propagate_dtmf) && 
06124               (command_source == SOURCE_LNK)) ||
06125              ((myrpt->p.propagate_phonedtmf) &&
06126             ((command_source == SOURCE_PHONE) ||
06127               (command_source == SOURCE_ALT) ||
06128                 (command_source == SOURCE_DPHONE))))
06129                do_dtmf_local(myrpt,
06130                   remdtmfstr[myatoi(param) - 200]);
06131       default:
06132          return DC_ERROR;
06133          
06134    }
06135    
06136    return DC_INDETERMINATE;
06137 }  
06138 
06139 /*
06140 * Autopatch up
06141 */
06142 
06143 static int function_autopatchup(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06144 {
06145    pthread_attr_t attr;
06146    int i, idx, paramlength;
06147    char *lparam;
06148    char *value = NULL;
06149    char *paramlist[20];
06150 
06151    static char *keywords[] = {
06152    "context",
06153    "dialtime",
06154    "farenddisconnect",
06155    "noct",
06156    "quiet",
06157    NULL
06158    };
06159       
06160    if (myrpt->p.s[myrpt->p.sysstate_cur].txdisable || myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable)
06161       return DC_ERROR;
06162       
06163    if(debug)
06164       printf("@@@@ Autopatch up\n");
06165 
06166    if(!myrpt->callmode){
06167       /* Set defaults */
06168       myrpt->patchnoct = 0;
06169       myrpt->patchdialtime = 0;
06170       myrpt->patchfarenddisconnect = 0;
06171       myrpt->patchquiet = 0;
06172       strncpy(myrpt->patchcontext, myrpt->p.ourcontext, MAXPATCHCONTEXT);
06173 
06174       if(param){
06175          /* Process parameter list */
06176          lparam = ast_strdup(param);
06177          if(!lparam){
06178             ast_log(LOG_ERROR,"App_rpt out of memory on line %d\n",__LINE__);
06179             return DC_ERROR;  
06180          }
06181          paramlength = finddelim(lparam, paramlist, 20);          
06182          for(i = 0; i < paramlength; i++){
06183             idx = matchkeyword(paramlist[i], &value, keywords);
06184             if(value)
06185                value = skipchars(value, "= ");
06186             switch(idx){
06187 
06188                case 1: /* context */
06189                   strncpy(myrpt->patchcontext, value, MAXPATCHCONTEXT - 1) ;
06190                   break;
06191                   
06192                case 2: /* dialtime */
06193                   myrpt->patchdialtime = atoi(value);
06194                   break;
06195 
06196                case 3: /* farenddisconnect */
06197                   myrpt->patchfarenddisconnect = atoi(value);
06198                   break;
06199 
06200                case 4:  /* noct */
06201                   myrpt->patchnoct = atoi(value);
06202                   break;
06203 
06204                case 5: /* quiet */
06205                   myrpt->patchquiet = atoi(value);
06206                   break;
06207                            
06208                default:
06209                   break;
06210             }
06211          }
06212       ast_free(lparam);
06213       }
06214    }
06215                
06216    rpt_mutex_lock(&myrpt->lock);
06217 
06218    /* if on call, force * into current audio stream */
06219    
06220    if ((myrpt->callmode == 2) || (myrpt->callmode == 3)){
06221       myrpt->mydtmf = myrpt->p.endchar;
06222    }
06223    if (myrpt->callmode){
06224       rpt_mutex_unlock(&myrpt->lock);
06225       return DC_COMPLETE;
06226    }
06227    myrpt->callmode = 1;
06228    myrpt->cidx = 0;
06229    myrpt->exten[myrpt->cidx] = 0;
06230    rpt_mutex_unlock(&myrpt->lock);
06231    pthread_attr_init(&attr);
06232    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
06233    ast_pthread_create(&myrpt->rpt_call_thread,&attr,rpt_call,(void *) myrpt);
06234    return DC_COMPLETE;
06235 }
06236 
06237 /*
06238 * Autopatch down
06239 */
06240 
06241 static int function_autopatchdn(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06242 {
06243    if (myrpt->p.s[myrpt->p.sysstate_cur].txdisable || myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable)
06244       return DC_ERROR;
06245    
06246    if(debug)
06247       printf("@@@@ Autopatch down\n");
06248       
06249    rpt_mutex_lock(&myrpt->lock);
06250    
06251    myrpt->macropatch=0;
06252 
06253    if (!myrpt->callmode){
06254       rpt_mutex_unlock(&myrpt->lock);
06255       return DC_COMPLETE;
06256    }
06257    
06258    myrpt->callmode = 0;
06259    channel_revert(myrpt);
06260    rpt_mutex_unlock(&myrpt->lock);
06261    rpt_telemetry(myrpt, TERM, NULL);
06262    return DC_COMPLETE;
06263 }
06264 
06265 /*
06266 * Status
06267 */
06268 
06269 static int function_status(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06270 {
06271 
06272    if (!param)
06273       return DC_ERROR;
06274 
06275    if ((myrpt->p.s[myrpt->p.sysstate_cur].txdisable) || (myrpt->p.s[myrpt->p.sysstate_cur].userfundisable))
06276       return DC_ERROR;
06277 
06278    if(debug)
06279       printf("@@@@ status param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
06280    
06281    switch(myatoi(param)){
06282       case 1: /* System ID */
06283          rpt_telemetry(myrpt, ID1, NULL);
06284          return DC_COMPLETE;
06285       case 2: /* System Time */
06286          rpt_telemetry(myrpt, STATS_TIME, NULL);
06287          return DC_COMPLETE;
06288       case 3: /* app_rpt.c version */
06289          rpt_telemetry(myrpt, STATS_VERSION, NULL);
06290          return DC_COMPLETE;
06291       case 11: /* System ID (local only)*/
06292           rpt_telemetry(myrpt, ID , NULL);
06293             return DC_COMPLETE;
06294         case 12: /* System Time (local only)*/
06295             rpt_telemetry(myrpt, STATS_TIME_LOCAL, NULL);
06296             return DC_COMPLETE;
06297       default:
06298          return DC_ERROR;
06299    }
06300    return DC_INDETERMINATE;
06301 }
06302 /*
06303 *  Macro-oni (without Salami)
06304 */
06305 static int function_macro(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06306 {
06307 char  *val;
06308 int   i;
06309    if (myrpt->remote)
06310       return DC_ERROR;
06311 
06312    if(debug) 
06313       printf("@@@@ macro-oni param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
06314    
06315    if(strlen(digitbuf) < 1) /* needs 1 digit */
06316       return DC_INDETERMINATE;
06317          
06318    for(i = 0 ; i < digitbuf[i] ; i++) {
06319       if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
06320          return DC_ERROR;
06321    }
06322    
06323    if (*digitbuf == '0') val = myrpt->p.startupmacro;
06324    else val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.macro, digitbuf);
06325    /* param was 1 for local buf */
06326    if (!val){
06327                 if (strlen(digitbuf) < myrpt->macro_longest)
06328                         return DC_INDETERMINATE;
06329       rpt_telemetry(myrpt, MACRO_NOTFOUND, NULL);
06330       return DC_COMPLETE;
06331    }        
06332    rpt_mutex_lock(&myrpt->lock);
06333    if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(val))
06334    {
06335       rpt_mutex_unlock(&myrpt->lock);
06336       rpt_telemetry(myrpt, MACRO_BUSY, NULL);
06337       return DC_ERROR;
06338    }
06339    myrpt->macrotimer = MACROTIME;
06340    strncat(myrpt->macrobuf,val,MAXMACRO - 1);
06341    rpt_mutex_unlock(&myrpt->lock);
06342    return DC_COMPLETE;  
06343 }
06344 
06345 /*
06346 *  Playback a recording
06347 */
06348 
06349 static int function_playback(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06350 {
06351 
06352    if (myrpt->remote)
06353       return DC_ERROR;
06354 
06355    if(debug) 
06356       printf("@@@@ playback param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
06357    
06358    if (ast_fileexists(param,NULL,myrpt->rxchannel->language) <= 0)
06359       return DC_ERROR;
06360 
06361    rpt_telemetry(myrpt,PLAYBACK,param);
06362    return DC_COMPLETE;
06363 }
06364 
06365 /*
06366 * COP - Control operator
06367 */
06368 
06369 static int function_cop(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
06370 {
06371    char string[16];
06372 
06373    int i, r;
06374 
06375    if(!param)
06376       return DC_ERROR;
06377    
06378    switch(myatoi(param)){
06379       case 1: /* System reset */
06380          return system("killall -9 asterisk");
06381 
06382       case 2:
06383          myrpt->p.s[myrpt->p.sysstate_cur].txdisable = 0;
06384          rpt_telemetry(myrpt, ARB_ALPHA, (void *) "RPTENA");
06385          return DC_COMPLETE;
06386          
06387       case 3:
06388          myrpt->p.s[myrpt->p.sysstate_cur].txdisable = 1;
06389          return DC_COMPLETE;
06390          
06391       case 4: /* test tone on */
06392          if (myrpt->stopgen < 0) 
06393          {
06394             myrpt->stopgen = 1;
06395          }
06396          else 
06397          {
06398             myrpt->stopgen = 0;
06399             rpt_telemetry(myrpt, TEST_TONE, NULL);
06400          }
06401          return DC_COMPLETE;
06402 
06403       case 5: /* Disgorge variables to log for debug purposes */
06404          myrpt->disgorgetime = time(NULL) + 10; /* Do it 10 seconds later */
06405          return DC_COMPLETE;
06406 
06407       case 6: /* Simulate COR being activated (phone only) */
06408          if (command_source != SOURCE_PHONE) return DC_INDETERMINATE;
06409          return DC_DOKEY;  
06410 
06411 
06412       case 7: /* Time out timer enable */
06413          myrpt->p.s[myrpt->p.sysstate_cur].totdisable = 0;
06414          rpt_telemetry(myrpt, ARB_ALPHA, (void *) "TOTENA");
06415          return DC_COMPLETE;
06416          
06417       case 8: /* Time out timer disable */
06418          myrpt->p.s[myrpt->p.sysstate_cur].totdisable = 1;
06419          rpt_telemetry(myrpt, ARB_ALPHA, (void *) "TOTDIS");
06420          return DC_COMPLETE;
06421 
06422                 case 9: /* Autopatch enable */
06423                         myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable = 0;
06424                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "APENA");
06425                         return DC_COMPLETE;
06426 
06427                 case 10: /* Autopatch disable */
06428                         myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable = 1;
06429                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "APDIS");
06430                         return DC_COMPLETE;
06431 
06432                 case 11: /* Link Enable */
06433                         myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable = 0;
06434                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "LNKENA");
06435                         return DC_COMPLETE;
06436 
06437                 case 12: /* Link Disable */
06438                         myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable = 1;
06439                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "LNKDIS");
06440                         return DC_COMPLETE;
06441 
06442       case 13: /* Query System State */
06443          string[0] = string[1] = 'S';
06444          string[2] = myrpt->p.sysstate_cur + '0';
06445          string[3] = '\0';
06446          rpt_telemetry(myrpt, ARB_ALPHA, (void *) string);
06447          return DC_COMPLETE;
06448 
06449       case 14: /* Change System State */
06450          if(strlen(digitbuf) == 0)
06451             break;
06452          if((digitbuf[0] < '0') || (digitbuf[0] > '9'))
06453             return DC_ERROR;
06454          myrpt->p.sysstate_cur = digitbuf[0] - '0';
06455                         string[0] = string[1] = 'S';
06456                         string[2] = myrpt->p.sysstate_cur + '0';
06457                         string[3] = '\0';
06458                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) string);
06459                         return DC_COMPLETE;
06460 
06461                 case 15: /* Scheduler Enable */
06462                         myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable = 0;
06463                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "SKENA");
06464                         return DC_COMPLETE;
06465 
06466                 case 16: /* Scheduler Disable */
06467                         myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable = 1;
06468                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "SKDIS");
06469                         return DC_COMPLETE;
06470 
06471                 case 17: /* User functions Enable */
06472                         myrpt->p.s[myrpt->p.sysstate_cur].userfundisable = 0;
06473                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "UFENA");
06474                         return DC_COMPLETE;
06475 
06476                 case 18: /* User Functions Disable */
06477                         myrpt->p.s[myrpt->p.sysstate_cur].userfundisable = 1;
06478                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "UFDIS");
06479                         return DC_COMPLETE;
06480 
06481                 case 19: /* Alternate Tail Enable */
06482                         myrpt->p.s[myrpt->p.sysstate_cur].alternatetail = 1;
06483                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "ATENA");
06484                         return DC_COMPLETE;
06485 
06486                 case 20: /* Alternate Tail Disable */
06487                         myrpt->p.s[myrpt->p.sysstate_cur].alternatetail = 0;
06488                         rpt_telemetry(myrpt, ARB_ALPHA, (void *) "ATDIS");
06489                         return DC_COMPLETE;
06490 
06491                 case 21: /* Parrot Mode Disable */
06492          birdbath(myrpt);
06493          if (myrpt->p.parrotmode < 2)
06494          {
06495             myrpt->p.parrotmode = 0;
06496             rpt_telemetry(myrpt,COMPLETE,NULL);
06497             return DC_COMPLETE;
06498          }
06499          break;
06500 
06501                 case 22: /* Parrot Mode Enable */
06502          birdbath(myrpt);
06503          if (myrpt->p.parrotmode < 2)
06504          {
06505             myrpt->p.parrotmode = 1;
06506             rpt_telemetry(myrpt,COMPLETE,NULL);
06507             return DC_COMPLETE;
06508          }
06509          break;
06510       case 23: /* flush parrot in progress */
06511          birdbath(myrpt);
06512          rpt_telemetry(myrpt,COMPLETE,NULL);
06513          return DC_COMPLETE;
06514       case 24: /* flush all telemetry */
06515          flush_telem(myrpt);
06516          rpt_telemetry(myrpt,COMPLETE,NULL);
06517          return DC_COMPLETE;
06518       case 25: /* request keying info (brief) */
06519          send_link_keyquery(myrpt);
06520          myrpt->topkeylong = 0;
06521          rpt_telemetry(myrpt,COMPLETE,NULL);
06522          return DC_COMPLETE;
06523       case 26: /* request keying info (full) */
06524          send_link_keyquery(myrpt);
06525          myrpt->topkeylong = 1;
06526          rpt_telemetry(myrpt,COMPLETE,NULL);
06527          return DC_COMPLETE;
06528 
06529       case 30: /* recall memory location on programmable radio */
06530 
06531          if(strlen(digitbuf) < 2) /* needs 2 digits */
06532             break;
06533          
06534          for(i = 0 ; i < 2 ; i++){
06535             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
06536                return DC_ERROR;
06537          }
06538        
06539          r = retreive_memory(myrpt, digitbuf);
06540          if (r < 0){
06541             rpt_telemetry(myrpt,MEMNOTFOUND,NULL);
06542             return DC_COMPLETE;
06543          }
06544          if (r > 0){
06545             return DC_ERROR;
06546          }
06547          if (setrem(myrpt) == -1) return DC_ERROR;
06548          return DC_COMPLETE;  
06549 
06550       case 31: 
06551           /* set channel. note that it's going to change channel 
06552              then confirm on the new channel! */
06553          if(strlen(digitbuf) < 2) /* needs 2 digits */
06554             break;
06555          
06556          for(i = 0 ; i < 2 ; i++){
06557             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
06558                return DC_ERROR;
06559          }
06560          channel_steer(myrpt,digitbuf);
06561          return DC_COMPLETE;  
06562 
06563       case 32: /* Touch Tone Pad Test */
06564          i = strlen(digitbuf);
06565          if(!i){
06566             if(debug > 3)
06567             ast_log(LOG_NOTICE,"Padtest entered");
06568             myrpt->inpadtest = 1;
06569          }
06570          else{
06571             if(debug > 3)
06572                ast_log(LOG_NOTICE,"Padtest len= %d digits=%s",i,digitbuf);
06573             if(digitbuf[i-1] != myrpt->p.endchar)
06574                break;
06575             rpt_telemetry(myrpt, ARB_ALPHA, digitbuf);
06576             myrpt->inpadtest = 0;
06577             if(debug > 3)
06578                ast_log(LOG_NOTICE,"Padtest exited");
06579             return DC_COMPLETE;
06580          }
06581    }  
06582    return DC_INDETERMINATE;
06583 }
06584 /*
06585 * Collect digits one by one until something matches
06586 */
06587 static int collect_function_digits(struct rpt *myrpt, char *digits, 
06588    int command_source, struct rpt_link *mylink)
06589 {
06590    int i,rv;
06591    char *stringp,*action,*param,*functiondigits;
06592    char function_table_name[30] = "";
06593    char workstring[200];
06594    
06595    struct ast_variable *vp;
06596    
06597    if (debug > 6) ast_log(LOG_NOTICE,"digits=%s  source=%d\n",digits, command_source);
06598 
06599    //if(debug) 
06600    // printf("@@@@ Digits collected: %s, source: %d\n", digits, command_source);
06601    
06602    if (command_source == SOURCE_DPHONE) {
06603       if (!myrpt->p.dphone_functions) return DC_INDETERMINATE;
06604       strncpy(function_table_name, myrpt->p.dphone_functions, sizeof(function_table_name) - 1);
06605       }
06606    else if (command_source == SOURCE_ALT) {
06607       if (!myrpt->p.alt_functions) return DC_INDETERMINATE;
06608       strncpy(function_table_name, myrpt->p.alt_functions, sizeof(function_table_name) - 1);
06609       }
06610    else if (command_source == SOURCE_PHONE) {
06611       if (!myrpt->p.phone_functions) return DC_INDETERMINATE;
06612       strncpy(function_table_name, myrpt->p.phone_functions, sizeof(function_table_name) - 1);
06613       }
06614    else if (command_source == SOURCE_LNK)
06615       strncpy(function_table_name, myrpt->p.link_functions, sizeof(function_table_name) - 1);
06616    else
06617       strncpy(function_table_name, myrpt->p.functions, sizeof(function_table_name) - 1);
06618     /* find context for function table in rpt.conf file */
06619    vp = ast_variable_browse(myrpt->cfg, function_table_name);
06620    while(vp) {
06621       if(!strncasecmp(vp->name, digits, strlen(vp->name)))
06622          break;
06623       vp = vp->next;
06624    }  
06625    /* if function context not found */
06626    if(!vp) {
06627       int n;
06628 
06629       n = myrpt->longestfunc;
06630       if (command_source == SOURCE_LNK) n = myrpt->link_longestfunc;
06631       else 
06632       if (command_source == SOURCE_PHONE) n = myrpt->phone_longestfunc;
06633       else 
06634       if (command_source == SOURCE_ALT) n = myrpt->alt_longestfunc;
06635       else 
06636       if (command_source == SOURCE_DPHONE) n = myrpt->dphone_longestfunc;
06637       
06638       if(strlen(digits) >= n)
06639          return DC_ERROR;
06640       else
06641          return DC_INDETERMINATE;
06642    }  
06643    /* Found a match, retrieve value part and parse */
06644    strncpy(workstring, vp->value, sizeof(workstring) - 1 );
06645    stringp = workstring;
06646    action = strsep(&stringp, ",");
06647    param = stringp;
06648    if(debug)
06649       printf("@@@@ action: %s, param = %s\n",action, (param) ? param : "(null)");
06650    /* Look up the action */
06651    for(i = 0 ; i < (sizeof(function_table)/sizeof(struct function_table_tag)); i++){
06652       if(!strncasecmp(action, function_table[i].action, strlen(action)))
06653          break;
06654    }
06655    if(debug)
06656       printf("@@@@ table index i = %d\n",i);
06657    if(i == (sizeof(function_table)/sizeof(struct function_table_tag))){
06658       /* Error, action not in table */
06659       return DC_ERROR;
06660    }
06661    if(function_table[i].function == NULL){
06662       /* Error, function undefined */
06663       if(debug)
06664          printf("@@@@ NULL for action: %s\n",action);
06665       return DC_ERROR;
06666    }
06667    functiondigits = digits + strlen(vp->name);
06668    rv=(*function_table[i].function)(myrpt, param, functiondigits, command_source, mylink);
06669    if (debug > 6) ast_log(LOG_NOTICE,"rv=%i\n",rv);
06670    return(rv);
06671 }
06672 
06673 
06674 static void handle_link_data(struct rpt *myrpt, struct rpt_link *mylink,
06675    char *str)
06676 {
06677 /* XXX ATTENTION: if you change the size of these arrays you MUST
06678  * change the limits in corresponding sscanf() calls below. */
06679 char  tmp[512],tmp1[512],cmd[300] = "",dest[300],src[300],c;
06680 int   i,seq, res, ts;
06681 struct rpt_link *l;
06682 struct   ast_frame wf;
06683 
06684    wf.frametype = AST_FRAME_TEXT;
06685    wf.subclass.integer = 0;
06686    wf.offset = 0;
06687    wf.mallocd = 0;
06688    wf.datalen = strlen(str) + 1;
06689    wf.samples = 0;
06690    /* put string in our buffer */
06691    strncpy(tmp,str,sizeof(tmp) - 1);
06692 
06693         if (!strcmp(tmp,discstr))
06694         {
06695                 mylink->disced = 1;
06696       mylink->retries = mylink->max_retries + 1;
06697                 ast_softhangup(mylink->chan,AST_SOFTHANGUP_DEV);
06698                 return;
06699         }
06700         if (!strcmp(tmp,newkeystr))
06701         {
06702       mylink->newkey = 1;
06703                 return;
06704         }
06705    if (tmp[0] == 'L')
06706    {
06707       rpt_mutex_lock(&myrpt->lock);
06708       strcpy(mylink->linklist,tmp + 2);
06709       time(&mylink->linklistreceived);
06710       rpt_mutex_unlock(&myrpt->lock);
06711       if (debug > 6) ast_log(LOG_NOTICE,"@@@@ node %s received node list %s from node %s\n",
06712          myrpt->name,tmp,mylink->name);
06713       return;
06714    }
06715    if (tmp[0] == 'K')
06716    {
06717       if (sscanf(tmp, "%299s %299s %299s %30d %30d", cmd, dest, src, &seq, &ts) != 5)
06718       {
06719          ast_log(LOG_WARNING, "Unable to parse keying string %s\n",str);
06720          return;
06721       }
06722       if (dest[0] == '0')
06723       {
06724          strcpy(dest,myrpt->name);
06725       }     
06726       /* if not for me, redistribute to all links */
06727       if (strcmp(dest,myrpt->name))
06728       {
06729          l = myrpt->links.next;
06730          /* see if this is one in list */
06731          while(l != &myrpt->links)
06732          {
06733             if (l->name[0] == '0') 
06734             {
06735                l = l->next;
06736                continue;
06737             }
06738             /* don't send back from where it came */
06739             if ((l == mylink) || (!strcmp(l->name,mylink->name)))
06740             {
06741                l = l->next;
06742                continue;
06743             }
06744             /* if it is, send it and we're done */
06745             if (!strcmp(l->name,dest))
06746             {
06747                /* send, but not to src */
06748                if (strcmp(l->name,src)) {
06749                   wf.data.ptr = str;
06750                   if (l->chan) ast_write(l->chan,&wf);
06751                }
06752                return;
06753             }
06754             l = l->next;
06755          }
06756       }
06757       /* if not for me, or is broadcast, redistribute to all links */
06758       if ((strcmp(dest,myrpt->name)) || (dest[0] == '*'))
06759       {
06760          l = myrpt->links.next;
06761          /* otherwise, send it to all of em */
06762          while(l != &myrpt->links)
06763          {
06764             if (l->name[0] == '0') 
06765             {
06766                l = l->next;
06767                continue;
06768             }
06769             /* don't send back from where it came */
06770             if ((l == mylink) || (!strcmp(l->name,mylink->name)))
06771             {
06772                l = l->next;
06773                continue;
06774             }
06775             /* send, but not to src */
06776             if (strcmp(l->name,src)) {
06777                wf.data.ptr = str;
06778                if (l->chan) ast_write(l->chan,&wf); 
06779             }
06780             l = l->next;
06781          }
06782       }
06783       /* if not for me, end here */
06784       if (strcmp(dest,myrpt->name) && (dest[0] != '*')) return;
06785       if (cmd[1] == '?')
06786       {
06787          time_t now;
06788          int n = 0;
06789 
06790          time(&now);
06791          if (myrpt->lastkeyedtime)
06792          {
06793             n = (int)(now - myrpt->lastkeyedtime);
06794          }
06795          sprintf(tmp1,"K %s %s %d %d",src,myrpt->name,myrpt->keyed,n);
06796          wf.data.ptr = tmp1;
06797          wf.datalen = strlen(tmp1) + 1;
06798          if (mylink->chan) ast_write(mylink->chan,&wf); 
06799          return;
06800       }
06801       if (myrpt->topkeystate != 1) return;
06802       rpt_mutex_lock(&myrpt->lock);
06803       for(i = 0; i < TOPKEYN; i++)
06804       {
06805          if (!strcmp(myrpt->topkey[i].node,src)) break;
06806       }
06807       if (i >= TOPKEYN)
06808       {
06809          for(i = 0; i < TOPKEYN; i++)
06810          {
06811             if (!myrpt->topkey[i].node[0]) break;
06812          }
06813       }
06814       if (i < TOPKEYN)
06815       {
06816          strncpy(myrpt->topkey[i].node,src,TOPKEYMAXSTR - 1);
06817          myrpt->topkey[i].timesince = ts;
06818          myrpt->topkey[i].keyed = seq;
06819       }
06820       rpt_mutex_unlock(&myrpt->lock);
06821       return;
06822    }
06823    if (tmp[0] == 'I')
06824    {
06825       /* XXX WARNING: be very careful with the limits on the folowing
06826        * sscanf() call, make sure they match the values defined above */
06827       if (sscanf(tmp,"%299s %299s %30x",cmd,src,&seq) != 3)
06828       {
06829          ast_log(LOG_WARNING, "Unable to parse ident string %s\n",str);
06830          return;
06831       }
06832       mdc1200_notify(myrpt,src,seq);
06833       strcpy(dest,"*");
06834    }
06835    else
06836    {
06837       /* XXX WARNING: be very careful with the limits on the folowing
06838        * sscanf() call, make sure they match the values defined above */
06839       if (sscanf(tmp,"%299s %299s %299s %30d %1c",cmd,dest,src,&seq,&c) != 5)
06840       {
06841          ast_log(LOG_WARNING, "Unable to parse link string %s\n",str);
06842          return;
06843       }
06844       if (strcmp(cmd,"D"))
06845       {
06846          ast_log(LOG_WARNING, "Unable to parse link string %s\n",str);
06847          return;
06848       }
06849    }
06850    if (dest[0] == '0')
06851    {
06852       strcpy(dest,myrpt->name);
06853    }     
06854 
06855    /* if not for me, redistribute to all links */
06856    if (strcmp(dest,myrpt->name))
06857    {
06858       l = myrpt->links.next;
06859       /* see if this is one in list */
06860       while(l != &myrpt->links)
06861       {
06862          if (l->name[0] == '0') 
06863          {
06864             l = l->next;
06865             continue;
06866          }
06867          /* don't send back from where it came */
06868          if ((l == mylink) || (!strcmp(l->name,mylink->name)))
06869          {
06870             l = l->next;
06871             continue;
06872          }
06873          /* if it is, send it and we're done */
06874          if (!strcmp(l->name,dest))
06875          {
06876             /* send, but not to src */
06877             if (strcmp(l->name,src)) {
06878                wf.data.ptr = str;
06879                if (l->chan) ast_write(l->chan,&wf);
06880             }
06881             return;
06882          }
06883          l = l->next;
06884       }
06885       l = myrpt->links.next;
06886       /* otherwise, send it to all of em */
06887       while(l != &myrpt->links)
06888       {
06889          if (l->name[0] == '0') 
06890          {
06891             l = l->next;
06892             continue;
06893          }
06894          /* don't send back from where it came */
06895          if ((l == mylink) || (!strcmp(l->name,mylink->name)))
06896          {
06897             l = l->next;
06898             continue;
06899          }
06900          /* send, but not to src */
06901          if (strcmp(l->name,src)) {
06902             wf.data.ptr = str;
06903             if (l->chan) ast_write(l->chan,&wf); 
06904          }
06905          l = l->next;
06906       }
06907       return;
06908    }
06909    if (myrpt->p.archivedir)
06910    {
06911       char dtmfstr[100];
06912 
06913       sprintf(dtmfstr,"DTMF,%s,%c",mylink->name,c);
06914       donodelog(myrpt,dtmfstr);
06915    }
06916    c = func_xlat(myrpt,c,&myrpt->p.outxlat);
06917    if (!c) return;
06918    rpt_mutex_lock(&myrpt->lock);
06919    if (c == myrpt->p.endchar) myrpt->stopgen = 1;
06920    if (myrpt->callmode == 1)
06921    {
06922       myrpt->exten[myrpt->cidx++] = c;
06923       myrpt->exten[myrpt->cidx] = 0;
06924       /* if this exists */
06925       if (ast_exists_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
06926       {
06927          /* if this really it, end now */
06928          if (!ast_matchmore_extension(myrpt->pchannel,myrpt->patchcontext,
06929             myrpt->exten,1,NULL)) 
06930          {
06931             myrpt->callmode = 2;
06932             if(!myrpt->patchquiet)
06933             {
06934                rpt_mutex_unlock(&myrpt->lock);
06935                rpt_telemetry(myrpt,PROC,NULL); 
06936                rpt_mutex_lock(&myrpt->lock);
06937             }
06938          }
06939          else /* othewise, reset timer */
06940          {
06941             myrpt->calldigittimer = 1;
06942          }
06943       }
06944       /* if can continue, do so */
06945       if (!ast_canmatch_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
06946       {
06947          /* call has failed, inform user */
06948          myrpt->callmode = 4;
06949       }
06950    }
06951    if ((!myrpt->inpadtest) &&(c == myrpt->p.funcchar))
06952    {
06953       myrpt->rem_dtmfidx = 0;
06954       myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx] = 0;
06955       time(&myrpt->rem_dtmf_time);
06956       rpt_mutex_unlock(&myrpt->lock);
06957       return;
06958    } 
06959    else if (myrpt->rem_dtmfidx < 0)
06960    {
06961       if ((myrpt->callmode == 2) || (myrpt->callmode == 3))
06962       {
06963          myrpt->mydtmf = c;
06964       }
06965       if (myrpt->p.propagate_dtmf) do_dtmf_local(myrpt,c);
06966       if (myrpt->p.propagate_phonedtmf) do_dtmf_phone(myrpt,mylink,c);
06967       rpt_mutex_unlock(&myrpt->lock);
06968       return;
06969    }
06970    else if (((myrpt->inpadtest) || (c != myrpt->p.endchar)) && (myrpt->rem_dtmfidx >= 0))
06971    {
06972       time(&myrpt->rem_dtmf_time);
06973       if (myrpt->rem_dtmfidx < MAXDTMF)
06974       {
06975          myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx++] = c;
06976          myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx] = 0;
06977          
06978          rpt_mutex_unlock(&myrpt->lock);
06979          strncpy(cmd, myrpt->rem_dtmfbuf, sizeof(cmd) - 1);
06980          res = collect_function_digits(myrpt, cmd, SOURCE_LNK, mylink);
06981          rpt_mutex_lock(&myrpt->lock);
06982          
06983          switch(res){
06984 
06985             case DC_INDETERMINATE:
06986                break;
06987             
06988             case DC_REQ_FLUSH:
06989                myrpt->rem_dtmfidx = 0;
06990                myrpt->rem_dtmfbuf[0] = 0;
06991                break;
06992             
06993             
06994             case DC_COMPLETE:
06995             case DC_COMPLETEQUIET:
06996                myrpt->totalexecdcommands++;
06997                myrpt->dailyexecdcommands++;
06998                strncpy(myrpt->lastdtmfcommand, cmd, MAXDTMF-1);
06999                myrpt->lastdtmfcommand[MAXDTMF-1] = '\0';
07000                myrpt->rem_dtmfbuf[0] = 0;
07001                myrpt->rem_dtmfidx = -1;
07002                myrpt->rem_dtmf_time = 0;
07003                break;
07004             
07005             case DC_ERROR:
07006             default:
07007                myrpt->rem_dtmfbuf[0] = 0;
07008                myrpt->rem_dtmfidx = -1;
07009                myrpt->rem_dtmf_time = 0;
07010                break;
07011          }
07012       }
07013 
07014    }
07015    rpt_mutex_unlock(&myrpt->lock);
07016    return;
07017 }
07018 
07019 static void handle_link_phone_dtmf(struct rpt *myrpt, struct rpt_link *mylink,
07020    char c)
07021 {
07022 
07023 char  cmd[300];
07024 int   res;
07025 
07026    if (myrpt->p.archivedir)
07027    {
07028       char str[100];
07029 
07030       sprintf(str,"DTMF(P),%s,%c",mylink->name,c);
07031       donodelog(myrpt,str);
07032    }
07033    rpt_mutex_lock(&myrpt->lock);
07034 
07035    if (mylink->phonemode == 3) /*If in simplex dumb phone mode */
07036    {
07037       if(c == myrpt->p.endchar) /* If end char */
07038       {
07039          mylink->lastrealrx = 0; /* Keying state = off */
07040          rpt_mutex_unlock(&myrpt->lock);
07041          return;
07042       }
07043 
07044       if(c == myrpt->p.funcchar) /* If lead-in char */
07045       {
07046          mylink->lastrealrx = !mylink->lastrealrx; /* Toggle keying state */
07047          rpt_mutex_unlock(&myrpt->lock);
07048          return;
07049       }
07050    }
07051    else
07052    {
07053       if (c == myrpt->p.endchar)
07054       {
07055          if (mylink->lastrx)
07056          {
07057             mylink->lastrealrx = 0;
07058             rpt_mutex_unlock(&myrpt->lock);
07059             return;
07060          }
07061          myrpt->stopgen = 1;
07062          if (myrpt->cmdnode[0])
07063          {
07064             myrpt->cmdnode[0] = 0;
07065             myrpt->dtmfidx = -1;
07066             myrpt->dtmfbuf[0] = 0;
07067             rpt_mutex_unlock(&myrpt->lock);
07068             rpt_telemetry(myrpt,COMPLETE,NULL);
07069             return;
07070          }
07071       }
07072    }
07073    if (myrpt->cmdnode[0])
07074    {
07075       rpt_mutex_unlock(&myrpt->lock);
07076       send_link_dtmf(myrpt,c);
07077       return;
07078    }
07079    if (myrpt->callmode == 1)
07080    {
07081       myrpt->exten[myrpt->cidx++] = c;
07082       myrpt->exten[myrpt->cidx] = 0;
07083       /* if this exists */
07084       if (ast_exists_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
07085       {
07086          /* if this really it, end now */
07087          if (!ast_matchmore_extension(myrpt->pchannel,myrpt->patchcontext,
07088             myrpt->exten,1,NULL)) 
07089          {
07090             myrpt->callmode = 2;
07091             if(!myrpt->patchquiet)
07092             {
07093                rpt_mutex_unlock(&myrpt->lock);
07094                rpt_telemetry(myrpt,PROC,NULL); 
07095                rpt_mutex_lock(&myrpt->lock);
07096             }
07097          }
07098          else /* othewise, reset timer */
07099          {
07100             myrpt->calldigittimer = 1;
07101          }
07102       }
07103       /* if can continue, do so */
07104       if (!ast_canmatch_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
07105       {
07106          /* call has failed, inform user */
07107          myrpt->callmode = 4;
07108       }
07109    }
07110    if ((myrpt->callmode == 2) || (myrpt->callmode == 3))
07111    {
07112       myrpt->mydtmf = c;
07113    }
07114    if ((!myrpt->inpadtest) && (c == myrpt->p.funcchar))
07115    {
07116       myrpt->rem_dtmfidx = 0;
07117       myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx] = 0;
07118       time(&myrpt->rem_dtmf_time);
07119       rpt_mutex_unlock(&myrpt->lock);
07120       return;
07121    } 
07122    else if (((myrpt->inpadtest) || (c != myrpt->p.endchar)) && (myrpt->rem_dtmfidx >= 0))
07123    {
07124       time(&myrpt->rem_dtmf_time);
07125       if (myrpt->rem_dtmfidx < MAXDTMF)
07126       {
07127          myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx++] = c;
07128          myrpt->rem_dtmfbuf[myrpt->rem_dtmfidx] = 0;
07129          
07130          rpt_mutex_unlock(&myrpt->lock);
07131          strncpy(cmd, myrpt->rem_dtmfbuf, sizeof(cmd) - 1);
07132          switch(mylink->phonemode)
07133          {
07134              case 1:
07135             res = collect_function_digits(myrpt, cmd, 
07136                SOURCE_PHONE, mylink);
07137             break;
07138              case 2:
07139             res = collect_function_digits(myrpt, cmd, 
07140                SOURCE_DPHONE,mylink);
07141             break;
07142              case 4:
07143             res = collect_function_digits(myrpt, cmd, 
07144                SOURCE_ALT,mylink);
07145             break;
07146              default:
07147             res = collect_function_digits(myrpt, cmd, 
07148                SOURCE_LNK, mylink);
07149             break;
07150          }
07151 
07152          rpt_mutex_lock(&myrpt->lock);
07153          
07154          switch(res){
07155 
07156             case DC_INDETERMINATE:
07157                break;
07158             
07159             case DC_DOKEY:
07160                mylink->lastrealrx = 1;
07161                break;
07162             
07163             case DC_REQ_FLUSH:
07164                myrpt->rem_dtmfidx = 0;
07165                myrpt->rem_dtmfbuf[0] = 0;
07166                break;
07167             
07168             
07169             case DC_COMPLETE:
07170             case DC_COMPLETEQUIET:
07171                myrpt->totalexecdcommands++;
07172                myrpt->dailyexecdcommands++;
07173                strncpy(myrpt->lastdtmfcommand, cmd, MAXDTMF-1);
07174                myrpt->lastdtmfcommand[MAXDTMF-1] = '\0';
07175                myrpt->rem_dtmfbuf[0] = 0;
07176                myrpt->rem_dtmfidx = -1;
07177                myrpt->rem_dtmf_time = 0;
07178                break;
07179             
07180             case DC_ERROR:
07181             default:
07182                myrpt->rem_dtmfbuf[0] = 0;
07183                myrpt->rem_dtmfidx = -1;
07184                myrpt->rem_dtmf_time = 0;
07185                break;
07186          }
07187       }
07188 
07189    }
07190    rpt_mutex_unlock(&myrpt->lock);
07191    return;
07192 }
07193 
07194 /* Doug Hall RBI-1 serial data definitions:
07195  *
07196  * Byte 0: Expansion external outputs 
07197  * Byte 1: 
07198  * Bits 0-3 are BAND as follows:
07199  * Bits 4-5 are POWER bits as follows:
07200  *    00 - Low Power
07201  *    01 - Hi Power
07202  *    02 - Med Power
07203  * Bits 6-7 are always set
07204  * Byte 2:
07205  * Bits 0-3 MHZ in BCD format
07206  * Bits 4-5 are offset as follows:
07207  *    00 - minus
07208  *    01 - plus
07209  *    02 - simplex
07210  *    03 - minus minus (whatever that is)
07211  * Bit 6 is the 0/5 KHZ bit
07212  * Bit 7 is always set
07213  * Byte 3:
07214  * Bits 0-3 are 10 KHZ in BCD format
07215  * Bits 4-7 are 100 KHZ in BCD format
07216  * Byte 4: PL Tone code and encode/decode enable bits
07217  * Bits 0-5 are PL tone code (comspec binary codes)
07218  * Bit 6 is encode enable/disable
07219  * Bit 7 is decode enable/disable
07220  */
07221 
07222 /* take the frequency from the 10 mhz digits (and up) and convert it
07223    to a band number */
07224 
07225 static int rbi_mhztoband(char *str)
07226 {
07227 int   i;
07228 
07229    i = atoi(str) / 10; /* get the 10's of mhz */
07230    switch(i)
07231    {
07232        case 2:
07233       return 10;
07234        case 5:
07235       return 11;
07236        case 14:
07237       return 2;
07238        case 22:
07239       return 3;
07240        case 44:
07241       return 4;
07242        case 124:
07243       return 0;
07244        case 125:
07245       return 1;
07246        case 126:
07247       return 8;
07248        case 127:
07249       return 5;
07250        case 128:
07251       return 6;
07252        case 129:
07253       return 7;
07254        default:
07255       break;
07256    }
07257    return -1;
07258 }
07259 
07260 /* take a PL frequency and turn it into a code */
07261 static int rbi_pltocode(char *str)
07262 {
07263 int i;
07264 char *s;
07265 
07266    s = strchr(str,'.');
07267    i = 0;
07268    if (s) i = atoi(s + 1);
07269    i += atoi(str) * 10;
07270    switch(i)
07271    {
07272        case 670:
07273       return 0;
07274        case 719:
07275       return 1;
07276        case 744:
07277       return 2;
07278        case 770:
07279       return 3;
07280        case 797:
07281       return 4;
07282        case 825:
07283       return 5;
07284        case 854:
07285       return 6;
07286        case 885:
07287       return 7;
07288        case 915:
07289       return 8;
07290        case 948:
07291       return 9;
07292        case 974:
07293       return 10;
07294        case 1000:
07295       return 11;
07296        case 1035:
07297       return 12;
07298        case 1072:
07299       return 13;
07300        case 1109:
07301       return 14;
07302        case 1148:
07303       return 15;
07304        case 1188:
07305       return 16;
07306        case 1230:
07307       return 17;
07308        case 1273:
07309       return 18;
07310        case 1318:
07311       return 19;
07312        case 1365:
07313       return 20;
07314        case 1413:
07315       return 21;
07316        case 1462:
07317       return 22;
07318        case 1514:
07319       return 23;
07320        case 1567:
07321       return 24;
07322        case 1622:
07323       return 25;
07324        case 1679:
07325       return 26;
07326        case 1738:
07327       return 27;
07328        case 1799:
07329       return 28;
07330        case 1862:
07331       return 29;
07332        case 1928:
07333       return 30;
07334        case 2035:
07335       return 31;
07336        case 2107:
07337       return 32;
07338        case 2181:
07339       return 33;
07340        case 2257:
07341       return 34;
07342        case 2336:
07343       return 35;
07344        case 2418:
07345       return 36;
07346        case 2503:
07347       return 37;
07348    }
07349    return -1;
07350 }
07351 
07352 /*
07353 * Shift out a formatted serial bit stream
07354 */
07355 
07356 static void rbi_out_parallel(struct rpt *myrpt,unsigned char *data)
07357     {
07358 #ifdef __i386__
07359     int i,j;
07360     unsigned char od,d;
07361     static volatile long long delayvar;
07362 
07363     for(i = 0 ; i < 5 ; i++){
07364         od = *data++; 
07365         for(j = 0 ; j < 8 ; j++){
07366             d = od & 1;
07367             outb(d,myrpt->p.iobase);
07368        /* >= 15 us */
07369        for(delayvar = 1; delayvar < 15000; delayvar++); 
07370             od >>= 1;
07371             outb(d | 2,myrpt->p.iobase);
07372        /* >= 30 us */
07373        for(delayvar = 1; delayvar < 30000; delayvar++); 
07374             outb(d,myrpt->p.iobase);
07375        /* >= 10 us */
07376        for(delayvar = 1; delayvar < 10000; delayvar++); 
07377             }
07378         }
07379    /* >= 50 us */
07380         for(delayvar = 1; delayvar < 50000; delayvar++); 
07381 #endif
07382     }
07383 
07384 static void rbi_out(struct rpt *myrpt,unsigned char *data)
07385 {
07386 struct dahdi_radio_param r;
07387 
07388    memset(&r,0,sizeof(struct dahdi_radio_param));
07389    r.radpar = DAHDI_RADPAR_REMMODE;
07390    r.data = DAHDI_RADPAR_REM_RBI1;
07391    /* if setparam ioctl fails, its probably not a pciradio card */
07392    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&r) == -1)
07393    {
07394       rbi_out_parallel(myrpt,data);
07395       return;
07396    }
07397    r.radpar = DAHDI_RADPAR_REMCOMMAND;
07398    memcpy(&r.data,data,5);
07399    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&r) == -1)
07400    {
07401       ast_log(LOG_WARNING,"Cannot send RBI command for channel %s\n",myrpt->dahdirxchannel->name);
07402       return;
07403    }
07404 }
07405 
07406 static int serial_remote_io(struct rpt *myrpt, unsigned char *txbuf, int txbytes, 
07407    unsigned char *rxbuf, int rxmaxbytes, int asciiflag)
07408 {
07409    int i,j,idx,oldmode,olddata;
07410    struct dahdi_radio_param prm;
07411    char c;
07412 
07413     if(debug) {
07414        ast_log(LOG_NOTICE, "ioport=%s  iofd=0x%x\n",myrpt->p.ioport,myrpt->iofd);
07415       printf("String output was:\n");
07416       for(i = 0; i < txbytes; i++)
07417          printf("%02X ", (unsigned char ) txbuf[i]);
07418       printf("\n");
07419    }
07420 
07421    if (myrpt->iofd >= 0)  /* if to do out a serial port */
07422    {
07423       if (write(myrpt->iofd,txbuf,txbytes) != txbytes)
07424       {
07425          return -1;
07426       }
07427       if ((!rxmaxbytes) || (rxbuf == NULL)) 
07428       {
07429          return(0);
07430       }
07431       memset(rxbuf,0,rxmaxbytes);
07432       for(i = 0; i < rxmaxbytes; i++)
07433       {
07434          j = read(myrpt->iofd,&c,1);
07435          if (j < 1) 
07436          {
07437             return(i);
07438          }
07439          rxbuf[i] = c;
07440          if (asciiflag & 1)
07441          {
07442             rxbuf[i + 1] = 0;
07443             if (c == '\r') break;
07444          }
07445       }              
07446       if(debug) {
07447          printf("String returned was:\n");
07448          for(j = 0; j < i; j++)
07449             printf("%02X ", (unsigned char ) rxbuf[j]);
07450          printf("\n");
07451       }
07452       return(i);
07453    }
07454 
07455    /* if not a DAHDI channel, cant use pciradio stuff */
07456    if (myrpt->rxchannel != myrpt->dahdirxchannel) return -1;   
07457 
07458    prm.radpar = DAHDI_RADPAR_UIOMODE;
07459    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_GETPARAM,&prm) == -1) return -1;
07460    oldmode = prm.data;
07461    prm.radpar = DAHDI_RADPAR_UIODATA;
07462    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_GETPARAM,&prm) == -1) return -1;
07463    olddata = prm.data;
07464         prm.radpar = DAHDI_RADPAR_REMMODE;
07465         if (asciiflag & 1)  prm.data = DAHDI_RADPAR_REM_SERIAL_ASCII;
07466         else prm.data = DAHDI_RADPAR_REM_SERIAL;
07467    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07468    if (asciiflag & 2)
07469    {
07470       i = DAHDI_ONHOOK;
07471       if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_HOOK,&i) == -1) return -1;
07472       usleep(100000);
07473    }
07474         prm.radpar = DAHDI_RADPAR_REMCOMMAND;
07475         prm.data = rxmaxbytes;
07476         memcpy(prm.buf,txbuf,txbytes);
07477         prm.index = txbytes;
07478    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07479         if (rxbuf)
07480         {
07481                 *rxbuf = 0;
07482                 memcpy(rxbuf,prm.buf,prm.index);
07483         }
07484    idx = prm.index;
07485         prm.radpar = DAHDI_RADPAR_REMMODE;
07486         prm.data = DAHDI_RADPAR_REM_NONE;
07487    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07488    if (asciiflag & 2)
07489    {
07490       i = DAHDI_OFFHOOK;
07491       if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_HOOK,&i) == -1) return -1;
07492    }
07493    prm.radpar = DAHDI_RADPAR_UIOMODE;
07494    prm.data = oldmode;
07495    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07496    prm.radpar = DAHDI_RADPAR_UIODATA;
07497    prm.data = olddata;
07498    if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_RADIO_SETPARAM,&prm) == -1) return -1;
07499         return(idx);
07500 }
07501 
07502 static int civ_cmd(struct rpt *myrpt,unsigned char *cmd, int cmdlen)
07503 {
07504 unsigned char rxbuf[100];
07505 int   i,rv ;
07506 
07507    rv = serial_remote_io(myrpt,cmd,cmdlen,rxbuf,cmdlen + 6,0);
07508    if (rv == -1) return(-1);
07509    if (rv != (cmdlen + 6)) return(1);
07510    for(i = 0; i < 6; i++)
07511       if (rxbuf[i] != cmd[i]) return(1);
07512    if (rxbuf[cmdlen] != 0xfe) return(1);
07513    if (rxbuf[cmdlen + 1] != 0xfe) return(1);
07514    if (rxbuf[cmdlen + 4] != 0xfb) return(1);
07515    if (rxbuf[cmdlen + 5] != 0xfd) return(1);
07516    return(0);
07517 }
07518 
07519 static int sendkenwood(struct rpt *myrpt,char *txstr, char *rxstr)
07520 {
07521 int   i;
07522 
07523 ast_log(LOG_NOTICE,"Sent to kenwood: %s\n",txstr);
07524    if (debug) printf("Send to kenwood: %s\n",txstr);
07525    i = serial_remote_io(myrpt, (unsigned char *)txstr, strlen(txstr), 
07526       (unsigned char *)rxstr,RAD_SERIAL_BUFLEN - 1,3);
07527    if (i < 0) return -1;
07528    if ((i > 0) && (rxstr[i - 1] == '\r'))
07529       rxstr[i-- - 1] = 0;
07530    if (debug) printf("Got from kenwood: %s\n",rxstr);
07531 ast_log(LOG_NOTICE,"Got from kenwood: %s\n",rxstr);
07532    return(i);
07533 }
07534 
07535 /* take a PL frequency and turn it into a code */
07536 static int kenwood_pltocode(char *str)
07537 {
07538 int i;
07539 char *s;
07540 
07541    s = strchr(str,'.');
07542    i = 0;
07543    if (s) i = atoi(s + 1);
07544    i += atoi(str) * 10;
07545    switch(i)
07546    {
07547        case 670:
07548       return 1;
07549        case 719:
07550       return 3;
07551        case 744:
07552       return 4;
07553        case 770:
07554       return 5;
07555        case 797:
07556       return 6;
07557        case 825:
07558       return 7;
07559        case 854:
07560       return 8;
07561        case 885:
07562       return 9;
07563        case 915:
07564       return 10;
07565        case 948:
07566       return 11;
07567        case 974:
07568       return 12;
07569        case 1000:
07570       return 13;
07571        case 1035:
07572       return 14;
07573        case 1072:
07574       return 15;
07575        case 1109:
07576       return 16;
07577        case 1148:
07578       return 17;
07579        case 1188:
07580       return 18;
07581        case 1230:
07582       return 19;
07583        case 1273:
07584       return 20;
07585        case 1318:
07586       return 21;
07587        case 1365:
07588       return 22;
07589        case 1413:
07590       return 23;
07591        case 1462:
07592       return 24;
07593        case 1514:
07594       return 25;
07595        case 1567:
07596       return 26;
07597        case 1622:
07598       return 27;
07599        case 1679:
07600       return 28;
07601        case 1738:
07602       return 29;
07603        case 1799:
07604       return 30;
07605        case 1862:
07606       return 31;
07607        case 1928:
07608       return 32;
07609        case 2035:
07610       return 33;
07611        case 2107:
07612       return 34;
07613        case 2181:
07614       return 35;
07615        case 2257:
07616       return 36;
07617        case 2336:
07618       return 37;
07619        case 2418:
07620       return 38;
07621        case 2503:
07622       return 39;
07623    }
07624    return -1;
07625 }
07626 
07627 static int sendrxkenwood(struct rpt *myrpt, char *txstr, char *rxstr, 
07628    char *cmpstr)
07629 {
07630 int   i,j;
07631 
07632    for(i = 0;i < KENWOOD_RETRIES;i++)
07633    {
07634       j = sendkenwood(myrpt,txstr,rxstr);
07635       if (j < 0) return(j);
07636       if (j == 0) continue;
07637       if (!strncmp(rxstr,cmpstr,strlen(cmpstr))) return(0);
07638    }
07639    return(-1);
07640 }     
07641 
07642 static int setkenwood(struct rpt *myrpt)
07643 {
07644 char rxstr[RAD_SERIAL_BUFLEN],txstr[RAD_SERIAL_BUFLEN],freq[20];
07645 char mhz[MAXREMSTR],offset[20],band,decimals[MAXREMSTR],band1,band2;
07646 int myrxpl;
07647    
07648 int offsets[] = {0,2,1};
07649 int powers[] = {2,1,0};
07650 
07651    if (sendrxkenwood(myrpt,"VMC 0,0\r",rxstr,"VMC") < 0) return -1;
07652    split_freq(mhz, decimals, myrpt->freq);
07653    if (atoi(mhz) > 400)
07654    {
07655       band = '6';
07656       band1 = '1';
07657       band2 = '5';
07658       strcpy(offset,"005000000");
07659    }
07660    else
07661    {
07662       band = '2';
07663       band1 = '0';
07664       band2 = '2';
07665       strcpy(offset,"000600000");
07666    }
07667    strcpy(freq,"000000");
07668    strncpy(freq,decimals,strlen(decimals));
07669    myrxpl = myrpt->rxplon;
07670    if (IS_XPMR(myrpt)) myrxpl = 0;
07671    sprintf(txstr,"VW %c,%05d%s,0,%d,0,%d,%d,,%02d,,%02d,%s\r",
07672       band,atoi(mhz),freq,offsets[(int)myrpt->offset],
07673       (myrpt->txplon != 0),myrxpl,
07674       kenwood_pltocode(myrpt->txpl),kenwood_pltocode(myrpt->rxpl),
07675       offset);
07676    if (sendrxkenwood(myrpt,txstr,rxstr,"VW") < 0) return -1;
07677    sprintf(txstr,"RBN %c\r",band2);
07678    if (sendrxkenwood(myrpt,txstr,rxstr,"RBN") < 0) return -1;
07679    sprintf(txstr,"PC %c,%d\r",band1,powers[(int)myrpt->powerlevel]);
07680    if (sendrxkenwood(myrpt,txstr,rxstr,"PC") < 0) return -1;
07681    return 0;
07682 }
07683 
07684 static int set_tm271(struct rpt *myrpt)
07685 {
07686 char rxstr[RAD_SERIAL_BUFLEN],txstr[RAD_SERIAL_BUFLEN],freq[20];
07687 char mhz[MAXREMSTR],decimals[MAXREMSTR];
07688    
07689 int offsets[] = {0,2,1};
07690 int powers[] = {2,1,0};
07691 
07692    split_freq(mhz, decimals, myrpt->freq);
07693    strcpy(freq,"000000");
07694    strncpy(freq,decimals,strlen(decimals));
07695 
07696    sprintf(txstr,"VF %04d%s,4,%d,0,%d,0,0,%d,%d,000,00600000,0,0\r",
07697       atoi(mhz),freq,offsets[(int)myrpt->offset],
07698       (myrpt->txplon != 0),kenwood_pltocode(myrpt->txpl),
07699       kenwood_pltocode(myrpt->rxpl));
07700 
07701    if (sendrxkenwood(myrpt,txstr,rxstr,"VF") < 0) return -1;
07702    if (sendrxkenwood(myrpt,"VM 0\r",rxstr,"VM") < 0) return -1;
07703    sprintf(txstr,"PC %d\r",powers[(int)myrpt->powerlevel]);
07704    if (sendrxkenwood(myrpt,txstr,rxstr,"PC") < 0) return -1;
07705    return 0;
07706 }
07707 
07708 static int setrbi(struct rpt *myrpt)
07709 {
07710 char tmp[MAXREMSTR] = "",*s;
07711 unsigned char rbicmd[5];
07712 int   band,txoffset = 0,txpower = 0,rxpl;
07713 
07714    /* must be a remote system */
07715    if (!myrpt->remoterig) return(0);
07716    if (!myrpt->remoterig[0]) return(0);
07717    /* must have rbi hardware */
07718    if (strncmp(myrpt->remoterig,remote_rig_rbi,3)) return(0);
07719    if (setrbi_check(myrpt) == -1) return(-1);
07720    strncpy(tmp, myrpt->freq, sizeof(tmp) - 1);
07721    s = strchr(tmp,'.');
07722    /* if no decimal, is invalid */
07723    
07724    if (s == NULL){
07725       if(debug)
07726          printf("@@@@ Frequency needs a decimal\n");
07727       return -1;
07728    }
07729    
07730    *s++ = 0;
07731    if (strlen(tmp) < 2){
07732       if(debug)
07733          printf("@@@@ Bad MHz digits: %s\n", tmp);
07734       return -1;
07735    }
07736     
07737    if (strlen(s) < 3){
07738       if(debug)
07739          printf("@@@@ Bad KHz digits: %s\n", s);
07740       return -1;
07741    }
07742 
07743    if ((s[2] != '0') && (s[2] != '5')){
07744       if(debug)
07745          printf("@@@@ KHz must end in 0 or 5: %c\n", s[2]);
07746       return -1;
07747    }
07748     
07749    band = rbi_mhztoband(tmp);
07750    if (band == -1){
07751       if(debug)
07752          printf("@@@@ Bad Band: %s\n", tmp);
07753       return -1;
07754    }
07755    
07756    rxpl = rbi_pltocode(myrpt->rxpl);
07757    
07758    if (rxpl == -1){
07759       if(debug)
07760          printf("@@@@ Bad TX PL: %s\n", myrpt->rxpl);
07761       return -1;
07762    }
07763 
07764    
07765    switch(myrpt->offset)
07766    {
07767        case REM_MINUS:
07768       txoffset = 0;
07769       break;
07770        case REM_PLUS:
07771       txoffset = 0x10;
07772       break;
07773        case REM_SIMPLEX:
07774       txoffset = 0x20;
07775       break;
07776    }
07777    switch(myrpt->powerlevel)
07778    {
07779        case REM_LOWPWR:
07780       txpower = 0;
07781       break;
07782        case REM_MEDPWR:
07783       txpower = 0x20;
07784       break;
07785        case REM_HIPWR:
07786       txpower = 0x10;
07787       break;
07788    }
07789    rbicmd[0] = 0;
07790    rbicmd[1] = band | txpower | 0xc0;
07791    rbicmd[2] = (*(s - 2) - '0') | txoffset | 0x80;
07792    if (s[2] == '5') rbicmd[2] |= 0x40;
07793    rbicmd[3] = ((*s - '0') << 4) + (s[1] - '0');
07794    rbicmd[4] = rxpl;
07795    if (myrpt->txplon) rbicmd[4] |= 0x40;
07796    if (myrpt->rxplon) rbicmd[4] |= 0x80;
07797    rbi_out(myrpt,rbicmd);
07798    return 0;
07799 }
07800 
07801 static int setrtx(struct rpt *myrpt)
07802 {
07803 char tmp[MAXREMSTR] = "",*s,rigstr[200],pwr,res = 0;
07804 int   band,rxpl,txpl;
07805 float ofac;
07806 double txfreq;
07807 
07808    /* must be a remote system */
07809    if (!myrpt->remoterig) return(0);
07810    if (!myrpt->remoterig[0]) return(0);
07811    /* must have rtx hardware */
07812    if (!ISRIG_RTX(myrpt->remoterig)) return(0);
07813    /* must be a usbradio interface type */
07814    if (!IS_XPMR(myrpt)) return(0);
07815    strncpy(tmp, myrpt->freq, sizeof(tmp) - 1);
07816    s = strchr(tmp,'.');
07817    /* if no decimal, is invalid */
07818    
07819    if(debug)printf("setrtx() %s %s\n",myrpt->name,myrpt->remoterig);
07820 
07821    if (s == NULL){
07822       if(debug)
07823          printf("@@@@ Frequency needs a decimal\n");
07824       return -1;
07825    }
07826    *s++ = 0;
07827    if (strlen(tmp) < 2){
07828       if(debug)
07829          printf("@@@@ Bad MHz digits: %s\n", tmp);
07830       return -1;
07831    }
07832     
07833    if (strlen(s) < 3){
07834       if(debug)
07835          printf("@@@@ Bad KHz digits: %s\n", s);
07836       return -1;
07837    }
07838 
07839    if ((s[2] != '0') && (s[2] != '5')){
07840       if(debug)
07841          printf("@@@@ KHz must end in 0 or 5: %c\n", s[2]);
07842       return -1;
07843    }
07844     
07845    band = rbi_mhztoband(tmp);
07846    if (band == -1){
07847       if(debug)
07848          printf("@@@@ Bad Band: %s\n", tmp);
07849       return -1;
07850    }
07851    
07852    rxpl = rbi_pltocode(myrpt->rxpl);
07853    
07854    if (rxpl == -1){
07855       if(debug)
07856          printf("@@@@ Bad RX PL: %s\n", myrpt->rxpl);
07857       return -1;
07858    }
07859 
07860    txpl = rbi_pltocode(myrpt->txpl);
07861    
07862    if (txpl == -1){
07863       if(debug)
07864          printf("@@@@ Bad TX PL: %s\n", myrpt->txpl);
07865       return -1;
07866    }
07867 
07868    res = setrtx_check(myrpt);
07869    if (res < 0) return res;
07870    ofac = 0.0;
07871    if (myrpt->offset == REM_MINUS) ofac = -1.0;
07872    if (myrpt->offset == REM_PLUS) ofac = 1.0;
07873 
07874    if (!strcmp(myrpt->remoterig,remote_rig_rtx450))
07875       txfreq = atof(myrpt->freq) +  (ofac * 5.0);
07876    else
07877       txfreq = atof(myrpt->freq) +  (ofac * 0.6);
07878 
07879    pwr = 'L';
07880    if (myrpt->powerlevel == REM_HIPWR) pwr = 'H';
07881    if (!res)
07882    {
07883       sprintf(rigstr,"SETFREQ %s %f %s %s %c",myrpt->freq,txfreq,
07884          (myrpt->rxplon) ? myrpt->rxpl : "0.0",
07885          (myrpt->txplon) ? myrpt->txpl : "0.0",pwr);
07886       send_usb_txt(myrpt,rigstr);
07887       rpt_telemetry(myrpt,COMPLETE,NULL);
07888       res = 0;
07889    }
07890    return 0;
07891 }
07892 #if 0
07893 /*
07894    sets current signaling code for xpmr routines
07895    under development for new radios.
07896 */
07897 static int setxpmr(struct rpt *myrpt)
07898 {
07899    char rigstr[200];
07900    int rxpl,txpl;
07901 
07902    /* must be a remote system */
07903    if (!myrpt->remoterig) return(0);
07904    if (!myrpt->remoterig[0]) return(0);
07905    /* must not have rtx hardware */
07906    if (ISRIG_RTX(myrpt->remoterig)) return(0);
07907    /* must be a usbradio interface type */
07908    if (!IS_XPMR(myrpt)) return(0);
07909    
07910    if(debug)printf("setxpmr() %s %s\n",myrpt->name,myrpt->remoterig );
07911 
07912    rxpl = rbi_pltocode(myrpt->rxpl);
07913    
07914    if (rxpl == -1){
07915       if(debug)
07916          printf("@@@@ Bad RX PL: %s\n", myrpt->rxpl);
07917       return -1;
07918    }
07919 
07920    txpl = rbi_pltocode(myrpt->txpl);
07921    if (txpl == -1){
07922       if(debug)
07923          printf("@@@@ Bad TX PL: %s\n", myrpt->txpl);
07924       return -1;
07925    }
07926    sprintf(rigstr,"SETFREQ 0.0 0.0 %s %s L",
07927       (myrpt->rxplon) ? myrpt->rxpl : "0.0",
07928       (myrpt->txplon) ? myrpt->txpl : "0.0");
07929    send_usb_txt(myrpt,rigstr);
07930    return 0;
07931 }
07932 #endif
07933 
07934 static int setrbi_check(struct rpt *myrpt)
07935 {
07936 char tmp[MAXREMSTR] = "",*s;
07937 int   band,txpl;
07938 
07939    /* must be a remote system */
07940    if (!myrpt->remote) return(0);
07941    /* must have rbi hardware */
07942    if (strncmp(myrpt->remoterig,remote_rig_rbi,3)) return(0);
07943    strncpy(tmp, myrpt->freq, sizeof(tmp) - 1);
07944    s = strchr(tmp,'.');
07945    /* if no decimal, is invalid */
07946    
07947    if (s == NULL){
07948       if(debug)
07949          printf("@@@@ Frequency needs a decimal\n");
07950       return -1;
07951    }
07952    
07953    *s++ = 0;
07954    if (strlen(tmp) < 2){
07955       if(debug)
07956          printf("@@@@ Bad MHz digits: %s\n", tmp);
07957       return -1;
07958    }
07959     
07960    if (strlen(s) < 3){
07961       if(debug)
07962          printf("@@@@ Bad KHz digits: %s\n", s);
07963       return -1;
07964    }
07965 
07966    if ((s[2] != '0') && (s[2] != '5')){
07967       if(debug)
07968          printf("@@@@ KHz must end in 0 or 5: %c\n", s[2]);
07969       return -1;
07970    }
07971     
07972    band = rbi_mhztoband(tmp);
07973    if (band == -1){
07974       if(debug)
07975          printf("@@@@ Bad Band: %s\n", tmp);
07976       return -1;
07977    }
07978    
07979    txpl = rbi_pltocode(myrpt->txpl);
07980    
07981    if (txpl == -1){
07982       if(debug)
07983          printf("@@@@ Bad TX PL: %s\n", myrpt->txpl);
07984       return -1;
07985    }
07986    return 0;
07987 }
07988 
07989 static int setrtx_check(struct rpt *myrpt)
07990 {
07991 char tmp[MAXREMSTR] = "",*s;
07992 int   band,txpl,rxpl;
07993 
07994    /* must be a remote system */
07995    if (!myrpt->remote) return(0);
07996    /* must have rbi hardware */
07997    if (strncmp(myrpt->remoterig,remote_rig_rbi,3)) return(0);
07998    strncpy(tmp, myrpt->freq, sizeof(tmp) - 1);
07999    s = strchr(tmp,'.');
08000    /* if no decimal, is invalid */
08001    
08002    if (s == NULL){
08003       if(debug)
08004          printf("@@@@ Frequency needs a decimal\n");
08005       return -1;
08006    }
08007    
08008    *s++ = 0;
08009    if (strlen(tmp) < 2){
08010       if(debug)
08011          printf("@@@@ Bad MHz digits: %s\n", tmp);
08012       return -1;
08013    }
08014     
08015    if (strlen(s) < 3){
08016       if(debug)
08017          printf("@@@@ Bad KHz digits: %s\n", s);
08018       return -1;
08019    }
08020 
08021    if ((s[2] != '0') && (s[2] != '5')){
08022       if(debug)
08023          printf("@@@@ KHz must end in 0 or 5: %c\n", s[2]);
08024       return -1;
08025    }
08026     
08027    band = rbi_mhztoband(tmp);
08028    if (band == -1){
08029       if(debug)
08030          printf("@@@@ Bad Band: %s\n", tmp);
08031       return -1;
08032    }
08033    
08034    txpl = rbi_pltocode(myrpt->txpl);
08035    
08036    if (txpl == -1){
08037       if(debug)
08038          printf("@@@@ Bad TX PL: %s\n", myrpt->txpl);
08039       return -1;
08040    }
08041 
08042    rxpl = rbi_pltocode(myrpt->rxpl);
08043    
08044    if (rxpl == -1){
08045       if(debug)
08046          printf("@@@@ Bad RX PL: %s\n", myrpt->rxpl);
08047       return -1;
08048    }
08049    return 0;
08050 }
08051 
08052 static int check_freq_kenwood(int m, int d, int *defmode)
08053 {
08054    int dflmd = REM_MODE_FM;
08055 
08056    if (m == 144){ /* 2 meters */
08057       if(d < 10100)
08058          return -1;
08059    }
08060    else if((m >= 145) && (m < 148)){
08061       ;
08062    }
08063    else if((m >= 430) && (m < 450)){ /* 70 centimeters */
08064       ;
08065    }
08066    else
08067       return -1;
08068    
08069    if(defmode)
08070       *defmode = dflmd; 
08071 
08072 
08073    return 0;
08074 }
08075 
08076 
08077 static int check_freq_tm271(int m, int d, int *defmode)
08078 {
08079    int dflmd = REM_MODE_FM;
08080 
08081    if (m == 144){ /* 2 meters */
08082       if(d < 10100)
08083          return -1;
08084    }
08085    else if((m >= 145) && (m < 148)){
08086       ;
08087    }
08088       return -1;
08089    
08090    if(defmode)
08091       *defmode = dflmd; 
08092 
08093 
08094    return 0;
08095 }
08096 
08097 
08098 /* Check for valid rbi frequency */
08099 /* Hard coded limits now, configurable later, maybe? */
08100 
08101 static int check_freq_rbi(int m, int d, int *defmode)
08102 {
08103    int dflmd = REM_MODE_FM;
08104 
08105    if(m == 50){ /* 6 meters */
08106       if(d < 10100)
08107          return -1;
08108    }
08109    else if((m >= 51) && ( m < 54)){
08110                 ;
08111    }
08112    else if(m == 144){ /* 2 meters */
08113       if(d < 10100)
08114          return -1;
08115    }
08116    else if((m >= 145) && (m < 148)){
08117       ;
08118    }
08119    else if((m >= 222) && (m < 225)){ /* 1.25 meters */
08120       ;
08121    }
08122    else if((m >= 430) && (m < 450)){ /* 70 centimeters */
08123       ;
08124    }
08125    else if((m >= 1240) && (m < 1300)){ /* 23 centimeters */
08126       ;
08127    }
08128    else
08129       return -1;
08130    
08131    if(defmode)
08132       *defmode = dflmd; 
08133 
08134 
08135    return 0;
08136 }
08137 
08138 /* Check for valid rtx frequency */
08139 /* Hard coded limits now, configurable later, maybe? */
08140 
08141 static int check_freq_rtx(int m, int d, int *defmode, struct rpt *myrpt)
08142 {
08143    int dflmd = REM_MODE_FM;
08144 
08145    if (!strcmp(myrpt->remoterig,remote_rig_rtx150))
08146    {
08147 
08148       if(m == 144){ /* 2 meters */
08149          if(d < 10100)
08150             return -1;
08151       }
08152       else if((m >= 145) && (m < 148)){
08153          ;
08154       }
08155       else
08156          return -1;
08157    }
08158    else 
08159    {
08160       if((m >= 430) && (m < 450)){ /* 70 centimeters */
08161          ;
08162       }
08163       else
08164          return -1;
08165    }
08166    if(defmode)
08167       *defmode = dflmd; 
08168 
08169 
08170    return 0;
08171 }
08172 
08173 /*
08174  * Convert decimals of frequency to int
08175  */
08176 
08177 static int decimals2int(char *fraction)
08178 {
08179    int i;
08180    char len = strlen(fraction);
08181    int multiplier = 100000;
08182    int res = 0;
08183 
08184    if(!len)
08185       return 0;
08186    for( i = 0 ; i < len ; i++, multiplier /= 10)
08187       res += (fraction[i] - '0') * multiplier;
08188    return res;
08189 }
08190 
08191 
08192 /*
08193 * Split frequency into mhz and decimals
08194 */
08195  
08196 static int split_freq(char *mhz, char *decimals, char *freq)
08197 {
08198    char freq_copy[MAXREMSTR];
08199    char *decp;
08200 
08201    decp = strchr(strncpy(freq_copy, freq, MAXREMSTR),'.');
08202    if(decp){
08203       *decp++ = 0;
08204       strncpy(mhz, freq_copy, MAXREMSTR);
08205       strcpy(decimals, "00000");
08206       strncpy(decimals, decp, strlen(decp));
08207       decimals[5] = 0;
08208       return 0;
08209    }
08210    else
08211       return -1;
08212 
08213 }
08214    
08215 /*
08216 * Split ctcss frequency into hertz and decimal
08217 */
08218  
08219 static int split_ctcss_freq(char *hertz, char *decimal, char *freq)
08220 {
08221    char freq_copy[MAXREMSTR];
08222    char *decp;
08223 
08224    decp = strchr(strncpy(freq_copy, freq, MAXREMSTR),'.');
08225    if(decp){
08226       *decp++ = 0;
08227       strncpy(hertz, freq_copy, MAXREMSTR);
08228       strncpy(decimal, decp, strlen(decp));
08229       decimal[strlen(decp)] = '\0';
08230       return 0;
08231    }
08232    else
08233       return -1;
08234 }
08235 
08236 
08237 
08238 /*
08239 * FT-897 I/O handlers
08240 */
08241 
08242 /* Check to see that the frequency is valid */
08243 /* Hard coded limits now, configurable later, maybe? */
08244 
08245 
08246 static int check_freq_ft897(int m, int d, int *defmode)
08247 {
08248    int dflmd = REM_MODE_FM;
08249 
08250    if(m == 1){ /* 160 meters */
08251       dflmd =  REM_MODE_LSB; 
08252       if(d < 80000)
08253          return -1;
08254    }
08255    else if(m == 3){ /* 80 meters */
08256       dflmd = REM_MODE_LSB;
08257       if(d < 50000)
08258          return -1;
08259    }
08260    else if(m == 7){ /* 40 meters */
08261       dflmd = REM_MODE_LSB;
08262       if(d > 30000)
08263          return -1;
08264    }
08265    else if(m == 14){ /* 20 meters */
08266       dflmd = REM_MODE_USB;
08267       if(d > 35000)
08268          return -1;
08269    }
08270    else if(m == 18){ /* 17 meters */
08271       dflmd = REM_MODE_USB;
08272       if((d < 6800) || (d > 16800))
08273          return -1;
08274    }
08275    else if(m == 21){ /* 15 meters */
08276       dflmd = REM_MODE_USB;
08277       if((d < 20000) || (d > 45000))
08278          return -1;
08279    }
08280    else if(m == 24){ /* 12 meters */
08281       dflmd = REM_MODE_USB;
08282       if((d < 89000) || (d > 99000))
08283          return -1;
08284    }
08285    else if(m == 28){ /* 10 meters */
08286       dflmd = REM_MODE_USB;
08287    }
08288    else if(m == 29){ 
08289       if(d >= 51000)
08290          dflmd = REM_MODE_FM;
08291       else
08292          dflmd = REM_MODE_USB;
08293       if(d > 70000)
08294          return -1;
08295    }
08296    else if(m == 50){ /* 6 meters */
08297       if(d >= 30000)
08298          dflmd = REM_MODE_FM;
08299       else
08300          dflmd = REM_MODE_USB;
08301 
08302    }
08303    else if((m >= 51) && ( m < 54)){
08304       dflmd = REM_MODE_FM;
08305    }
08306    else if(m == 144){ /* 2 meters */
08307       if(d >= 30000)
08308          dflmd = REM_MODE_FM;
08309       else
08310          dflmd = REM_MODE_USB;
08311    }
08312    else if((m >= 145) && (m < 148)){
08313       dflmd = REM_MODE_FM;
08314    }
08315    else if((m >= 430) && (m < 450)){ /* 70 centimeters */
08316       if(m  < 438)
08317          dflmd = REM_MODE_USB;
08318       else
08319          dflmd = REM_MODE_FM;
08320       ;
08321    }
08322    else
08323       return -1;
08324 
08325    if(defmode)
08326       *defmode = dflmd;
08327 
08328    return 0;
08329 }
08330 
08331 /*
08332 * Set a new frequency for the FT897
08333 */
08334 
08335 static int set_freq_ft897(struct rpt *myrpt, char *newfreq)
08336 {
08337    unsigned char cmdstr[5];
08338    int m,d;
08339    char mhz[MAXREMSTR];
08340    char decimals[MAXREMSTR];
08341 
08342    if(debug) 
08343       printf("New frequency: %s\n",newfreq);
08344 
08345    if(split_freq(mhz, decimals, newfreq))
08346       return -1; 
08347 
08348    m = atoi(mhz);
08349    d = atoi(decimals);
08350 
08351    /* The FT-897 likes packed BCD frequencies */
08352 
08353    cmdstr[0] = ((m / 100) << 4) + ((m % 100)/10);        /* 100MHz 10Mhz */
08354    cmdstr[1] = ((m % 10) << 4) + (d / 10000);         /* 1MHz 100KHz */
08355    cmdstr[2] = (((d % 10000)/1000) << 4) + ((d % 1000)/ 100);  /* 10KHz 1KHz */
08356    cmdstr[3] = (((d % 100)/10) << 4) + (d % 10);         /* 100Hz 10Hz */
08357    cmdstr[4] = 0x01;                /* command */
08358 
08359    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08360 
08361 }
08362 
08363 /* ft-897 simple commands */
08364 
08365 static int simple_command_ft897(struct rpt *myrpt, char command)
08366 {
08367    unsigned char cmdstr[5];
08368    
08369    memset(cmdstr, 0, 5);
08370 
08371    cmdstr[4] = command; 
08372 
08373    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08374 
08375 }
08376 
08377 /* ft-897 offset */
08378 
08379 static int set_offset_ft897(struct rpt *myrpt, char offset)
08380 {
08381    unsigned char cmdstr[5];
08382    
08383    memset(cmdstr, 0, 5);
08384 
08385    switch(offset){
08386       case  REM_SIMPLEX:
08387          cmdstr[0] = 0x89;
08388          break;
08389 
08390       case  REM_MINUS:
08391          cmdstr[0] = 0x09;
08392          break;
08393       
08394       case  REM_PLUS:
08395          cmdstr[0] = 0x49;
08396          break;   
08397 
08398       default:
08399          return -1;
08400    }
08401 
08402    cmdstr[4] = 0x09; 
08403 
08404    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08405 }
08406 
08407 /* ft-897 mode */
08408 
08409 static int set_mode_ft897(struct rpt *myrpt, char newmode)
08410 {
08411    unsigned char cmdstr[5];
08412    
08413    memset(cmdstr, 0, 5);
08414    
08415    switch(newmode){
08416       case  REM_MODE_FM:
08417          cmdstr[0] = 0x08;
08418          break;
08419 
08420       case  REM_MODE_USB:
08421          cmdstr[0] = 0x01;
08422          break;
08423 
08424       case  REM_MODE_LSB:
08425          cmdstr[0] = 0x00;
08426          break;
08427 
08428       case  REM_MODE_AM:
08429          cmdstr[0] = 0x04;
08430          break;
08431       
08432       default:
08433          return -1;
08434    }
08435    cmdstr[4] = 0x07; 
08436 
08437    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08438 }
08439 
08440 /* Set tone encode and decode modes */
08441 
08442 static int set_ctcss_mode_ft897(struct rpt *myrpt, char txplon, char rxplon)
08443 {
08444    unsigned char cmdstr[5];
08445    
08446    memset(cmdstr, 0, 5);
08447    
08448    if(rxplon && txplon)
08449       cmdstr[0] = 0x2A; /* Encode and Decode */
08450    else if (!rxplon && txplon)
08451       cmdstr[0] = 0x4A; /* Encode only */
08452    else if (rxplon && !txplon)
08453       cmdstr[0] = 0x3A; /* Encode only */
08454    else
08455       cmdstr[0] = 0x8A; /* OFF */
08456 
08457    cmdstr[4] = 0x0A; 
08458 
08459    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08460 }
08461 
08462 
08463 /* Set transmit and receive ctcss tone frequencies */
08464 
08465 static int set_ctcss_freq_ft897(struct rpt *myrpt, char *txtone, char *rxtone)
08466 {
08467    unsigned char cmdstr[5];
08468    char hertz[MAXREMSTR],decimal[MAXREMSTR];
08469    int h,d; 
08470 
08471    memset(cmdstr, 0, 5);
08472 
08473    if(split_ctcss_freq(hertz, decimal, txtone))
08474       return -1; 
08475 
08476    h = atoi(hertz);
08477    d = atoi(decimal);
08478    
08479    cmdstr[0] = ((h / 100) << 4) + (h % 100)/ 10;
08480    cmdstr[1] = ((h % 10) << 4) + (d % 10);
08481    
08482    if(rxtone){
08483    
08484       if(split_ctcss_freq(hertz, decimal, rxtone))
08485          return -1; 
08486 
08487       h = atoi(hertz);
08488       d = atoi(decimal);
08489    
08490       cmdstr[2] = ((h / 100) << 4) + (h % 100)/ 10;
08491       cmdstr[3] = ((h % 10) << 4) + (d % 10);
08492    }
08493    cmdstr[4] = 0x0B; 
08494 
08495    return serial_remote_io(myrpt, cmdstr, 5, NULL, 0, 0);
08496 }  
08497 
08498 
08499 
08500 static int set_ft897(struct rpt *myrpt)
08501 {
08502    int res;
08503    
08504    if(debug)
08505       printf("@@@@ lock on\n");
08506 
08507    res = simple_command_ft897(myrpt, 0x00);  /* LOCK on */  
08508 
08509    if(debug)
08510       printf("@@@@ ptt off\n");
08511 
08512    if(!res)
08513       res = simple_command_ft897(myrpt, 0x88);     /* PTT off */
08514 
08515    if(debug)
08516       printf("Modulation mode\n");
08517 
08518    if(!res)
08519       res = set_mode_ft897(myrpt, myrpt->remmode);    /* Modulation mode */
08520 
08521    if(debug)
08522       printf("Split off\n");
08523 
08524    if(!res)
08525       simple_command_ft897(myrpt, 0x82);        /* Split off */
08526 
08527    if(debug)
08528       printf("Frequency\n");
08529 
08530    if(!res)
08531       res = set_freq_ft897(myrpt, myrpt->freq);    /* Frequency */
08532    if((myrpt->remmode == REM_MODE_FM)){
08533       if(debug)
08534          printf("Offset\n");
08535       if(!res)
08536          res = set_offset_ft897(myrpt, myrpt->offset);   /* Offset if FM */
08537       if((!res)&&(myrpt->rxplon || myrpt->txplon)){
08538          if(debug)
08539             printf("CTCSS tone freqs.\n");
08540          res = set_ctcss_freq_ft897(myrpt, myrpt->txpl, myrpt->rxpl); /* CTCSS freqs if CTCSS is enabled */
08541       }
08542       if(!res){
08543          if(debug)
08544             printf("CTCSS mode\n");
08545          res = set_ctcss_mode_ft897(myrpt, myrpt->txplon, myrpt->rxplon); /* CTCSS mode */
08546       }
08547    }
08548    if((myrpt->remmode == REM_MODE_USB)||(myrpt->remmode == REM_MODE_LSB)){
08549       if(debug)
08550          printf("Clarifier off\n");
08551       simple_command_ft897(myrpt, 0x85);        /* Clarifier off if LSB or USB */
08552    }
08553    return res;
08554 }
08555 
08556 static int closerem_ft897(struct rpt *myrpt)
08557 {
08558    simple_command_ft897(myrpt, 0x88); /* PTT off */
08559    return 0;
08560 }  
08561 
08562 /*
08563 * Bump frequency up or down by a small amount 
08564 * Return 0 if the new frequnecy is valid, or -1 if invalid
08565 * Interval is in Hz, resolution is 10Hz 
08566 */
08567 
08568 static int multimode_bump_freq_ft897(struct rpt *myrpt, int interval)
08569 {
08570    int m,d;
08571    char mhz[MAXREMSTR], decimals[MAXREMSTR];
08572 
08573    if(debug)
08574       printf("Before bump: %s\n", myrpt->freq);
08575 
08576    if(split_freq(mhz, decimals, myrpt->freq))
08577       return -1;
08578    
08579    m = atoi(mhz);
08580    d = atoi(decimals);
08581 
08582    d += (interval / 10); /* 10Hz resolution */
08583    if(d < 0){
08584       m--;
08585       d += 100000;
08586    }
08587    else if(d >= 100000){
08588       m++;
08589       d -= 100000;
08590    }
08591 
08592    if(check_freq_ft897(m, d, NULL)){
08593       if(debug)
08594          printf("Bump freq invalid\n");
08595       return -1;
08596    }
08597 
08598    snprintf(myrpt->freq, MAXREMSTR, "%d.%05d", m, d);
08599 
08600    if(debug)
08601       printf("After bump: %s\n", myrpt->freq);
08602 
08603    return set_freq_ft897(myrpt, myrpt->freq);   
08604 }
08605 
08606 
08607 
08608 /*
08609 * IC-706 I/O handlers
08610 */
08611 
08612 /* Check to see that the frequency is valid */
08613 /* returns 0 if frequency is valid          */
08614 
08615 static int check_freq_ic706(int m, int d, int *defmode, char mars)
08616 {
08617    int dflmd = REM_MODE_FM;
08618    int rv=0;
08619 
08620    if(debug > 6)
08621       ast_log(LOG_NOTICE,"(%i,%i,%i,%i)\n",m,d,*defmode,mars);
08622 
08623    /* first test for standard amateur radio bands */
08624 
08625    if(m == 1){                /* 160 meters */
08626       dflmd =  REM_MODE_LSB; 
08627       if(d < 80000)rv=-1;
08628    }
08629    else if(m == 3){           /* 80 meters */
08630       dflmd = REM_MODE_LSB;
08631       if(d < 50000)rv=-1;
08632    }
08633    else if(m == 7){           /* 40 meters */
08634       dflmd = REM_MODE_LSB;
08635       if(d > 30000)rv=-1;
08636    }
08637    else if(m == 14){             /* 20 meters */
08638       dflmd = REM_MODE_USB;
08639       if(d > 35000)rv=-1;
08640    }
08641    else if(m == 18){                      /* 17 meters */
08642       dflmd = REM_MODE_USB;
08643       if((d < 6800) || (d > 16800))rv=-1;
08644    }
08645    else if(m == 21){ /* 15 meters */
08646       dflmd = REM_MODE_USB;
08647       if((d < 20000) || (d > 45000))rv=-1;
08648    }
08649    else if(m == 24){ /* 12 meters */
08650       dflmd = REM_MODE_USB;
08651       if((d < 89000) || (d > 99000))rv=-1;
08652    }
08653    else if(m == 28){                      /* 10 meters */
08654       dflmd = REM_MODE_USB;
08655    }
08656    else if(m == 29){ 
08657       if(d >= 51000)
08658          dflmd = REM_MODE_FM;
08659       else
08660          dflmd = REM_MODE_USB;
08661       if(d > 70000)rv=-1;
08662    }
08663    else if(m == 50){                      /* 6 meters */
08664       if(d >= 30000)
08665          dflmd = REM_MODE_FM;
08666       else
08667          dflmd = REM_MODE_USB;
08668    }
08669    else if((m >= 51) && ( m < 54)){
08670       dflmd = REM_MODE_FM;
08671    }
08672    else if(m == 144){ /* 2 meters */
08673       if(d >= 30000)
08674          dflmd = REM_MODE_FM;
08675       else
08676          dflmd = REM_MODE_USB;
08677    }
08678    else if((m >= 145) && (m < 148)){
08679       dflmd = REM_MODE_FM;
08680    }
08681    else if((m >= 430) && (m < 450)){         /* 70 centimeters */
08682       if(m  < 438)
08683          dflmd = REM_MODE_USB;
08684       else
08685          dflmd = REM_MODE_FM;
08686    }
08687 
08688    /* check expanded coverage */
08689    if(mars && rv<0){
08690       if((m >= 450) && (m < 470)){        /* LMR */
08691          dflmd = REM_MODE_FM;
08692          rv=0;
08693       }
08694       else if((m >= 148) && (m < 174)){      /* LMR */
08695          dflmd = REM_MODE_FM;
08696          rv=0;
08697       }
08698       else if((m >= 138) && (m < 144)){      /* VHF-AM AIRCRAFT */
08699          dflmd = REM_MODE_AM;
08700          rv=0;
08701       }
08702       else if((m >= 108) && (m < 138)){      /* VHF-AM AIRCRAFT */
08703          dflmd = REM_MODE_AM;
08704          rv=0;
08705       }
08706       else if( (m==0 && d>=55000) || (m==1 && d<=75000) ){  /* AM BCB*/
08707          dflmd = REM_MODE_AM;
08708          rv=0;
08709       }
08710       else if( (m == 1 && d>75000) || (m>1 && m<30) ){      /* HF SWL*/
08711          dflmd = REM_MODE_AM;
08712          rv=0;
08713       }
08714    }
08715 
08716    if(defmode)
08717       *defmode = dflmd;
08718 
08719    if(debug > 1)
08720       ast_log(LOG_NOTICE,"(%i,%i,%i,%i) returning %i\n",m,d,*defmode,mars,rv);
08721 
08722    return rv;
08723 }
08724 
08725 /* take a PL frequency and turn it into a code */
08726 static int ic706_pltocode(char *str)
08727 {
08728    int i;
08729    char *s;
08730    int rv=-1;
08731 
08732    s = strchr(str,'.');
08733    i = 0;
08734    if (s) i = atoi(s + 1);
08735    i += atoi(str) * 10;
08736    switch(i)
08737    {
08738        case 670:
08739          rv=0;
08740        case 693:
08741          rv=1;
08742        case 719:
08743          rv=2;
08744        case 744:
08745          rv=3;
08746        case 770:
08747          rv=4;
08748        case 797:
08749          rv=5;
08750        case 825:
08751          rv=6;
08752        case 854:
08753          rv=7;
08754        case 885:
08755          rv=8;
08756        case 915:
08757          rv=9;
08758        case 948:
08759          rv=10;
08760        case 974:
08761          rv=11;
08762        case 1000:
08763          rv=12;
08764        case 1035:
08765          rv=13;
08766        case 1072:
08767          rv=14;
08768        case 1109:
08769          rv=15;
08770        case 1148:
08771          rv=16;
08772        case 1188:
08773          rv=17;
08774        case 1230:
08775          rv=18;
08776        case 1273:
08777          rv=19;
08778        case 1318:
08779          rv=20;
08780        case 1365:
08781          rv=21;
08782        case 1413:
08783          rv=22;
08784        case 1462:
08785          rv=23;
08786        case 1514:
08787          rv=24;
08788        case 1567:
08789          rv=25;
08790        case 1598:
08791          rv=26;
08792        case 1622:
08793          rv=27;
08794        case 1655:
08795          rv=28;      
08796        case 1679:
08797          rv=29;
08798        case 1713:
08799          rv=30;
08800        case 1738:
08801          rv=31;
08802        case 1773:
08803          rv=32;
08804        case 1799:
08805          rv=33;
08806         case 1835:
08807          rv=34;
08808        case 1862:
08809          rv=35;
08810        case 1899:
08811          rv=36;
08812        case 1928:
08813          rv=37;
08814        case 1966:
08815          rv=38;
08816        case 1995:
08817          rv=39;
08818        case 2035:
08819          rv=40;
08820        case 2065:
08821          rv=41;
08822        case 2107:
08823          rv=42;
08824        case 2181:
08825          rv=43;
08826        case 2257:
08827          rv=44;
08828        case 2291:
08829          rv=45;
08830        case 2336:
08831          rv=46;
08832        case 2418:
08833          rv=47;
08834        case 2503:
08835          rv=48;
08836        case 2541:
08837          rv=49;
08838    }
08839    if(debug > 1)
08840       ast_log(LOG_NOTICE,"%i  rv=%i\n",i, rv);
08841 
08842    return rv;
08843 }
08844 
08845 /* ic-706 simple commands */
08846 
08847 static int simple_command_ic706(struct rpt *myrpt, char command, char subcommand)
08848 {
08849    unsigned char cmdstr[10];
08850    
08851    cmdstr[0] = cmdstr[1] = 0xfe;
08852    cmdstr[2] = myrpt->p.civaddr;
08853    cmdstr[3] = 0xe0;
08854    cmdstr[4] = command;
08855    cmdstr[5] = subcommand;
08856    cmdstr[6] = 0xfd;
08857 
08858    return(civ_cmd(myrpt,cmdstr,7));
08859 }
08860 
08861 /*
08862 * Set a new frequency for the ic706
08863 */
08864 
08865 static int set_freq_ic706(struct rpt *myrpt, char *newfreq)
08866 {
08867    unsigned char cmdstr[20];
08868    char mhz[MAXREMSTR], decimals[MAXREMSTR];
08869    int m,d;
08870 
08871    if(debug) 
08872       ast_log(LOG_NOTICE,"newfreq:%s\n",newfreq);        
08873 
08874    if(split_freq(mhz, decimals, newfreq))
08875       return -1; 
08876 
08877    m = atoi(mhz);
08878    d = atoi(decimals);
08879 
08880    /* The ic-706 likes packed BCD frequencies */
08881 
08882    cmdstr[0] = cmdstr[1] = 0xfe;
08883    cmdstr[2] = myrpt->p.civaddr;
08884    cmdstr[3] = 0xe0;
08885    cmdstr[4] = 5;
08886    cmdstr[5] = ((d % 10) << 4);
08887    cmdstr[6] = (((d % 1000)/ 100) << 4) + ((d % 100)/10);
08888    cmdstr[7] = ((d / 10000) << 4) + ((d % 10000)/1000);
08889    cmdstr[8] = (((m % 100)/10) << 4) + (m % 10);
08890    cmdstr[9] = (m / 100);
08891    cmdstr[10] = 0xfd;
08892 
08893    return(civ_cmd(myrpt,cmdstr,11));
08894 }
08895 
08896 /* ic-706 offset */
08897 
08898 static int set_offset_ic706(struct rpt *myrpt, char offset)
08899 {
08900    unsigned char c;
08901 
08902    if(debug > 6)
08903       ast_log(LOG_NOTICE,"offset=%i\n",offset);
08904 
08905    switch(offset){
08906       case  REM_SIMPLEX:
08907          c = 0x10;
08908          break;
08909 
08910       case  REM_MINUS:
08911          c = 0x11;
08912          break;
08913       
08914       case  REM_PLUS:
08915          c = 0x12;
08916          break;   
08917 
08918       default:
08919          return -1;
08920    }
08921 
08922    return simple_command_ic706(myrpt,0x0f,c);
08923 
08924 }
08925 
08926 /* ic-706 mode */
08927 
08928 static int set_mode_ic706(struct rpt *myrpt, char newmode)
08929 {
08930    unsigned char c;
08931    
08932    if(debug > 6)
08933       ast_log(LOG_NOTICE,"newmode=%i\n",newmode);
08934 
08935    switch(newmode){
08936       case  REM_MODE_FM:
08937          c = 5;
08938          break;
08939 
08940       case  REM_MODE_USB:
08941          c = 1;
08942          break;
08943 
08944       case  REM_MODE_LSB:
08945          c = 0;
08946          break;
08947 
08948       case  REM_MODE_AM:
08949          c = 2;
08950          break;
08951       
08952       default:
08953          return -1;
08954    }
08955    return simple_command_ic706(myrpt,6,c);
08956 }
08957 
08958 /* Set tone encode and decode modes */
08959 
08960 static int set_ctcss_mode_ic706(struct rpt *myrpt, char txplon, char rxplon)
08961 {
08962    unsigned char cmdstr[10];
08963    int rv;
08964 
08965    if(debug > 6)
08966       ast_log(LOG_NOTICE,"txplon=%i  rxplon=%i \n",txplon,rxplon);
08967 
08968    cmdstr[0] = cmdstr[1] = 0xfe;
08969    cmdstr[2] = myrpt->p.civaddr;
08970    cmdstr[3] = 0xe0;
08971    cmdstr[4] = 0x16;
08972    cmdstr[5] = 0x42;
08973    cmdstr[6] = (txplon != 0);
08974    cmdstr[7] = 0xfd;
08975 
08976    rv = civ_cmd(myrpt,cmdstr,8);
08977    if (rv) return(-1);
08978 
08979    cmdstr[0] = cmdstr[1] = 0xfe;
08980    cmdstr[2] = myrpt->p.civaddr;
08981    cmdstr[3] = 0xe0;
08982    cmdstr[4] = 0x16;
08983    cmdstr[5] = 0x43;
08984    cmdstr[6] = (rxplon != 0);
08985    cmdstr[7] = 0xfd;
08986 
08987    return(civ_cmd(myrpt,cmdstr,8));
08988 }
08989 
08990 #if 0
08991 /* Set transmit and receive ctcss tone frequencies */
08992 
08993 static int set_ctcss_freq_ic706(struct rpt *myrpt, char *txtone, char *rxtone)
08994 {
08995    unsigned char cmdstr[10];
08996    char hertz[MAXREMSTR],decimal[MAXREMSTR];
08997    int h,d,rv;
08998 
08999    memset(cmdstr, 0, 5);
09000 
09001    if(debug > 6)
09002       ast_log(LOG_NOTICE,"txtone=%s  rxtone=%s \n",txtone,rxtone);
09003 
09004    if(split_ctcss_freq(hertz, decimal, txtone))
09005       return -1; 
09006 
09007    h = atoi(hertz);
09008    d = atoi(decimal);
09009    
09010    cmdstr[0] = cmdstr[1] = 0xfe;
09011    cmdstr[2] = myrpt->p.civaddr;
09012    cmdstr[3] = 0xe0;
09013    cmdstr[4] = 0x1b;
09014    cmdstr[5] = 0;
09015    cmdstr[6] = ((h / 100) << 4) + (h % 100)/ 10;
09016    cmdstr[7] = ((h % 10) << 4) + (d % 10);
09017    cmdstr[8] = 0xfd;
09018 
09019    rv = civ_cmd(myrpt,cmdstr,9);
09020    if (rv) return(-1);
09021 
09022    if (!rxtone) return(0);
09023 
09024    if(split_ctcss_freq(hertz, decimal, rxtone))
09025       return -1; 
09026 
09027    h = atoi(hertz);
09028    d = atoi(decimal);
09029 
09030    cmdstr[0] = cmdstr[1] = 0xfe;
09031    cmdstr[2] = myrpt->p.civaddr;
09032    cmdstr[3] = 0xe0;
09033    cmdstr[4] = 0x1b;
09034    cmdstr[5] = 1;
09035    cmdstr[6] = ((h / 100) << 4) + (h % 100)/ 10;
09036    cmdstr[7] = ((h % 10) << 4) + (d % 10);
09037    cmdstr[8] = 0xfd;
09038    return(civ_cmd(myrpt,cmdstr,9));
09039 }  
09040 #endif
09041 
09042 static int vfo_ic706(struct rpt *myrpt)
09043 {
09044    unsigned char cmdstr[10];
09045    
09046    cmdstr[0] = cmdstr[1] = 0xfe;
09047    cmdstr[2] = myrpt->p.civaddr;
09048    cmdstr[3] = 0xe0;
09049    cmdstr[4] = 7;
09050    cmdstr[5] = 0xfd;
09051 
09052    return(civ_cmd(myrpt,cmdstr,6));
09053 }
09054 
09055 static int mem2vfo_ic706(struct rpt *myrpt)
09056 {
09057    unsigned char cmdstr[10];
09058    
09059    cmdstr[0] = cmdstr[1] = 0xfe;
09060    cmdstr[2] = myrpt->p.civaddr;
09061    cmdstr[3] = 0xe0;
09062    cmdstr[4] = 0x0a;
09063    cmdstr[5] = 0xfd;
09064 
09065    return(civ_cmd(myrpt,cmdstr,6));
09066 }
09067 
09068 static int select_mem_ic706(struct rpt *myrpt, int slot)
09069 {
09070    unsigned char cmdstr[10];
09071    
09072    cmdstr[0] = cmdstr[1] = 0xfe;
09073    cmdstr[2] = myrpt->p.civaddr;
09074    cmdstr[3] = 0xe0;
09075    cmdstr[4] = 8;
09076    cmdstr[5] = 0;
09077    cmdstr[6] = ((slot / 10) << 4) + (slot % 10);
09078    cmdstr[7] = 0xfd;
09079 
09080    return(civ_cmd(myrpt,cmdstr,8));
09081 }
09082 
09083 static int set_ic706(struct rpt *myrpt)
09084 {
09085    int res = 0,i;
09086    
09087    if(debug)ast_log(LOG_NOTICE, "Set to VFO A iobase=%i\n",myrpt->p.iobase);
09088 
09089    if (!res)
09090       res = simple_command_ic706(myrpt,7,0);
09091 
09092    if((myrpt->remmode == REM_MODE_FM))
09093    {
09094       i = ic706_pltocode(myrpt->rxpl);
09095       if (i == -1) return -1;
09096       if(debug)
09097          printf("Select memory number\n");
09098       if (!res)
09099          res = select_mem_ic706(myrpt,i + IC706_PL_MEMORY_OFFSET);
09100       if(debug)
09101          printf("Transfer memory to VFO\n");
09102       if (!res)
09103          res = mem2vfo_ic706(myrpt);
09104    }
09105       
09106    if(debug)
09107       printf("Set to VFO\n");
09108 
09109    if (!res)
09110       res = vfo_ic706(myrpt);
09111 
09112    if(debug)
09113       printf("Modulation mode\n");
09114 
09115    if (!res)
09116       res = set_mode_ic706(myrpt, myrpt->remmode);    /* Modulation mode */
09117 
09118    if(debug)
09119       printf("Split off\n");
09120 
09121    if(!res)
09122       simple_command_ic706(myrpt, 0x82,0);         /* Split off */
09123 
09124    if(debug)
09125       printf("Frequency\n");
09126 
09127    if(!res)
09128       res = set_freq_ic706(myrpt, myrpt->freq);    /* Frequency */
09129    if((myrpt->remmode == REM_MODE_FM)){
09130       if(debug)
09131          printf("Offset\n");
09132       if(!res)
09133          res = set_offset_ic706(myrpt, myrpt->offset);   /* Offset if FM */
09134       if(!res){
09135          if(debug)
09136             printf("CTCSS mode\n");
09137          res = set_ctcss_mode_ic706(myrpt, myrpt->txplon, myrpt->rxplon); /* CTCSS mode */
09138       }
09139    }
09140    return res;
09141 }
09142 
09143 /*
09144 * Bump frequency up or down by a small amount 
09145 * Return 0 if the new frequnecy is valid, or -1 if invalid
09146 * Interval is in Hz, resolution is 10Hz 
09147 */
09148 
09149 static int multimode_bump_freq_ic706(struct rpt *myrpt, int interval)
09150 {
09151    int m,d;
09152    char mhz[MAXREMSTR], decimals[MAXREMSTR];
09153    unsigned char cmdstr[20];
09154 
09155    if(debug)
09156       printf("Before bump: %s\n", myrpt->freq);
09157 
09158    if(split_freq(mhz, decimals, myrpt->freq))
09159       return -1;
09160    
09161    m = atoi(mhz);
09162    d = atoi(decimals);
09163 
09164    d += (interval / 10); /* 10Hz resolution */
09165    if(d < 0){
09166       m--;
09167       d += 100000;
09168    }
09169    else if(d >= 100000){
09170       m++;
09171       d -= 100000;
09172    }
09173 
09174    if(check_freq_ic706(m, d, NULL,myrpt->p.remote_mars)){
09175       if(debug)
09176          printf("Bump freq invalid\n");
09177       return -1;
09178    }
09179 
09180    snprintf(myrpt->freq, MAXREMSTR, "%d.%05d", m, d);
09181 
09182    if(debug)
09183       printf("After bump: %s\n", myrpt->freq);
09184 
09185    /* The ic-706 likes packed BCD frequencies */
09186 
09187    cmdstr[0] = cmdstr[1] = 0xfe;
09188    cmdstr[2] = myrpt->p.civaddr;
09189    cmdstr[3] = 0xe0;
09190    cmdstr[4] = 0;
09191    cmdstr[5] = ((d % 10) << 4);
09192    cmdstr[6] = (((d % 1000)/ 100) << 4) + ((d % 100)/10);
09193    cmdstr[7] = ((d / 10000) << 4) + ((d % 10000)/1000);
09194    cmdstr[8] = (((m % 100)/10) << 4) + (m % 10);
09195    cmdstr[9] = (m / 100);
09196    cmdstr[10] = 0xfd;
09197 
09198    return(serial_remote_io(myrpt,cmdstr,11,NULL,0,0));
09199 }
09200 
09201 
09202 
09203 /*
09204 * Dispatch to correct I/O handler 
09205 */
09206 static int setrem(struct rpt *myrpt)
09207 {
09208 char  str[300];
09209 char  *offsets[] = {"SIMPLEX","MINUS","PLUS"};
09210 char  *powerlevels[] = {"LOW","MEDIUM","HIGH"};
09211 char  *modes[] = {"FM","USB","LSB","AM"};
09212 int   res = -1;
09213 
09214 #if   0
09215 printf("FREQ,%s,%s,%s,%s,%s,%s,%d,%d\n",myrpt->freq,
09216    modes[(int)myrpt->remmode],
09217    myrpt->txpl,myrpt->rxpl,offsets[(int)myrpt->offset],
09218    powerlevels[(int)myrpt->powerlevel],myrpt->txplon,
09219    myrpt->rxplon);
09220 #endif
09221    if (myrpt->p.archivedir)
09222    {
09223       sprintf(str,"FREQ,%s,%s,%s,%s,%s,%s,%d,%d",myrpt->freq,
09224          modes[(int)myrpt->remmode],
09225          myrpt->txpl,myrpt->rxpl,offsets[(int)myrpt->offset],
09226          powerlevels[(int)myrpt->powerlevel],myrpt->txplon,
09227          myrpt->rxplon);
09228       donodelog(myrpt,str);
09229    }
09230    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
09231    {
09232       rpt_telemetry(myrpt,SETREMOTE,NULL);
09233       res = 0;
09234    }
09235    if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09236    {
09237       rpt_telemetry(myrpt,SETREMOTE,NULL);
09238       res = 0;
09239    }
09240    if(!strcmp(myrpt->remoterig, remote_rig_tm271))
09241    {
09242       rpt_telemetry(myrpt,SETREMOTE,NULL);
09243       res = 0;
09244    }
09245    else if(!strcmp(myrpt->remoterig, remote_rig_rbi))
09246    {
09247       res = setrbi_check(myrpt);
09248       if (!res)
09249       {
09250          rpt_telemetry(myrpt,SETREMOTE,NULL);
09251          res = 0;
09252       }
09253    }
09254    else if(ISRIG_RTX(myrpt->remoterig))
09255    {
09256       setrtx(myrpt);
09257       res = 0;
09258    }
09259    else if(!strcmp(myrpt->remoterig, remote_rig_kenwood)) {
09260       rpt_telemetry(myrpt,SETREMOTE,NULL);
09261       res = 0;
09262    }
09263    else
09264       res = 0;
09265 
09266    if (res < 0) ast_log(LOG_ERROR,"Unable to send remote command on node %s\n",myrpt->name);
09267 
09268    return res;
09269 }
09270 
09271 static int closerem(struct rpt *myrpt)
09272 {
09273    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
09274       return closerem_ft897(myrpt);
09275    else
09276       return 0;
09277 }
09278 
09279 /*
09280 * Dispatch to correct RX frequency checker
09281 */
09282 
09283 static int check_freq(struct rpt *myrpt, int m, int d, int *defmode)
09284 {
09285    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
09286       return check_freq_ft897(m, d, defmode);
09287    else if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09288       return check_freq_ic706(m, d, defmode,myrpt->p.remote_mars);
09289    else if(!strcmp(myrpt->remoterig, remote_rig_rbi))
09290       return check_freq_rbi(m, d, defmode);
09291    else if(!strcmp(myrpt->remoterig, remote_rig_kenwood))
09292       return check_freq_kenwood(m, d, defmode);
09293    else if(!strcmp(myrpt->remoterig, remote_rig_tm271))
09294       return check_freq_tm271(m, d, defmode);
09295    else if(ISRIG_RTX(myrpt->remoterig))
09296       return check_freq_rtx(m, d, defmode, myrpt);
09297    else
09298       return -1;
09299 }
09300 
09301 /*
09302  * Check TX frequency before transmitting
09303    rv=1 if tx frequency in ok.
09304 */
09305 
09306 static char check_tx_freq(struct rpt *myrpt)
09307 {
09308    int i,rv=0;
09309    int radio_mhz, radio_decimals, ulimit_mhz, ulimit_decimals, llimit_mhz, llimit_decimals;
09310    char radio_mhz_char[MAXREMSTR];
09311    char radio_decimals_char[MAXREMSTR];
09312    char limit_mhz_char[MAXREMSTR];
09313    char limit_decimals_char[MAXREMSTR];
09314    char limits[256];
09315    char *limit_ranges[40];
09316    struct ast_variable *limitlist;
09317    
09318    if(debug > 3){
09319       ast_log(LOG_NOTICE, "myrpt->freq = %s\n", myrpt->freq);
09320    }
09321 
09322    /* Must have user logged in and tx_limits defined */
09323 
09324    if(!myrpt->p.txlimitsstanzaname || !myrpt->loginuser[0] || !myrpt->loginlevel[0]){
09325       if(debug > 3){
09326          ast_log(LOG_NOTICE, "No tx band table defined, or no user logged in. rv=1\n");
09327       }
09328       rv=1;
09329       return 1; /* Assume it's ok otherwise */
09330    }
09331 
09332    /* Retrieve the band table for the loginlevel */
09333    limitlist = ast_variable_browse(myrpt->cfg, myrpt->p.txlimitsstanzaname);
09334 
09335    if(!limitlist){
09336       ast_log(LOG_WARNING, "No entries in %s band table stanza. rv=0\n", myrpt->p.txlimitsstanzaname);
09337       rv=0;
09338       return 0;
09339    }
09340 
09341    split_freq(radio_mhz_char, radio_decimals_char, myrpt->freq);
09342    radio_mhz = atoi(radio_mhz_char);
09343    radio_decimals = decimals2int(radio_decimals_char);
09344 
09345    if(debug > 3){
09346       ast_log(LOG_NOTICE, "Login User = %s, login level = %s\n", myrpt->loginuser, myrpt->loginlevel);
09347    }
09348 
09349    /* Find our entry */
09350 
09351    for(;limitlist; limitlist=limitlist->next){
09352       if(!strcmp(limitlist->name, myrpt->loginlevel))
09353          break;
09354    }
09355 
09356    if(!limitlist){
09357       ast_log(LOG_WARNING, "Can't find %s entry in band table stanza %s. rv=0\n", myrpt->loginlevel, myrpt->p.txlimitsstanzaname);
09358       rv=0;
09359        return 0;
09360    }
09361    
09362    if(debug > 3){
09363       ast_log(LOG_NOTICE, "Auth: %s = %s\n", limitlist->name, limitlist->value);
09364    }
09365 
09366    /* Parse the limits */
09367 
09368    strncpy(limits, limitlist->value, 256);
09369    limits[255] = 0;
09370    finddelim(limits, limit_ranges, 40);
09371    for(i = 0; i < 40 && limit_ranges[i] ; i++){
09372       char range[40];
09373       char *r,*s;
09374       strncpy(range, limit_ranges[i], 40);
09375       range[39] = 0;
09376         if(debug > 3) 
09377          ast_log(LOG_NOTICE, "Check %s within %s\n", myrpt->freq, range);
09378    
09379       r = strchr(range, '-');
09380       if(!r){
09381          ast_log(LOG_WARNING, "Malformed range in %s tx band table entry. rv=0\n", limitlist->name);
09382          rv=0;
09383          break;
09384       }
09385       *r++ = 0;
09386       s = eatwhite(range);
09387       r = eatwhite(r);
09388       split_freq(limit_mhz_char, limit_decimals_char, s);
09389       llimit_mhz = atoi(limit_mhz_char);
09390       llimit_decimals = decimals2int(limit_decimals_char);
09391       split_freq(limit_mhz_char, limit_decimals_char, r);
09392       ulimit_mhz = atoi(limit_mhz_char);
09393       ulimit_decimals = decimals2int(limit_decimals_char);
09394          
09395       if((radio_mhz >= llimit_mhz) && (radio_mhz <= ulimit_mhz)){
09396          if(radio_mhz == llimit_mhz){ /* CASE 1: TX freq is in llimit mhz portion of band */
09397             if(radio_decimals >= llimit_decimals){ /* Cannot be below llimit decimals */
09398                if(llimit_mhz == ulimit_mhz){ /* If bandwidth < 1Mhz, check ulimit decimals */
09399                   if(radio_decimals <= ulimit_decimals){
09400                      rv=1;
09401                      break;
09402                   }
09403                   else{
09404                      if(debug > 3)
09405                         ast_log(LOG_NOTICE, "Invalid TX frequency, debug msg 1\n");
09406                      rv=0;
09407                      break;
09408                   }
09409                }
09410                else{
09411                   rv=1;
09412                   break;
09413                }
09414             }
09415             else{ /* Is below llimit decimals */
09416                if(debug > 3)
09417                   ast_log(LOG_NOTICE, "Invalid TX frequency, debug msg 2\n");
09418                rv=0;
09419                break;
09420             }
09421          }
09422          else if(radio_mhz == ulimit_mhz){ /* CASE 2: TX freq not in llimit mhz portion of band */
09423             if(radio_decimals <= ulimit_decimals){
09424                if(debug > 3)
09425                   ast_log(LOG_NOTICE, "radio_decimals <= ulimit_decimals\n");
09426                rv=1;
09427                break;
09428             }
09429             else{ /* Is above ulimit decimals */
09430                if(debug > 3)
09431                   ast_log(LOG_NOTICE, "Invalid TX frequency, debug msg 3\n");
09432                rv=0;
09433                break;
09434             }
09435          }
09436          else /* CASE 3: TX freq within a multi-Mhz band and ok */
09437             if(debug > 3)
09438                   ast_log(LOG_NOTICE, "Valid TX freq within a multi-Mhz band and ok.\n");
09439             rv=1;
09440             break;
09441       }
09442    }
09443    if(debug > 3)  
09444       ast_log(LOG_NOTICE, "rv=%i\n",rv);
09445 
09446    return rv;
09447 }
09448 
09449 
09450 /*
09451 * Dispatch to correct frequency bumping function
09452 */
09453 
09454 static int multimode_bump_freq(struct rpt *myrpt, int interval)
09455 {
09456    if(!strcmp(myrpt->remoterig, remote_rig_ft897))
09457       return multimode_bump_freq_ft897(myrpt, interval);
09458    else if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09459       return multimode_bump_freq_ic706(myrpt, interval);
09460    else
09461       return -1;
09462 }
09463 
09464 
09465 /*
09466 * Queue announcment that scan has been stopped 
09467 */
09468 
09469 static void stop_scan(struct rpt *myrpt)
09470 {
09471    myrpt->hfscanstop = 1;
09472    rpt_telemetry(myrpt,SCAN,0);
09473 }
09474 
09475 /*
09476 * This is called periodically when in scan mode
09477 */
09478 
09479 
09480 static int service_scan(struct rpt *myrpt)
09481 {
09482    int res, interval;
09483    char mhz[MAXREMSTR], decimals[MAXREMSTR], k10=0i, k100=0;
09484 
09485    switch(myrpt->hfscanmode){
09486 
09487       case HF_SCAN_DOWN_SLOW:
09488          interval = -10; /* 100Hz /sec */
09489          break;
09490 
09491       case HF_SCAN_DOWN_QUICK:
09492          interval = -50; /* 500Hz /sec */
09493          break;
09494 
09495       case HF_SCAN_DOWN_FAST:
09496          interval = -200; /* 2KHz /sec */
09497          break;
09498 
09499       case HF_SCAN_UP_SLOW:
09500          interval = 10; /* 100Hz /sec */
09501          break;
09502 
09503       case HF_SCAN_UP_QUICK:
09504          interval = 50; /* 500 Hz/sec */
09505          break;
09506 
09507       case HF_SCAN_UP_FAST:
09508          interval = 200; /* 2KHz /sec */
09509          break;
09510 
09511       default:
09512          myrpt->hfscanmode = 0; /* Huh? */
09513          return -1;
09514    }
09515 
09516    res = split_freq(mhz, decimals, myrpt->freq);
09517       
09518    if(!res){
09519       k100 =decimals[0];
09520       k10 = decimals[1];
09521       res = multimode_bump_freq(myrpt, interval);
09522    }
09523 
09524    if(!res)
09525       res = split_freq(mhz, decimals, myrpt->freq);
09526 
09527 
09528    if(res){
09529       myrpt->hfscanmode = 0;
09530       myrpt->hfscanstatus = -2;
09531       return -1;
09532    }
09533 
09534    /* Announce 10KHz boundaries */
09535    if(k10 != decimals[1]){
09536       int myhund = (interval < 0) ? k100 : decimals[0];
09537       int myten = (interval < 0) ? k10 : decimals[1];
09538       myrpt->hfscanstatus = (myten == '0') ? (myhund - '0') * 100 : (myten - '0') * 10;
09539    } else myrpt->hfscanstatus = 0;
09540    return res;
09541 
09542 }
09543 /*
09544    retrieve memory setting and set radio
09545 */
09546 static int get_mem_set(struct rpt *myrpt, char *digitbuf)
09547 {
09548    int res=0;
09549    if(debug)ast_log(LOG_NOTICE," digitbuf=%s\n", digitbuf);
09550    res = retreive_memory(myrpt, digitbuf);
09551    if(!res)res=setrem(myrpt); 
09552    if(debug)ast_log(LOG_NOTICE," freq=%s  res=%i\n", myrpt->freq, res);
09553    return res;
09554 }
09555 /*
09556    steer the radio selected channel to either one programmed into the radio
09557    or if the radio is VFO agile, to an rpt.conf memory location.
09558 */
09559 static int channel_steer(struct rpt *myrpt, char *data)
09560 {
09561    int res=0;
09562 
09563    if(debug)ast_log(LOG_NOTICE,"remoterig=%s, data=%s\n",myrpt->remoterig,data);
09564    if (!myrpt->remoterig) return(0);
09565    if(data<=0)
09566    {
09567       res=-1;
09568    }
09569    else
09570    {
09571       myrpt->nowchan=strtod(data,NULL);
09572       if(!strcmp(myrpt->remoterig, remote_rig_ppp16))
09573       {
09574          char string[16];
09575          sprintf(string,"SETCHAN %d ",myrpt->nowchan);
09576          send_usb_txt(myrpt,string);   
09577       }
09578       else
09579       {
09580          if(get_mem_set(myrpt, data))res=-1;
09581       }
09582    }
09583    if(debug)ast_log(LOG_NOTICE,"nowchan=%i  res=%i\n",myrpt->nowchan, res);
09584    return res;
09585 }
09586 /*
09587 */
09588 static int channel_revert(struct rpt *myrpt)
09589 {
09590    int res=0;
09591    if(debug)ast_log(LOG_NOTICE,"remoterig=%s, nowchan=%02d, waschan=%02d\n",myrpt->remoterig,myrpt->nowchan,myrpt->waschan);
09592    if (!myrpt->remoterig) return(0);
09593    if(myrpt->nowchan!=myrpt->waschan)
09594    {
09595       char data[8];
09596         if(debug)ast_log(LOG_NOTICE,"reverting.\n");
09597       sprintf(data,"%02d",myrpt->waschan);
09598       myrpt->nowchan=myrpt->waschan;
09599       channel_steer(myrpt,data);
09600       res=1;
09601    }
09602    return(res);
09603 }
09604 /*
09605 * Remote base function
09606 */
09607 
09608 static int function_remote(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink)
09609 {
09610    char *s,*s1,*s2;
09611    int i,j,r,ht,k,l,ls2,m,d,offset,offsave, modesave, defmode=0;
09612    intptr_t p;
09613    char multimode = 0;
09614    char oc,*cp,*cp1,*cp2;
09615    char tmp[20], freq[20] = "", savestr[20] = "";
09616    char mhz[MAXREMSTR], decimals[MAXREMSTR];
09617 
09618     if(debug > 6) {
09619       ast_log(LOG_NOTICE,"%s param=%s digitbuf=%s source=%i\n",myrpt->name,param,digitbuf,command_source);
09620    }
09621 
09622    if((!param) || (command_source == SOURCE_RPT) || (command_source == SOURCE_LNK))
09623       return DC_ERROR;
09624       
09625    p = myatoi(param);
09626 
09627    if ((p != 99) && (p != 5) && (p != 140) && myrpt->p.authlevel && 
09628       (!myrpt->loginlevel[0])) return DC_ERROR;
09629    multimode = multimode_capable(myrpt);
09630 
09631    switch(p){
09632 
09633       case 1:  /* retrieve memory */
09634          if(strlen(digitbuf) < 2) /* needs 2 digits */
09635             break;
09636          
09637          for(i = 0 ; i < 2 ; i++){
09638             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
09639                return DC_ERROR;
09640          }
09641          r=get_mem_set(myrpt, digitbuf);
09642          if (r < 0){
09643             rpt_telemetry(myrpt,MEMNOTFOUND,NULL);
09644             return DC_COMPLETE;
09645          }
09646          else if (r > 0){
09647             return DC_ERROR;
09648          }
09649          return DC_COMPLETE;  
09650          
09651       case 2:  /* set freq and offset */
09652       
09653          
09654             for(i = 0, j = 0, k = 0, l = 0 ; digitbuf[i] ; i++){ /* look for M+*K+*O or M+*H+* depending on mode */
09655             if(digitbuf[i] == '*'){
09656                j++;
09657                continue;
09658             }
09659             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
09660                goto invalid_freq;
09661             else{
09662                if(j == 0)
09663                   l++; /* # of digits before first * */
09664                if(j == 1)
09665                   k++; /* # of digits after first * */
09666             }
09667          }
09668       
09669          i = strlen(digitbuf) - 1;
09670          if(multimode){
09671             if((j > 2) || (l > 3) || (k > 6))
09672                goto invalid_freq; /* &^@#! */
09673          }
09674          else{
09675             if((j > 2) || (l > 4) || (k > 3))
09676                goto invalid_freq; /* &^@#! */
09677          }
09678 
09679          /* Wait for M+*K+* */
09680 
09681          if(j < 2)
09682             break; /* Not yet */
09683 
09684          /* We have a frequency */
09685 
09686          strncpy(tmp, digitbuf ,sizeof(tmp) - 1);
09687          
09688          s = tmp;
09689          s1 = strsep(&s, "*"); /* Pick off MHz */
09690          s2 = strsep(&s,"*"); /* Pick off KHz and Hz */
09691          ls2 = strlen(s2); 
09692          
09693          switch(ls2){ /* Allow partial entry of khz and hz digits for laziness support */
09694             case 1:
09695                ht = 0;
09696                k = 100 * atoi(s2);
09697                break;
09698             
09699             case 2:
09700                ht = 0;
09701                k = 10 * atoi(s2);
09702                break;
09703                
09704             case 3:
09705                if(!multimode){
09706                   if((s2[2] != '0')&&(s2[2] != '5'))
09707                      goto invalid_freq;
09708                }
09709                ht = 0;
09710                k = atoi(s2);
09711                   break;
09712             case 4:
09713                k = atoi(s2)/10;
09714                ht = 10 * (atoi(s2+(ls2-1)));
09715                break;
09716 
09717             case 5:
09718                k = atoi(s2)/100;
09719                ht = (atoi(s2+(ls2-2)));
09720                break;
09721                
09722             default:
09723                goto invalid_freq;
09724          }
09725 
09726          /* Check frequency for validity and establish a default mode */
09727          
09728          snprintf(freq, sizeof(freq), "%s.%03d%02d",s1, k, ht);
09729 
09730          if(debug)
09731             ast_log(LOG_NOTICE, "New frequency: %s\n", freq);
09732    
09733          split_freq(mhz, decimals, freq);
09734          m = atoi(mhz);
09735          d = atoi(decimals);
09736 
09737          if(check_freq(myrpt, m, d, &defmode)) /* Check to see if frequency entered is legit */
09738                  goto invalid_freq;
09739 
09740 
09741          if((defmode == REM_MODE_FM) && (digitbuf[i] == '*')) /* If FM, user must enter and additional offset digit */
09742             break; /* Not yet */
09743 
09744 
09745          offset = REM_SIMPLEX; /* Assume simplex */
09746 
09747          if(defmode == REM_MODE_FM){
09748             oc = *s; /* Pick off offset */
09749          
09750             if (oc){
09751                switch(oc){
09752                   case '1':
09753                      offset = REM_MINUS;
09754                      break;
09755                   
09756                   case '2':
09757                      offset = REM_SIMPLEX;
09758                   break;
09759                   
09760                   case '3':
09761                      offset = REM_PLUS;
09762                      break;
09763                   
09764                   default:
09765                      goto invalid_freq;
09766                } 
09767             } 
09768          }  
09769          offsave = myrpt->offset;
09770          modesave = myrpt->remmode;
09771          strncpy(savestr, myrpt->freq, sizeof(savestr) - 1);
09772          strncpy(myrpt->freq, freq, sizeof(myrpt->freq) - 1);
09773          myrpt->offset = offset;
09774          myrpt->remmode = defmode;
09775 
09776          if (setrem(myrpt) == -1){
09777             myrpt->offset = offsave;
09778             myrpt->remmode = modesave;
09779             strncpy(myrpt->freq, savestr, sizeof(myrpt->freq) - 1);
09780             goto invalid_freq;
09781          }
09782 
09783          return DC_COMPLETE;
09784 
09785 invalid_freq:
09786          rpt_telemetry(myrpt,INVFREQ,NULL);
09787          return DC_ERROR; 
09788       
09789       case 3: /* set rx PL tone */
09790             for(i = 0, j = 0, k = 0, l = 0 ; digitbuf[i] ; i++){ /* look for N+*N */
09791             if(digitbuf[i] == '*'){
09792                j++;
09793                continue;
09794             }
09795             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
09796                return DC_ERROR;
09797             else{
09798                if(j)
09799                   l++;
09800                else
09801                   k++;
09802             }
09803          }
09804          if((j > 1) || (k > 3) || (l > 1))
09805             return DC_ERROR; /* &$@^! */
09806          i = strlen(digitbuf) - 1;
09807          if((j != 1) || (k < 2)|| (l != 1))
09808             break; /* Not yet */
09809          if(debug)
09810             printf("PL digits entered %s\n", digitbuf);
09811             
09812          strncpy(tmp, digitbuf, sizeof(tmp) - 1);
09813          /* see if we have at least 1 */
09814          s = strchr(tmp,'*');
09815          if(s)
09816             *s = '.';
09817          strncpy(savestr, myrpt->rxpl, sizeof(savestr) - 1);
09818          strncpy(myrpt->rxpl, tmp, sizeof(myrpt->rxpl) - 1);
09819          if(!strcmp(myrpt->remoterig, remote_rig_rbi))
09820          {
09821             strncpy(myrpt->txpl, tmp, sizeof(myrpt->txpl) - 1);
09822          }
09823          if (setrem(myrpt) == -1){
09824             strncpy(myrpt->rxpl, savestr, sizeof(myrpt->rxpl) - 1);
09825             return DC_ERROR;
09826          }
09827          return DC_COMPLETE;
09828       
09829       case 4: /* set tx PL tone */
09830          /* cant set tx tone on RBI (rx tone does both) */
09831          if(!strcmp(myrpt->remoterig, remote_rig_rbi))
09832             return DC_ERROR;
09833          /*  eventually for the ic706 instead of just throwing the exception
09834             we can check if we are in encode only mode and allow the tx
09835             ctcss code to be changed. but at least the warning message is
09836             issued for now.
09837          */
09838          if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09839          {
09840             if(debug)
09841                ast_log(LOG_WARNING,"Setting IC706 Tx CTCSS Code Not Supported. Set Rx Code for both.\n");
09842             return DC_ERROR;
09843          }
09844          for(i = 0, j = 0, k = 0, l = 0 ; digitbuf[i] ; i++){ /* look for N+*N */
09845             if(digitbuf[i] == '*'){
09846                j++;
09847                continue;
09848             }
09849             if((digitbuf[i] < '0') || (digitbuf[i] > '9'))
09850                return DC_ERROR;
09851             else{
09852                if(j)
09853                   l++;
09854                else
09855                   k++;
09856             }
09857          }
09858          if((j > 1) || (k > 3) || (l > 1))
09859             return DC_ERROR; /* &$@^! */
09860          i = strlen(digitbuf) - 1;
09861          if((j != 1) || (k < 2)|| (l != 1))
09862             break; /* Not yet */
09863          if(debug)
09864             printf("PL digits entered %s\n", digitbuf);
09865             
09866          strncpy(tmp, digitbuf, sizeof(tmp) - 1);
09867          /* see if we have at least 1 */
09868          s = strchr(tmp,'*');
09869          if(s)
09870             *s = '.';
09871          strncpy(savestr, myrpt->txpl, sizeof(savestr) - 1);
09872          strncpy(myrpt->txpl, tmp, sizeof(myrpt->txpl) - 1);
09873          
09874          if (setrem(myrpt) == -1){
09875             strncpy(myrpt->txpl, savestr, sizeof(myrpt->txpl) - 1);
09876             return DC_ERROR;
09877          }
09878          return DC_COMPLETE;
09879       
09880 
09881       case 6: /* MODE (FM,USB,LSB,AM) */
09882          if(strlen(digitbuf) < 1)
09883             break;
09884 
09885          if(!multimode)
09886             return DC_ERROR; /* Multimode radios only */
09887 
09888          switch(*digitbuf){
09889             case '1':
09890                split_freq(mhz, decimals, myrpt->freq); 
09891                m=atoi(mhz);
09892                if(m < 29) /* No FM allowed below 29MHz! */
09893                   return DC_ERROR;
09894                myrpt->remmode = REM_MODE_FM;
09895                
09896                rpt_telemetry(myrpt,REMMODE,NULL);
09897                break;
09898 
09899             case '2':
09900                myrpt->remmode = REM_MODE_USB;
09901                rpt_telemetry(myrpt,REMMODE,NULL);
09902                break;   
09903 
09904             case '3':
09905                myrpt->remmode = REM_MODE_LSB;
09906                rpt_telemetry(myrpt,REMMODE,NULL);
09907                break;
09908             
09909             case '4':
09910                myrpt->remmode = REM_MODE_AM;
09911                rpt_telemetry(myrpt,REMMODE,NULL);
09912                break;
09913       
09914             default:
09915                return DC_ERROR;
09916          }
09917 
09918          if(setrem(myrpt))
09919             return DC_ERROR;
09920          return DC_COMPLETEQUIET;
09921       case 99:
09922          /* cant log in when logged in */
09923          if (myrpt->loginlevel[0]) 
09924             return DC_ERROR;
09925          *myrpt->loginuser = 0;
09926          myrpt->loginlevel[0] = 0;
09927          cp = ast_strdup(param);
09928          cp1 = strchr(cp,',');
09929          ast_mutex_lock(&myrpt->lock);
09930          if (cp1) 
09931          {
09932             *cp1 = 0;
09933             cp2 = strchr(cp1 + 1,',');
09934             if (cp2) 
09935             {
09936                *cp2 = 0;
09937                strncpy(myrpt->loginlevel,cp2 + 1,
09938                   sizeof(myrpt->loginlevel) - 1);
09939             }
09940             strncpy(myrpt->loginuser,cp1 + 1,sizeof(myrpt->loginuser));
09941             ast_mutex_unlock(&myrpt->lock);
09942             if (myrpt->p.archivedir)
09943             {
09944                char str[100];
09945 
09946                sprintf(str,"LOGIN,%s,%s",
09947                    myrpt->loginuser,myrpt->loginlevel);
09948                donodelog(myrpt,str);
09949             }
09950             if (debug) 
09951                printf("loginuser %s level %s\n",myrpt->loginuser,myrpt->loginlevel);
09952             rpt_telemetry(myrpt,REMLOGIN,NULL);
09953          }
09954          ast_free(cp);
09955          return DC_COMPLETEQUIET;
09956       case 100: /* RX PL Off */
09957          myrpt->rxplon = 0;
09958          setrem(myrpt);
09959          rpt_telemetry(myrpt,REMXXX,(void *)p);
09960          return DC_COMPLETEQUIET;
09961       case 101: /* RX PL On */
09962          myrpt->rxplon = 1;
09963          setrem(myrpt);
09964          rpt_telemetry(myrpt,REMXXX,(void *)p);
09965          return DC_COMPLETEQUIET;
09966       case 102: /* TX PL Off */
09967          myrpt->txplon = 0;
09968          setrem(myrpt);
09969          rpt_telemetry(myrpt,REMXXX,(void *)p);
09970          return DC_COMPLETEQUIET;
09971       case 103: /* TX PL On */
09972          myrpt->txplon = 1;
09973          setrem(myrpt);
09974          rpt_telemetry(myrpt,REMXXX,(void *)p);
09975          return DC_COMPLETEQUIET;
09976       case 104: /* Low Power */
09977          if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09978             return DC_ERROR;
09979          myrpt->powerlevel = REM_LOWPWR;
09980          setrem(myrpt);
09981          rpt_telemetry(myrpt,REMXXX,(void *)p);
09982          return DC_COMPLETEQUIET;
09983       case 105: /* Medium Power */
09984          if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09985             return DC_ERROR;
09986          if (ISRIG_RTX(myrpt->remoterig)) return DC_ERROR;
09987          myrpt->powerlevel = REM_MEDPWR;
09988          setrem(myrpt);
09989          rpt_telemetry(myrpt,REMXXX,(void *)p);
09990          return DC_COMPLETEQUIET;
09991       case 106: /* Hi Power */
09992          if(!strcmp(myrpt->remoterig, remote_rig_ic706))
09993             return DC_ERROR;
09994          myrpt->powerlevel = REM_HIPWR;
09995          setrem(myrpt);
09996          rpt_telemetry(myrpt,REMXXX,(void *)p);
09997          return DC_COMPLETEQUIET;
09998       case 107: /* Bump down 20Hz */
09999          multimode_bump_freq(myrpt, -20);
10000          return DC_COMPLETE;
10001       case 108: /* Bump down 100Hz */
10002          multimode_bump_freq(myrpt, -100);
10003          return DC_COMPLETE;
10004       case 109: /* Bump down 500Hz */
10005          multimode_bump_freq(myrpt, -500);
10006          return DC_COMPLETE;
10007       case 110: /* Bump up 20Hz */
10008          multimode_bump_freq(myrpt, 20);
10009          return DC_COMPLETE;
10010       case 111: /* Bump up 100Hz */
10011          multimode_bump_freq(myrpt, 100);
10012          return DC_COMPLETE;
10013       case 112: /* Bump up 500Hz */
10014          multimode_bump_freq(myrpt, 500);
10015          return DC_COMPLETE;
10016       case 113: /* Scan down slow */
10017          myrpt->scantimer = REM_SCANTIME;
10018          myrpt->hfscanmode = HF_SCAN_DOWN_SLOW;
10019          rpt_telemetry(myrpt,REMXXX,(void *)p);
10020          return DC_COMPLETEQUIET;
10021       case 114: /* Scan down quick */
10022          myrpt->scantimer = REM_SCANTIME;
10023          myrpt->hfscanmode = HF_SCAN_DOWN_QUICK;
10024          rpt_telemetry(myrpt,REMXXX,(void *)p);
10025          return DC_COMPLETEQUIET;
10026       case 115: /* Scan down fast */
10027          myrpt->scantimer = REM_SCANTIME;
10028          myrpt->hfscanmode = HF_SCAN_DOWN_FAST;
10029          rpt_telemetry(myrpt,REMXXX,(void *)p);
10030          return DC_COMPLETEQUIET;
10031       case 116: /* Scan up slow */
10032          myrpt->scantimer = REM_SCANTIME;
10033          myrpt->hfscanmode = HF_SCAN_UP_SLOW;
10034          rpt_telemetry(myrpt,REMXXX,(void *)p);
10035          return DC_COMPLETEQUIET;
10036       case 117: /* Scan up quick */
10037          myrpt->scantimer = REM_SCANTIME;
10038          myrpt->hfscanmode = HF_SCAN_UP_QUICK;
10039          rpt_telemetry(myrpt,REMXXX,(void *)p);
10040          return DC_COMPLETEQUIET;
10041       case 118: /* Scan up fast */
10042          myrpt->scantimer = REM_SCANTIME;
10043          myrpt->hfscanmode = HF_SCAN_UP_FAST;
10044          rpt_telemetry(myrpt,REMXXX,(void *)p);
10045          return DC_COMPLETEQUIET;
10046       case 119: /* Tune Request */
10047          if(debug > 3)
10048             ast_log(LOG_NOTICE,"TUNE REQUEST\n");
10049          /* if not currently going, and valid to do */
10050          if((!myrpt->tunerequest) && 
10051              ((!strcmp(myrpt->remoterig, remote_rig_ft897) || 
10052             !strcmp(myrpt->remoterig, remote_rig_ic706)) )) { 
10053             myrpt->remotetx = 0;
10054             ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_UNKEY);
10055             myrpt->tunerequest = 1;
10056             rpt_telemetry(myrpt,TUNE,NULL);
10057             return DC_COMPLETEQUIET;
10058          }
10059          return DC_ERROR;        
10060       case 5: /* Long Status */
10061          rpt_telemetry(myrpt,REMLONGSTATUS,NULL);
10062          return DC_COMPLETEQUIET;
10063       case 140: /* Short Status */
10064          rpt_telemetry(myrpt,REMSHORTSTATUS,NULL);
10065          return DC_COMPLETEQUIET;
10066       case 200:
10067       case 201:
10068       case 202:
10069       case 203:
10070       case 204:
10071       case 205:
10072       case 206:
10073       case 207:
10074       case 208:
10075       case 209:
10076       case 210:
10077       case 211:
10078       case 212:
10079       case 213:
10080       case 214:
10081       case 215:
10082          do_dtmf_local(myrpt,remdtmfstr[p - 200]);
10083          return DC_COMPLETEQUIET;
10084       default:
10085          break;
10086    }
10087    return DC_INDETERMINATE;
10088 }
10089 
10090 
10091 static int handle_remote_dtmf_digit(struct rpt *myrpt,char c, char *keyed, int phonemode)
10092 {
10093 time_t   now;
10094 int   ret,res = 0,src;
10095 
10096    if(debug > 6)
10097       ast_log(LOG_NOTICE,"c=%c  phonemode=%i  dtmfidx=%i\n",c,phonemode,myrpt->dtmfidx);
10098 
10099    time(&myrpt->last_activity_time);
10100    /* Stop scan mode if in scan mode */
10101    if(myrpt->hfscanmode){
10102       stop_scan(myrpt);
10103       return 0;
10104    }
10105 
10106    time(&now);
10107    /* if timed-out */
10108    if ((myrpt->dtmf_time_rem + DTMF_TIMEOUT) < now)
10109    {
10110       myrpt->dtmfidx = -1;
10111       myrpt->dtmfbuf[0] = 0;
10112       myrpt->dtmf_time_rem = 0;
10113    }
10114    /* if decode not active */
10115    if (myrpt->dtmfidx == -1)
10116    {
10117       /* if not lead-in digit, don't worry */
10118       if (c != myrpt->p.funcchar)
10119       {
10120          if (!myrpt->p.propagate_dtmf)
10121          {
10122             rpt_mutex_lock(&myrpt->lock);
10123             do_dtmf_local(myrpt,c);
10124             rpt_mutex_unlock(&myrpt->lock);
10125          }
10126          return 0;
10127       }
10128       myrpt->dtmfidx = 0;
10129       myrpt->dtmfbuf[0] = 0;
10130       myrpt->dtmf_time_rem = now;
10131       return 0;
10132    }
10133    /* if too many in buffer, start over */
10134    if (myrpt->dtmfidx >= MAXDTMF)
10135    {
10136       myrpt->dtmfidx = 0;
10137       myrpt->dtmfbuf[0] = 0;
10138       myrpt->dtmf_time_rem = now;
10139    }
10140    if (c == myrpt->p.funcchar)
10141    {
10142       /* if star at beginning, or 2 together, erase buffer */
10143       if ((myrpt->dtmfidx < 1) || 
10144          (myrpt->dtmfbuf[myrpt->dtmfidx - 1] == myrpt->p.funcchar))
10145       {
10146          myrpt->dtmfidx = 0;
10147          myrpt->dtmfbuf[0] = 0;
10148          myrpt->dtmf_time_rem = now;
10149          return 0;
10150       }
10151    }
10152    myrpt->dtmfbuf[myrpt->dtmfidx++] = c;
10153    myrpt->dtmfbuf[myrpt->dtmfidx] = 0;
10154    myrpt->dtmf_time_rem = now;
10155    
10156    
10157    src = SOURCE_RMT;
10158    if (phonemode == 2) src = SOURCE_DPHONE;
10159    else if (phonemode) src = SOURCE_PHONE;
10160    else if (phonemode == 4) src = SOURCE_ALT;
10161    ret = collect_function_digits(myrpt, myrpt->dtmfbuf, src, NULL);
10162    
10163    switch(ret){
10164    
10165       case DC_INDETERMINATE:
10166          res = 0;
10167          break;
10168             
10169       case DC_DOKEY:
10170          if (keyed) *keyed = 1;
10171          res = 0;
10172          break;
10173             
10174       case DC_REQ_FLUSH:
10175          myrpt->dtmfidx = 0;
10176          myrpt->dtmfbuf[0] = 0;
10177          res = 0;
10178          break;
10179             
10180             
10181       case DC_COMPLETE:
10182          res = 1;
10183       case DC_COMPLETEQUIET:
10184          myrpt->totalexecdcommands++;
10185          myrpt->dailyexecdcommands++;
10186          strncpy(myrpt->lastdtmfcommand, myrpt->dtmfbuf, MAXDTMF-1);
10187          myrpt->lastdtmfcommand[MAXDTMF-1] = '\0';
10188          myrpt->dtmfbuf[0] = 0;
10189          myrpt->dtmfidx = -1;
10190          myrpt->dtmf_time_rem = 0;
10191          break;
10192             
10193       case DC_ERROR:
10194       default:
10195          myrpt->dtmfbuf[0] = 0;
10196          myrpt->dtmfidx = -1;
10197          myrpt->dtmf_time_rem = 0;
10198          res = 0;
10199          break;
10200    }
10201 
10202    return res;
10203 }
10204 
10205 static int handle_remote_data(struct rpt *myrpt, char *str)
10206 {
10207 /* XXX ATTENTION: if you change the size of these arrays you MUST
10208  * change the limits in corresponding sscanf() calls below. */
10209 char  tmp[300],cmd[300],dest[300],src[300],c;
10210 int   seq,res;
10211 
10212    /* put string in our buffer */
10213    strncpy(tmp,str,sizeof(tmp) - 1);
10214    if (!strcmp(tmp,discstr)) return 0;
10215         if (!strcmp(tmp,newkeystr))
10216         {
10217       myrpt->newkey = 1;
10218                 return 0;
10219         }
10220 
10221 #ifndef  DO_NOT_NOTIFY_MDC1200_ON_REMOTE_BASES
10222    if (tmp[0] == 'I')
10223    {
10224       /* XXX WARNING: be very careful with the limits on the folowing
10225        * sscanf() call, make sure they match the values defined above */
10226       if (sscanf(tmp,"%299s %299s %30x",cmd,src,&seq) != 3)
10227       {
10228          ast_log(LOG_WARNING, "Unable to parse ident string %s\n",str);
10229          return 0;
10230       }
10231       mdc1200_notify(myrpt,src,seq);
10232       return 0;
10233    }
10234 #endif
10235    /* XXX WARNING: be very careful with the limits on the folowing
10236     * sscanf() call, make sure they match the values defined above */
10237    if (sscanf(tmp,"%299s %299s %299s %30d %1c",cmd,dest,src,&seq,&c) != 5)
10238    {
10239       ast_log(LOG_WARNING, "Unable to parse link string %s\n",str);
10240       return 0;
10241    }
10242    if (strcmp(cmd,"D"))
10243    {
10244       ast_log(LOG_WARNING, "Unable to parse link string %s\n",str);
10245       return 0;
10246    }
10247    /* if not for me, ignore */
10248    if (strcmp(dest,myrpt->name)) return 0;
10249    if (myrpt->p.archivedir)
10250    {
10251       char dtmfstr[100];
10252 
10253       sprintf(dtmfstr,"DTMF,%c",c);
10254       donodelog(myrpt,dtmfstr);
10255    }
10256    c = func_xlat(myrpt,c,&myrpt->p.outxlat);
10257    if (!c) return(0);
10258    res = handle_remote_dtmf_digit(myrpt,c, NULL, 0);
10259    if (res != 1)
10260       return res;
10261    rpt_telemetry(myrpt,COMPLETE,NULL);
10262    return 0;
10263 }
10264 
10265 static int handle_remote_phone_dtmf(struct rpt *myrpt, char c, char *keyed, int phonemode)
10266 {
10267 int   res;
10268 
10269 
10270    if(phonemode == 3) /* simplex phonemode, funcchar key/unkey toggle */
10271    {
10272       if (keyed && *keyed && ((c == myrpt->p.funcchar) || (c == myrpt->p.endchar)))
10273       {
10274          *keyed = 0; /* UNKEY */
10275          return 0;
10276       }
10277       else if (keyed && !*keyed && (c = myrpt->p.funcchar))
10278       {
10279          *keyed = 1; /* KEY */
10280          return 0;
10281       }
10282    }
10283    else /* endchar unkey */
10284    {
10285 
10286       if (keyed && *keyed && (c == myrpt->p.endchar))
10287       {
10288          *keyed = 0;
10289          return DC_INDETERMINATE;
10290       }
10291    }
10292    if (myrpt->p.archivedir)
10293    {
10294       char str[100];
10295 
10296       sprintf(str,"DTMF(P),%c",c);
10297       donodelog(myrpt,str);
10298    }
10299    res = handle_remote_dtmf_digit(myrpt,c,keyed, phonemode);
10300    if (res != 1)
10301       return res;
10302    rpt_telemetry(myrpt,COMPLETE,NULL);
10303    return 0;
10304 }
10305 
10306 static int attempt_reconnect(struct rpt *myrpt, struct rpt_link *l)
10307 {
10308    char *val, *s, *s1, *tele;
10309    char tmp[300], deststr[300] = "";
10310    char sx[320],*sy;
10311 
10312 
10313    val = node_lookup(myrpt,l->name);
10314    if (!val)
10315    {
10316       fprintf(stderr,"attempt_reconnect: cannot find node %s\n",l->name);
10317       return -1;
10318    }
10319 
10320    rpt_mutex_lock(&myrpt->lock);
10321    /* remove from queue */
10322    remque((struct qelem *) l);
10323    rpt_mutex_unlock(&myrpt->lock);
10324    strncpy(tmp,val,sizeof(tmp) - 1);
10325    s = tmp;
10326    s1 = strsep(&s,",");
10327    if (!strchr(s1,':') && strchr(s1,'/') && strncasecmp(s1, "local/", 6))
10328    {
10329       sy = strchr(s1,'/');    
10330       *sy = 0;
10331       sprintf(sx,"%s:4569/%s",s1,sy + 1);
10332       s1 = sx;
10333    }
10334    strsep(&s,",");
10335    snprintf(deststr, sizeof(deststr), "IAX2/%s", s1);
10336    tele = strchr(deststr, '/');
10337    if (!tele) {
10338       fprintf(stderr,"attempt_reconnect:Dial number (%s) must be in format tech/number\n",deststr);
10339       return -1;
10340    }
10341    *tele++ = 0;
10342    l->elaptime = 0;
10343    l->connecttime = 0;
10344    l->thisconnected = 0;
10345    l->newkey = 0;
10346    l->chan = ast_request(deststr, AST_FORMAT_SLINEAR, NULL, tele, NULL);
10347    if (l->chan){
10348       ast_set_read_format(l->chan, AST_FORMAT_SLINEAR);
10349       ast_set_write_format(l->chan, AST_FORMAT_SLINEAR);
10350 #ifndef  NEW_ASTERISK
10351       l->chan->whentohangup = 0;
10352 #endif
10353       l->chan->appl = "Apprpt";
10354       l->chan->data = "(Remote Rx)";
10355       if (option_verbose > 2)
10356          ast_verbose(VERBOSE_PREFIX_3 "rpt (attempt_reconnect) initiating call to %s/%s on %s\n",
10357             deststr, tele, l->chan->name);
10358       l->chan->caller.id.number.valid = 1;
10359       ast_free(l->chan->caller.id.number.str);
10360       l->chan->caller.id.number.str = ast_strdup(myrpt->name);
10361                 ast_call(l->chan,tele,999); 
10362 
10363    }
10364    else 
10365    {
10366       if (option_verbose > 2)
10367          ast_verbose(VERBOSE_PREFIX_3 "Unable to place call to %s/%s on %s\n",
10368             deststr,tele,l->chan->name);
10369       return -1;
10370    }
10371    rpt_mutex_lock(&myrpt->lock);
10372    /* put back in queue */
10373    insque((struct qelem *)l,(struct qelem *)myrpt->links.next);
10374    rpt_mutex_unlock(&myrpt->lock);
10375    ast_log(LOG_WARNING,"Reconnect Attempt to %s in process\n",l->name);
10376    if (!l->phonemode) send_newkey(l->chan);
10377    return 0;
10378 }
10379 
10380 /* 0 return=continue, 1 return = break, -1 return = error */
10381 static void local_dtmf_helper(struct rpt *myrpt,char c_in)
10382 {
10383 int   res;
10384 pthread_attr_t attr;
10385 char  cmd[MAXDTMF+1] = "",c;
10386 
10387 
10388    c = c_in & 0x7f;
10389    if (myrpt->p.archivedir)
10390    {
10391       char str[100];
10392 
10393       sprintf(str,"DTMF,MAIN,%c",c);
10394       donodelog(myrpt,str);
10395    }
10396    if (c == myrpt->p.endchar)
10397    {
10398    /* if in simple mode, kill autopatch */
10399       if (myrpt->p.simple && myrpt->callmode)
10400       {   
10401          if(debug)
10402             ast_log(LOG_WARNING, "simple mode autopatch kill\n");
10403          rpt_mutex_lock(&myrpt->lock);
10404          myrpt->callmode = 0;
10405          myrpt->macropatch=0;
10406          channel_revert(myrpt);
10407          rpt_mutex_unlock(&myrpt->lock);
10408          rpt_telemetry(myrpt,TERM,NULL);
10409          return;
10410       }
10411       rpt_mutex_lock(&myrpt->lock);
10412       myrpt->stopgen = 1;
10413       if (myrpt->cmdnode[0])
10414       {
10415          myrpt->cmdnode[0] = 0;
10416          myrpt->dtmfidx = -1;
10417          myrpt->dtmfbuf[0] = 0;
10418          rpt_mutex_unlock(&myrpt->lock);
10419          rpt_telemetry(myrpt,COMPLETE,NULL);
10420          return;
10421       } 
10422       else if(!myrpt->inpadtest)
10423                 {
10424                         rpt_mutex_unlock(&myrpt->lock);
10425                         if (myrpt->p.propagate_phonedtmf)
10426                                do_dtmf_phone(myrpt,NULL,c);
10427          return;
10428                 }
10429       else
10430          rpt_mutex_unlock(&myrpt->lock);
10431    }
10432    rpt_mutex_lock(&myrpt->lock);
10433    if (myrpt->cmdnode[0])
10434    {
10435       rpt_mutex_unlock(&myrpt->lock);
10436       send_link_dtmf(myrpt,c);
10437       return;
10438    }
10439    if (!myrpt->p.simple)
10440    {
10441       if ((!myrpt->inpadtest)&&(c == myrpt->p.funcchar))
10442       {
10443          myrpt->dtmfidx = 0;
10444          myrpt->dtmfbuf[myrpt->dtmfidx] = 0;
10445          rpt_mutex_unlock(&myrpt->lock);
10446          time(&myrpt->dtmf_time);
10447          return;
10448       } 
10449       else if (((myrpt->inpadtest)||(c != myrpt->p.endchar)) && (myrpt->dtmfidx >= 0))
10450       {
10451          time(&myrpt->dtmf_time);
10452          
10453          if (myrpt->dtmfidx < MAXDTMF)
10454          {
10455             int src;
10456 
10457             myrpt->dtmfbuf[myrpt->dtmfidx++] = c;
10458             myrpt->dtmfbuf[myrpt->dtmfidx] = 0;
10459             
10460             strncpy(cmd, myrpt->dtmfbuf, sizeof(cmd) - 1);
10461             
10462             rpt_mutex_unlock(&myrpt->lock);
10463             src = SOURCE_RPT;
10464             if (c_in & 0x80) src = SOURCE_ALT;
10465             res = collect_function_digits(myrpt, cmd, src, NULL);
10466             rpt_mutex_lock(&myrpt->lock);
10467             switch(res){
10468                 case DC_INDETERMINATE:
10469                break;
10470                 case DC_REQ_FLUSH:
10471                myrpt->dtmfidx = 0;
10472                myrpt->dtmfbuf[0] = 0;
10473                break;
10474                 case DC_COMPLETE:
10475                 case DC_COMPLETEQUIET:
10476                myrpt->totalexecdcommands++;
10477                myrpt->dailyexecdcommands++;
10478                strncpy(myrpt->lastdtmfcommand, cmd, MAXDTMF-1);
10479                myrpt->lastdtmfcommand[MAXDTMF-1] = '\0';
10480                myrpt->dtmfbuf[0] = 0;
10481                myrpt->dtmfidx = -1;
10482                myrpt->dtmf_time = 0;
10483                break;
10484 
10485                 case DC_ERROR:
10486                 default:
10487                myrpt->dtmfbuf[0] = 0;
10488                myrpt->dtmfidx = -1;
10489                myrpt->dtmf_time = 0;
10490                break;
10491             }
10492             if(res != DC_INDETERMINATE) {
10493                rpt_mutex_unlock(&myrpt->lock);
10494                return;
10495             }
10496          } 
10497       }
10498    }
10499    else /* if simple */
10500    {
10501       if ((!myrpt->callmode) && (c == myrpt->p.funcchar))
10502       {
10503          myrpt->callmode = 1;
10504          myrpt->patchnoct = 0;
10505          myrpt->patchquiet = 0;
10506          myrpt->patchfarenddisconnect = 0;
10507          myrpt->patchdialtime = 0;
10508          strncpy(myrpt->patchcontext, myrpt->p.ourcontext, MAXPATCHCONTEXT);
10509          myrpt->cidx = 0;
10510          myrpt->exten[myrpt->cidx] = 0;
10511          rpt_mutex_unlock(&myrpt->lock);
10512               pthread_attr_init(&attr);
10513               pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
10514          ast_pthread_create(&myrpt->rpt_call_thread,&attr,rpt_call,(void *)myrpt);
10515          return;
10516       }
10517    }
10518    if (myrpt->callmode == 1)
10519    {
10520       myrpt->exten[myrpt->cidx++] = c;
10521       myrpt->exten[myrpt->cidx] = 0;
10522       /* if this exists */
10523       if (ast_exists_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
10524       {
10525          /* if this really it, end now */
10526          if (!ast_matchmore_extension(myrpt->pchannel,myrpt->patchcontext,
10527             myrpt->exten,1,NULL)) 
10528          {
10529             myrpt->callmode = 2;
10530             rpt_mutex_unlock(&myrpt->lock);
10531             if(!myrpt->patchquiet)
10532                rpt_telemetry(myrpt,PROC,NULL); 
10533             return;
10534          }
10535          else /* othewise, reset timer */
10536          {
10537             myrpt->calldigittimer = 1;
10538          }
10539       }
10540       /* if can continue, do so */
10541       if (!ast_canmatch_extension(myrpt->pchannel,myrpt->patchcontext,myrpt->exten,1,NULL))
10542       {
10543          /* call has failed, inform user */
10544          myrpt->callmode = 4;
10545       }
10546       rpt_mutex_unlock(&myrpt->lock);
10547       return;
10548    }
10549    if ((myrpt->callmode == 2) || (myrpt->callmode == 3))
10550    {
10551       myrpt->mydtmf = c;
10552    }
10553    rpt_mutex_unlock(&myrpt->lock);
10554    if ((myrpt->dtmfidx < 0) && myrpt->p.propagate_phonedtmf)
10555       do_dtmf_phone(myrpt,NULL,c);
10556    return;
10557 }
10558 
10559 
10560 /* place an ID event in the telemetry queue */
10561 
10562 static void queue_id(struct rpt *myrpt)
10563 {
10564    if(myrpt->p.idtime){ /* ID time must be non-zero */
10565       myrpt->mustid = myrpt->tailid = 0;
10566       myrpt->idtimer = myrpt->p.idtime; /* Reset our ID timer */
10567       rpt_mutex_unlock(&myrpt->lock);
10568       rpt_telemetry(myrpt,ID,NULL);
10569       rpt_mutex_lock(&myrpt->lock);
10570    }
10571 }
10572 
10573 /* Scheduler */
10574 /* must be called locked */
10575 
10576 static void do_scheduler(struct rpt *myrpt)
10577 {
10578    int i,res;
10579 
10580 #ifdef   NEW_ASTERISK
10581    struct ast_tm tmnow;
10582 #else
10583    struct tm tmnow;
10584 #endif
10585    struct ast_variable *skedlist;
10586    char *strs[5],*vp,*val,value[100];
10587 
10588    memcpy(&myrpt->lasttv, &myrpt->curtv, sizeof(struct timeval));
10589    
10590    if( (res = gettimeofday(&myrpt->curtv, NULL)) < 0)
10591       ast_log(LOG_NOTICE, "Scheduler gettime of day returned: %s\n", strerror(res));
10592 
10593    /* Try to get close to a 1 second resolution */
10594    
10595    if(myrpt->lasttv.tv_sec == myrpt->curtv.tv_sec)
10596       return;
10597 
10598    rpt_localtime(&myrpt->curtv.tv_sec, &tmnow);
10599 
10600    /* If midnight, then reset all daily statistics */
10601    
10602    if((tmnow.tm_hour == 0)&&(tmnow.tm_min == 0)&&(tmnow.tm_sec == 0)){
10603       myrpt->dailykeyups = 0;
10604       myrpt->dailytxtime = 0;
10605       myrpt->dailykerchunks = 0;
10606       myrpt->dailyexecdcommands = 0;
10607    }
10608 
10609    if(tmnow.tm_sec != 0)
10610       return;
10611 
10612    /* Code below only executes once per minute */
10613 
10614 
10615    /* Don't schedule if remote */
10616 
10617         if (myrpt->remote)
10618                 return;
10619 
10620    /* Don't schedule if disabled */
10621 
10622         if(myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable){
10623       if(debug > 6)
10624          ast_log(LOG_NOTICE, "Scheduler disabled\n");
10625       return;
10626    }
10627 
10628    if(!myrpt->p.skedstanzaname){ /* No stanza means we do nothing */
10629       if(debug > 6)
10630          ast_log(LOG_NOTICE,"No stanza for scheduler in rpt.conf\n");
10631       return;
10632    }
10633 
10634     /* get pointer to linked list of scheduler entries */
10635     skedlist = ast_variable_browse(myrpt->cfg, myrpt->p.skedstanzaname);
10636 
10637    if(debug > 6){
10638       ast_log(LOG_NOTICE, "Time now: %02d:%02d %02d %02d %02d\n",
10639          tmnow.tm_hour,tmnow.tm_min,tmnow.tm_mday,tmnow.tm_mon + 1, tmnow.tm_wday); 
10640    }
10641    /* walk the list */
10642    for(; skedlist; skedlist = skedlist->next){
10643       if(debug > 6)
10644          ast_log(LOG_NOTICE, "Scheduler entry %s = %s being considered\n",skedlist->name, skedlist->value);
10645       strncpy(value,skedlist->value,99);
10646       value[99] = 0;
10647       /* point to the substrings for minute, hour, dom, month, and dow */
10648       for( i = 0, vp = value ; i < 5; i++){
10649          if(!*vp)
10650             break;
10651          while((*vp == ' ') || (*vp == 0x09)) /* get rid of any leading white space */
10652             vp++;
10653          strs[i] = vp; /* save pointer to beginning of substring */
10654          while((*vp != ' ') && (*vp != 0x09) && (*vp != 0)) /* skip over substring */
10655             vp++;
10656          if(*vp)
10657             *vp++ = 0; /* mark end of substring */
10658       }
10659       if(debug > 6)
10660          ast_log(LOG_NOTICE, "i = %d, min = %s, hour = %s, mday=%s, mon=%s, wday=%s\n",i,
10661             strs[0], strs[1], strs[2], strs[3], strs[4]); 
10662       if(i == 5){
10663          if((*strs[0] != '*')&&(atoi(strs[0]) != tmnow.tm_min))
10664             continue;
10665          if((*strs[1] != '*')&&(atoi(strs[1]) != tmnow.tm_hour))
10666             continue;
10667          if((*strs[2] != '*')&&(atoi(strs[2]) != tmnow.tm_mday))
10668             continue;
10669          if((*strs[3] != '*')&&(atoi(strs[3]) != tmnow.tm_mon + 1))
10670             continue;
10671          if(atoi(strs[4]) == 7)
10672             strs[4] = "0";
10673          if((*strs[4] != '*')&&(atoi(strs[4]) != tmnow.tm_wday))
10674             continue;
10675          if(debug)
10676             ast_log(LOG_NOTICE, "Executing scheduler entry %s = %s\n", skedlist->name, skedlist->value);
10677          if(atoi(skedlist->name) == 0)
10678             return; /* Zero is reserved for the startup macro */
10679          val = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.macro, skedlist->name);
10680          if (!val){
10681             ast_log(LOG_WARNING,"Scheduler could not find macro %s\n",skedlist->name);
10682             return; /* Macro not found */
10683          }
10684          if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(val)){
10685             ast_log(LOG_WARNING, "Scheduler could not execute macro %s: Macro buffer full\n",
10686                skedlist->name);
10687             return; /* Macro buffer full */
10688          }
10689          myrpt->macrotimer = MACROTIME;
10690          strncat(myrpt->macrobuf,val,MAXMACRO - 1);
10691       }
10692       else{
10693          ast_log(LOG_WARNING,"Malformed scheduler entry in rpt.conf: %s = %s\n",
10694             skedlist->name, skedlist->value);
10695       }
10696    }
10697 
10698 }
10699 
10700 /* single thread with one file (request) to dial */
10701 static void *rpt(void *this)
10702 {
10703 struct   rpt *myrpt = (struct rpt *)this;
10704 char *tele,*idtalkover,c,myfirst,*p;
10705 int ms = MSWAIT,i,lasttx=0,val,remrx=0,identqueued,othertelemqueued;
10706 int tailmessagequeued,ctqueued,dtmfed,lastmyrx,localmsgqueued;
10707 struct ast_channel *who;
10708 struct dahdi_confinfo ci;  /* conference info */
10709 time_t   t;
10710 struct rpt_link *l,*m;
10711 struct rpt_tele *telem;
10712 char tmpstr[300],lstr[MAXLINKLIST];
10713 
10714 
10715    if (myrpt->p.archivedir) mkdir(myrpt->p.archivedir,0600);
10716    sprintf(tmpstr,"%s/%s",myrpt->p.archivedir,myrpt->name);
10717    mkdir(tmpstr,0600);
10718    rpt_mutex_lock(&myrpt->lock);
10719 
10720    telem = myrpt->tele.next;
10721    while(telem != &myrpt->tele)
10722    {
10723       ast_softhangup(telem->chan,AST_SOFTHANGUP_DEV);
10724       telem = telem->next;
10725    }
10726    rpt_mutex_unlock(&myrpt->lock);
10727    /* find our index, and load the vars initially */
10728    for(i = 0; i < nrpts; i++)
10729    {
10730       if (&rpt_vars[i] == myrpt)
10731       {
10732          load_rpt_vars(i,0);
10733          break;
10734       }
10735    }
10736 
10737    rpt_mutex_lock(&myrpt->lock);
10738    while(myrpt->xlink)
10739    {
10740       myrpt->xlink = 3;
10741       rpt_mutex_unlock(&myrpt->lock);
10742       usleep(100000);
10743       rpt_mutex_lock(&myrpt->lock);
10744    }
10745 #ifdef HAVE_IOPERM
10746    if ((!strcmp(myrpt->remoterig, remote_rig_rbi)) &&
10747      (ioperm(myrpt->p.iobase,1,1) == -1))
10748    {
10749       rpt_mutex_unlock(&myrpt->lock);
10750       ast_log(LOG_WARNING, "Cant get io permission on IO port %x hex\n",myrpt->p.iobase);
10751       myrpt->rpt_thread = AST_PTHREADT_STOP;
10752       pthread_exit(NULL);
10753    }
10754 #endif
10755    strncpy(tmpstr,myrpt->rxchanname,sizeof(tmpstr) - 1);
10756    tele = strchr(tmpstr,'/');
10757    if (!tele)
10758    {
10759       fprintf(stderr,"rpt:Rxchannel Dial number (%s) must be in format tech/number\n",myrpt->rxchanname);
10760       rpt_mutex_unlock(&myrpt->lock);
10761       myrpt->rpt_thread = AST_PTHREADT_STOP;
10762       pthread_exit(NULL);
10763    }
10764    *tele++ = 0;
10765    myrpt->rxchannel = ast_request(tmpstr, AST_FORMAT_SLINEAR, NULL, tele, NULL);
10766    myrpt->dahdirxchannel = NULL;
10767    if (!strcasecmp(tmpstr,"DAHDI"))
10768       myrpt->dahdirxchannel = myrpt->rxchannel;
10769    if (myrpt->rxchannel)
10770    {
10771       if (myrpt->rxchannel->_state == AST_STATE_BUSY)
10772       {
10773          fprintf(stderr,"rpt:Sorry unable to obtain Rx channel\n");
10774          rpt_mutex_unlock(&myrpt->lock);
10775          ast_hangup(myrpt->rxchannel);
10776          myrpt->rpt_thread = AST_PTHREADT_STOP;
10777          pthread_exit(NULL);
10778       }
10779       ast_set_read_format(myrpt->rxchannel,AST_FORMAT_SLINEAR);
10780       ast_set_write_format(myrpt->rxchannel,AST_FORMAT_SLINEAR);
10781 #ifdef   AST_CDR_FLAG_POST_DISABLED
10782       if (myrpt->rxchannel->cdr)
10783          ast_set_flag(myrpt->rxchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10784 #endif
10785 #ifndef  NEW_ASTERISK
10786       myrpt->rxchannel->whentohangup = 0;
10787 #endif
10788       myrpt->rxchannel->appl = "Apprpt";
10789       myrpt->rxchannel->data = "(Repeater Rx)";
10790       if (option_verbose > 2)
10791          ast_verbose(VERBOSE_PREFIX_3 "rpt (Rx) initiating call to %s/%s on %s\n",
10792             tmpstr,tele,myrpt->rxchannel->name);
10793       ast_call(myrpt->rxchannel,tele,999);
10794       if (myrpt->rxchannel->_state != AST_STATE_UP)
10795       {
10796          rpt_mutex_unlock(&myrpt->lock);
10797          ast_hangup(myrpt->rxchannel);
10798          myrpt->rpt_thread = AST_PTHREADT_STOP;
10799          pthread_exit(NULL);
10800       }
10801    }
10802    else
10803    {
10804       fprintf(stderr,"rpt:Sorry unable to obtain Rx channel\n");
10805       rpt_mutex_unlock(&myrpt->lock);
10806       myrpt->rpt_thread = AST_PTHREADT_STOP;
10807       pthread_exit(NULL);
10808    }
10809    myrpt->dahditxchannel = NULL;
10810    if (myrpt->txchanname)
10811    {
10812       strncpy(tmpstr,myrpt->txchanname,sizeof(tmpstr) - 1);
10813       tele = strchr(tmpstr,'/');
10814       if (!tele)
10815       {
10816          fprintf(stderr,"rpt:Txchannel Dial number (%s) must be in format tech/number\n",myrpt->txchanname);
10817          rpt_mutex_unlock(&myrpt->lock);
10818          ast_hangup(myrpt->rxchannel);
10819          myrpt->rpt_thread = AST_PTHREADT_STOP;
10820          pthread_exit(NULL);
10821       }
10822       *tele++ = 0;
10823       myrpt->txchannel = ast_request(tmpstr, AST_FORMAT_SLINEAR, NULL, tele, NULL);
10824       if (!strcasecmp(tmpstr,"DAHDI"))
10825          myrpt->dahditxchannel = myrpt->txchannel;
10826       if (myrpt->txchannel)
10827       {
10828          if (myrpt->txchannel->_state == AST_STATE_BUSY)
10829          {
10830             fprintf(stderr,"rpt:Sorry unable to obtain Tx channel\n");
10831             rpt_mutex_unlock(&myrpt->lock);
10832             ast_hangup(myrpt->txchannel);
10833             ast_hangup(myrpt->rxchannel);
10834             myrpt->rpt_thread = AST_PTHREADT_STOP;
10835             pthread_exit(NULL);
10836          }        
10837          ast_set_read_format(myrpt->txchannel,AST_FORMAT_SLINEAR);
10838          ast_set_write_format(myrpt->txchannel,AST_FORMAT_SLINEAR);
10839 #ifdef   AST_CDR_FLAG_POST_DISABLED
10840          if (myrpt->txchannel->cdr)
10841             ast_set_flag(myrpt->txchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10842 #endif
10843 #ifndef  NEW_ASTERISK
10844          myrpt->txchannel->whentohangup = 0;
10845 #endif
10846          myrpt->txchannel->appl = "Apprpt";
10847          myrpt->txchannel->data = "(Repeater Tx)";
10848          if (option_verbose > 2)
10849             ast_verbose(VERBOSE_PREFIX_3 "rpt (Tx) initiating call to %s/%s on %s\n",
10850                tmpstr,tele,myrpt->txchannel->name);
10851          ast_call(myrpt->txchannel,tele,999);
10852          if (myrpt->rxchannel->_state != AST_STATE_UP)
10853          {
10854             rpt_mutex_unlock(&myrpt->lock);
10855             ast_hangup(myrpt->rxchannel);
10856             ast_hangup(myrpt->txchannel);
10857             myrpt->rpt_thread = AST_PTHREADT_STOP;
10858             pthread_exit(NULL);
10859          }
10860       }
10861       else
10862       {
10863          fprintf(stderr,"rpt:Sorry unable to obtain Tx channel\n");
10864          rpt_mutex_unlock(&myrpt->lock);
10865          ast_hangup(myrpt->rxchannel);
10866          myrpt->rpt_thread = AST_PTHREADT_STOP;
10867          pthread_exit(NULL);
10868       }
10869    }
10870    else
10871    {
10872       myrpt->txchannel = myrpt->rxchannel;
10873       if (!strncasecmp(myrpt->rxchanname,"DAHDI",3))
10874          myrpt->dahditxchannel = myrpt->txchannel;
10875    }
10876    ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_KEY);
10877    ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_UNKEY);
10878    /* allocate a pseudo-channel thru asterisk */
10879    myrpt->pchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
10880    if (!myrpt->pchannel)
10881    {
10882       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
10883       rpt_mutex_unlock(&myrpt->lock);
10884       if (myrpt->txchannel != myrpt->rxchannel) 
10885          ast_hangup(myrpt->txchannel);
10886       ast_hangup(myrpt->rxchannel);
10887       myrpt->rpt_thread = AST_PTHREADT_STOP;
10888       pthread_exit(NULL);
10889    }
10890 #ifdef   AST_CDR_FLAG_POST_DISABLED
10891    if (myrpt->pchannel->cdr)
10892       ast_set_flag(myrpt->pchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10893 #endif
10894    if (!myrpt->dahdirxchannel) myrpt->dahdirxchannel = myrpt->pchannel;
10895    if (!myrpt->dahditxchannel)
10896    {
10897       /* allocate a pseudo-channel thru asterisk */
10898       myrpt->dahditxchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
10899       if (!myrpt->dahditxchannel)
10900       {
10901          fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
10902          rpt_mutex_unlock(&myrpt->lock);
10903          if (myrpt->txchannel != myrpt->rxchannel) 
10904             ast_hangup(myrpt->txchannel);
10905          ast_hangup(myrpt->rxchannel);
10906          myrpt->rpt_thread = AST_PTHREADT_STOP;
10907          pthread_exit(NULL);
10908       }
10909       ast_set_read_format(myrpt->dahditxchannel,AST_FORMAT_SLINEAR);
10910       ast_set_write_format(myrpt->dahditxchannel,AST_FORMAT_SLINEAR);
10911 #ifdef   AST_CDR_FLAG_POST_DISABLED
10912       if (myrpt->dahditxchannel->cdr)
10913          ast_set_flag(myrpt->dahditxchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10914 #endif
10915    }
10916    /* allocate a pseudo-channel thru asterisk */
10917    myrpt->monchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
10918    if (!myrpt->monchannel)
10919    {
10920       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
10921       rpt_mutex_unlock(&myrpt->lock);
10922       if (myrpt->txchannel != myrpt->rxchannel) 
10923          ast_hangup(myrpt->txchannel);
10924       ast_hangup(myrpt->rxchannel);
10925       myrpt->rpt_thread = AST_PTHREADT_STOP;
10926       pthread_exit(NULL);
10927    }
10928    ast_set_read_format(myrpt->monchannel,AST_FORMAT_SLINEAR);
10929    ast_set_write_format(myrpt->monchannel,AST_FORMAT_SLINEAR);
10930 #ifdef   AST_CDR_FLAG_POST_DISABLED
10931    if (myrpt->monchannel->cdr)
10932       ast_set_flag(myrpt->monchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
10933 #endif
10934    /* make a conference for the tx */
10935    ci.chan = 0;
10936    ci.confno = -1; /* make a new conf */
10937    ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_LISTENER;
10938    /* first put the channel on the conference in proper mode */
10939    if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
10940    {
10941       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
10942       rpt_mutex_unlock(&myrpt->lock);
10943       ast_hangup(myrpt->pchannel);
10944       ast_hangup(myrpt->monchannel);
10945       if (myrpt->txchannel != myrpt->rxchannel) 
10946          ast_hangup(myrpt->txchannel);
10947       ast_hangup(myrpt->rxchannel);
10948       myrpt->rpt_thread = AST_PTHREADT_STOP;
10949       pthread_exit(NULL);
10950    }
10951    /* save tx conference number */
10952    myrpt->txconf = ci.confno;
10953    /* make a conference for the pseudo */
10954    ci.chan = 0;
10955    ci.confno = -1; /* make a new conf */
10956    ci.confmode = ((myrpt->p.duplex == 2) || (myrpt->p.duplex == 4)) ? DAHDI_CONF_CONFANNMON :
10957       (DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER);
10958    /* first put the channel on the conference in announce mode */
10959    if (ioctl(myrpt->pchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
10960    {
10961       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
10962       rpt_mutex_unlock(&myrpt->lock);
10963       ast_hangup(myrpt->pchannel);
10964       ast_hangup(myrpt->monchannel);
10965       if (myrpt->txchannel != myrpt->rxchannel) 
10966          ast_hangup(myrpt->txchannel);
10967       ast_hangup(myrpt->rxchannel);
10968       myrpt->rpt_thread = AST_PTHREADT_STOP;
10969       pthread_exit(NULL);
10970    }
10971    /* save pseudo channel conference number */
10972    myrpt->conf = ci.confno;
10973    /* make a conference for the pseudo */
10974    ci.chan = 0;
10975    if ((strstr(myrpt->txchannel->name,"pseudo") == NULL) &&
10976       (myrpt->dahditxchannel == myrpt->txchannel))
10977    {
10978       /* get tx channel's port number */
10979       if (ioctl(myrpt->txchannel->fds[0],DAHDI_CHANNO,&ci.confno) == -1)
10980       {
10981          ast_log(LOG_WARNING, "Unable to set tx channel's chan number\n");
10982          rpt_mutex_unlock(&myrpt->lock);
10983          ast_hangup(myrpt->pchannel);
10984          ast_hangup(myrpt->monchannel);
10985          if (myrpt->txchannel != myrpt->rxchannel) 
10986             ast_hangup(myrpt->txchannel);
10987          ast_hangup(myrpt->rxchannel);
10988          myrpt->rpt_thread = AST_PTHREADT_STOP;
10989          pthread_exit(NULL);
10990       }
10991       ci.confmode = DAHDI_CONF_MONITORTX;
10992    }
10993    else
10994    {
10995       ci.confno = myrpt->txconf;
10996       ci.confmode = DAHDI_CONF_CONFANNMON;
10997    }
10998    /* first put the channel on the conference in announce mode */
10999    if (ioctl(myrpt->monchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
11000    {
11001       ast_log(LOG_WARNING, "Unable to set conference mode for monitor\n");
11002       rpt_mutex_unlock(&myrpt->lock);
11003       ast_hangup(myrpt->pchannel);
11004       ast_hangup(myrpt->monchannel);
11005       if (myrpt->txchannel != myrpt->rxchannel) 
11006          ast_hangup(myrpt->txchannel);
11007       ast_hangup(myrpt->rxchannel);
11008       myrpt->rpt_thread = AST_PTHREADT_STOP;
11009       pthread_exit(NULL);
11010    }
11011    /* allocate a pseudo-channel thru asterisk */
11012    myrpt->parrotchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
11013    if (!myrpt->parrotchannel)
11014    {
11015       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
11016       rpt_mutex_unlock(&myrpt->lock);
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    ast_set_read_format(myrpt->parrotchannel,AST_FORMAT_SLINEAR);
11024    ast_set_write_format(myrpt->parrotchannel,AST_FORMAT_SLINEAR);
11025 #ifdef   AST_CDR_FLAG_POST_DISABLED
11026    if (myrpt->parrotchannel->cdr)
11027       ast_set_flag(myrpt->parrotchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
11028 #endif
11029    /* allocate a pseudo-channel thru asterisk */
11030    myrpt->voxchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
11031    if (!myrpt->voxchannel)
11032    {
11033       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
11034       rpt_mutex_unlock(&myrpt->lock);
11035       if (myrpt->txchannel != myrpt->rxchannel) 
11036          ast_hangup(myrpt->txchannel);
11037       ast_hangup(myrpt->rxchannel);
11038       myrpt->rpt_thread = AST_PTHREADT_STOP;
11039       pthread_exit(NULL);
11040    }
11041    ast_set_read_format(myrpt->voxchannel,AST_FORMAT_SLINEAR);
11042    ast_set_write_format(myrpt->voxchannel,AST_FORMAT_SLINEAR);
11043 #ifdef   AST_CDR_FLAG_POST_DISABLED
11044    if (myrpt->voxchannel->cdr)
11045       ast_set_flag(myrpt->voxchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
11046 #endif
11047    /* allocate a pseudo-channel thru asterisk */
11048    myrpt->txpchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
11049    if (!myrpt->txpchannel)
11050    {
11051       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
11052       rpt_mutex_unlock(&myrpt->lock);
11053       ast_hangup(myrpt->pchannel);
11054       ast_hangup(myrpt->monchannel);
11055       if (myrpt->txchannel != myrpt->rxchannel) 
11056          ast_hangup(myrpt->txchannel);
11057       ast_hangup(myrpt->rxchannel);
11058       myrpt->rpt_thread = AST_PTHREADT_STOP;
11059       pthread_exit(NULL);
11060    }
11061 #ifdef   AST_CDR_FLAG_POST_DISABLED
11062    if (myrpt->txpchannel->cdr)
11063       ast_set_flag(myrpt->txpchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
11064 #endif
11065    /* make a conference for the tx */
11066    ci.chan = 0;
11067    ci.confno = myrpt->txconf;
11068    ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER ;
11069    /* first put the channel on the conference in proper mode */
11070    if (ioctl(myrpt->txpchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
11071    {
11072       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
11073       rpt_mutex_unlock(&myrpt->lock);
11074       ast_hangup(myrpt->txpchannel);
11075       ast_hangup(myrpt->monchannel);
11076       if (myrpt->txchannel != myrpt->rxchannel) 
11077          ast_hangup(myrpt->txchannel);
11078       ast_hangup(myrpt->rxchannel);
11079       myrpt->rpt_thread = AST_PTHREADT_STOP;
11080       pthread_exit(NULL);
11081    }
11082    /* if serial io port, open it */
11083    myrpt->iofd = -1;
11084    if (myrpt->p.ioport && ((myrpt->iofd = openserial(myrpt,myrpt->p.ioport)) == -1))
11085    {
11086       ast_log(LOG_ERROR, "Unable to open %s\n",myrpt->p.ioport);
11087       rpt_mutex_unlock(&myrpt->lock);
11088       ast_hangup(myrpt->pchannel);
11089       if (myrpt->txchannel != myrpt->rxchannel) 
11090          ast_hangup(myrpt->txchannel);
11091       ast_hangup(myrpt->rxchannel);
11092       pthread_exit(NULL);
11093    }
11094    /* Now, the idea here is to copy from the physical rx channel buffer
11095       into the pseudo tx buffer, and from the pseudo rx buffer into the 
11096       tx channel buffer */
11097    myrpt->links.next = &myrpt->links;
11098    myrpt->links.prev = &myrpt->links;
11099    myrpt->tailtimer = 0;
11100    myrpt->totimer = 0;
11101    myrpt->tmsgtimer = myrpt->p.tailmessagetime;
11102    myrpt->idtimer = myrpt->p.politeid;
11103    myrpt->mustid = myrpt->tailid = 0;
11104    myrpt->callmode = 0;
11105    myrpt->tounkeyed = 0;
11106    myrpt->tonotify = 0;
11107    myrpt->retxtimer = 0;
11108    myrpt->rerxtimer = 0;
11109    myrpt->skedtimer = 0;
11110    myrpt->tailevent = 0;
11111    lasttx = 0;
11112    myrpt->keyed = 0;
11113    myrpt->txkeyed = 0;
11114    time(&myrpt->lastkeyedtime);
11115    myrpt->lastkeyedtime -= RPT_LOCKOUT_SECS;
11116    time(&myrpt->lasttxkeyedtime);
11117    myrpt->lasttxkeyedtime -= RPT_LOCKOUT_SECS;
11118    idtalkover = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->name, "idtalkover");
11119    myrpt->dtmfidx = -1;
11120    myrpt->dtmfbuf[0] = 0;
11121    myrpt->rem_dtmfidx = -1;
11122    myrpt->rem_dtmfbuf[0] = 0;
11123    myrpt->dtmf_time = 0;
11124    myrpt->rem_dtmf_time = 0;
11125    myrpt->inpadtest = 0;
11126    myrpt->disgorgetime = 0;
11127    myrpt->lastnodewhichkeyedusup[0] = '\0';
11128    myrpt->dailytxtime = 0;
11129    myrpt->totaltxtime = 0;
11130    myrpt->dailykeyups = 0;
11131    myrpt->totalkeyups = 0;
11132    myrpt->dailykerchunks = 0;
11133    myrpt->totalkerchunks = 0;
11134    myrpt->dailyexecdcommands = 0;
11135    myrpt->totalexecdcommands = 0;
11136    myrpt->timeouts = 0;
11137    myrpt->exten[0] = '\0';
11138    myrpt->lastdtmfcommand[0] = '\0';
11139    voxinit_rpt(myrpt,1);
11140    myrpt->wasvox = 0;
11141    if (myrpt->p.startupmacro)
11142    {
11143       snprintf(myrpt->macrobuf,MAXMACRO - 1,"PPPP%s",myrpt->p.startupmacro);
11144    }
11145    rpt_mutex_unlock(&myrpt->lock);
11146    val = 1;
11147    ast_channel_setoption(myrpt->rxchannel,AST_OPTION_RELAXDTMF,&val,sizeof(char),0);
11148    val = 1;
11149    ast_channel_setoption(myrpt->rxchannel,AST_OPTION_TONE_VERIFY,&val,sizeof(char),0);
11150    if (myrpt->p.archivedir) donodelog(myrpt,"STARTUP");
11151    dtmfed = 0;
11152    if (myrpt->remoterig && !ISRIG_RTX(myrpt->remoterig)) setrem(myrpt);
11153    lastmyrx = 0;
11154    myfirst = 0;
11155    while (ms >= 0)
11156    {
11157       struct ast_frame *f,*f1,*f2;
11158       struct ast_channel *cs[300],*cs1[300];
11159       int totx=0,elap=0,n,x,toexit=0;
11160 
11161       /* DEBUG Dump */
11162       if((myrpt->disgorgetime) && (time(NULL) >= myrpt->disgorgetime)){
11163          struct rpt_link *dl;
11164          struct rpt_tele *dt;
11165 
11166          myrpt->disgorgetime = 0;
11167          ast_log(LOG_NOTICE,"********** Variable Dump Start (app_rpt) **********\n");
11168          ast_log(LOG_NOTICE,"totx = %d\n",totx);
11169          ast_log(LOG_NOTICE,"remrx = %d\n",remrx);
11170          ast_log(LOG_NOTICE,"lasttx = %d\n",lasttx);
11171          ast_log(LOG_NOTICE,"elap = %d\n",elap);
11172          ast_log(LOG_NOTICE,"toexit = %d\n",toexit);
11173 
11174          ast_log(LOG_NOTICE,"myrpt->keyed = %d\n",myrpt->keyed);
11175          ast_log(LOG_NOTICE,"myrpt->localtx = %d\n",myrpt->localtx);
11176          ast_log(LOG_NOTICE,"myrpt->callmode = %d\n",myrpt->callmode);
11177          ast_log(LOG_NOTICE,"myrpt->mustid = %d\n",myrpt->mustid);
11178          ast_log(LOG_NOTICE,"myrpt->tounkeyed = %d\n",myrpt->tounkeyed);
11179          ast_log(LOG_NOTICE,"myrpt->tonotify = %d\n",myrpt->tonotify);
11180          ast_log(LOG_NOTICE,"myrpt->retxtimer = %ld\n",myrpt->retxtimer);
11181          ast_log(LOG_NOTICE,"myrpt->totimer = %d\n",myrpt->totimer);
11182          ast_log(LOG_NOTICE,"myrpt->tailtimer = %d\n",myrpt->tailtimer);
11183          ast_log(LOG_NOTICE,"myrpt->tailevent = %d\n",myrpt->tailevent);
11184 
11185          dl = myrpt->links.next;
11186                   while(dl != &myrpt->links){
11187             ast_log(LOG_NOTICE,"*** Link Name: %s ***\n",dl->name);
11188             ast_log(LOG_NOTICE,"        link->lasttx %d\n",dl->lasttx);
11189             ast_log(LOG_NOTICE,"        link->lastrx %d\n",dl->lastrx);
11190             ast_log(LOG_NOTICE,"        link->connected %d\n",dl->connected);
11191             ast_log(LOG_NOTICE,"        link->hasconnected %d\n",dl->hasconnected);
11192             ast_log(LOG_NOTICE,"        link->outbound %d\n",dl->outbound);
11193             ast_log(LOG_NOTICE,"        link->disced %d\n",dl->disced);
11194             ast_log(LOG_NOTICE,"        link->killme %d\n",dl->killme);
11195             ast_log(LOG_NOTICE,"        link->disctime %ld\n",dl->disctime);
11196             ast_log(LOG_NOTICE,"        link->retrytimer %ld\n",dl->retrytimer);
11197             ast_log(LOG_NOTICE,"        link->retries = %d\n",dl->retries);
11198             ast_log(LOG_NOTICE,"        link->reconnects = %d\n",dl->reconnects);
11199             ast_log(LOG_NOTICE,"        link->newkey = %d\n",dl->newkey);
11200                            dl = dl->next;
11201                   }
11202                                                                                                                                
11203          dt = myrpt->tele.next;
11204          if(dt != &myrpt->tele)
11205             ast_log(LOG_NOTICE,"*** Telemetry Queue ***\n");
11206                   while(dt != &myrpt->tele){
11207             ast_log(LOG_NOTICE,"        Telemetry mode: %d\n",dt->mode);
11208                            dt = dt->next;
11209                   }
11210          ast_log(LOG_NOTICE,"******* Variable Dump End (app_rpt) *******\n");
11211 
11212       }  
11213 
11214 
11215       if (myrpt->reload)
11216       {
11217          struct rpt_tele *inner_telem;
11218 
11219          rpt_mutex_lock(&myrpt->lock);
11220          inner_telem = myrpt->tele.next;
11221          while(inner_telem != &myrpt->tele)
11222          {
11223             ast_softhangup(inner_telem->chan,AST_SOFTHANGUP_DEV);
11224             inner_telem = inner_telem->next;
11225          }
11226          myrpt->reload = 0;
11227          rpt_mutex_unlock(&myrpt->lock);
11228          usleep(10000);
11229          /* find our index, and load the vars */
11230          for(i = 0; i < nrpts; i++)
11231          {
11232             if (&rpt_vars[i] == myrpt)
11233             {
11234                load_rpt_vars(i,0);
11235                break;
11236             }
11237          }
11238       }
11239 
11240       rpt_mutex_lock(&myrpt->lock);
11241       if (ast_check_hangup(myrpt->rxchannel)) break;
11242       if (ast_check_hangup(myrpt->txchannel)) break;
11243       if (ast_check_hangup(myrpt->pchannel)) break;
11244       if (ast_check_hangup(myrpt->monchannel)) break;
11245       if (myrpt->parrotchannel && 
11246          ast_check_hangup(myrpt->parrotchannel)) break;
11247       if (myrpt->voxchannel && 
11248          ast_check_hangup(myrpt->voxchannel)) break;
11249       if (ast_check_hangup(myrpt->txpchannel)) break;
11250       if (myrpt->dahditxchannel && ast_check_hangup(myrpt->dahditxchannel)) break;
11251 
11252       /* Set local tx with keyed */
11253       myrpt->localtx = myrpt->keyed;
11254       /* If someone's connected, and they're transmitting from their end to us, set remrx true */
11255       l = myrpt->links.next;
11256       remrx = 0;
11257       while(l != &myrpt->links)
11258       {
11259          if (l->lastrx){
11260             remrx = 1;
11261             if(l->name[0] != '0') /* Ignore '0' nodes */
11262                strcpy(myrpt->lastnodewhichkeyedusup, l->name); /* Note the node which is doing the key up */
11263          }
11264          l = l->next;
11265       }
11266       /* Create a "must_id" flag for the cleanup ID */      
11267       if(myrpt->p.idtime) /* ID time must be non-zero */
11268          myrpt->mustid |= (myrpt->idtimer) && (myrpt->keyed || remrx) ;
11269       /* Build a fresh totx from myrpt->keyed and autopatch activated */
11270       /* If full duplex, add local tx to totx */
11271       if (myrpt->p.duplex > 1) 
11272       {
11273          totx = myrpt->callmode;
11274          totx = totx || myrpt->localtx;
11275       }
11276       else
11277       {
11278          int myrx = myrpt->localtx || remrx || (!myrpt->callmode);
11279 
11280          if (lastmyrx != myrx)
11281          {
11282             voxinit_rpt(myrpt,!myrx);
11283             lastmyrx = myrx;
11284          }
11285          totx = 0;
11286          if (myrpt->callmode && (myrpt->voxtotimer <= 0))
11287          {
11288             if (myrpt->voxtostate)
11289             {
11290                myrpt->voxtotimer = myrpt->p.voxtimeout_ms;
11291                myrpt->voxtostate = 0;
11292             }           
11293             else
11294             {
11295                myrpt->voxtotimer = myrpt->p.voxrecover_ms;
11296                myrpt->voxtostate = 1;
11297             }
11298          }
11299          if (!myrpt->voxtostate)
11300             totx = myrpt->callmode && myrpt->wasvox;
11301       }
11302       /* Traverse the telemetry list to see what's queued */
11303       identqueued = 0;
11304       localmsgqueued = 0;
11305       othertelemqueued = 0;
11306       tailmessagequeued = 0;
11307       ctqueued = 0;
11308       telem = myrpt->tele.next;
11309       while(telem != &myrpt->tele)
11310       {
11311          if((telem->mode == ID) || (telem->mode == IDTALKOVER)){
11312             identqueued = 1; /* Identification telemetry */
11313          }
11314          else if(telem->mode == TAILMSG)
11315          {
11316             tailmessagequeued = 1; /* Tail message telemetry */
11317          }
11318          else if(telem->mode == STATS_TIME_LOCAL) 
11319          {
11320             localmsgqueued = 1; /* Local message */
11321          }
11322          else
11323          {
11324             if ((telem->mode != UNKEY) && (telem->mode != LINKUNKEY))
11325                othertelemqueued = 1;  /* Other telemetry */
11326             else
11327                ctqueued = 1; /* Courtesy tone telemetry */
11328          }
11329          telem = telem->next;
11330       }
11331    
11332       /* Add in any "other" telemetry, unless specified otherwise */
11333       if (!myrpt->p.notelemtx) totx = totx || othertelemqueued;
11334       /* Update external (to links) transmitter PTT state with everything but */
11335       /* ID, CT, local messages, and tailmessage telemetry */
11336       myrpt->exttx = totx;
11337       totx = totx || myrpt->dtmf_local_timer;
11338       /* If half or 3/4 duplex, add localtx to external link tx */
11339       if (myrpt->p.duplex < 2) myrpt->exttx = myrpt->exttx || myrpt->localtx;
11340       /* Add in ID telemetry to local transmitter */
11341       totx = totx || remrx;
11342       /* If 3/4 or full duplex, add in ident, CT telemetry, and local messages */
11343       if (myrpt->p.duplex > 0)
11344          totx = totx || identqueued || ctqueued || localmsgqueued;
11345       /* If full duplex, add local dtmf stuff active */
11346       if (myrpt->p.duplex > 1) 
11347       {
11348          totx = totx || (myrpt->dtmfidx > -1) ||
11349             myrpt->cmdnode[0];
11350       }
11351       /* add in parrot stuff */
11352       totx = totx || (myrpt->parrotstate > 1);
11353       /* Reset time out timer variables if there is no activity */
11354       if (!totx) 
11355       {
11356          myrpt->totimer = myrpt->p.totime;
11357          myrpt->tounkeyed = 0;
11358          myrpt->tonotify = 0;
11359       }
11360       else{
11361          myrpt->tailtimer = myrpt->p.s[myrpt->p.sysstate_cur].alternatetail ?
11362             myrpt->p.althangtime : /* Initialize tail timer */
11363             myrpt->p.hangtime;
11364       }
11365       /* Disable the local transmitter if we are timed out */
11366       totx = totx && myrpt->totimer;
11367       /* if timed-out and not said already, say it */
11368       if ((!myrpt->totimer) && (!myrpt->tonotify))
11369       {
11370          myrpt->tonotify = 1;
11371          myrpt->timeouts++;
11372          rpt_mutex_unlock(&myrpt->lock);
11373          rpt_telemetry(myrpt,TIMEOUT,NULL);
11374          rpt_mutex_lock(&myrpt->lock);
11375       }
11376 
11377       /* If unkey and re-key, reset time out timer */
11378       if ((!totx) && (!myrpt->totimer) && (!myrpt->tounkeyed) && (!myrpt->keyed))
11379       {
11380          myrpt->tounkeyed = 1;
11381       }
11382       if ((!totx) && (!myrpt->totimer) && myrpt->tounkeyed && myrpt->keyed)
11383       {
11384          myrpt->totimer = myrpt->p.totime;
11385          myrpt->tounkeyed = 0;
11386          myrpt->tonotify = 0;
11387          rpt_mutex_unlock(&myrpt->lock);
11388          continue;
11389       }
11390       /* if timed-out and in circuit busy after call */
11391       if ((!totx) && (!myrpt->totimer) && (myrpt->callmode == 4))
11392       {
11393           if(debug)
11394             ast_log(LOG_NOTICE, "timed-out and in circuit busy after call\n");
11395          myrpt->callmode = 0;
11396          myrpt->macropatch=0;
11397          channel_revert(myrpt);
11398       }
11399       /* get rid of tail if timed out */
11400       if (!myrpt->totimer) myrpt->tailtimer = 0;
11401       /* if not timed-out, add in tail */
11402       if (myrpt->totimer) totx = totx || myrpt->tailtimer;
11403       /* If user or links key up or are keyed up over standard ID, switch to talkover ID, if one is defined */
11404       /* If tail message, kill the message if someone keys up over it */ 
11405       if ((myrpt->keyed || remrx) && ((identqueued && idtalkover) || (tailmessagequeued))) {
11406          int hasid = 0,hastalkover = 0;
11407 
11408          telem = myrpt->tele.next;
11409          while(telem != &myrpt->tele){
11410             if(telem->mode == ID){
11411                if (telem->chan) ast_softhangup(telem->chan, AST_SOFTHANGUP_DEV); /* Whoosh! */
11412                hasid = 1;
11413             }
11414             if(telem->mode == TAILMSG){
11415                                         if (telem->chan) ast_softhangup(telem->chan, AST_SOFTHANGUP_DEV); /* Whoosh! */
11416                                 }
11417             if (telem->mode == IDTALKOVER) hastalkover = 1;
11418             telem = telem->next;
11419          }
11420          rpt_mutex_unlock(&myrpt->lock);
11421          if (hasid && (!hastalkover)) rpt_telemetry(myrpt, IDTALKOVER, NULL); /* Start Talkover ID */
11422          rpt_mutex_lock(&myrpt->lock);
11423       }
11424       /* Try to be polite */
11425       /* If the repeater has been inactive for longer than the ID time, do an initial ID in the tail*/
11426       /* If within 30 seconds of the time to ID, try do it in the tail */
11427       /* else if at ID time limit, do it right over the top of them */
11428       /* Lastly, if the repeater has been keyed, and the ID timer is expired, do a clean up ID */
11429       if(myrpt->mustid && (!myrpt->idtimer))
11430          queue_id(myrpt);
11431 
11432       if ((myrpt->p.idtime && totx && (!myrpt->exttx) &&
11433           (myrpt->idtimer <= myrpt->p.politeid) && myrpt->tailtimer)) /* ID time must be non-zero */ 
11434          {
11435             myrpt->tailid = 1;
11436          }
11437 
11438       /* If tail timer expires, then check for tail messages */
11439 
11440       if(myrpt->tailevent){
11441          myrpt->tailevent = 0;
11442          if(myrpt->tailid){
11443             totx = 1;
11444             queue_id(myrpt);
11445          }
11446          else if ((myrpt->p.tailmessages[0]) &&
11447             (myrpt->p.tailmessagetime) && (myrpt->tmsgtimer == 0)){
11448                totx = 1;
11449                myrpt->tmsgtimer = myrpt->p.tailmessagetime; 
11450                rpt_mutex_unlock(&myrpt->lock);
11451                rpt_telemetry(myrpt, TAILMSG, NULL);
11452                rpt_mutex_lock(&myrpt->lock);
11453          }  
11454       }
11455 
11456       /* Main TX control */
11457 
11458       /* let telemetry transmit anyway (regardless of timeout) */
11459       if (myrpt->p.duplex > 0) totx = totx || (myrpt->tele.next != &myrpt->tele);
11460       totx = totx && !myrpt->p.s[myrpt->p.sysstate_cur].txdisable;
11461       myrpt->txrealkeyed = totx;
11462       totx = totx || (!AST_LIST_EMPTY(&myrpt->txq));
11463       if (totx && (!lasttx))
11464       {
11465          char mydate[100],myfname[100];
11466          time_t myt;
11467 
11468          if (myrpt->monstream) ast_closestream(myrpt->monstream);
11469          if (myrpt->p.archivedir)
11470          {
11471             long blocksleft;
11472 
11473             time(&myt);
11474             strftime(mydate,sizeof(mydate) - 1,"%Y%m%d%H%M%S",
11475                localtime(&myt));
11476             sprintf(myfname,"%s/%s/%s",myrpt->p.archivedir,
11477                myrpt->name,mydate);
11478             myrpt->monstream = ast_writefile(myfname,"wav49",
11479                "app_rpt Air Archive",O_CREAT | O_APPEND,0,0600);
11480             if (myrpt->p.monminblocks)
11481             {
11482                blocksleft = diskavail(myrpt);
11483                if (blocksleft >= myrpt->p.monminblocks)
11484                   donodelog(myrpt,"TXKEY,MAIN");
11485             } else donodelog(myrpt,"TXKEY,MAIN");
11486          }
11487          lasttx = 1;
11488          myrpt->txkeyed = 1;
11489          time(&myrpt->lasttxkeyedtime);
11490          myrpt->dailykeyups++;
11491          myrpt->totalkeyups++;
11492          rpt_mutex_unlock(&myrpt->lock);
11493          ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_KEY);
11494          rpt_mutex_lock(&myrpt->lock);
11495       }
11496       if ((!totx) && lasttx)
11497       {
11498          if (myrpt->monstream) ast_closestream(myrpt->monstream);
11499          myrpt->monstream = NULL;
11500 
11501          lasttx = 0;
11502          myrpt->txkeyed = 0;
11503          time(&myrpt->lasttxkeyedtime);
11504          rpt_mutex_unlock(&myrpt->lock);
11505          ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_UNKEY);
11506          rpt_mutex_lock(&myrpt->lock);
11507          donodelog(myrpt,"TXUNKEY,MAIN");
11508       }
11509       time(&t);
11510       /* if DTMF timeout */
11511       if ((!myrpt->cmdnode[0]) && (myrpt->dtmfidx >= 0) && ((myrpt->dtmf_time + DTMF_TIMEOUT) < t))
11512       {
11513          myrpt->inpadtest = 0;
11514          myrpt->dtmfidx = -1;
11515          myrpt->dtmfbuf[0] = 0;
11516       }        
11517       /* if remote DTMF timeout */
11518       if ((myrpt->rem_dtmfidx >= 0) && ((myrpt->rem_dtmf_time + DTMF_TIMEOUT) < t))
11519       {
11520          myrpt->inpadtest = 0;
11521          myrpt->rem_dtmfidx = -1;
11522          myrpt->rem_dtmfbuf[0] = 0;
11523       }  
11524 
11525       if (myrpt->exttx && myrpt->parrotchannel && 
11526          myrpt->p.parrotmode && (!myrpt->parrotstate))
11527       {
11528          char myfname[300];
11529 
11530          ci.confno = myrpt->conf;
11531          ci.confmode = DAHDI_CONF_CONFANNMON;
11532          ci.chan = 0;
11533 
11534          /* first put the channel on the conference in announce mode */
11535          if (ioctl(myrpt->parrotchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
11536          {
11537             ast_log(LOG_WARNING, "Unable to set conference mode for parrot\n");
11538             break;
11539          }
11540 
11541          sprintf(myfname,PARROTFILE,myrpt->name,myrpt->parrotcnt);
11542          strcat(myfname,".wav");
11543          unlink(myfname);        
11544          sprintf(myfname,PARROTFILE,myrpt->name,myrpt->parrotcnt);
11545          myrpt->parrotstate = 1;
11546          myrpt->parrottimer = myrpt->p.parrottime;
11547          if (myrpt->parrotstream) 
11548             ast_closestream(myrpt->parrotstream);
11549          myrpt->parrotstream = NULL;
11550          myrpt->parrotstream = ast_writefile(myfname,"wav",
11551             "app_rpt Parrot",O_CREAT | O_TRUNC,0,0600);
11552       }
11553 
11554       /* Reconnect */
11555    
11556       l = myrpt->links.next;
11557       while(l != &myrpt->links)
11558       {
11559          if (l->killme)
11560          {
11561             /* remove from queue */
11562             remque((struct qelem *) l);
11563             if (!strcmp(myrpt->cmdnode,l->name))
11564                myrpt->cmdnode[0] = 0;
11565             rpt_mutex_unlock(&myrpt->lock);
11566             /* hang-up on call to device */
11567             if (l->chan) ast_hangup(l->chan);
11568             ast_hangup(l->pchan);
11569             ast_free(l);
11570             rpt_mutex_lock(&myrpt->lock);
11571             /* re-start link traversal */
11572             l = myrpt->links.next;
11573             continue;
11574          }
11575          l = l->next;
11576       }
11577       n = 0;
11578       cs[n++] = myrpt->rxchannel;
11579       cs[n++] = myrpt->pchannel;
11580       cs[n++] = myrpt->monchannel;
11581       if (myrpt->parrotchannel) cs[n++] = myrpt->parrotchannel;
11582       if (myrpt->voxchannel) cs[n++] = myrpt->voxchannel;
11583       cs[n++] = myrpt->txpchannel;
11584       if (myrpt->txchannel != myrpt->rxchannel) cs[n++] = myrpt->txchannel;
11585       if (myrpt->dahditxchannel != myrpt->txchannel)
11586          cs[n++] = myrpt->dahditxchannel;
11587       l = myrpt->links.next;
11588       while(l != &myrpt->links)
11589       {
11590          if ((!l->killme) && (!l->disctime) && l->chan)
11591          {
11592             cs[n++] = l->chan;
11593             cs[n++] = l->pchan;
11594          }
11595          l = l->next;
11596       }
11597       if ((myrpt->topkeystate == 1) && 
11598           ((t - myrpt->topkeytime) > TOPKEYWAIT))
11599       {
11600          myrpt->topkeystate = 2;
11601          qsort(myrpt->topkey,TOPKEYN,sizeof(struct rpt_topkey),
11602             topcompar);
11603       }
11604       rpt_mutex_unlock(&myrpt->lock);
11605 
11606       if (myrpt->topkeystate == 2)
11607       {
11608          rpt_telemetry(myrpt,TOPKEY,NULL);
11609          myrpt->topkeystate = 3;
11610       }
11611       ms = MSWAIT;
11612       for(x = 0; x < n; x++)
11613       {
11614          int s = -(-x - myrpt->scram - 1) % n;
11615          cs1[x] = cs[s];
11616       }
11617       myrpt->scram++;
11618       who = ast_waitfor_n(cs1,n,&ms);
11619       if (who == NULL) ms = 0;
11620       elap = MSWAIT - ms;
11621       rpt_mutex_lock(&myrpt->lock);
11622       l = myrpt->links.next;
11623       while(l != &myrpt->links)
11624       {
11625          int myrx;
11626 
11627          if (l->voxtotimer) l->voxtotimer -= elap;
11628          if (l->voxtotimer < 0) l->voxtotimer = 0;
11629 
11630          if (l->lasttx != l->lasttx1)
11631          {
11632             voxinit_link(l,!l->lasttx);
11633             l->lasttx1 = l->lasttx;
11634          }
11635          myrx = l->lastrealrx;
11636          if ((l->phonemode) && (l->phonevox))
11637          {
11638             myrx = myrx || (!AST_LIST_EMPTY(&l->rxq));
11639             if (l->voxtotimer <= 0)
11640             {
11641                if (l->voxtostate)
11642                {
11643                   l->voxtotimer = myrpt->p.voxtimeout_ms;
11644                   l->voxtostate = 0;
11645                }           
11646                else
11647                {
11648                   l->voxtotimer = myrpt->p.voxrecover_ms;
11649                   l->voxtostate = 1;
11650                }
11651             }
11652             if (!l->voxtostate)
11653                myrx = myrx || l->wasvox ;
11654          }
11655          l->lastrx = myrx;
11656          if (l->linklisttimer)
11657          {
11658             l->linklisttimer -= elap;
11659             if (l->linklisttimer < 0) l->linklisttimer = 0;
11660          }
11661          if ((!l->linklisttimer) && (l->name[0] != '0') && (!l->isremote))
11662          {
11663             struct   ast_frame lf;
11664 
11665             memset(&lf,0,sizeof(lf));
11666             lf.frametype = AST_FRAME_TEXT;
11667             lf.subclass.integer = 0;
11668             lf.offset = 0;
11669             lf.mallocd = 0;
11670             lf.samples = 0;
11671             l->linklisttimer = LINKLISTTIME;
11672             strcpy(lstr,"L ");
11673             __mklinklist(myrpt,l,lstr + 2);
11674             if (l->chan)
11675             {
11676                lf.datalen = strlen(lstr) + 1;
11677                lf.data.ptr = lstr;
11678                ast_write(l->chan,&lf);
11679                if (debug > 6) ast_log(LOG_NOTICE,
11680                   "@@@@ node %s sent node string %s to node %s\n",
11681                      myrpt->name,lstr,l->name);
11682             }
11683          }
11684          if (l->newkey)
11685          {
11686             if ((l->retxtimer += elap) >= REDUNDANT_TX_TIME)
11687             {
11688                l->retxtimer = 0;
11689                if (l->chan && l->phonemode == 0) 
11690                {
11691                   if (l->lasttx)
11692                      ast_indicate(l->chan,AST_CONTROL_RADIO_KEY);
11693                   else
11694                      ast_indicate(l->chan,AST_CONTROL_RADIO_UNKEY);
11695                }
11696             }
11697             if ((l->rerxtimer += elap) >= (REDUNDANT_TX_TIME * 5))
11698             {
11699                if (debug == 7) printf("@@@@ rx un-key\n");
11700                l->lastrealrx = 0;
11701                l->rerxtimer = 0;
11702                if (l->lastrx1)
11703                {
11704                   if (myrpt->p.archivedir)
11705                   {
11706                      char str[100];
11707    
11708                      sprintf(str,"RXUNKEY(T),%s",l->name);
11709                      donodelog(myrpt,str);
11710                   }
11711                   if(myrpt->p.duplex) 
11712                      rpt_telemetry(myrpt,LINKUNKEY,l);
11713                   l->lastrx1 = 0;
11714                }
11715             }
11716          }
11717          if (l->disctime) /* Disconnect timer active on a channel ? */
11718          {
11719             l->disctime -= elap;
11720             if (l->disctime <= 0) /* Disconnect timer expired on inbound channel ? */
11721                l->disctime = 0; /* Yep */
11722          }
11723 
11724          if (l->retrytimer)
11725          {
11726             l->retrytimer -= elap;
11727             if (l->retrytimer < 0) l->retrytimer = 0;
11728          }
11729 
11730          /* Tally connect time */
11731          l->connecttime += elap;
11732 
11733          /* ignore non-timing channels */
11734          if (l->elaptime < 0)
11735          {
11736             l = l->next;
11737             continue;
11738          }
11739          l->elaptime += elap;
11740          /* if connection has taken too long */
11741          if ((l->elaptime > MAXCONNECTTIME) && 
11742             ((!l->chan) || (l->chan->_state != AST_STATE_UP)))
11743          {
11744             l->elaptime = 0;
11745             rpt_mutex_unlock(&myrpt->lock);
11746             if (l->chan) ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
11747             rpt_mutex_lock(&myrpt->lock);
11748             break;
11749          }
11750          if ((!l->chan) && (!l->retrytimer) && l->outbound && 
11751             (l->retries++ < l->max_retries) && (l->hasconnected))
11752          {
11753             if (l->chan) ast_hangup(l->chan);
11754             l->chan = 0;
11755             rpt_mutex_unlock(&myrpt->lock);
11756             if ((l->name[0] != '0') && (!l->isremote))
11757             {
11758                if (attempt_reconnect(myrpt,l) == -1)
11759                {
11760                   l->retrytimer = RETRY_TIMER_MS;
11761                } 
11762             }
11763             else 
11764             {
11765                l->retrytimer = l->max_retries + 1;
11766             }
11767 
11768             rpt_mutex_lock(&myrpt->lock);
11769             break;
11770          }
11771          if ((!l->chan) && (!l->retrytimer) && l->outbound &&
11772             (l->retries >= l->max_retries))
11773          {
11774             /* remove from queue */
11775             remque((struct qelem *) l);
11776             if (!strcmp(myrpt->cmdnode,l->name))
11777                myrpt->cmdnode[0] = 0;
11778             rpt_mutex_unlock(&myrpt->lock);
11779             if (l->name[0] != '0')
11780             {
11781                if (!l->hasconnected)
11782                   rpt_telemetry(myrpt,CONNFAIL,l);
11783                else rpt_telemetry(myrpt,REMDISC,l);
11784             }
11785             if (myrpt->p.archivedir)
11786             {
11787                char str[100];
11788 
11789                if (!l->hasconnected)
11790                   sprintf(str,"LINKFAIL,%s",l->name);
11791                else
11792                   sprintf(str,"LINKDISC,%s",l->name);
11793                donodelog(myrpt,str);
11794             }
11795             /* hang-up on call to device */
11796             ast_hangup(l->pchan);
11797             ast_free(l);
11798                                 rpt_mutex_lock(&myrpt->lock);
11799             break;
11800          }
11801             if ((!l->chan) && (!l->disctime) && (!l->outbound))
11802             {
11803             if(debug)ast_log(LOG_NOTICE, "LINKDISC AA\n");
11804                 /* remove from queue */
11805                 remque((struct qelem *) l);
11806             if(myrpt->links.next==&myrpt->links)channel_revert(myrpt);
11807                 if (!strcmp(myrpt->cmdnode,l->name))myrpt->cmdnode[0] = 0;
11808                 rpt_mutex_unlock(&myrpt->lock);
11809             if (l->name[0] != '0') 
11810             {
11811                   rpt_telemetry(myrpt,REMDISC,l);
11812             }
11813             if (myrpt->p.archivedir)
11814             {
11815                char str[100];
11816                sprintf(str,"LINKDISC,%s",l->name);
11817                donodelog(myrpt,str);
11818             }
11819                 /* hang-up on call to device */
11820                 ast_hangup(l->pchan);
11821                 ast_free(l);
11822                 rpt_mutex_lock(&myrpt->lock);
11823                 break;
11824             }
11825          l = l->next;
11826       }
11827       if (myrpt->linkposttimer)
11828       {
11829          myrpt->linkposttimer -= elap;
11830          if (myrpt->linkposttimer < 0) myrpt->linkposttimer = 0;
11831       }
11832       if (myrpt->linkposttimer <= 0)
11833       {
11834          int nstr;
11835          char lst,*str;
11836          time_t now;
11837 
11838          myrpt->linkposttimer = LINKPOSTTIME;
11839          nstr = 0;
11840          for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
11841          {
11842             /* if is not a real link, ignore it */
11843             if (l->name[0] == '0') continue;
11844             nstr += strlen(l->name) + 1;
11845          }
11846          str = ast_malloc(nstr + 256);
11847          if (!str)
11848          {
11849             ast_log(LOG_NOTICE,"Cannot ast_malloc()\n");
11850             break;
11851          }
11852          nstr = 0;
11853          strcpy(str,"nodes=");
11854          for(l = myrpt->links.next; l != &myrpt->links; l = l->next)
11855          {
11856             /* if is not a real link, ignore it */
11857             if (l->name[0] == '0') continue;
11858             lst = 'T';
11859             if (!l->mode) lst = 'R';
11860             if (!l->thisconnected) lst = 'C';
11861             if (nstr) strcat(str,",");
11862             sprintf(str + strlen(str),"%c%s",lst,l->name);
11863             nstr = 1;
11864          }
11865                   p = strstr(tdesc, "version");
11866                   if(p){
11867             int vmajor,vminor;
11868             if(sscanf(p, "version %30d.%30d", &vmajor, &vminor) == 2)
11869                sprintf(str + strlen(str),"&apprptvers=%d.%d",vmajor,vminor);
11870          }
11871          time(&now);
11872          sprintf(str + strlen(str),"&apprptuptime=%d",(int)(now-starttime));
11873          sprintf(str + strlen(str),
11874          "&totalkerchunks=%d&totalkeyups=%d&totaltxtime=%d&timeouts=%d&totalexecdcommands=%d",
11875          myrpt->totalkerchunks,myrpt->totalkeyups,(int) myrpt->totaltxtime/1000,
11876          myrpt->timeouts,myrpt->totalexecdcommands);
11877          rpt_mutex_unlock(&myrpt->lock);
11878          statpost(myrpt,str);
11879          rpt_mutex_lock(&myrpt->lock);
11880          ast_free(str);
11881       }
11882       if (myrpt->keyposttimer)
11883       {
11884          myrpt->keyposttimer -= elap;
11885          if (myrpt->keyposttimer < 0) myrpt->keyposttimer = 0;
11886       }
11887       if (myrpt->keyposttimer <= 0)
11888       {
11889          char str[100];
11890          int diff = 0;
11891          time_t now;
11892 
11893          myrpt->keyposttimer = KEYPOSTTIME;
11894          time(&now);
11895          if (myrpt->lastkeyedtime)
11896          {
11897             diff = (int)(now - myrpt->lastkeyedtime);
11898          }
11899          sprintf(str,"keyed=%d&keytime=%d",myrpt->keyed,diff);
11900          rpt_mutex_unlock(&myrpt->lock);
11901          statpost(myrpt,str);
11902          rpt_mutex_lock(&myrpt->lock);
11903       }
11904       if(totx){
11905          myrpt->dailytxtime += elap;
11906          myrpt->totaltxtime += elap;
11907       }
11908       i = myrpt->tailtimer;
11909       if (myrpt->tailtimer) myrpt->tailtimer -= elap;
11910       if (myrpt->tailtimer < 0) myrpt->tailtimer = 0;
11911       if((i) && (myrpt->tailtimer == 0))
11912          myrpt->tailevent = 1;
11913       if ((!myrpt->p.s[myrpt->p.sysstate_cur].totdisable) && myrpt->totimer) myrpt->totimer -= elap;
11914       if (myrpt->totimer < 0) myrpt->totimer = 0;
11915       if (myrpt->idtimer) myrpt->idtimer -= elap;
11916       if (myrpt->idtimer < 0) myrpt->idtimer = 0;
11917       if (myrpt->tmsgtimer) myrpt->tmsgtimer -= elap;
11918       if (myrpt->tmsgtimer < 0) myrpt->tmsgtimer = 0;
11919       if (myrpt->voxtotimer) myrpt->voxtotimer -= elap;
11920       if (myrpt->voxtotimer < 0) myrpt->voxtotimer = 0;
11921       if (myrpt->exttx)
11922       {
11923          myrpt->parrottimer = myrpt->p.parrottime;
11924       }
11925       else
11926       {
11927          if (myrpt->parrottimer) myrpt->parrottimer -= elap;
11928          if (myrpt->parrottimer < 0) myrpt->parrottimer = 0;
11929       }
11930       /* do macro timers */
11931       if (myrpt->macrotimer) myrpt->macrotimer -= elap;
11932       if (myrpt->macrotimer < 0) myrpt->macrotimer = 0;
11933       /* do local dtmf timer */
11934       if (myrpt->dtmf_local_timer)
11935       {
11936          if (myrpt->dtmf_local_timer > 1) myrpt->dtmf_local_timer -= elap;
11937          if (myrpt->dtmf_local_timer < 1) myrpt->dtmf_local_timer = 1;
11938       }
11939       do_dtmf_local(myrpt,0);
11940       /* Execute scheduler appx. every 2 tenths of a second */
11941       if (myrpt->skedtimer <= 0){
11942          myrpt->skedtimer = 200;
11943          do_scheduler(myrpt);
11944       }
11945       else
11946          myrpt->skedtimer -=elap;
11947       if (!ms) 
11948       {
11949          rpt_mutex_unlock(&myrpt->lock);
11950          continue;
11951       }
11952       if (myrpt->p.parrotmode && (myrpt->parrotstate == 1) &&
11953          (myrpt->parrottimer <= 0))
11954       {
11955 
11956          ci.confno = 0;
11957          ci.confmode = 0;
11958          ci.chan = 0;
11959 
11960          /* first put the channel on the conference in announce mode */
11961          if (ioctl(myrpt->parrotchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
11962          {
11963             ast_log(LOG_WARNING, "Unable to set conference mode for parrot\n");
11964             break;
11965          }
11966          if (myrpt->parrotstream) 
11967             ast_closestream(myrpt->parrotstream);
11968          myrpt->parrotstream = NULL;
11969          myrpt->parrotstate = 2;
11970          rpt_telemetry(myrpt,PARROT,(void *) ((intptr_t)myrpt->parrotcnt++)); 
11971       }        
11972       if (myrpt->cmdAction.state == CMD_STATE_READY)
11973       { /* there is a command waiting to be processed */
11974          myrpt->cmdAction.state = CMD_STATE_EXECUTING;
11975          // lose the lock
11976          rpt_mutex_unlock(&myrpt->lock);
11977          // do the function
11978          (*function_table[myrpt->cmdAction.functionNumber].function)(myrpt,myrpt->cmdAction.param, myrpt->cmdAction.digits, myrpt->cmdAction.command_source, NULL);
11979          // get the lock again
11980          rpt_mutex_lock(&myrpt->lock);
11981          myrpt->cmdAction.state = CMD_STATE_IDLE;
11982       } /* if myrpt->cmdAction.state == CMD_STATE_READY */
11983       
11984       c = myrpt->macrobuf[0];
11985       time(&t);
11986       if (c && (!myrpt->macrotimer) && 
11987          starttime && (t > (starttime + START_DELAY)))
11988       {
11989          char cin = c & 0x7f;
11990          myrpt->macrotimer = MACROTIME;
11991          memmove(myrpt->macrobuf,myrpt->macrobuf + 1,MAXMACRO - 1);
11992          if ((cin == 'p') || (cin == 'P'))
11993             myrpt->macrotimer = MACROPTIME;
11994          rpt_mutex_unlock(&myrpt->lock);
11995          if (myrpt->p.archivedir)
11996          {
11997             char str[100];
11998 
11999             sprintf(str,"DTMF(M),MAIN,%c",cin);
12000             donodelog(myrpt,str);
12001          }
12002          local_dtmf_helper(myrpt,c);
12003       } else rpt_mutex_unlock(&myrpt->lock);
12004       if (who == myrpt->rxchannel) /* if it was a read from rx */
12005       {
12006          int ismuted;
12007 
12008          f = ast_read(myrpt->rxchannel);
12009          if (!f)
12010          {
12011             if (debug) printf("@@@@ rpt:Hung Up\n");
12012             break;
12013          }
12014          if (f->frametype == AST_FRAME_VOICE)
12015          {
12016 #ifdef   _MDC_DECODE_H_
12017             unsigned char ubuf[2560];
12018             short *sp;
12019             int n;
12020 #endif
12021 
12022             if ((!myrpt->localtx) && (!myrpt->p.linktolink)) {
12023                memset(f->data.ptr,0,f->datalen);
12024             }
12025 
12026 #ifdef   _MDC_DECODE_H_
12027             sp = (short *) f->data;
12028             /* convert block to unsigned char */
12029             for(n = 0; n < f->datalen / 2; n++)
12030             {
12031                ubuf[n] = (*sp++ >> 8) + 128;
12032             }
12033             n = mdc_decoder_process_samples(myrpt->mdc,ubuf,f->datalen / 2);
12034             if (n == 1)
12035             {
12036                   unsigned char op,arg;
12037                   unsigned short unitID;
12038 
12039                   mdc_decoder_get_packet(myrpt->mdc,&op,&arg,&unitID);
12040                   if (debug > 2)
12041                   {
12042                      ast_log(LOG_NOTICE,"Got (single-length) packet:\n");
12043                      ast_log(LOG_NOTICE,"op: %02x, arg: %02x, UnitID: %04x\n",
12044                         op & 255,arg & 255,unitID);
12045                   }
12046                   if ((op == 1) && (arg == 0))
12047                   {
12048                      myrpt->lastunit = unitID;
12049                      mdc1200_notify(myrpt,NULL,myrpt->lastunit);
12050                      mdc1200_send(myrpt,myrpt->lastunit);
12051                   }
12052             }
12053             if ((debug > 2) && (i == 2))
12054             {
12055                unsigned char op,arg,ex1,ex2,ex3,ex4;
12056                unsigned short unitID;
12057 
12058                mdc_decoder_get_double_packet(myrpt->mdc,&op,&arg,&unitID,
12059                   &ex1,&ex2,&ex3,&ex4);
12060                ast_log(LOG_NOTICE,"Got (double-length) packet:\n");
12061                ast_log(LOG_NOTICE,"op: %02x, arg: %02x, UnitID: %04x\n",
12062                   op & 255,arg & 255,unitID);
12063                ast_log(LOG_NOTICE,"ex1: %02x, ex2: %02x, ex3: %02x, ex4: %02x\n",
12064                   ex1 & 255, ex2 & 255, ex3 & 255, ex4 & 255);
12065             }
12066 #endif
12067 #ifdef   __RPT_NOTCH
12068             /* apply inbound filters, if any */
12069             rpt_filter(myrpt,f->data,f->datalen / 2);
12070 #endif
12071             if (ioctl(myrpt->dahdirxchannel->fds[0], DAHDI_GETCONFMUTE, &ismuted) == -1)
12072             {
12073                ismuted = 0;
12074             }
12075             if (dtmfed) ismuted = 1;
12076             dtmfed = 0;
12077             if (ismuted)
12078             {
12079                memset(f->data.ptr,0,f->datalen);
12080                if (myrpt->lastf1)
12081                   memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
12082                if (myrpt->lastf2)
12083                   memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
12084             } 
12085             if (f) f2 = ast_frdup(f);
12086             else f2 = NULL;
12087             f1 = myrpt->lastf2;
12088             myrpt->lastf2 = myrpt->lastf1;
12089             myrpt->lastf1 = f2;
12090             if (ismuted)
12091             {
12092                if (myrpt->lastf1)
12093                   memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
12094                if (myrpt->lastf2)
12095                   memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
12096             }
12097             if (f1)
12098             {
12099                ast_write(myrpt->pchannel,f1);
12100                ast_frfree(f1);
12101             }
12102          }
12103 #ifndef  OLD_ASTERISK
12104          else if (f->frametype == AST_FRAME_DTMF_BEGIN)
12105          {
12106             if (myrpt->lastf1)
12107                memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
12108             if (myrpt->lastf2)
12109                memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
12110             dtmfed = 1;
12111          }
12112 #endif
12113          else if (f->frametype == AST_FRAME_DTMF)
12114          {
12115             c = (char) f->subclass.integer; /* get DTMF char */
12116             ast_frfree(f);
12117             if (myrpt->lastf1)
12118                memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
12119             if (myrpt->lastf2)
12120                memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
12121             dtmfed = 1;
12122             if (!myrpt->keyed) continue;
12123             c = func_xlat(myrpt,c,&myrpt->p.inxlat);
12124             if (c) local_dtmf_helper(myrpt,c);
12125             continue;
12126          }                 
12127          else if (f->frametype == AST_FRAME_CONTROL)
12128          {
12129             if (f->subclass.integer == AST_CONTROL_HANGUP)
12130             {
12131                if (debug) printf("@@@@ rpt:Hung Up\n");
12132                ast_frfree(f);
12133                break;
12134             }
12135             /* if RX key */
12136             if (f->subclass.integer == AST_CONTROL_RADIO_KEY)
12137             {
12138                if ((!lasttx) || (myrpt->p.duplex > 1) || (myrpt->p.linktolink)) 
12139                {
12140                   if (debug == 7) printf("@@@@ rx key\n");
12141                   myrpt->keyed = 1;
12142                   time(&myrpt->lastkeyedtime);
12143                   myrpt->keyposttimer = KEYPOSTSHORTTIME;
12144                }
12145                if (myrpt->p.archivedir)
12146                {
12147                   donodelog(myrpt,"RXKEY,MAIN");
12148                }
12149                if (f->datalen && f->data.ptr)
12150                {
12151                   char busy = 0;
12152 
12153                   if (debug) ast_log(LOG_NOTICE,"Got PL %s on node %s\n",(char *)f->data.ptr,myrpt->name);
12154                   // ctcss code autopatch initiate
12155                   if (strstr((char *)f->data.ptr,"/M/")&& !myrpt->macropatch)
12156                   {
12157                      char value[16] = "";
12158                      strcat(value,"*6");
12159                      myrpt->macropatch=1;
12160                      rpt_mutex_lock(&myrpt->lock);
12161                      if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(value)){
12162                         rpt_mutex_unlock(&myrpt->lock);
12163                         busy=1;
12164                      }
12165                      if(!busy){
12166                         myrpt->macrotimer = MACROTIME;
12167                         strncat(myrpt->macrobuf,value,MAXMACRO - 1);
12168                         if (!busy) strcpy(myrpt->lasttone,(char*)f->data.ptr);
12169                      }
12170                      rpt_mutex_unlock(&myrpt->lock);
12171                   }
12172                   else if (strcmp((char *)f->data.ptr,myrpt->lasttone))
12173                   {
12174                      char *value = (char *) ast_variable_retrieve(myrpt->cfg, myrpt->p.tonemacro, (char *)f->data.ptr);
12175                      if (value)
12176                      {
12177                         if (debug) ast_log(LOG_NOTICE,"Tone %s doing %s on node %s\n",(char *) f->data.ptr,value,myrpt->name);
12178                         rpt_mutex_lock(&myrpt->lock);
12179                         if ((MAXMACRO - strlen(myrpt->macrobuf)) < strlen(value)){
12180                            rpt_mutex_unlock(&myrpt->lock);
12181                            busy=1;
12182                         }
12183                         if(!busy){
12184                            myrpt->macrotimer = MACROTIME;
12185                            strncat(myrpt->macrobuf,value,MAXMACRO - 1);
12186                         }
12187                         rpt_mutex_unlock(&myrpt->lock);
12188                      }
12189                      if (!busy) strcpy(myrpt->lasttone,(char*)f->data.ptr);
12190                   }
12191                } else myrpt->lasttone[0] = 0;
12192             }
12193             /* if RX un-key */
12194             if (f->subclass.integer == AST_CONTROL_RADIO_UNKEY)
12195             {
12196                if ((!lasttx) || (myrpt->p.duplex > 1) || (myrpt->p.linktolink))
12197                {
12198                   if (debug == 7) printf("@@@@ rx un-key\n");
12199                   if(myrpt->p.duplex && myrpt->keyed) {
12200                      rpt_telemetry(myrpt,UNKEY,NULL);
12201                   }
12202                }
12203                myrpt->keyed = 0;
12204                time(&myrpt->lastkeyedtime);
12205                myrpt->keyposttimer = KEYPOSTSHORTTIME;
12206                if (myrpt->p.archivedir)
12207                {
12208                   donodelog(myrpt,"RXUNKEY,MAIN");
12209                }
12210             }
12211          }
12212          ast_frfree(f);
12213          continue;
12214       }
12215       if (who == myrpt->pchannel) /* if it was a read from pseudo */
12216       {
12217          f = ast_read(myrpt->pchannel);
12218          if (!f)
12219          {
12220             if (debug) printf("@@@@ rpt:Hung Up\n");
12221             break;
12222          }
12223          if (f->frametype == AST_FRAME_VOICE)
12224          {
12225             ast_write(myrpt->txpchannel,f);
12226          }
12227          if (f->frametype == AST_FRAME_CONTROL)
12228          {
12229             if (f->subclass.integer == AST_CONTROL_HANGUP)
12230             {
12231                if (debug) printf("@@@@ rpt:Hung Up\n");
12232                ast_frfree(f);
12233                break;
12234             }
12235          }
12236          ast_frfree(f);
12237          continue;
12238       }
12239       if (who == myrpt->txchannel) /* if it was a read from tx */
12240       {
12241          f = ast_read(myrpt->txchannel);
12242          if (!f)
12243          {
12244             if (debug) printf("@@@@ rpt:Hung Up\n");
12245             break;
12246          }
12247          if (f->frametype == AST_FRAME_CONTROL)
12248          {
12249             if (f->subclass.integer == AST_CONTROL_HANGUP)
12250             {
12251                if (debug) printf("@@@@ rpt:Hung Up\n");
12252                ast_frfree(f);
12253                break;
12254             }
12255          }
12256          ast_frfree(f);
12257          continue;
12258       }
12259       if (who == myrpt->dahditxchannel) /* if it was a read from pseudo-tx */
12260       {
12261          f = ast_read(myrpt->dahditxchannel);
12262          if (!f)
12263          {
12264             if (debug) printf("@@@@ rpt:Hung Up\n");
12265             break;
12266          }
12267          if (f->frametype == AST_FRAME_VOICE)
12268          {
12269             struct ast_frame *vframe;
12270 
12271             if (myrpt->p.duplex < 2)
12272             {
12273                if (myrpt->txrealkeyed) 
12274                {
12275                   if ((!myfirst) && myrpt->callmode)
12276                   {
12277                       x = 0;
12278                       AST_LIST_TRAVERSE(&myrpt->txq, vframe,
12279                      frame_list) x++;
12280                       for(;x < myrpt->p.simplexpatchdelay; x++)
12281                       {
12282                         vframe = ast_frdup(f);
12283                         memset(vframe->data.ptr,0,vframe->datalen);
12284                         AST_LIST_INSERT_TAIL(&myrpt->txq,vframe,frame_list);
12285                       }
12286                       myfirst = 1;
12287                   }
12288                   vframe = ast_frdup(f);
12289                   AST_LIST_INSERT_TAIL(&myrpt->txq,
12290                      vframe,frame_list);
12291                } else myfirst = 0;
12292                x = 0;
12293                AST_LIST_TRAVERSE(&myrpt->txq, vframe,
12294                   frame_list) x++;
12295                if (!x)
12296                {
12297                   memset(f->data.ptr,0,f->datalen);
12298                }
12299                else
12300                {
12301                   ast_frfree(f);
12302                   f = AST_LIST_REMOVE_HEAD(&myrpt->txq,
12303                      frame_list);
12304                }
12305             }
12306             else
12307             {
12308                while((vframe = AST_LIST_REMOVE_HEAD(&myrpt->txq,
12309                   frame_list))) ast_frfree(vframe);
12310             }
12311             ast_write(myrpt->txchannel,f);
12312          }
12313          if (f->frametype == AST_FRAME_CONTROL)
12314          {
12315             if (f->subclass.integer == AST_CONTROL_HANGUP)
12316             {
12317                if (debug) printf("@@@@ rpt:Hung Up\n");
12318                ast_frfree(f);
12319                break;
12320             }
12321          }
12322          ast_frfree(f);
12323          continue;
12324       }
12325       toexit = 0;
12326       rpt_mutex_lock(&myrpt->lock);
12327       l = myrpt->links.next;
12328       while(l != &myrpt->links)
12329       {
12330          int remnomute;
12331          struct timeval now;
12332 
12333          if (l->disctime)
12334          {
12335             l = l->next;
12336             continue;
12337          }
12338 
12339          remrx = 0;
12340          /* see if any other links are receiving */
12341          m = myrpt->links.next;
12342          while(m != &myrpt->links)
12343          {
12344             /* if not us, count it */
12345             if ((m != l) && (m->lastrx)) remrx = 1;
12346             m = m->next;
12347          }
12348          rpt_mutex_unlock(&myrpt->lock);
12349          now = ast_tvnow();
12350          if ((who == l->chan) || (!l->lastlinktv.tv_sec) ||
12351             (ast_tvdiff_ms(now,l->lastlinktv) >= 19))
12352          {
12353             l->lastlinktv = now;
12354             remnomute = myrpt->localtx && 
12355                 (!(myrpt->cmdnode[0] || 
12356                (myrpt->dtmfidx > -1)));
12357             totx = (((l->isremote) ? (remnomute) : 
12358                myrpt->exttx) || remrx) && l->mode;
12359             if (l->phonemode == 0 && l->chan && (l->lasttx != totx))
12360             {
12361                if (totx)
12362                {
12363                   ast_indicate(l->chan,AST_CONTROL_RADIO_KEY);
12364                }
12365                else
12366                {
12367                   ast_indicate(l->chan,AST_CONTROL_RADIO_UNKEY);
12368                }
12369                if (myrpt->p.archivedir)
12370                {
12371                   char str[100];
12372 
12373                   if (totx)
12374                      sprintf(str,"TXKEY,%s",l->name);
12375                   else
12376                      sprintf(str,"TXUNKEY,%s",l->name);
12377                   donodelog(myrpt,str);
12378                }
12379             }
12380             l->lasttx = totx;
12381          }
12382          rpt_mutex_lock(&myrpt->lock);
12383          if (who == l->chan) /* if it was a read from rx */
12384          {
12385             rpt_mutex_unlock(&myrpt->lock);
12386             f = ast_read(l->chan);
12387             if (!f)
12388             {
12389                rpt_mutex_lock(&myrpt->lock);
12390                __kickshort(myrpt);
12391                rpt_mutex_unlock(&myrpt->lock);
12392                if ((!l->disced) && (!l->outbound))
12393                {
12394                   if ((l->name[0] == '0') || l->isremote)
12395                      l->disctime = 1;
12396                   else
12397                      l->disctime = DISC_TIME;
12398                   rpt_mutex_lock(&myrpt->lock);
12399                   ast_hangup(l->chan);
12400                   l->chan = 0;
12401                   break;
12402                }
12403 
12404                if (l->retrytimer) 
12405                {
12406                   ast_hangup(l->chan);
12407                   l->chan = 0;
12408                   rpt_mutex_lock(&myrpt->lock);
12409                   break; 
12410                }
12411                if (l->outbound && (l->retries++ < l->max_retries) && (l->hasconnected))
12412                {
12413                   rpt_mutex_lock(&myrpt->lock);
12414                   if (l->chan) ast_hangup(l->chan);
12415                   l->chan = 0;
12416                   l->hasconnected = 1;
12417                   l->retrytimer = RETRY_TIMER_MS;
12418                   l->elaptime = 0;
12419                   l->connecttime = 0;
12420                   l->thisconnected = 0;
12421                   break;
12422                }
12423                rpt_mutex_lock(&myrpt->lock);
12424                /* remove from queue */
12425                remque((struct qelem *) l);
12426                if (!strcmp(myrpt->cmdnode,l->name))
12427                   myrpt->cmdnode[0] = 0;
12428                __kickshort(myrpt);
12429                rpt_mutex_unlock(&myrpt->lock);
12430                if (!l->hasconnected)
12431                   rpt_telemetry(myrpt,CONNFAIL,l);
12432                else if (l->disced != 2) rpt_telemetry(myrpt,REMDISC,l);
12433                if (myrpt->p.archivedir)
12434                {
12435                   char str[100];
12436 
12437                   if (!l->hasconnected)
12438                      sprintf(str,"LINKFAIL,%s",l->name);
12439                   else
12440                      sprintf(str,"LINKDISC,%s",l->name);
12441                   donodelog(myrpt,str);
12442                }
12443                if (l->lastf1) ast_frfree(l->lastf1);
12444                l->lastf1 = NULL;
12445                if (l->lastf2) ast_frfree(l->lastf2);
12446                l->lastf2 = NULL;
12447                /* hang-up on call to device */
12448                ast_hangup(l->chan);
12449                ast_hangup(l->pchan);
12450                ast_free(l);
12451                rpt_mutex_lock(&myrpt->lock);
12452                break;
12453             }
12454             if (f->frametype == AST_FRAME_VOICE)
12455             {
12456                int ismuted,n1;
12457 
12458                if ((l->phonemode) && (l->phonevox))
12459                {
12460                   n1 = dovox(&l->vox,
12461                      f->data.ptr,f->datalen / 2);
12462                   if (n1 != l->wasvox)
12463                   {
12464                      if (debug)ast_log(LOG_DEBUG,"Link Node %s, vox %d\n",l->name,n1);
12465                      l->wasvox = n1;
12466                      l->voxtostate = 0;
12467                      if (n1) l->voxtotimer = myrpt->p.voxtimeout_ms;
12468                      else l->voxtotimer = 0;
12469                   }
12470                   if (l->lastrealrx || n1)
12471                   {
12472                      if (!myfirst)
12473                      {
12474                          x = 0;
12475                          AST_LIST_TRAVERSE(&l->rxq, f1,
12476                         frame_list) x++;
12477                          for(;x < myrpt->p.simplexphonedelay; x++)
12478                         {
12479                            f1 = ast_frdup(f);
12480                            memset(f1->data.ptr,0,f1->datalen);
12481                            AST_LIST_INSERT_TAIL(&l->rxq,
12482                               f1,frame_list);
12483                          }
12484                          myfirst = 1;
12485                      }
12486                      f1 = ast_frdup(f);
12487                      AST_LIST_INSERT_TAIL(&l->rxq,f1,frame_list);
12488                   } else myfirst = 0; 
12489                   x = 0;
12490                   AST_LIST_TRAVERSE(&l->rxq, f1,frame_list) x++;
12491                   if (!x)
12492                   {
12493                      memset(f->data.ptr,0,f->datalen);
12494                   }
12495                   else
12496                   {
12497                      ast_frfree(f);
12498                      f = AST_LIST_REMOVE_HEAD(&l->rxq,frame_list);
12499                   }
12500                   if (ioctl(l->chan->fds[0], DAHDI_GETCONFMUTE, &ismuted) == -1)
12501                   {
12502                      ismuted = 0;
12503                   }
12504                   /* if not receiving, zero-out audio */
12505                   ismuted |= (!l->lastrx);
12506                   if (l->dtmfed && l->phonemode) ismuted = 1;
12507                   l->dtmfed = 0;
12508                   if (ismuted)
12509                   {
12510                      memset(f->data.ptr,0,f->datalen);
12511                      if (l->lastf1)
12512                         memset(l->lastf1->data.ptr,0,l->lastf1->datalen);
12513                      if (l->lastf2)
12514                         memset(l->lastf2->data.ptr,0,l->lastf2->datalen);
12515                   } 
12516                   if (f) f2 = ast_frdup(f);
12517                   else f2 = NULL;
12518                   f1 = l->lastf2;
12519                   l->lastf2 = l->lastf1;
12520                   l->lastf1 = f2;
12521                   if (ismuted)
12522                   {
12523                      if (l->lastf1)
12524                         memset(l->lastf1->data.ptr,0,l->lastf1->datalen);
12525                      if (l->lastf2)
12526                         memset(l->lastf2->data.ptr,0,l->lastf2->datalen);
12527                   }
12528                   if (f1)
12529                   {
12530                      ast_write(l->pchan,f1);
12531                      ast_frfree(f1);
12532                   }
12533                }
12534                else
12535                {
12536                   if (!l->lastrx)
12537                      memset(f->data.ptr,0,f->datalen);
12538                   ast_write(l->pchan,f);
12539                }
12540             }
12541 #ifndef  OLD_ASTERISK
12542             else if (f->frametype == AST_FRAME_DTMF_BEGIN)
12543             {
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                l->dtmfed = 1;
12549             }
12550 #endif
12551             if (f->frametype == AST_FRAME_TEXT)
12552             {
12553                handle_link_data(myrpt,l,f->data.ptr);
12554             }
12555             if (f->frametype == AST_FRAME_DTMF)
12556             {
12557                if (l->lastf1)
12558                   memset(l->lastf1->data.ptr,0,l->lastf1->datalen);
12559                if (l->lastf2)
12560                   memset(l->lastf2->data.ptr,0,l->lastf2->datalen);
12561                l->dtmfed = 1;
12562                handle_link_phone_dtmf(myrpt,l,f->subclass.integer);
12563             }
12564             if (f->frametype == AST_FRAME_CONTROL)
12565             {
12566                if (f->subclass.integer == AST_CONTROL_ANSWER)
12567                {
12568                   char lconnected = l->connected;
12569 
12570                   __kickshort(myrpt);
12571                   l->connected = 1;
12572                   l->hasconnected = 1;
12573                   l->thisconnected = 1;
12574                   l->elaptime = -1;
12575                   if (!l->phonemode) send_newkey(l->chan);
12576                   if (!l->isremote) l->retries = 0;
12577                   if (!lconnected) 
12578                   {
12579                      rpt_telemetry(myrpt,CONNECTED,l);
12580                      if (myrpt->p.archivedir)
12581                      {
12582                         char str[100];
12583 
12584                         if (l->mode)
12585                            sprintf(str,"LINKTRX,%s",l->name);
12586                         else
12587                            sprintf(str,"LINKMONITOR,%s",l->name);
12588                         donodelog(myrpt,str);
12589                      }
12590                   }     
12591                   else
12592                      l->reconnects++;
12593                }
12594                /* if RX key */
12595                if (f->subclass.integer == AST_CONTROL_RADIO_KEY)
12596                {
12597                   if (debug == 7 ) printf("@@@@ rx key\n");
12598                   l->lastrealrx = 1;
12599                   l->rerxtimer = 0;
12600                   if (!l->lastrx1)
12601                   {
12602                      if (myrpt->p.archivedir)
12603                      {
12604                         char str[100];
12605 
12606                         sprintf(str,"RXKEY,%s",l->name);
12607                         donodelog(myrpt,str);
12608                      }
12609                      l->lastrx1 = 1;
12610                   }
12611                }
12612                /* if RX un-key */
12613                if (f->subclass.integer == AST_CONTROL_RADIO_UNKEY)
12614                {
12615                   if (debug == 7) printf("@@@@ rx un-key\n");
12616                   l->lastrealrx = 0;
12617                   l->rerxtimer = 0;
12618                   if (l->lastrx1)
12619                   {
12620                      if (myrpt->p.archivedir)
12621                      {
12622                         char str[100];
12623 
12624                         sprintf(str,"RXUNKEY,%s",l->name);
12625                         donodelog(myrpt,str);
12626                      }
12627                      l->lastrx1 = 0;
12628                      if(myrpt->p.duplex) 
12629                         rpt_telemetry(myrpt,LINKUNKEY,l);
12630                   }
12631                }
12632                if (f->subclass.integer == AST_CONTROL_HANGUP)
12633                {
12634                   ast_frfree(f);
12635                   rpt_mutex_lock(&myrpt->lock);
12636                   __kickshort(myrpt);
12637                   rpt_mutex_unlock(&myrpt->lock);
12638                   if ((!l->outbound) && (!l->disced))
12639                   {
12640                      if ((l->name[0] == '0') || l->isremote)
12641                         l->disctime = 1;
12642                      else
12643                         l->disctime = DISC_TIME;
12644                      rpt_mutex_lock(&myrpt->lock);
12645                      ast_hangup(l->chan);
12646                      l->chan = 0;
12647                      break;
12648                   }
12649                   if (l->retrytimer) 
12650                   {
12651                      if (l->chan) ast_hangup(l->chan);
12652                      l->chan = 0;
12653                      rpt_mutex_lock(&myrpt->lock);
12654                      break;
12655                   }
12656                   if (l->outbound && (l->retries++ < l->max_retries) && (l->hasconnected))
12657                   {
12658                      rpt_mutex_lock(&myrpt->lock);
12659                      if (l->chan) ast_hangup(l->chan);
12660                      l->chan = 0;
12661                      l->hasconnected = 1;
12662                      l->elaptime = 0;
12663                      l->retrytimer = RETRY_TIMER_MS;
12664                      l->connecttime = 0;
12665                      l->thisconnected = 0;
12666                      break;
12667                   }
12668                   rpt_mutex_lock(&myrpt->lock);
12669                   /* remove from queue */
12670                   remque((struct qelem *) l);
12671                   if (!strcmp(myrpt->cmdnode,l->name))
12672                      myrpt->cmdnode[0] = 0;
12673                   __kickshort(myrpt);
12674                   rpt_mutex_unlock(&myrpt->lock);
12675                   if (!l->hasconnected)
12676                      rpt_telemetry(myrpt,CONNFAIL,l);
12677                   else if (l->disced != 2) rpt_telemetry(myrpt,REMDISC,l);
12678                   if (myrpt->p.archivedir)
12679                   {
12680                      char str[100];
12681 
12682                      if (!l->hasconnected)
12683                         sprintf(str,"LINKFAIL,%s",l->name);
12684                      else
12685                         sprintf(str,"LINKDISC,%s",l->name);
12686                      donodelog(myrpt,str);
12687                   }
12688                   if (l->lastf1) ast_frfree(l->lastf1);
12689                   l->lastf1 = NULL;
12690                   if (l->lastf2) ast_frfree(l->lastf2);
12691                   l->lastf2 = NULL;
12692                   /* hang-up on call to device */
12693                   ast_hangup(l->chan);
12694                   ast_hangup(l->pchan);
12695                   ast_free(l);
12696                   rpt_mutex_lock(&myrpt->lock);
12697                   break;
12698                }
12699             }
12700             ast_frfree(f);
12701             rpt_mutex_lock(&myrpt->lock);
12702             break;
12703          }
12704          if (who == l->pchan) 
12705          {
12706             rpt_mutex_unlock(&myrpt->lock);
12707             f = ast_read(l->pchan);
12708             if (!f)
12709             {
12710                if (debug) printf("@@@@ rpt:Hung Up\n");
12711                toexit = 1;
12712                rpt_mutex_lock(&myrpt->lock);
12713                break;
12714             }
12715             if (f->frametype == AST_FRAME_VOICE)
12716             {
12717                if (l->chan) ast_write(l->chan,f);
12718             }
12719             if (f->frametype == AST_FRAME_CONTROL)
12720             {
12721                if (f->subclass.integer == AST_CONTROL_HANGUP)
12722                {
12723                   if (debug) printf("@@@@ rpt:Hung Up\n");
12724                   ast_frfree(f);
12725                   toexit = 1;
12726                   rpt_mutex_lock(&myrpt->lock);
12727                   break;
12728                }
12729             }
12730             ast_frfree(f);
12731             rpt_mutex_lock(&myrpt->lock);
12732             break;
12733          }
12734          l = l->next;
12735       }
12736       rpt_mutex_unlock(&myrpt->lock);
12737       if (toexit) break;
12738       if (who == myrpt->monchannel) 
12739       {
12740          f = ast_read(myrpt->monchannel);
12741          if (!f)
12742          {
12743             if (debug) printf("@@@@ rpt:Hung Up\n");
12744             break;
12745          }
12746          if (f->frametype == AST_FRAME_VOICE)
12747          {
12748             if (myrpt->monstream) 
12749                ast_writestream(myrpt->monstream,f);
12750          }
12751          if (f->frametype == AST_FRAME_CONTROL)
12752          {
12753             if (f->subclass.integer == AST_CONTROL_HANGUP)
12754             {
12755                if (debug) printf("@@@@ rpt:Hung Up\n");
12756                ast_frfree(f);
12757                break;
12758             }
12759          }
12760          ast_frfree(f);
12761          continue;
12762       }
12763       if (myrpt->parrotchannel && (who == myrpt->parrotchannel))
12764       {
12765          f = ast_read(myrpt->parrotchannel);
12766          if (!f)
12767          {
12768             if (debug) printf("@@@@ rpt:Hung Up\n");
12769             break;
12770          }
12771          if (!myrpt->p.parrotmode)
12772          {
12773             char myfname[300];
12774 
12775             if (myrpt->parrotstream)
12776             {
12777                ast_closestream(myrpt->parrotstream);
12778                myrpt->parrotstream = 0;
12779             }
12780             sprintf(myfname,PARROTFILE,myrpt->name,myrpt->parrotcnt);
12781             strcat(myfname,".wav");
12782             unlink(myfname);        
12783          } else if (f->frametype == AST_FRAME_VOICE)
12784          {
12785             if (myrpt->parrotstream) 
12786                ast_writestream(myrpt->parrotstream,f);
12787          }
12788          if (f->frametype == AST_FRAME_CONTROL)
12789          {
12790             if (f->subclass.integer == AST_CONTROL_HANGUP)
12791             {
12792                if (debug) printf("@@@@ rpt:Hung Up\n");
12793                ast_frfree(f);
12794                break;
12795             }
12796          }
12797          ast_frfree(f);
12798          continue;
12799       }
12800       if (myrpt->voxchannel && (who == myrpt->voxchannel))
12801       {
12802          f = ast_read(myrpt->voxchannel);
12803          if (!f)
12804          {
12805             if (debug) printf("@@@@ rpt:Hung Up\n");
12806             break;
12807          }
12808          if (f->frametype == AST_FRAME_VOICE)
12809          {
12810             n = dovox(&myrpt->vox,f->data.ptr,f->datalen / 2);
12811             if (n != myrpt->wasvox)
12812             {
12813                if (debug) ast_log(LOG_DEBUG,"Node %s, vox %d\n",myrpt->name,n);
12814                myrpt->wasvox = n;
12815                myrpt->voxtostate = 0;
12816                if (n) myrpt->voxtotimer = myrpt->p.voxtimeout_ms;
12817                else myrpt->voxtotimer = 0;
12818             }
12819          }
12820          if (f->frametype == AST_FRAME_CONTROL)
12821          {
12822             if (f->subclass.integer == AST_CONTROL_HANGUP)
12823             {
12824                if (debug) printf("@@@@ rpt:Hung Up\n");
12825                ast_frfree(f);
12826                break;
12827             }
12828          }
12829          ast_frfree(f);
12830          continue;
12831       }
12832       if (who == myrpt->txpchannel) /* if it was a read from remote tx */
12833       {
12834          f = ast_read(myrpt->txpchannel);
12835          if (!f)
12836          {
12837             if (debug) printf("@@@@ rpt:Hung Up\n");
12838             break;
12839          }
12840          if (f->frametype == AST_FRAME_CONTROL)
12841          {
12842             if (f->subclass.integer == AST_CONTROL_HANGUP)
12843             {
12844                if (debug) printf("@@@@ rpt:Hung Up\n");
12845                ast_frfree(f);
12846                break;
12847             }
12848          }
12849          ast_frfree(f);
12850          continue;
12851       }
12852    }
12853    usleep(100000);
12854    ast_hangup(myrpt->pchannel);
12855    ast_hangup(myrpt->monchannel);
12856    if (myrpt->parrotchannel) ast_hangup(myrpt->parrotchannel);
12857    myrpt->parrotstate = 0;
12858    if (myrpt->voxchannel) ast_hangup(myrpt->voxchannel);
12859    ast_hangup(myrpt->txpchannel);
12860    if (myrpt->txchannel != myrpt->rxchannel) ast_hangup(myrpt->txchannel);
12861    if (myrpt->dahditxchannel != myrpt->txchannel) ast_hangup(myrpt->dahditxchannel);
12862    if (myrpt->lastf1) ast_frfree(myrpt->lastf1);
12863    myrpt->lastf1 = NULL;
12864    if (myrpt->lastf2) ast_frfree(myrpt->lastf2);
12865    myrpt->lastf2 = NULL;
12866    ast_hangup(myrpt->rxchannel);
12867    rpt_mutex_lock(&myrpt->lock);
12868    l = myrpt->links.next;
12869    while(l != &myrpt->links)
12870    {
12871       struct rpt_link *ll = l;
12872       /* remove from queue */
12873       remque((struct qelem *) l);
12874       /* hang-up on call to device */
12875       if (l->chan) ast_hangup(l->chan);
12876       ast_hangup(l->pchan);
12877       l = l->next;
12878       ast_free(ll);
12879    }
12880    if (myrpt->xlink  == 1) myrpt->xlink = 2;
12881    rpt_mutex_unlock(&myrpt->lock);
12882    if (debug) printf("@@@@ rpt:Hung up channel\n");
12883    myrpt->rpt_thread = AST_PTHREADT_STOP;
12884    pthread_exit(NULL); 
12885    return NULL;
12886 }
12887 
12888    
12889 static void *rpt_master(void *ignore)
12890 {
12891 int   i,n;
12892 pthread_attr_t attr;
12893 struct ast_config *cfg;
12894 char *this,*val;
12895 
12896    /* init nodelog queue */
12897    nodelog.next = nodelog.prev = &nodelog;
12898    /* go thru all the specified repeaters */
12899    this = NULL;
12900    n = 0;
12901 #ifndef OLD_ASTERISK
12902    /* wait until asterisk starts */
12903         while(!ast_test_flag(&ast_options,AST_OPT_FLAG_FULLY_BOOTED))
12904                 usleep(250000);
12905 #endif
12906 #ifdef   NEW_ASTERISK
12907    rpt_vars[n].cfg = ast_config_load("rpt.conf",config_flags);
12908 #else
12909    rpt_vars[n].cfg = ast_config_load("rpt.conf");
12910 #endif
12911    cfg = rpt_vars[n].cfg;
12912    if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
12913       ast_log(LOG_NOTICE, "Unable to open radio repeater configuration rpt.conf.  Radio Repeater disabled.\n");
12914       pthread_exit(NULL);
12915    }
12916    while((this = ast_category_browse(cfg,this)) != NULL)
12917    {
12918       for(i = 0 ; i < strlen(this) ; i++){
12919          if((this[i] < '0') || (this[i] > '9'))
12920             break;
12921       }
12922       if(i != strlen(this)) continue; /* Not a node defn */
12923       memset(&rpt_vars[n],0,sizeof(rpt_vars[n]));
12924       rpt_vars[n].name = ast_strdup(this);
12925       val = (char *) ast_variable_retrieve(cfg,this,"rxchannel");
12926       if (val) rpt_vars[n].rxchanname = ast_strdup(val);
12927       val = (char *) ast_variable_retrieve(cfg,this,"txchannel");
12928       if (val) rpt_vars[n].txchanname = ast_strdup(val);
12929       rpt_vars[n].remote = 0;
12930       rpt_vars[n].remoterig = "";
12931       val = (char *) ast_variable_retrieve(cfg,this,"remote");
12932       if (val) 
12933       {
12934          rpt_vars[n].remoterig = ast_strdup(val);
12935          rpt_vars[n].remote = 1;
12936       }
12937       val = (char *) ast_variable_retrieve(cfg,this,"radiotype");
12938       if (val) rpt_vars[n].remoterig = ast_strdup(val);
12939       ast_mutex_init(&rpt_vars[n].lock);
12940       ast_mutex_init(&rpt_vars[n].remlock);
12941       ast_mutex_init(&rpt_vars[n].statpost_lock);
12942       rpt_vars[n].tele.next = &rpt_vars[n].tele;
12943       rpt_vars[n].tele.prev = &rpt_vars[n].tele;
12944       rpt_vars[n].rpt_thread = AST_PTHREADT_NULL;
12945       rpt_vars[n].tailmessagen = 0;
12946 #ifdef   _MDC_DECODE_H_
12947       rpt_vars[n].mdc = mdc_decoder_new(8000);
12948 #endif
12949       n++;
12950    }
12951    nrpts = n;
12952    ast_config_destroy(cfg);
12953 
12954    /* start em all */
12955    for(i = 0; i < n; i++)
12956    {
12957       load_rpt_vars(i,1);
12958 
12959       /* if is a remote, don't start one for it */
12960       if (rpt_vars[i].remote)
12961       {
12962          if(retreive_memory(&rpt_vars[i],"init")){ /* Try to retreive initial memory channel */
12963             if (!strcmp(rpt_vars[i].remoterig,remote_rig_rtx450))
12964                strncpy(rpt_vars[i].freq, "446.500", sizeof(rpt_vars[i].freq) - 1);
12965             else
12966                strncpy(rpt_vars[i].freq, "146.580", sizeof(rpt_vars[i].freq) - 1);
12967             strncpy(rpt_vars[i].rxpl, "100.0", sizeof(rpt_vars[i].rxpl) - 1);
12968 
12969             strncpy(rpt_vars[i].txpl, "100.0", sizeof(rpt_vars[i].txpl) - 1);
12970             rpt_vars[i].remmode = REM_MODE_FM;
12971             rpt_vars[i].offset = REM_SIMPLEX;
12972             rpt_vars[i].powerlevel = REM_LOWPWR;
12973          }
12974          continue;
12975       }
12976       else /* is a normal repeater */
12977       {
12978           rpt_vars[i].p.memory = rpt_vars[i].name;
12979          if(retreive_memory(&rpt_vars[i],"radiofreq")){ /* Try to retreive initial memory channel */
12980             if (!strcmp(rpt_vars[i].remoterig,remote_rig_rtx450))
12981                strncpy(rpt_vars[i].freq, "446.500", sizeof(rpt_vars[i].freq) - 1);
12982             else if (!strcmp(rpt_vars[i].remoterig,remote_rig_rtx150))
12983                strncpy(rpt_vars[i].freq, "146.580", sizeof(rpt_vars[i].freq) - 1);
12984             strncpy(rpt_vars[i].rxpl, "100.0", sizeof(rpt_vars[i].rxpl) - 1);
12985 
12986             strncpy(rpt_vars[i].txpl, "100.0", sizeof(rpt_vars[i].txpl) - 1);
12987             rpt_vars[i].remmode = REM_MODE_FM;
12988             rpt_vars[i].offset = REM_SIMPLEX;
12989             rpt_vars[i].powerlevel = REM_LOWPWR;
12990          }
12991          ast_log(LOG_NOTICE,"Normal Repeater Init  %s  %s  %s\n",rpt_vars[i].name, rpt_vars[i].remoterig, rpt_vars[i].freq);
12992       }
12993       if (!rpt_vars[i].p.ident)
12994       {
12995          ast_log(LOG_WARNING,"Did not specify ident for node %s\n",rpt_vars[i].name);
12996          ast_config_destroy(cfg);
12997          pthread_exit(NULL);
12998       }
12999            pthread_attr_init(&attr);
13000            pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13001       ast_pthread_create(&rpt_vars[i].rpt_thread,&attr,rpt,(void *) &rpt_vars[i]);
13002    }
13003    usleep(500000);
13004    time(&starttime);
13005    for(;;)
13006    {
13007       /* Now monitor each thread, and restart it if necessary */
13008       for(i = 0; i < n; i++)
13009       { 
13010          int rv;
13011          if (rpt_vars[i].remote) continue;
13012          if (rpt_vars[i].rpt_thread == AST_PTHREADT_STOP) 
13013             rv = -1;
13014          else
13015             rv = pthread_kill(rpt_vars[i].rpt_thread,0);
13016          if (rv)
13017          {
13018             if(time(NULL) - rpt_vars[i].lastthreadrestarttime <= 15)
13019             {
13020                if(rpt_vars[i].threadrestarts >= 5)
13021                {
13022                   ast_log(LOG_ERROR,"Continual RPT thread restarts, killing Asterisk\n");
13023                   exit(1); /* Stuck in a restart loop, kill Asterisk and start over */
13024                }
13025                else
13026                {
13027                   ast_log(LOG_NOTICE,"RPT thread restarted on %s\n",rpt_vars[i].name);
13028                   rpt_vars[i].threadrestarts++;
13029                }
13030             }
13031             else
13032                rpt_vars[i].threadrestarts = 0;
13033 
13034             rpt_vars[i].lastthreadrestarttime = time(NULL);
13035                  pthread_attr_init(&attr);
13036                  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
13037             ast_pthread_create(&rpt_vars[i].rpt_thread,&attr,rpt,(void *) &rpt_vars[i]);
13038             /* if (!rpt_vars[i].xlink) */
13039                ast_log(LOG_WARNING, "rpt_thread restarted on node %s\n", rpt_vars[i].name);
13040          }
13041 
13042       }
13043       for(;;)
13044       {
13045          struct nodelog *nodep;
13046          char *space,datestr[100],fname[300];
13047          int fd;
13048 
13049          ast_mutex_lock(&nodeloglock);
13050          nodep = nodelog.next;
13051          if(nodep == &nodelog) /* if nothing in queue */
13052          {
13053             ast_mutex_unlock(&nodeloglock);
13054             break;
13055          }
13056          remque((struct qelem *)nodep);
13057          ast_mutex_unlock(&nodeloglock);
13058          space = strchr(nodep->str,' ');
13059          if (!space) 
13060          {
13061             ast_free(nodep);
13062             continue;
13063          }
13064          *space = 0;
13065          strftime(datestr,sizeof(datestr) - 1,"%Y%m%d",
13066             localtime(&nodep->timestamp));
13067          sprintf(fname,"%s/%s/%s.txt",nodep->archivedir,
13068             nodep->str,datestr);
13069          fd = open(fname,O_WRONLY | O_CREAT | O_APPEND,0600);
13070          if (fd == -1)
13071          {
13072             ast_log(LOG_ERROR,"Cannot open node log file %s for write",space + 1);
13073             ast_free(nodep);
13074             continue;
13075          }
13076          if (write(fd,space + 1,strlen(space + 1)) !=
13077             strlen(space + 1))
13078          {
13079             ast_log(LOG_ERROR,"Cannot write node log file %s for write",space + 1);
13080             ast_free(nodep);
13081             continue;
13082          }
13083          close(fd);
13084          ast_free(nodep);
13085       }
13086       sleep(2);
13087    }
13088    ast_config_destroy(cfg);
13089    pthread_exit(NULL);
13090 }
13091 
13092 static int rpt_exec(struct ast_channel *chan, const char *data)
13093 {
13094    int res=-1,i,rem_totx,rem_rx,remkeyed,n,phone_mode = 0;
13095    int iskenwood_pci4,authtold,authreq,setting,notremming,reming;
13096    int ismuted,dtmfed,phone_vox = 0;
13097 #ifdef   OLD_ASTERISK
13098    struct localuser *u;
13099 #endif
13100    char tmp[256], keyed = 0,keyed1 = 0;
13101    char *options,*stringp,*tele,c,*altp,*memp;
13102    char sx[320],*sy;
13103    struct   rpt *myrpt;
13104    struct ast_frame *f,*f1,*f2;
13105    struct ast_channel *who;
13106    struct ast_channel *cs[20];
13107    struct   rpt_link *l;
13108    struct dahdi_confinfo ci;  /* conference info */
13109    struct dahdi_params par;
13110    int ms,elap,nullfd;
13111    time_t t,last_timeout_warning;
13112    struct   dahdi_radio_param z;
13113    struct rpt_tele *telem;
13114    int   numlinks;
13115 
13116    nullfd = open("/dev/null",O_RDWR);
13117    if (ast_strlen_zero(data)) {
13118       ast_log(LOG_WARNING, "Rpt requires an argument (system node)\n");
13119       return -1;
13120    }
13121 
13122    strncpy(tmp, (char *)data, sizeof(tmp)-1);
13123    time(&t);
13124    /* if time has externally shifted negative, screw it */
13125    if (t < starttime) t = starttime + START_DELAY;
13126    if ((!starttime) || (t < (starttime + START_DELAY)))
13127    {
13128       ast_log(LOG_NOTICE,"Node %s rejecting call: too soon!\n",tmp);
13129       ast_safe_sleep(chan,3000);
13130       return -1;
13131    }
13132 
13133    ast_log(LOG_NOTICE,"parsing argument=%s \n",tmp);
13134 
13135    altp=strstr(tmp, "|*");
13136    if(altp){
13137       altp[0]=0;
13138       altp++;
13139     }
13140 
13141    memp=strstr(tmp, "|M");
13142    if(memp){
13143       memp[0]=0;
13144       memp+=2;
13145     }
13146 
13147    stringp=tmp;
13148    strsep(&stringp, "|");
13149    options = stringp;
13150 
13151    ast_log(LOG_NOTICE,"options=%s \n",options);
13152    if(memp>0)ast_log(LOG_NOTICE,"memp=%s \n",memp);
13153    if(altp>0)ast_log(LOG_NOTICE,"altp=%s \n",altp);
13154 
13155    myrpt = NULL;
13156    /* see if we can find our specified one */
13157    for(i = 0; i < nrpts; i++)
13158    {
13159       /* if name matches, assign it and exit loop */
13160       if (!strcmp(tmp,rpt_vars[i].name))
13161       {
13162          myrpt = &rpt_vars[i];
13163          break;
13164       }
13165    }
13166 
13167    pbx_builtin_setvar_helper(chan, "RPT_STAT_ERR", "");
13168 
13169    if (myrpt == NULL)
13170    {
13171       pbx_builtin_setvar_helper(chan, "RPT_STAT_ERR", "NODE_NOT_FOUND");
13172       ast_log(LOG_WARNING, "Cannot find specified system node %s\n",tmp);
13173       return (priority_jump(NULL,chan));
13174    }
13175 
13176    numlinks=linkcount(myrpt);
13177 
13178    if(options && *options == 'q')
13179    {
13180       char buf2[128];
13181 
13182       if(myrpt->keyed)
13183          pbx_builtin_setvar_helper(chan, "RPT_STAT_RXKEYED", "1");
13184       else
13185          pbx_builtin_setvar_helper(chan, "RPT_STAT_RXKEYED", "0");   
13186 
13187       if(myrpt->txkeyed)
13188          pbx_builtin_setvar_helper(chan, "RPT_STAT_TXKEYED", "1");
13189       else
13190          pbx_builtin_setvar_helper(chan, "RPT_STAT_TXKEYED", "0");   
13191 
13192       snprintf(buf2,sizeof(buf2),"%s=%i", "RPT_STAT_XLINK", myrpt->xlink);
13193       pbx_builtin_setvar(chan, buf2);
13194       snprintf(buf2,sizeof(buf2),"%s=%i", "RPT_STAT_LINKS", numlinks);
13195       pbx_builtin_setvar(chan, buf2);
13196       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_WASCHAN", myrpt->waschan);
13197       pbx_builtin_setvar(chan, buf2);
13198       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_NOWCHAN", myrpt->nowchan);
13199       pbx_builtin_setvar(chan, buf2);
13200       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_DUPLEX", myrpt->p.duplex);
13201       pbx_builtin_setvar(chan, buf2);
13202       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_PARROT", myrpt->p.parrotmode);
13203       pbx_builtin_setvar(chan, buf2);
13204       //snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_PHONEVOX", myrpt->phonevox);
13205       //pbx_builtin_setvar(chan, buf2);
13206       //snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_CONNECTED", myrpt->connected);
13207       //pbx_builtin_setvar(chan, buf2);
13208       snprintf(buf2,sizeof(buf2),"%s=%d", "RPT_STAT_CALLMODE", myrpt->callmode);
13209       pbx_builtin_setvar(chan, buf2);
13210       snprintf(buf2,sizeof(buf2),"%s=%s", "RPT_STAT_LASTTONE", myrpt->lasttone);
13211       pbx_builtin_setvar(chan, buf2);
13212 
13213       return priority_jump(myrpt,chan);
13214    }
13215 
13216    if(options && *options == 'o')
13217    {
13218       return(channel_revert(myrpt));
13219    }
13220 
13221    #if 0
13222    if((altp)&&(*options == 'Z'))
13223    {
13224       rpt_push_alt_macro(myrpt,altp);
13225       return 0;
13226    }
13227    #endif
13228 
13229 
13230    /* if not phone access, must be an IAX connection */
13231    if (options && ((*options == 'P') || (*options == 'D') || (*options == 'R') || (*options == 'S')))
13232    {
13233       int val;
13234 
13235       pbx_builtin_setvar_helper(chan, "RPT_STAT_BUSY", "0");
13236        
13237       myrpt->bargechan=0;
13238       if(options && strstr(options, "f")>0)
13239       {
13240          myrpt->bargechan=1;     
13241       }
13242 
13243       if(memp>0)
13244       {
13245          char radiochan;
13246          radiochan=strtod(data,NULL);
13247          // if(myrpt->nowchan!=0 && radiochan!=myrpt->nowchan && !myrpt->bargechan)
13248 
13249          if(numlinks>0 && radiochan!=myrpt->nowchan && !myrpt->bargechan)
13250          {
13251             pbx_builtin_setvar_helper(chan, "RPT_STAT_BUSY", "1");
13252             ast_log(LOG_NOTICE, "Radio Channel Busy.\n");
13253             return (priority_jump(myrpt,chan));
13254          }
13255          else if(radiochan!=myrpt->nowchan || myrpt->bargechan)
13256          {
13257             channel_steer(myrpt,memp); 
13258          }
13259       }
13260       if(altp)rpt_push_alt_macro(myrpt,altp);
13261       phone_mode = 1;
13262       if (*options == 'D') phone_mode = 2;
13263       if (*options == 'S') phone_mode = 3;
13264       ast_set_callerid(chan,"0","app_rpt user","0");
13265       val = 1;
13266       ast_channel_setoption(chan,AST_OPTION_TONE_VERIFY,&val,sizeof(char),0);
13267       if ((*(options + 1) == 'V') || (*(options + 1) == 'v')) phone_vox = 1;
13268    }
13269    else
13270    {
13271 #ifdef ALLOW_LOCAL_CHANNELS
13272            /* Check to insure the connection is IAX2 or Local*/
13273            if ( (strncmp(chan->name,"IAX2",4)) && (strncmp(chan->name,"Local",5)) ) {
13274                ast_log(LOG_WARNING, "We only accept links via IAX2 or Local!!\n");
13275                return -1;
13276            }
13277 #else
13278       if (strncmp(chan->name,"IAX2",4))
13279       {
13280          ast_log(LOG_WARNING, "We only accept links via IAX2!!\n");
13281          return -1;
13282       }
13283 #endif
13284            if(myrpt->p.s[myrpt->p.sysstate_cur].txdisable){ /* Do not allow incoming radio connections if disabled */
13285                  ast_log(LOG_NOTICE, "Connect attempt to node %s  with tx disabled", myrpt->name);
13286                   return -1;
13287          }  
13288    }
13289    if (options && (*options == 'R'))
13290    {
13291       /* Parts of this section taken from app_parkandannounce */
13292       char *return_context;
13293       int length, m, lot, timeout = 0;
13294       char buffer[256],*template;
13295       char *working, *context, *exten, *priority;
13296       char *s,*orig_s;
13297 
13298       rpt_mutex_lock(&myrpt->lock);
13299       m = myrpt->callmode;
13300       rpt_mutex_unlock(&myrpt->lock);
13301 
13302       if ((!myrpt->p.nobusyout) && m)
13303       {
13304          if (chan->_state != AST_STATE_UP)
13305          {
13306             ast_indicate(chan,AST_CONTROL_BUSY);
13307          }
13308          while(ast_safe_sleep(chan,10000) != -1);
13309          return -1;
13310       }
13311 
13312       if (chan->_state != AST_STATE_UP)
13313       {
13314          ast_answer(chan);
13315          if (!phone_mode) send_newkey(chan);
13316       }
13317 
13318       length=strlen(options)+2;
13319       orig_s=ast_malloc(length);
13320       if(!orig_s) {
13321          ast_log(LOG_WARNING, "Out of memory\n");
13322          return -1;
13323       }
13324       s=orig_s;
13325       strncpy(s,options,length);
13326 
13327       template=strsep(&s,"|");
13328       if(!template) {
13329          ast_log(LOG_WARNING, "An announce template must be defined\n");
13330          ast_free(orig_s);
13331          return -1;
13332       } 
13333   
13334       if(s) {
13335          timeout = atoi(strsep(&s, "|"));
13336          timeout *= 1000;
13337       }
13338    
13339       return_context = s;
13340   
13341       if(return_context != NULL) {
13342          /* set the return context. Code borrowed from the Goto builtin */
13343     
13344          working = return_context;
13345          context = strsep(&working, "|");
13346          exten = strsep(&working, "|");
13347          if(!exten) {
13348             /* Only a priority in this one */
13349             priority = context;
13350             exten = NULL;
13351             context = NULL;
13352          } else {
13353             priority = strsep(&working, "|");
13354             if(!priority) {
13355                /* Only an extension and priority in this one */
13356                priority = exten;
13357                exten = context;
13358                context = NULL;
13359          }
13360       }
13361       if(atoi(priority) < 0) {
13362          ast_log(LOG_WARNING, "Priority '%s' must be a number > 0\n", priority);
13363          ast_free(orig_s);
13364          return -1;
13365       }
13366       /* At this point we have a priority and maybe an extension and a context */
13367       chan->priority = atoi(priority);
13368 #ifdef OLD_ASTERISK
13369       if(exten && strcasecmp(exten, "BYEXTENSION"))
13370 #else
13371       if(exten)
13372 #endif
13373          strncpy(chan->exten, exten, sizeof(chan->exten)-1);
13374       if(context)
13375          strncpy(chan->context, context, sizeof(chan->context)-1);
13376       } else {  /* increment the priority by default*/
13377          chan->priority++;
13378       }
13379 
13380       if(option_verbose > 2) {
13381          ast_verbose(VERBOSE_PREFIX_3 "Return Context: (%s,%s,%d) ID: %s\n",
13382             chan->context, chan->exten, chan->priority,
13383             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, ""));
13384          if(!ast_exists_extension(chan, chan->context, chan->exten, chan->priority,
13385             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
13386             ast_verbose( VERBOSE_PREFIX_3 "Warning: Return Context Invalid, call will return to default|s\n");
13387          }
13388       }
13389   
13390       /* we are using masq_park here to protect * from touching the channel once we park it.  If the channel comes out of timeout
13391       before we are done announcing and the channel is messed with, Kablooeee.  So we use Masq to prevent this.  */
13392 
13393       ast_masq_park_call(chan, NULL, timeout, &lot);
13394 
13395       if (option_verbose > 2) ast_verbose( VERBOSE_PREFIX_3 "Call Parking Called, lot: %d, timeout: %d, context: %s\n", lot, timeout, return_context);
13396 
13397       snprintf(buffer, sizeof(buffer) - 1, "%d,%s", lot, template + 1);
13398 
13399       rpt_telemetry(myrpt,REV_PATCH,buffer);
13400 
13401       ast_free(orig_s);
13402 
13403       return 0;
13404 
13405    }
13406 
13407    if (!options)
13408    {
13409         struct ast_hostent ahp;
13410         struct hostent *hp;
13411         struct in_addr ia;
13412         char hisip[100],nodeip[100],*val, *s, *s1, *s2, *s3, *b,*b1;
13413 
13414       /* look at callerid to see what node this comes from */
13415       b = S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL);
13416       if (!b) /* if doesn't have caller id */
13417       {
13418          ast_log(LOG_WARNING, "Does not have callerid on %s\n",tmp);
13419          return -1;
13420       }
13421       /* get his IP from IAX2 module */
13422       memset(hisip,0,sizeof(hisip));
13423 #ifdef ALLOW_LOCAL_CHANNELS
13424         /* set IP address if this is a local connection*/
13425         if (strncmp(chan->name,"Local",5)==0) {
13426             strcpy(hisip,"127.0.0.1");
13427         } else {
13428          pbx_substitute_variables_helper(chan,"${IAXPEER(CURRENTCHANNEL)}",hisip,sizeof(hisip) - 1);
13429       }
13430 #else
13431       pbx_substitute_variables_helper(chan,"${IAXPEER(CURRENTCHANNEL)}",hisip,sizeof(hisip) - 1);
13432 #endif
13433 
13434       if (!hisip[0])
13435       {
13436          ast_log(LOG_WARNING, "Link IP address cannot be determined!!\n");
13437          return -1;
13438       }
13439       
13440       b1 = ast_strdupa(b);
13441       ast_shrink_phone_number(b1);
13442       if (!strcmp(myrpt->name,b1))
13443       {
13444          ast_log(LOG_WARNING, "Trying to link to self!!\n");
13445          return -1;
13446       }
13447 
13448       if (*b1 < '1')
13449       {
13450          ast_log(LOG_WARNING, "Node %s Invalid for connection here!!\n",b1);
13451          return -1;
13452       }
13453 
13454 
13455       /* look for his reported node string */
13456       val = node_lookup(myrpt,b1);
13457       if (!val)
13458       {
13459          ast_log(LOG_WARNING, "Reported node %s cannot be found!!\n",b1);
13460          return -1;
13461       }
13462       strncpy(tmp,val,sizeof(tmp) - 1);
13463       s = tmp;
13464       s1 = strsep(&s,",");
13465       if (!strchr(s1,':') && strchr(s1,'/') && strncasecmp(s1, "local/", 6))
13466       {
13467          sy = strchr(s1,'/');    
13468          *sy = 0;
13469          sprintf(sx,"%s:4569/%s",s1,sy + 1);
13470          s1 = sx;
13471       }
13472       s2 = strsep(&s,",");
13473       if (!s2)
13474       {
13475          ast_log(LOG_WARNING, "Reported node %s not in correct format!!\n",b1);
13476          return -1;
13477       }
13478                 if (strcmp(s2,"NONE")) {
13479          hp = ast_gethostbyname(s2, &ahp);
13480          if (!hp)
13481          {
13482             ast_log(LOG_WARNING, "Reported node %s, name %s cannot be found!!\n",b1,s2);
13483             return -1;
13484          }
13485          memcpy(&ia,hp->h_addr,sizeof(in_addr_t));
13486 #ifdef   OLD_ASTERISK
13487          ast_inet_ntoa(nodeip,sizeof(nodeip) - 1,ia);
13488 #else
13489          strncpy(nodeip,ast_inet_ntoa(ia),sizeof(nodeip) - 1);
13490 #endif
13491          s3 = strchr(hisip,':');
13492          if (s3) *s3 = 0;
13493          if (strcmp(hisip,nodeip))
13494          {
13495             s3 = strchr(s1,'@');
13496             if (s3) s1 = s3 + 1;
13497             s3 = strchr(s1,'/');
13498             if (s3) *s3 = 0;
13499             s3 = strchr(s1,':');
13500             if (s3) *s3 = 0;
13501             hp = ast_gethostbyname(s1, &ahp);
13502             if (!hp)
13503             {
13504                ast_log(LOG_WARNING, "Reported node %s, name %s cannot be found!!\n",b1,s1);
13505                return -1;
13506             }
13507             memcpy(&ia,hp->h_addr,sizeof(in_addr_t));
13508 #ifdef   OLD_ASTERISK
13509             ast_inet_ntoa(nodeip,sizeof(nodeip) - 1,ia);
13510 #else
13511             strncpy(nodeip,ast_inet_ntoa(ia),sizeof(nodeip) - 1);
13512 #endif
13513             if (strcmp(hisip,nodeip))
13514             {
13515                ast_log(LOG_WARNING, "Node %s IP %s does not match link IP %s!!\n",b1,nodeip,hisip);
13516                return -1;
13517             }
13518          }
13519       }
13520    }
13521 
13522    /* if is not a remote */
13523    if (!myrpt->remote)
13524    {
13525       char *b,*b1;
13526       int reconnects = 0;
13527 
13528       rpt_mutex_lock(&myrpt->lock);
13529       i = myrpt->xlink;
13530       rpt_mutex_unlock(&myrpt->lock);
13531       if (i)
13532       {
13533          ast_log(LOG_WARNING, "Cannot connect to node %s, system busy\n",myrpt->name);
13534          return -1;
13535       }
13536       /* look at callerid to see what node this comes from */
13537       b = S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL);
13538       if (!b) /* if doesn't have caller id */
13539       {
13540          ast_log(LOG_WARNING, "Doesnt have callerid on %s\n",tmp);
13541          return -1;
13542       }
13543 
13544       b1 = ast_strdupa(b);
13545       ast_shrink_phone_number(b1);
13546       if (!strcmp(myrpt->name,b1))
13547       {
13548          ast_log(LOG_WARNING, "Trying to link to self!!\n");
13549          return -1;
13550       }
13551       rpt_mutex_lock(&myrpt->lock);
13552       l = myrpt->links.next;
13553       /* try to find this one in queue */
13554       while(l != &myrpt->links)
13555       {
13556          if (l->name[0] == '0') 
13557          {
13558             l = l->next;
13559             continue;
13560          }
13561          /* if found matching string */
13562          if (!strcmp(l->name,b1)) break;
13563          l = l->next;
13564       }
13565       /* if found */
13566       if (l != &myrpt->links) 
13567       {
13568          l->killme = 1;
13569          l->retries = l->max_retries + 1;
13570          l->disced = 2;
13571          reconnects = l->reconnects;
13572          reconnects++;
13573                         rpt_mutex_unlock(&myrpt->lock);
13574          usleep(500000);   
13575       } else 
13576          rpt_mutex_unlock(&myrpt->lock);
13577       /* establish call in tranceive mode */
13578       l = ast_malloc(sizeof(struct rpt_link));
13579       if (!l)
13580       {
13581          ast_log(LOG_WARNING, "Unable to malloc\n");
13582          pthread_exit(NULL);
13583       }
13584       /* zero the silly thing */
13585       memset((char *)l,0,sizeof(struct rpt_link));
13586       l->mode = 1;
13587       strncpy(l->name,b1,MAXNODESTR - 1);
13588       l->isremote = 0;
13589       l->chan = chan;
13590       l->connected = 1;
13591       l->thisconnected = 1;
13592       l->hasconnected = 1;
13593       l->reconnects = reconnects;
13594       l->phonemode = phone_mode;
13595       l->phonevox = phone_vox;
13596       l->lastf1 = NULL;
13597       l->lastf2 = NULL;
13598       l->dtmfed = 0;
13599       voxinit_link(l,1);
13600       ast_set_read_format(l->chan,AST_FORMAT_SLINEAR);
13601       ast_set_write_format(l->chan,AST_FORMAT_SLINEAR);
13602       /* allocate a pseudo-channel thru asterisk */
13603       l->pchan = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
13604       if (!l->pchan)
13605       {
13606          fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
13607          pthread_exit(NULL);
13608       }
13609       ast_set_read_format(l->pchan,AST_FORMAT_SLINEAR);
13610       ast_set_write_format(l->pchan,AST_FORMAT_SLINEAR);
13611 #ifdef   AST_CDR_FLAG_POST_DISABLED
13612       if (l->pchan->cdr)
13613          ast_set_flag(l->pchan->cdr,AST_CDR_FLAG_POST_DISABLED);
13614 #endif
13615       /* make a conference for the tx */
13616       ci.chan = 0;
13617       ci.confno = myrpt->conf;
13618       ci.confmode = DAHDI_CONF_CONF | DAHDI_CONF_LISTENER | DAHDI_CONF_TALKER;
13619       /* first put the channel on the conference in proper mode */
13620       if (ioctl(l->pchan->fds[0],DAHDI_SETCONF,&ci) == -1)
13621       {
13622          ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
13623          pthread_exit(NULL);
13624       }
13625       rpt_mutex_lock(&myrpt->lock);
13626       if ((phone_mode == 2) && (!phone_vox)) l->lastrealrx = 1;
13627       l->max_retries = MAX_RETRIES;
13628       /* insert at end of queue */
13629       insque((struct qelem *)l,(struct qelem *)myrpt->links.next);
13630       __kickshort(myrpt);
13631       rpt_mutex_unlock(&myrpt->lock);
13632       if (chan->_state != AST_STATE_UP) {
13633          ast_answer(chan);
13634          if (!phone_mode) send_newkey(chan);
13635       }
13636       if (myrpt->p.archivedir)
13637       {
13638          char str[100];
13639 
13640          if (l->phonemode)
13641             sprintf(str,"LINK(P),%s",l->name);
13642          else
13643             sprintf(str,"LINK,%s",l->name);
13644          donodelog(myrpt,str);
13645       }
13646       if (!phone_mode) send_newkey(chan);
13647       return 0;
13648    }
13649    /* well, then it is a remote */
13650    rpt_mutex_lock(&myrpt->lock);
13651    /* if remote, error if anyone else already linked */
13652    if (myrpt->remoteon)
13653    {
13654       rpt_mutex_unlock(&myrpt->lock);
13655       usleep(500000);
13656       if (myrpt->remoteon)
13657       {
13658          ast_log(LOG_WARNING, "Trying to use busy link on %s\n",tmp);
13659 #ifdef   AST_CDR_FLAG_POST_DISABLED
13660          if (chan->cdr)
13661             ast_set_flag(chan->cdr,AST_CDR_FLAG_POST_DISABLED);
13662 #endif
13663          return -1;
13664       }     
13665       rpt_mutex_lock(&myrpt->lock);
13666    }
13667    if (myrpt->p.rptnode)
13668    {
13669       char killedit = 0;
13670       time_t now;
13671 
13672       time(&now);
13673       for(i = 0; i < nrpts; i++)
13674       {
13675          if (!strcasecmp(rpt_vars[i].name,myrpt->p.rptnode))
13676          {
13677             if ((rpt_vars[i].links.next != &rpt_vars[i].links) ||
13678                rpt_vars[i].keyed ||
13679                 ((rpt_vars[i].lastkeyedtime + RPT_LOCKOUT_SECS) > now) ||
13680                  rpt_vars[i].txkeyed ||
13681                   ((rpt_vars[i].lasttxkeyedtime + RPT_LOCKOUT_SECS) > now))
13682             {
13683                rpt_mutex_unlock(&myrpt->lock);
13684                ast_log(LOG_WARNING, "Trying to use busy link (repeater node %s) on %s\n",rpt_vars[i].name,tmp);
13685 #ifdef   AST_CDR_FLAG_POST_DISABLED
13686                if (chan->cdr)
13687                   ast_set_flag(chan->cdr,AST_CDR_FLAG_POST_DISABLED);
13688 #endif
13689                return -1;
13690             }
13691             while(rpt_vars[i].xlink != 3)
13692             {
13693                if (!killedit)
13694                {
13695                   ast_softhangup(rpt_vars[i].rxchannel,AST_SOFTHANGUP_DEV);
13696                   rpt_vars[i].xlink = 1;
13697                   killedit = 1;
13698                }
13699                rpt_mutex_unlock(&myrpt->lock);
13700                if (ast_safe_sleep(chan,500) == -1)
13701                {
13702 #ifdef   AST_CDR_FLAG_POST_DISABLED
13703                   if (chan->cdr)
13704                      ast_set_flag(chan->cdr,AST_CDR_FLAG_POST_DISABLED);
13705 #endif
13706                   return -1;
13707                }
13708                rpt_mutex_lock(&myrpt->lock);
13709             }
13710             break;
13711          }
13712       }
13713    }
13714 
13715 #ifdef HAVE_IOPERM
13716    if ( (!strcmp(myrpt->remoterig, remote_rig_rbi)||!strcmp(myrpt->remoterig, remote_rig_ppp16)) &&
13717      (ioperm(myrpt->p.iobase,1,1) == -1))
13718    {
13719       rpt_mutex_unlock(&myrpt->lock);
13720       ast_log(LOG_WARNING, "Can't get io permission on IO port %x hex\n",myrpt->p.iobase);
13721       return -1;
13722    }
13723 #endif
13724    myrpt->remoteon = 1;
13725 #ifdef   OLD_ASTERISK
13726    LOCAL_USER_ADD(u);
13727 #endif
13728    rpt_mutex_unlock(&myrpt->lock);
13729    /* find our index, and load the vars initially */
13730    for(i = 0; i < nrpts; i++)
13731    {
13732       if (&rpt_vars[i] == myrpt)
13733       {
13734          load_rpt_vars(i,0);
13735          break;
13736       }
13737    }
13738    rpt_mutex_lock(&myrpt->lock);
13739    tele = strchr(myrpt->rxchanname,'/');
13740    if (!tele)
13741    {
13742       fprintf(stderr,"rpt:Dial number must be in format tech/number\n");
13743       rpt_mutex_unlock(&myrpt->lock);
13744       pthread_exit(NULL);
13745    }
13746    *tele++ = 0;
13747    myrpt->rxchannel = ast_request(myrpt->rxchanname, AST_FORMAT_SLINEAR, NULL, tele, NULL);
13748    myrpt->dahdirxchannel = NULL;
13749    if (!strcasecmp(myrpt->rxchanname,"DAHDI"))
13750       myrpt->dahdirxchannel = myrpt->rxchannel;
13751    if (myrpt->rxchannel)
13752    {
13753       ast_set_read_format(myrpt->rxchannel,AST_FORMAT_SLINEAR);
13754       ast_set_write_format(myrpt->rxchannel,AST_FORMAT_SLINEAR);
13755 #ifdef   AST_CDR_FLAG_POST_DISABLED
13756       if (myrpt->rxchannel->cdr)
13757          ast_set_flag(myrpt->rxchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
13758 #endif
13759 #ifndef  NEW_ASTERISK
13760       myrpt->rxchannel->whentohangup = 0;
13761 #endif
13762       myrpt->rxchannel->appl = "Apprpt";
13763       myrpt->rxchannel->data = "(Link Rx)";
13764       if (option_verbose > 2)
13765          ast_verbose(VERBOSE_PREFIX_3 "rpt (Rx) initiating call to %s/%s on %s\n",
13766             myrpt->rxchanname,tele,myrpt->rxchannel->name);
13767       rpt_mutex_unlock(&myrpt->lock);
13768       ast_call(myrpt->rxchannel,tele,999);
13769       rpt_mutex_lock(&myrpt->lock);
13770    }
13771    else
13772    {
13773       fprintf(stderr,"rpt:Sorry unable to obtain Rx channel\n");
13774       rpt_mutex_unlock(&myrpt->lock);
13775       pthread_exit(NULL);
13776    }
13777    *--tele = '/';
13778    myrpt->dahditxchannel = NULL;
13779    if (myrpt->txchanname)
13780    {
13781       tele = strchr(myrpt->txchanname,'/');
13782       if (!tele)
13783       {
13784          fprintf(stderr,"rpt:Dial number must be in format tech/number\n");
13785          rpt_mutex_unlock(&myrpt->lock);
13786          ast_hangup(myrpt->rxchannel);
13787          pthread_exit(NULL);
13788       }
13789       *tele++ = 0;
13790       myrpt->txchannel = ast_request(myrpt->txchanname, AST_FORMAT_SLINEAR, NULL, tele, NULL);
13791       if (!strncasecmp(myrpt->txchanname,"DAHDI",3))
13792          myrpt->dahditxchannel = myrpt->txchannel;
13793       if (myrpt->txchannel)
13794       {
13795          ast_set_read_format(myrpt->txchannel,AST_FORMAT_SLINEAR);
13796          ast_set_write_format(myrpt->txchannel,AST_FORMAT_SLINEAR);
13797 #ifdef   AST_CDR_FLAG_POST_DISABLED
13798          if (myrpt->txchannel->cdr)
13799             ast_set_flag(myrpt->txchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
13800 #endif
13801 #ifndef  NEW_ASTERISK
13802          myrpt->txchannel->whentohangup = 0;
13803 #endif
13804          myrpt->txchannel->appl = "Apprpt";
13805          myrpt->txchannel->data = "(Link Tx)";
13806          if (option_verbose > 2)
13807             ast_verbose(VERBOSE_PREFIX_3 "rpt (Tx) initiating call to %s/%s on %s\n",
13808                myrpt->txchanname,tele,myrpt->txchannel->name);
13809          rpt_mutex_unlock(&myrpt->lock);
13810          ast_call(myrpt->txchannel,tele,999);
13811          rpt_mutex_lock(&myrpt->lock);
13812       }
13813       else
13814       {
13815          fprintf(stderr,"rpt:Sorry unable to obtain Tx channel\n");
13816          rpt_mutex_unlock(&myrpt->lock);
13817          ast_hangup(myrpt->rxchannel);
13818          pthread_exit(NULL);
13819       }
13820       *--tele = '/';
13821    }
13822    else
13823    {
13824       myrpt->txchannel = myrpt->rxchannel;
13825       if (!strncasecmp(myrpt->rxchanname,"DAHDI",3))
13826          myrpt->dahditxchannel = myrpt->rxchannel;
13827    }
13828    /* allocate a pseudo-channel thru asterisk */
13829    myrpt->pchannel = ast_request("DAHDI", AST_FORMAT_SLINEAR, NULL, "pseudo", NULL);
13830    if (!myrpt->pchannel)
13831    {
13832       fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
13833       rpt_mutex_unlock(&myrpt->lock);
13834       if (myrpt->txchannel != myrpt->rxchannel) 
13835          ast_hangup(myrpt->txchannel);
13836       ast_hangup(myrpt->rxchannel);
13837       pthread_exit(NULL);
13838    }
13839    ast_set_read_format(myrpt->pchannel,AST_FORMAT_SLINEAR);
13840    ast_set_write_format(myrpt->pchannel,AST_FORMAT_SLINEAR);
13841 #ifdef   AST_CDR_FLAG_POST_DISABLED
13842    if (myrpt->pchannel->cdr)
13843       ast_set_flag(myrpt->pchannel->cdr,AST_CDR_FLAG_POST_DISABLED);
13844 #endif
13845    if (!myrpt->dahdirxchannel) myrpt->dahdirxchannel = myrpt->pchannel;
13846    if (!myrpt->dahditxchannel) myrpt->dahditxchannel = myrpt->pchannel;
13847    /* make a conference for the pseudo */
13848    ci.chan = 0;
13849    ci.confno = -1; /* make a new conf */
13850    ci.confmode = DAHDI_CONF_CONFANNMON ;
13851    /* first put the channel on the conference in announce/monitor mode */
13852    if (ioctl(myrpt->pchannel->fds[0],DAHDI_SETCONF,&ci) == -1)
13853    {
13854       ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
13855       rpt_mutex_unlock(&myrpt->lock);
13856       ast_hangup(myrpt->pchannel);
13857       if (myrpt->txchannel != myrpt->rxchannel) 
13858          ast_hangup(myrpt->txchannel);
13859       ast_hangup(myrpt->rxchannel);
13860       pthread_exit(NULL);
13861    }
13862    /* save pseudo channel conference number */
13863    myrpt->conf = myrpt->txconf = ci.confno;
13864    /* if serial io port, open it */
13865    myrpt->iofd = -1;
13866    if (myrpt->p.ioport && ((myrpt->iofd = openserial(myrpt,myrpt->p.ioport)) == -1))
13867    {
13868       rpt_mutex_unlock(&myrpt->lock);
13869       ast_hangup(myrpt->pchannel);
13870       if (myrpt->txchannel != myrpt->rxchannel) 
13871          ast_hangup(myrpt->txchannel);
13872       ast_hangup(myrpt->rxchannel);
13873       pthread_exit(NULL);
13874    }
13875    iskenwood_pci4 = 0;
13876    memset(&z,0,sizeof(z));
13877    if ((myrpt->iofd < 1) && (myrpt->txchannel == myrpt->dahditxchannel))
13878    {
13879       z.radpar = DAHDI_RADPAR_REMMODE;
13880       z.data = DAHDI_RADPAR_REM_NONE;
13881       res = ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z);
13882       /* if PCIRADIO and kenwood selected */
13883       if ((!res) && (!strcmp(myrpt->remoterig,remote_rig_kenwood)))
13884       {
13885          z.radpar = DAHDI_RADPAR_UIOMODE;
13886          z.data = 1;
13887          if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
13888          {
13889             ast_log(LOG_ERROR,"Cannot set UIOMODE\n");
13890             return -1;
13891          }
13892          z.radpar = DAHDI_RADPAR_UIODATA;
13893          z.data = 3;
13894          if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
13895          {
13896             ast_log(LOG_ERROR,"Cannot set UIODATA\n");
13897             return -1;
13898          }
13899          i = DAHDI_OFFHOOK;
13900          if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_HOOK,&i) == -1)
13901          {
13902             ast_log(LOG_ERROR,"Cannot set hook\n");
13903             return -1;
13904          }
13905          iskenwood_pci4 = 1;
13906       }
13907    }
13908    if (myrpt->txchannel == myrpt->dahditxchannel)
13909    {
13910       i = DAHDI_ONHOOK;
13911       ioctl(myrpt->dahditxchannel->fds[0],DAHDI_HOOK,&i);
13912       /* if PCIRADIO and Yaesu ft897/ICOM IC-706 selected */
13913       if ((myrpt->iofd < 1) && (!res) &&
13914          ((!strcmp(myrpt->remoterig,remote_rig_ft897)) ||
13915             (!strcmp(myrpt->remoterig,remote_rig_ic706)) ||
13916                (!strcmp(myrpt->remoterig,remote_rig_tm271))))
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       }
13933    }
13934    myrpt->remoterx = 0;
13935    myrpt->remotetx = 0;
13936    myrpt->retxtimer = 0;
13937    myrpt->rerxtimer = 0;
13938    myrpt->remoteon = 1;
13939    myrpt->dtmfidx = -1;
13940    myrpt->dtmfbuf[0] = 0;
13941    myrpt->dtmf_time_rem = 0;
13942    myrpt->hfscanmode = 0;
13943    myrpt->hfscanstatus = 0;
13944    if (myrpt->p.startupmacro)
13945    {
13946       snprintf(myrpt->macrobuf,MAXMACRO - 1,"PPPP%s",myrpt->p.startupmacro);
13947    }
13948    time(&myrpt->start_time);
13949    myrpt->last_activity_time = myrpt->start_time;
13950    last_timeout_warning = 0;
13951    myrpt->reload = 0;
13952    myrpt->tele.next = &myrpt->tele;
13953    myrpt->tele.prev = &myrpt->tele;
13954    myrpt->newkey = 0;
13955    rpt_mutex_unlock(&myrpt->lock);
13956    ast_set_write_format(chan, AST_FORMAT_SLINEAR);
13957    ast_set_read_format(chan, AST_FORMAT_SLINEAR);
13958    rem_rx = 0;
13959    remkeyed = 0;
13960    /* if we are on 2w loop and are a remote, turn EC on */
13961    if (myrpt->remote && (myrpt->rxchannel == myrpt->txchannel))
13962    {
13963       i = 128;
13964       ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_ECHOCANCEL,&i);
13965    }
13966    if (chan->_state != AST_STATE_UP) {
13967       ast_answer(chan);
13968       if (!phone_mode) send_newkey(chan);
13969    }
13970 
13971    if (myrpt->rxchannel == myrpt->dahdirxchannel)
13972    {
13973       if (ioctl(myrpt->dahdirxchannel->fds[0],DAHDI_GET_PARAMS,&par) != -1)
13974       {
13975          if (par.rxisoffhook)
13976          {
13977             ast_indicate(chan,AST_CONTROL_RADIO_KEY);
13978             myrpt->remoterx = 1;
13979             remkeyed = 1;
13980          }
13981       }
13982    }
13983    if (myrpt->p.archivedir)
13984    {
13985       char mycmd[100],mydate[100],*b,*b1;
13986       time_t myt;
13987       long blocksleft;
13988 
13989 
13990       mkdir(myrpt->p.archivedir,0600);
13991       sprintf(mycmd,"%s/%s",myrpt->p.archivedir,myrpt->name);
13992       mkdir(mycmd,0600);
13993       time(&myt);
13994       strftime(mydate,sizeof(mydate) - 1,"%Y%m%d%H%M%S",
13995          localtime(&myt));
13996       sprintf(mycmd,"mixmonitor start %s %s/%s/%s.wav49 a",chan->name,
13997          myrpt->p.archivedir,myrpt->name,mydate);
13998       if (myrpt->p.monminblocks)
13999       {
14000          blocksleft = diskavail(myrpt);
14001          if (myrpt->p.remotetimeout)
14002          {
14003             blocksleft -= (myrpt->p.remotetimeout *
14004                MONITOR_DISK_BLOCKS_PER_MINUTE) / 60;
14005          }
14006          if (blocksleft >= myrpt->p.monminblocks)
14007             ast_cli_command(nullfd,mycmd);
14008       } else ast_cli_command(nullfd,mycmd);
14009       /* look at callerid to see what node this comes from */
14010       b = S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL);
14011       if (!b) /* if doesn't have caller id */
14012       {
14013          b1 = "0";
14014       } else {
14015          b1 = ast_strdupa(b);
14016          ast_shrink_phone_number(b1);
14017       }
14018       sprintf(mycmd,"CONNECT,%s",b1);
14019       donodelog(myrpt,mycmd);
14020    }
14021    myrpt->loginuser[0] = 0;
14022    myrpt->loginlevel[0] = 0;
14023    myrpt->authtelltimer = 0;
14024    myrpt->authtimer = 0;
14025    authtold = 0;
14026    authreq = 0;
14027    if (myrpt->p.authlevel > 1) authreq = 1;
14028    setrem(myrpt); 
14029    n = 0;
14030    dtmfed = 0;
14031    cs[n++] = chan;
14032    cs[n++] = myrpt->rxchannel;
14033    cs[n++] = myrpt->pchannel;
14034    if (myrpt->rxchannel != myrpt->txchannel)
14035       cs[n++] = myrpt->txchannel;
14036    if (!phone_mode) send_newkey(chan);
14037    /* start un-locked */
14038    for(;;) 
14039    {
14040       if (ast_check_hangup(chan)) break;
14041       if (ast_check_hangup(myrpt->rxchannel)) break;
14042       notremming = 0;
14043       setting = 0;
14044       reming = 0;
14045       telem = myrpt->tele.next;
14046       while(telem != &myrpt->tele)
14047       {
14048          if (telem->mode == SETREMOTE) setting = 1;
14049          if ((telem->mode == SETREMOTE) ||
14050              (telem->mode == SCAN) ||
14051             (telem->mode == TUNE))  reming = 1;
14052          else notremming = 1;
14053          telem = telem->next;
14054       }
14055       if (myrpt->reload)
14056       {
14057          myrpt->reload = 0;
14058          /* find our index, and load the vars */
14059          for(i = 0; i < nrpts; i++)
14060          {
14061             if (&rpt_vars[i] == myrpt)
14062             {
14063                load_rpt_vars(i,0);
14064                break;
14065             }
14066          }
14067       }
14068       time(&t);
14069       if (myrpt->p.remotetimeout)
14070       { 
14071          time_t r;
14072 
14073          r = (t - myrpt->start_time);
14074          if (r >= myrpt->p.remotetimeout)
14075          {
14076             saynode(myrpt,chan,myrpt->name);
14077             sayfile(chan,"rpt/timeout");
14078             ast_safe_sleep(chan,1000);
14079             break;
14080          }
14081          if ((myrpt->p.remotetimeoutwarning) && 
14082              (r >= (myrpt->p.remotetimeout -
14083             myrpt->p.remotetimeoutwarning)) &&
14084                 (r <= (myrpt->p.remotetimeout - 
14085                   myrpt->p.remotetimeoutwarningfreq)))
14086          {
14087             if (myrpt->p.remotetimeoutwarningfreq)
14088             {
14089                 if ((t - last_timeout_warning) >=
14090                myrpt->p.remotetimeoutwarningfreq)
14091                 {
14092                time(&last_timeout_warning);
14093                rpt_telemetry(myrpt,TIMEOUT_WARNING,0);
14094                 }
14095             }
14096             else
14097             {
14098                 if (!last_timeout_warning)
14099                 {
14100                time(&last_timeout_warning);
14101                rpt_telemetry(myrpt,TIMEOUT_WARNING,0);
14102                 }
14103             }
14104          }
14105       }
14106       if (myrpt->p.remoteinacttimeout && myrpt->last_activity_time)
14107       { 
14108          time_t r;
14109 
14110          r = (t - myrpt->last_activity_time);
14111          if (r >= myrpt->p.remoteinacttimeout)
14112          {
14113             saynode(myrpt,chan,myrpt->name);
14114             ast_safe_sleep(chan,1000);
14115             break;
14116          }
14117          if ((myrpt->p.remotetimeoutwarning) && 
14118              (r >= (myrpt->p.remoteinacttimeout -
14119             myrpt->p.remotetimeoutwarning)) &&
14120                 (r <= (myrpt->p.remoteinacttimeout - 
14121                   myrpt->p.remotetimeoutwarningfreq)))
14122          {
14123             if (myrpt->p.remotetimeoutwarningfreq)
14124             {
14125                 if ((t - last_timeout_warning) >=
14126                myrpt->p.remotetimeoutwarningfreq)
14127                 {
14128                time(&last_timeout_warning);
14129                rpt_telemetry(myrpt,ACT_TIMEOUT_WARNING,0);
14130                 }
14131             }
14132             else
14133             {
14134                 if (!last_timeout_warning)
14135                 {
14136                time(&last_timeout_warning);
14137                rpt_telemetry(myrpt,ACT_TIMEOUT_WARNING,0);
14138                 }
14139             }
14140          }
14141       }
14142       ms = MSWAIT;
14143       who = ast_waitfor_n(cs,n,&ms);
14144       if (who == NULL) ms = 0;
14145       elap = MSWAIT - ms;
14146       if (myrpt->macrotimer) myrpt->macrotimer -= elap;
14147       if (myrpt->macrotimer < 0) myrpt->macrotimer = 0;
14148       if (!ms) continue;
14149       /* do local dtmf timer */
14150       if (myrpt->dtmf_local_timer)
14151       {
14152          if (myrpt->dtmf_local_timer > 1) myrpt->dtmf_local_timer -= elap;
14153          if (myrpt->dtmf_local_timer < 1) myrpt->dtmf_local_timer = 1;
14154       }
14155       rpt_mutex_lock(&myrpt->lock);
14156       do_dtmf_local(myrpt,0);
14157       rpt_mutex_unlock(&myrpt->lock);
14158       //
14159       rem_totx =  myrpt->dtmf_local_timer && (!phone_mode);
14160       rem_totx |= keyed && (!myrpt->tunerequest);
14161       rem_rx = (remkeyed && (!setting)) || (myrpt->tele.next != &myrpt->tele);
14162       if(!strcmp(myrpt->remoterig, remote_rig_ic706))
14163          rem_totx |= myrpt->tunerequest;
14164       //
14165        if((debug > 6) && rem_totx) {
14166          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);
14167       }
14168       if (keyed && (!keyed1))
14169       {
14170          keyed1 = 1;
14171       }
14172 
14173       if (!keyed && (keyed1))
14174       {
14175          time_t myt;
14176 
14177          keyed1 = 0;
14178          time(&myt);
14179          /* if login necessary, and not too soon */
14180          if ((myrpt->p.authlevel) && 
14181              (!myrpt->loginlevel[0]) &&
14182             (myt > (t + 3)))
14183          {
14184             authreq = 1;
14185             authtold = 0;
14186             myrpt->authtelltimer = AUTHTELLTIME - AUTHTXTIME;
14187          }
14188       }
14189 
14190       if (rem_rx && (!myrpt->remoterx))
14191       {
14192          myrpt->remoterx = 1;
14193          ast_indicate(chan,AST_CONTROL_RADIO_KEY);
14194       }
14195       if ((!rem_rx) && (myrpt->remoterx))
14196       {
14197          myrpt->remoterx = 0;
14198          ast_indicate(chan,AST_CONTROL_RADIO_UNKEY);
14199       }
14200       /* if auth requested, and not authed yet */
14201       if (authreq && (!myrpt->loginlevel[0]))
14202       {
14203          if ((!authtold) && ((myrpt->authtelltimer += elap)
14204              >= AUTHTELLTIME))
14205          {
14206             authtold = 1;
14207             rpt_telemetry(myrpt,LOGINREQ,NULL);
14208          }
14209          if ((myrpt->authtimer += elap) >= AUTHLOGOUTTIME)
14210          {
14211             break; /* if not logged in, hang up after a time */
14212          }
14213       }
14214       if (myrpt->newkey)
14215       {
14216          if ((myrpt->retxtimer += elap) >= REDUNDANT_TX_TIME)
14217          {
14218             myrpt->retxtimer = 0;
14219             if ((myrpt->remoterx) && (!myrpt->remotetx))
14220                ast_indicate(chan,AST_CONTROL_RADIO_KEY);
14221             else
14222                ast_indicate(chan,AST_CONTROL_RADIO_UNKEY);
14223          }
14224 
14225          if ((myrpt->rerxtimer += elap) >= (REDUNDANT_TX_TIME * 2))
14226          {
14227             keyed = 0;
14228             myrpt->rerxtimer = 0;
14229          }
14230       }
14231       if (rem_totx && (!myrpt->remotetx))
14232       {
14233          /* if not authed, and needed, do not transmit */
14234          if ((!myrpt->p.authlevel) || myrpt->loginlevel[0])
14235          {
14236             if(debug > 6)
14237                ast_log(LOG_NOTICE,"Handle rem_totx=%i.  dtmf_local_timer=%i  tunerequest=%i\n",rem_totx,myrpt->dtmf_local_timer,myrpt->tunerequest);
14238 
14239             myrpt->remotetx = 1;
14240             /* asdf maw ??? is this really what you want? Doesn't it always get executed? */
14241             if((myrpt->remtxfreqok = check_tx_freq(myrpt)))
14242             {
14243                time(&myrpt->last_activity_time);
14244                if ((iskenwood_pci4) && (myrpt->txchannel == myrpt->dahditxchannel))
14245                {
14246                   z.radpar = DAHDI_RADPAR_UIODATA;
14247                   z.data = 1;
14248                   if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
14249                   {
14250                      ast_log(LOG_ERROR,"Cannot set UIODATA\n");
14251                      return -1;
14252                   }
14253                }
14254                else
14255                {
14256                   ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_KEY);
14257                }
14258                if (myrpt->p.archivedir) donodelog(myrpt,"TXKEY");
14259             }
14260          }
14261       }
14262       if ((!rem_totx) && myrpt->remotetx) /* Remote base radio TX unkey */
14263       {
14264          myrpt->remotetx = 0;
14265          if(!myrpt->remtxfreqok){
14266             rpt_telemetry(myrpt,UNAUTHTX,NULL);
14267          }
14268          if ((iskenwood_pci4) && (myrpt->txchannel == myrpt->dahditxchannel))
14269          {
14270             z.radpar = DAHDI_RADPAR_UIODATA;
14271             z.data = 3;
14272             if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
14273             {
14274                ast_log(LOG_ERROR,"Cannot set UIODATA\n");
14275                return -1;
14276             }
14277          }
14278          else
14279          {
14280             ast_indicate(myrpt->txchannel,AST_CONTROL_RADIO_UNKEY);
14281          }
14282          if (myrpt->p.archivedir) donodelog(myrpt,"TXUNKEY");
14283       }
14284       if (myrpt->hfscanmode){
14285          myrpt->scantimer -= elap;
14286          if(myrpt->scantimer <= 0){
14287             if (!reming)
14288             {
14289                myrpt->scantimer = REM_SCANTIME;
14290                rpt_telemetry(myrpt,SCAN,0);
14291             } else myrpt->scantimer = 1;
14292          }
14293       }
14294       rpt_mutex_lock(&myrpt->lock);
14295       c = myrpt->macrobuf[0];
14296       if (c && (!myrpt->macrotimer))
14297       {
14298          myrpt->macrotimer = MACROTIME;
14299          memmove(myrpt->macrobuf,myrpt->macrobuf + 1,MAXMACRO - 1);
14300          if ((c == 'p') || (c == 'P'))
14301             myrpt->macrotimer = MACROPTIME;
14302          rpt_mutex_unlock(&myrpt->lock);
14303          if (myrpt->p.archivedir)
14304          {
14305             char str[100];
14306                sprintf(str,"DTMF(M),%c",c);
14307             donodelog(myrpt,str);
14308          }
14309          if (handle_remote_dtmf_digit(myrpt,c,&keyed,0) == -1) break;
14310          continue;
14311       } else rpt_mutex_unlock(&myrpt->lock);
14312       if (who == chan) /* if it was a read from incoming */
14313       {
14314          f = ast_read(chan);
14315          if (!f)
14316          {
14317             if (debug) printf("@@@@ link:Hung Up\n");
14318             break;
14319          }
14320          if (f->frametype == AST_FRAME_VOICE)
14321          {
14322             if (ioctl(chan->fds[0], DAHDI_GETCONFMUTE, &ismuted) == -1)
14323             {
14324                ismuted = 0;
14325             }
14326             /* if not transmitting, zero-out audio */
14327             ismuted |= (!myrpt->remotetx);
14328             if (dtmfed && phone_mode) ismuted = 1;
14329             dtmfed = 0;
14330             if (ismuted)
14331             {
14332                memset(f->data.ptr,0,f->datalen);
14333                if (myrpt->lastf1)
14334                   memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
14335                if (myrpt->lastf2)
14336                   memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
14337             } 
14338             if (f) f2 = ast_frdup(f);
14339             else f2 = NULL;
14340             f1 = myrpt->lastf2;
14341             myrpt->lastf2 = myrpt->lastf1;
14342             myrpt->lastf1 = f2;
14343             if (ismuted)
14344             {
14345                if (myrpt->lastf1)
14346                   memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
14347                if (myrpt->lastf2)
14348                   memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
14349             }
14350             if (f1)
14351             {
14352                if (phone_mode)
14353                   ast_write(myrpt->txchannel,f1);
14354                else
14355                   ast_write(myrpt->txchannel,f);
14356                ast_frfree(f1);
14357             }
14358          }
14359 #ifndef  OLD_ASTERISK
14360          else if (f->frametype == AST_FRAME_DTMF_BEGIN)
14361          {
14362             if (myrpt->lastf1)
14363                memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
14364             if (myrpt->lastf2)
14365                memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
14366             dtmfed = 1;
14367          }
14368 #endif
14369          if (f->frametype == AST_FRAME_DTMF)
14370          {
14371             if (myrpt->lastf1)
14372                memset(myrpt->lastf1->data.ptr,0,myrpt->lastf1->datalen);
14373             if (myrpt->lastf2)
14374                memset(myrpt->lastf2->data.ptr,0,myrpt->lastf2->datalen);
14375             dtmfed = 1;
14376             if (handle_remote_phone_dtmf(myrpt,f->subclass.integer,&keyed,phone_mode) == -1)
14377             {
14378                if (debug) printf("@@@@ rpt:Hung Up\n");
14379                ast_frfree(f);
14380                break;
14381             }
14382          }
14383          if (f->frametype == AST_FRAME_TEXT)
14384          {
14385             if (handle_remote_data(myrpt,f->data.ptr) == -1)
14386             {
14387                if (debug) printf("@@@@ rpt:Hung Up\n");
14388                ast_frfree(f);
14389                break;
14390             }
14391          }
14392          if (f->frametype == AST_FRAME_CONTROL)
14393          {
14394             if (f->subclass.integer == AST_CONTROL_HANGUP)
14395             {
14396                if (debug) printf("@@@@ rpt:Hung Up\n");
14397                ast_frfree(f);
14398                break;
14399             }
14400             /* if RX key */
14401             if (f->subclass.integer == AST_CONTROL_RADIO_KEY)
14402             {
14403                if (debug == 7) printf("@@@@ rx key\n");
14404                keyed = 1;
14405                myrpt->rerxtimer = 0;
14406             }
14407             /* if RX un-key */
14408             if (f->subclass.integer == AST_CONTROL_RADIO_UNKEY)
14409             {
14410                myrpt->rerxtimer = 0;
14411                if (debug == 7) printf("@@@@ rx un-key\n");
14412                keyed = 0;
14413             }
14414          }
14415          ast_frfree(f);
14416          continue;
14417       }
14418       if (who == myrpt->rxchannel) /* if it was a read from radio */
14419       {
14420          f = ast_read(myrpt->rxchannel);
14421          if (!f)
14422          {
14423             if (debug) printf("@@@@ link:Hung Up\n");
14424             break;
14425          }
14426          if (f->frametype == AST_FRAME_VOICE)
14427          {
14428             int myreming = 0;
14429 
14430             if(!strcmp(myrpt->remoterig, remote_rig_kenwood))
14431                myreming = reming;
14432 
14433             if (myreming || (!remkeyed) ||
14434             ((myrpt->remote) && (myrpt->remotetx)) ||
14435               ((myrpt->remmode != REM_MODE_FM) &&
14436                 notremming))
14437                memset(f->data.ptr,0,f->datalen); 
14438              ast_write(myrpt->pchannel,f);
14439          }
14440          else if (f->frametype == AST_FRAME_CONTROL)
14441          {
14442             if (f->subclass.integer == AST_CONTROL_HANGUP)
14443             {
14444                if (debug) printf("@@@@ rpt:Hung Up\n");
14445                ast_frfree(f);
14446                break;
14447             }
14448             /* if RX key */
14449             if (f->subclass.integer == AST_CONTROL_RADIO_KEY)
14450             {
14451                if (debug == 7) printf("@@@@ remote rx key\n");
14452                if (!myrpt->remotetx)
14453                {
14454                   remkeyed = 1;
14455                }
14456             }
14457             /* if RX un-key */
14458             if (f->subclass.integer == AST_CONTROL_RADIO_UNKEY)
14459             {
14460                if (debug == 7) printf("@@@@ remote rx un-key\n");
14461                if (!myrpt->remotetx) 
14462                {
14463                   remkeyed = 0;
14464                }
14465             }
14466          }
14467          ast_frfree(f);
14468          continue;
14469       }
14470       if (who == myrpt->pchannel) /* if is remote mix output */
14471       {
14472          f = ast_read(myrpt->pchannel);
14473          if (!f)
14474          {
14475             if (debug) printf("@@@@ link:Hung Up\n");
14476             break;
14477          }
14478          if (f->frametype == AST_FRAME_VOICE)
14479          {
14480             ast_write(chan,f);
14481          }
14482          if (f->frametype == AST_FRAME_CONTROL)
14483          {
14484             if (f->subclass.integer == AST_CONTROL_HANGUP)
14485             {
14486                if (debug) printf("@@@@ rpt:Hung Up\n");
14487                ast_frfree(f);
14488                break;
14489             }
14490          }
14491          ast_frfree(f);
14492          continue;
14493       }
14494       if ((myrpt->rxchannel != myrpt->txchannel) && 
14495          (who == myrpt->txchannel)) /* do this cuz you have to */
14496       {
14497          f = ast_read(myrpt->txchannel);
14498          if (!f)
14499          {
14500             if (debug) printf("@@@@ link:Hung Up\n");
14501             break;
14502          }
14503          if (f->frametype == AST_FRAME_CONTROL)
14504          {
14505             if (f->subclass.integer == AST_CONTROL_HANGUP)
14506             {
14507                if (debug) printf("@@@@ rpt:Hung Up\n");
14508                ast_frfree(f);
14509                break;
14510             }
14511          }
14512          ast_frfree(f);
14513          continue;
14514       }
14515    }
14516    if (myrpt->p.archivedir)
14517    {
14518       char mycmd[100],*b,*b1;
14519 
14520       /* look at callerid to see what node this comes from */
14521       b = S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL);
14522       if (!b) /* if doesn't have caller id */
14523       {
14524          b1 = "0";
14525       } else {
14526          b1 = ast_strdupa(b);
14527          ast_shrink_phone_number(b1);
14528       }
14529       sprintf(mycmd,"DISCONNECT,%s",b1);
14530       donodelog(myrpt,mycmd);
14531    }
14532    /* wait for telem to be done */
14533    while(myrpt->tele.next != &myrpt->tele) usleep(100000);
14534    sprintf(tmp,"mixmonitor stop %s",chan->name);
14535    ast_cli_command(nullfd,tmp);
14536    close(nullfd);
14537    rpt_mutex_lock(&myrpt->lock);
14538    myrpt->hfscanmode = 0;
14539    myrpt->hfscanstatus = 0;
14540    myrpt->remoteon = 0;
14541    rpt_mutex_unlock(&myrpt->lock);
14542    if (myrpt->lastf1) ast_frfree(myrpt->lastf1);
14543    myrpt->lastf1 = NULL;
14544    if (myrpt->lastf2) ast_frfree(myrpt->lastf2);
14545    myrpt->lastf2 = NULL;
14546    if ((iskenwood_pci4) && (myrpt->txchannel == myrpt->dahditxchannel))
14547    {
14548       z.radpar = DAHDI_RADPAR_UIOMODE;
14549       z.data = 3;
14550       if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
14551       {
14552          ast_log(LOG_ERROR,"Cannot set UIOMODE\n");
14553          return -1;
14554       }
14555       z.radpar = DAHDI_RADPAR_UIODATA;
14556       z.data = 3;
14557       if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_RADIO_SETPARAM,&z) == -1)
14558       {
14559          ast_log(LOG_ERROR,"Cannot set UIODATA\n");
14560          return -1;
14561       }
14562       i = DAHDI_OFFHOOK;
14563       if (ioctl(myrpt->dahditxchannel->fds[0],DAHDI_HOOK,&i) == -1)
14564       {
14565          ast_log(LOG_ERROR,"Cannot set hook\n");
14566          return -1;
14567       }
14568    }
14569    if (myrpt->iofd) close(myrpt->iofd);
14570    myrpt->iofd = -1;
14571    ast_hangup(myrpt->pchannel);
14572    if (myrpt->rxchannel != myrpt->txchannel) ast_hangup(myrpt->txchannel);
14573    ast_hangup(myrpt->rxchannel);
14574    closerem(myrpt);
14575    if (myrpt->p.rptnode)
14576    {
14577       rpt_mutex_lock(&myrpt->lock);
14578       for(i = 0; i < nrpts; i++)
14579       {
14580          if (!strcasecmp(rpt_vars[i].name,myrpt->p.rptnode))
14581          {
14582             rpt_vars[i].xlink = 0;
14583             break;
14584          }
14585       }
14586       rpt_mutex_unlock(&myrpt->lock);
14587    }
14588 #ifdef   OLD_ASTERISK
14589    LOCAL_USER_REMOVE(u);
14590 #endif
14591    return res;
14592 }
14593 
14594 #ifndef OLD_ASTERISK
14595 /*!\brief callback to display list of locally configured nodes
14596    \addtogroup Group_AMI
14597  */
14598 static int manager_rpt_local_nodes(struct mansession *s, const struct message *m)
14599 {
14600     int i;
14601     astman_append(s, "<?xml version=\"1.0\"?>\r\n");
14602     astman_append(s, "<nodes>\r\n");
14603     for (i=0; i< nrpts; i++)
14604     {
14605         astman_append(s, "  <node>%s</node>\r\n", rpt_vars[i].name);        
14606     } /* for i */
14607     astman_append(s, "</nodes>\r\n");
14608     astman_append(s, "\r\n"); /* Properly terminate Manager output */
14609     return RESULT_SUCCESS;
14610 } /* manager_rpt_local_nodes() */
14611 
14612 
14613 
14614 /*
14615  * Append Success and ActionID to manager response message
14616  */
14617 
14618 static void rpt_manager_success(struct mansession *s, const struct message *m)
14619 {
14620    const char *id = astman_get_header(m, "ActionID");
14621    if (!ast_strlen_zero(id))
14622       astman_append(s, "ActionID: %s\r\n", id);
14623    astman_append(s, "Response: Success\r\n");
14624 }
14625 
14626 /*
14627 * Dump statistics to manager session
14628 */
14629 
14630 static int rpt_manager_do_stats(struct mansession *s, const struct message *m, char *str)
14631 {
14632    int i,j,numoflinks;
14633    int dailytxtime, dailykerchunks;
14634    time_t now;
14635    int totalkerchunks, dailykeyups, totalkeyups, timeouts;
14636    int totalexecdcommands, dailyexecdcommands, hours, minutes, seconds;
14637    long long totaltxtime;
14638    struct   rpt_link *l;
14639    char *listoflinks[MAX_STAT_LINKS];  
14640    char *lastdtmfcommand,*parrot_ena;
14641    char *tot_state, *ider_state, *patch_state;
14642    char *reverse_patch_state, *sys_ena, *tot_ena, *link_ena, *patch_ena;
14643    char *sch_ena, *input_signal, *called_number, *user_funs, *tail_type;
14644    char *transmitterkeyed;
14645    const char *node = astman_get_header(m, "Node");
14646    struct rpt *myrpt;
14647 
14648    static char *not_applicable = "N/A";
14649 
14650    tot_state = ider_state = 
14651    patch_state = reverse_patch_state = 
14652    input_signal = not_applicable;
14653    called_number = lastdtmfcommand = transmitterkeyed = NULL;
14654 
14655    time(&now);
14656    for(i = 0; i < nrpts; i++)
14657    {
14658       if ((node)&&(!strcmp(node,rpt_vars[i].name))){
14659          rpt_manager_success(s,m);
14660 
14661          myrpt = &rpt_vars[i];
14662 
14663          if(myrpt->remote){ /* Remote base ? */
14664             char *loginuser, *loginlevel, *freq, *rxpl, *txpl, *modestr;
14665             char offset = 0, powerlevel = 0, rxplon = 0, txplon = 0, remoteon, remmode = 0, reportfmstuff;
14666             char offsetc,powerlevelc;
14667 
14668             loginuser = loginlevel = freq = rxpl = txpl = NULL;
14669             /* Make a copy of all stat variables while locked */
14670             rpt_mutex_lock(&myrpt->lock); /* LOCK */
14671             if((remoteon = myrpt->remoteon)){
14672                if(!ast_strlen_zero(myrpt->loginuser))
14673                   loginuser = ast_strdup(myrpt->loginuser);
14674                if(!ast_strlen_zero(myrpt->loginlevel))
14675                   loginlevel = ast_strdup(myrpt->loginlevel);
14676                if(!ast_strlen_zero(myrpt->freq))
14677                   freq = ast_strdup(myrpt->freq);
14678                if(!ast_strlen_zero(myrpt->rxpl))
14679                   rxpl = ast_strdup(myrpt->rxpl);
14680                if(!ast_strlen_zero(myrpt->txpl))
14681                   txpl = ast_strdup(myrpt->txpl);
14682                remmode = myrpt->remmode;
14683                offset = myrpt->offset;
14684                powerlevel = myrpt->powerlevel;
14685                rxplon = myrpt->rxplon;
14686                txplon = myrpt->txplon;       
14687             }
14688             rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
14689             astman_append(s, "IsRemoteBase: YES\r\n");
14690             astman_append(s, "RemoteOn: %s\r\n",(remoteon) ? "YES": "NO");
14691             if(remoteon){
14692                if(loginuser){
14693                   astman_append(s, "LogInUser: %s\r\n", loginuser);
14694                   ast_free(loginuser);
14695                }
14696                if(loginlevel){
14697                   astman_append(s, "LogInLevel: %s\r\n", loginlevel);
14698                   ast_free(loginlevel);
14699                }
14700                if(freq){
14701                   astman_append(s, "Freq: %s\r\n", freq);
14702                   ast_free(freq);
14703                }
14704                reportfmstuff = 0;
14705                switch(remmode){
14706                   case REM_MODE_FM:
14707                      modestr = "FM";   
14708                      reportfmstuff = 1;
14709                      break;
14710                   case REM_MODE_AM:
14711                      modestr = "AM";
14712                      break;
14713                   case REM_MODE_USB:
14714                      modestr = "USB";
14715                      break;
14716                   default:
14717                      modestr = "LSB";
14718                      break;
14719                }
14720                astman_append(s, "RemMode: %s\r\n", modestr);
14721                if(reportfmstuff){
14722                   switch(offset){
14723                      case REM_SIMPLEX:
14724                         offsetc = 'S';
14725                         break;
14726                      case REM_MINUS:
14727                         offsetc = '-';
14728                         break;
14729                      default:
14730                         offsetc = '+';
14731                         break;
14732                   }
14733                   astman_append(s, "RemOffset: %c\r\n", offsetc);
14734                   if(rxplon && rxpl){
14735                      astman_append(s, "RxPl: %s\r\n",rxpl);
14736                      ast_free(rxpl);
14737                   }
14738                   if(txplon && txpl){
14739                      astman_append(s, "TxPl: %s\r\n",txpl);
14740                      ast_free(txpl);
14741                   }
14742                }
14743                switch(powerlevel){
14744                   case REM_LOWPWR:
14745                      powerlevelc = 'L';
14746                      break;
14747                   case REM_MEDPWR:
14748                      powerlevelc = 'M';
14749                      break;
14750                   default:
14751                      powerlevelc = 'H';
14752                      break;
14753                }
14754                astman_append(s,"PowerLevel: %c\r\n", powerlevelc);
14755             }
14756             astman_append(s, "\r\n");
14757             return 0; /* End of remote base status reporting */
14758          }  
14759 
14760          /* ELSE Process as a repeater node */
14761          /* Make a copy of all stat variables while locked */
14762          rpt_mutex_lock(&myrpt->lock); /* LOCK */
14763          dailytxtime = myrpt->dailytxtime;
14764          totaltxtime = myrpt->totaltxtime;
14765          dailykeyups = myrpt->dailykeyups;
14766          totalkeyups = myrpt->totalkeyups;
14767          dailykerchunks = myrpt->dailykerchunks;
14768          totalkerchunks = myrpt->totalkerchunks;
14769          dailyexecdcommands = myrpt->dailyexecdcommands;
14770          totalexecdcommands = myrpt->totalexecdcommands;
14771          timeouts = myrpt->timeouts;
14772 
14773 
14774          /* Traverse the list of connected nodes */
14775          reverse_patch_state = "DOWN";
14776          numoflinks = 0;
14777          l = myrpt->links.next;
14778          while(l && (l != &myrpt->links)){
14779             if(numoflinks >= MAX_STAT_LINKS){
14780                ast_log(LOG_NOTICE,
14781                "maximum number of links exceeds %d in rpt_do_stats()!",MAX_STAT_LINKS);
14782                break;
14783             }
14784             if (l->name[0] == '0'){ /* Skip '0' nodes */
14785                reverse_patch_state = "UP";
14786                l = l->next;
14787                continue;
14788             }
14789             listoflinks[numoflinks] = ast_strdup(l->name);
14790             if(listoflinks[numoflinks] == NULL){
14791                break;
14792             }
14793             else{
14794                numoflinks++;
14795             }
14796             l = l->next;
14797          }
14798 
14799          if(myrpt->keyed)
14800             input_signal = "YES";
14801          else
14802             input_signal = "NO";
14803          
14804          if(myrpt->txkeyed)
14805             transmitterkeyed = "YES";
14806          else
14807             transmitterkeyed = "NO";
14808 
14809          if(myrpt->p.parrotmode)
14810             parrot_ena = "ENABLED";
14811          else
14812             parrot_ena = "DISABLED";
14813 
14814          if(myrpt->p.s[myrpt->p.sysstate_cur].txdisable)
14815             sys_ena = "DISABLED";
14816          else
14817             sys_ena = "ENABLED";
14818 
14819          if(myrpt->p.s[myrpt->p.sysstate_cur].totdisable)
14820             tot_ena = "DISABLED";
14821          else
14822             tot_ena = "ENABLED";
14823 
14824          if(myrpt->p.s[myrpt->p.sysstate_cur].linkfundisable)
14825             link_ena = "DISABLED";
14826          else
14827             link_ena = "ENABLED";
14828 
14829          if(myrpt->p.s[myrpt->p.sysstate_cur].autopatchdisable)
14830             patch_ena = "DISABLED";
14831          else
14832             patch_ena = "ENABLED";
14833 
14834          if(myrpt->p.s[myrpt->p.sysstate_cur].schedulerdisable)
14835             sch_ena = "DISABLED";
14836          else
14837             sch_ena = "ENABLED";
14838 
14839          if(myrpt->p.s[myrpt->p.sysstate_cur].userfundisable)
14840             user_funs = "DISABLED";
14841          else
14842             user_funs = "ENABLED";
14843 
14844          if(myrpt->p.s[myrpt->p.sysstate_cur].alternatetail)
14845             tail_type = "ALTERNATE";
14846          else
14847             tail_type = "STANDARD";
14848 
14849          if(!myrpt->totimer)
14850             tot_state = "TIMED OUT!";
14851          else if(myrpt->totimer != myrpt->p.totime)
14852             tot_state = "ARMED";
14853          else
14854             tot_state = "RESET";
14855 
14856          if(myrpt->tailid)
14857             ider_state = "QUEUED IN TAIL";
14858          else if(myrpt->mustid)
14859             ider_state = "QUEUED FOR CLEANUP";
14860          else
14861             ider_state = "CLEAN";
14862 
14863          switch(myrpt->callmode){
14864             case 1:
14865                patch_state = "DIALING";
14866                break;
14867             case 2:
14868                patch_state = "CONNECTING";
14869                break;
14870             case 3:
14871                patch_state = "UP";
14872                break;
14873 
14874             case 4:
14875                patch_state = "CALL FAILED";
14876                break;
14877 
14878             default:
14879                patch_state = "DOWN";
14880          }
14881 
14882          if(strlen(myrpt->exten)){
14883             called_number = ast_strdup(myrpt->exten);
14884          }
14885 
14886          if(strlen(myrpt->lastdtmfcommand)){
14887             lastdtmfcommand = ast_strdup(myrpt->lastdtmfcommand);
14888          }
14889          rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
14890 
14891          astman_append(s, "IsRemoteBase: NO\r\n");
14892          astman_append(s, "NodeState: %d\r\n", myrpt->p.sysstate_cur);
14893          astman_append(s, "SignalOnInput: %s\r\n", input_signal);
14894          astman_append(s, "TransmitterKeyed: %s\r\n", transmitterkeyed);
14895          astman_append(s, "Transmitter: %s\r\n", sys_ena);
14896          astman_append(s, "Parrot: %s\r\n", parrot_ena);
14897          astman_append(s, "Scheduler: %s\r\n", sch_ena);
14898          astman_append(s, "TailLength: %s\r\n", tail_type);
14899          astman_append(s, "TimeOutTimer: %s\r\n", tot_ena);
14900          astman_append(s, "TimeOutTimerState: %s\r\n", tot_state);
14901          astman_append(s, "TimeOutsSinceSystemInitialization: %d\r\n", timeouts);
14902          astman_append(s, "IdentifierState: %s\r\n", ider_state);
14903          astman_append(s, "KerchunksToday: %d\r\n", dailykerchunks);
14904          astman_append(s, "KerchunksSinceSystemInitialization: %d\r\n", totalkerchunks);
14905          astman_append(s, "KeyupsToday: %d\r\n", dailykeyups);
14906          astman_append(s, "KeyupsSinceSystemInitialization: %d\r\n", totalkeyups);
14907          astman_append(s, "DtmfCommandsToday: %d\r\n", dailyexecdcommands);
14908          astman_append(s, "DtmfCommandsSinceSystemInitialization: %d\r\n", totalexecdcommands);
14909          astman_append(s, "LastDtmfCommandExecuted: %s\r\n", 
14910          (lastdtmfcommand && strlen(lastdtmfcommand)) ? lastdtmfcommand : not_applicable);
14911          hours = dailytxtime/3600000;
14912          dailytxtime %= 3600000;
14913          minutes = dailytxtime/60000;
14914          dailytxtime %= 60000;
14915          seconds = dailytxtime/1000;
14916          dailytxtime %= 1000;
14917 
14918          astman_append(s, "TxTimeToday: %02d:%02d:%02d.%d\r\n",
14919             hours, minutes, seconds, dailytxtime);
14920 
14921          hours = (int) totaltxtime/3600000;
14922          totaltxtime %= 3600000;
14923          minutes = (int) totaltxtime/60000;
14924          totaltxtime %= 60000;
14925          seconds = (int)  totaltxtime/1000;
14926          totaltxtime %= 1000;
14927 
14928          astman_append(s, "TxTimeSinceSystemInitialization: %02d:%02d:%02d.%d\r\n",
14929              hours, minutes, seconds, (int) totaltxtime);
14930 
14931          sprintf(str, "NodesCurrentlyConnectedToUs: ");
14932                         if(!numoflinks){
14933                          strcat(str,"<NONE>");
14934                         }
14935          else{
14936             for(j = 0 ;j < numoflinks; j++){
14937                sprintf(str+strlen(str), "%s", listoflinks[j]);
14938                if(j < numoflinks - 1)
14939                   strcat(str,",");
14940             }
14941          }
14942          astman_append(s,"%s\r\n", str);
14943 
14944          astman_append(s, "Autopatch: %s\r\n", patch_ena);
14945          astman_append(s, "AutopatchState: %s\r\n", patch_state);
14946          astman_append(s, "AutopatchCalledNumber: %s\r\n",
14947          (called_number && strlen(called_number)) ? called_number : not_applicable);
14948          astman_append(s, "ReversePatchIaxrptConnected: %s\r\n", reverse_patch_state);
14949          astman_append(s, "UserLinkingCommands: %s\r\n", link_ena);
14950          astman_append(s, "UserFunctions: %s\r\n", user_funs);
14951 
14952          for(j = 0; j < numoflinks; j++){ /* ast_free() all link names */
14953             ast_free(listoflinks[j]);
14954          }
14955          if(called_number){
14956             ast_free(called_number);
14957          }
14958          if(lastdtmfcommand){
14959             ast_free(lastdtmfcommand);
14960          }
14961          astman_append(s, "\r\n"); /* We're Done! */
14962               return 0;
14963       }
14964    }
14965    astman_send_error(s, m, "RptStatus unknown or missing node");
14966    return -1;
14967 }
14968 
14969 
14970 
14971 /*
14972  * Implement the RptStatus Manager Interface
14973  */
14974 
14975 static int manager_rpt_status(struct mansession *s, const struct message *m)
14976 {
14977    int i,res,len,idx;
14978    int uptime,hours,minutes;
14979    time_t now;
14980    const char *cmd = astman_get_header(m, "Command");
14981    char *str;
14982    enum {MGRCMD_RPTSTAT,MGRCMD_NODESTAT};
14983    struct mgrcmdtbl{
14984       const char *cmd;
14985       int index;
14986    };
14987    static struct mgrcmdtbl mct[] = {
14988       {"RptStat",MGRCMD_RPTSTAT},
14989       {"NodeStat",MGRCMD_NODESTAT},
14990       {NULL,0} /* NULL marks end of command table */
14991    };
14992 
14993    time(&now);
14994 
14995    len = 1024; /* Allocate a working buffer */
14996    if(!(str = ast_malloc(len)))
14997       return -1;
14998 
14999    /* Check for Command */
15000    if(ast_strlen_zero(cmd)){
15001       astman_send_error(s, m, "RptStatus missing command");
15002       ast_free(str);
15003       return 0;
15004    }
15005    /* Try to find the command in the table */
15006    for(i = 0 ; mct[i].cmd ; i++){
15007       if(!strcmp(mct[i].cmd, cmd))
15008          break;
15009    }
15010 
15011    if(!mct[i].cmd){ /* Found or not found ? */
15012       astman_send_error(s, m, "RptStatus unknown command");
15013       ast_free(str);
15014       return 0;
15015    }
15016    else
15017       idx = mct[i].index;
15018 
15019    switch(idx){ /* Use the index to go to the correct command */
15020 
15021       case MGRCMD_RPTSTAT:
15022          /* Return Nodes: and a comma separated list of nodes */
15023          if((res = snprintf(str, len, "Nodes: ")) > -1)
15024             len -= res;
15025          else{
15026             ast_free(str);
15027             return 0;
15028          }
15029          for(i = 0; i < nrpts; i++){
15030             if(i < nrpts - 1){
15031                if((res = snprintf(str+strlen(str), len, "%s,",rpt_vars[i].name)) < 0){
15032                   ast_free(str);
15033                   return 0;
15034                }
15035             }
15036             else{
15037                if((res = snprintf(str+strlen(str), len, "%s",rpt_vars[i].name)) < 0){
15038                   ast_free(str);
15039                   return 0;
15040                }
15041             }
15042             len -= res;
15043          }
15044 
15045          rpt_manager_success(s,m);
15046          
15047          if(!nrpts)
15048             astman_append(s, "<NONE>\r\n");
15049          else
15050             astman_append(s, "%s\r\n", str);
15051 
15052          uptime = (int)(now - starttime);
15053                         hours = uptime/3600;
15054                         uptime %= 3600;
15055                         minutes = uptime/60;
15056                         uptime %= 60;
15057 
15058                         astman_append(s, "RptUptime: %02d:%02d:%02d\r\n",
15059                                 hours, minutes, uptime);
15060 
15061          astman_append(s, "\r\n");
15062          break;      
15063 
15064       case  MGRCMD_NODESTAT:
15065          res = rpt_manager_do_stats(s,m,str);
15066          ast_free(str);
15067          return res;
15068 
15069       default:
15070          astman_send_error(s, m, "RptStatus invalid command");
15071          break;
15072    }
15073    ast_free(str);
15074    return 0;
15075 }
15076 
15077 #endif
15078 
15079 #ifdef   OLD_ASTERISK
15080 int unload_module()
15081 #else
15082 static int unload_module(void)
15083 #endif
15084 {
15085    int i, res;
15086 
15087 #ifdef   OLD_ASTERISK
15088    STANDARD_HANGUP_LOCALUSERS;
15089 #endif
15090    for(i = 0; i < nrpts; i++) {
15091       if (!strcmp(rpt_vars[i].name,rpt_vars[i].p.nodes)) continue;
15092                 ast_mutex_destroy(&rpt_vars[i].lock);
15093                 ast_mutex_destroy(&rpt_vars[i].remlock);
15094    }
15095    res = ast_unregister_application(app);
15096 
15097 #ifdef   NEW_ASTERISK
15098    ast_cli_unregister_multiple(rpt_cli, ARRAY_LEN(rpt_cli));
15099 #else
15100    /* Unregister cli extensions */
15101    ast_cli_unregister(&cli_debug);
15102    ast_cli_unregister(&cli_dump);
15103    ast_cli_unregister(&cli_stats);
15104    ast_cli_unregister(&cli_lstats);
15105    ast_cli_unregister(&cli_nodes);
15106    ast_cli_unregister(&cli_local_nodes);
15107    ast_cli_unregister(&cli_reload);
15108    ast_cli_unregister(&cli_restart);
15109    ast_cli_unregister(&cli_fun);
15110    ast_cli_unregister(&cli_fun1);
15111    res |= ast_cli_unregister(&cli_cmd);
15112 #endif
15113 #ifndef OLD_ASTERISK
15114    res |= ast_manager_unregister("RptLocalNodes");
15115    res |= ast_manager_unregister("RptStatus");
15116 #endif
15117    return res;
15118 }
15119 
15120 #ifdef   OLD_ASTERISK
15121 int load_module()
15122 #else
15123 static int load_module(void)
15124 #endif
15125 {
15126    int res;
15127    ast_pthread_create(&rpt_master_thread,NULL,rpt_master,NULL);
15128 
15129 #ifdef   NEW_ASTERISK
15130    ast_cli_register_multiple(rpt_cli, ARRAY_LEN(rpt_cli));
15131    res = 0;
15132 #else
15133    /* Register cli extensions */
15134    ast_cli_register(&cli_debug);
15135    ast_cli_register(&cli_dump);
15136    ast_cli_register(&cli_stats);
15137    ast_cli_register(&cli_lstats);
15138    ast_cli_register(&cli_nodes);
15139    ast_cli_register(&cli_local_nodes);
15140    ast_cli_register(&cli_reload);
15141    ast_cli_register(&cli_restart);
15142    ast_cli_register(&cli_fun);
15143    ast_cli_register(&cli_fun1);
15144    res = ast_cli_register(&cli_cmd);
15145 #endif
15146 #ifndef OLD_ASTERISK
15147    res |= ast_manager_register("RptLocalNodes", 0, manager_rpt_local_nodes, "List local node numbers");
15148    res |= ast_manager_register("RptStatus", 0, manager_rpt_status, "Return Rpt Status for CGI");
15149 
15150 #endif
15151    res |= ast_register_application(app, rpt_exec, synopsis, descrip);
15152    return res;
15153 }
15154 
15155 #ifdef   OLD_ASTERISK
15156 char *description()
15157 {
15158    return tdesc;
15159 }
15160 int usecount(void)
15161 {
15162    int res;
15163    STANDARD_USECOUNT(res);
15164    return res;
15165 }
15166 
15167 char *key()
15168 {
15169    return ASTERISK_GPL_KEY;
15170 }
15171 #endif
15172 
15173 #ifdef   OLD_ASTERISK
15174 int reload()
15175 #else
15176 static int reload(void)
15177 #endif
15178 {
15179 int   n;
15180 
15181    for(n = 0; n < nrpts; n++) rpt_vars[n].reload = 1;
15182    return(0);
15183 }
15184 
15185 
15186 #ifndef  OLD_ASTERISK
15187 /* STD_MOD(MOD_1, reload, NULL, NULL); */
15188 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Radio Repeater/Remote Base Application",
15189       .load = load_module,
15190       .unload = unload_module,
15191       .reload = reload,
15192           );
15193 #endif
15194