decd98b7e942e6778e951b69e37f44766a49ff7b
[asterisk/asterisk.git] / apps / app_rpt.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2002-2005, Jim Dixon, WB6NIL
5  *
6  * Jim Dixon, WB6NIL <jim@lambdatel.com>
7  * Serious contributions by Steve RoDgers, WA6ZFT <hwstar@rodgers.sdcoxmail.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \brief Radio Repeater / Remote Base program 
23  *  version 0.48 06/13/06
24  * 
25  * \author Jim Dixon, WB6NIL <jim@lambdatel.com>
26  *
27  * \note Serious contributions by Steve RoDgers, WA6ZFT <hwstar@rodgers.sdcoxmail.com>
28  * 
29  * See http://www.zapatatelephony.org/app_rpt.html
30  *
31  *
32  * Repeater / Remote Functions:
33  * "Simple" Mode:  * - autopatch access, # - autopatch hangup
34  * Normal mode:
35  * See the function list in rpt.conf (autopatchup, autopatchdn)
36  * autopatchup can optionally take comma delimited setting=value pairs:
37  *  
38  *
39  * context=string               :       Override default context with "string"
40  * dialtime=ms                  :       Specify the max number of milliseconds between phone number digits (1000 milliseconds = 1 second)
41  * farenddisconnect=1           :       Automatically disconnect when called party hangs up
42  * noct=1                       :       Don't send repeater courtesy tone during autopatch calls
43  * quiet=1                      :       Don't send dial tone, or connect messages. Do not send patch down message when called party hangs up
44  *
45  *
46  * Example: 123=autopatchup,dialtime=20000,noct=1,farenddisconnect=1
47  *
48  *  To send an asterisk (*) while dialing or talking on phone,
49  *  use the autopatch acess code.
50  *
51  *
52  * status cmds:
53  *
54  *  1 - Force ID
55  *  2 - Give Time of Day
56  *  3 - Give software Version
57  *
58  * cop (control operator) cmds:
59  *
60  *  1 - System warm boot
61  *  2 - System enable
62  *  3 - System disable
63  *  4 - Test Tone On
64  *  5 - Dump System Variables on Console (debug)
65  *  6 - PTT (phone mode only)
66  *
67  * ilink cmds:
68  *
69  *  1 - Disconnect specified link
70  *  2 - Connect specified link -- monitor only
71  *  3 - Connect specified link -- tranceive
72  *  4 - Enter command mode on specified link
73  *  5 - System status
74  *  6 - Disconnect all links
75  *
76  * remote cmds:
77  *
78  *  1 - Recall Memory MM  (*000-*099) (Gets memory from rpt.conf)
79  *  2 - Set VFO MMMMM*KKK*O   (Mhz digits, Khz digits, Offset)
80  *  3 - Set Rx PL Tone HHH*D*
81  *  4 - Set Tx PL Tone HHH*D* (Not currently implemented with DHE RBI-1)
82  *  5 - Link Status (long)
83  *  6 - Set operating mode M (FM, USB, LSB, AM, etc)
84  *  100 - RX PL off (Default)
85  *  101 - RX PL On
86  *  102 - TX PL Off (Default)
87  *  103 - TX PL On
88  *  104 - Low Power
89  *  105 - Med Power
90  *  106 - Hi Power
91  *  107 - Bump Down 20 Hz
92  *  108 - Bump Down 100 Hz
93  *  109 - Bump Down 500 Hz
94  *  110 - Bump Up 20 Hz
95  *  111 - Bump Up 100 Hz
96  *  112 - Bump Up 500 Hz
97  *  113 - Scan Down Slow
98  *  114 - Scan Down Medium
99  *  115 - Scan Down Fast
100  *  116 - Scan Up Slow
101  *  117 - Scan Up Medium
102  *  118 - Scan Up Fast
103  *  119 - Transmit allowing auto-tune
104  *  140 - Link Status (brief)
105  *
106  *
107  *
108  * 'duplex' modes:  (defaults to duplex=2)
109  *
110  * 0 - Only remote links key Tx and no main repeat audio.
111  * 1 - Everything other then main Rx keys Tx, no main repeat audio.
112  * 2 - Normal mode
113  * 3 - Normal except no main repeat audio.
114  * 4 - Normal except no main repeat audio during autopatch only
115  *
116 */
117
118 /*** MODULEINFO
119         <depend>zaptel</depend>
120         <depend>tonezone</depend>
121         <defaultenabled>no</defaultenabled>
122  ***/
123
124 /* Un-comment the following to include support for MDC-1200 digital tone
125    signalling protocol (using KA6SQG's GPL'ed implementation) */
126 /* #include "mdc_decode.c" */
127
128 /* Un-comment the following to include support for notch filters in the
129    rx audio stream (using Tony Fisher's mknotch (mkfilter) implementation) */
130 /* #include "rpt_notch.c" */
131
132 /* maximum digits in DTMF buffer, and seconds after * for DTMF command timeout */
133
134 #define MAXDTMF 32
135 #define MAXMACRO 2048
136 #define MACROTIME 100
137 #define MACROPTIME 500
138 #define DTMF_TIMEOUT 3
139
140 #ifdef  __RPT_NOTCH
141 #define MAXFILTERS 10
142 #endif
143
144 #define DISC_TIME 10000  /* report disc after 10 seconds of no connect */
145 #define MAX_RETRIES 5
146
147 #define REDUNDANT_TX_TIME 2000
148
149 #define RETRY_TIMER_MS 5000
150
151 #define MAXPEERSTR 31
152 #define MAXREMSTR 15
153
154 #define DELIMCHR ','
155 #define QUOTECHR 34
156
157 #define NODES "nodes"
158 #define MEMORY "memory"
159 #define MACRO "macro"
160 #define FUNCTIONS "functions"
161 #define TELEMETRY "telemetry"
162 #define MORSE "morse"
163 #define FUNCCHAR '*'
164 #define ENDCHAR '#'
165
166 #define DEFAULT_IOBASE 0x378
167
168 #define MAXCONNECTTIME 5000
169
170 #define MAXNODESTR 300
171
172 #define MAXPATCHCONTEXT 100
173
174 #define ACTIONSIZE 32
175
176 #define TELEPARAMSIZE 256
177
178 #define REM_SCANTIME 100
179
180
181 enum {REM_OFF,REM_MONITOR,REM_TX};
182
183 enum{ID,PROC,TERM,COMPLETE,UNKEY,REMDISC,REMALREADY,REMNOTFOUND,REMGO,
184         CONNECTED,CONNFAIL,STATUS,TIMEOUT,ID1, STATS_TIME,
185         STATS_VERSION, IDTALKOVER, ARB_ALPHA, TEST_TONE, REV_PATCH,
186         TAILMSG, MACRO_NOTFOUND, MACRO_BUSY, LASTNODEKEY};
187
188 enum {REM_SIMPLEX,REM_MINUS,REM_PLUS};
189
190 enum {REM_LOWPWR,REM_MEDPWR,REM_HIPWR};
191
192 enum {DC_INDETERMINATE, DC_REQ_FLUSH, DC_ERROR, DC_COMPLETE, DC_DOKEY};
193
194 enum {SOURCE_RPT, SOURCE_LNK, SOURCE_RMT, SOURCE_PHONE, SOURCE_DPHONE};
195
196 enum {DLY_TELEM, DLY_ID, DLY_UNKEY, DLY_CALLTERM};
197
198 enum {REM_MODE_FM,REM_MODE_USB,REM_MODE_LSB,REM_MODE_AM};
199
200 enum {HF_SCAN_OFF,HF_SCAN_DOWN_SLOW,HF_SCAN_DOWN_QUICK,
201       HF_SCAN_DOWN_FAST,HF_SCAN_UP_SLOW,HF_SCAN_UP_QUICK,HF_SCAN_UP_FAST};
202
203 #include "asterisk.h"
204
205 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
206
207 #include <signal.h>
208 #include <stdio.h>
209 #include <unistd.h>
210 #include <string.h>
211 #include <stdlib.h>
212 #include <search.h>
213 #include <sys/types.h>
214 #include <sys/stat.h>
215 #include <errno.h>
216 #include <dirent.h>
217 #include <ctype.h>
218 #include <sys/stat.h>
219 #include <sys/time.h>
220 #include <sys/file.h>
221 #include <sys/ioctl.h>
222 #include <sys/io.h>
223 #include <math.h>
224 #include <zaptel/zaptel.h>
225 #include <zaptel/tonezone.h>
226 #include <netinet/in.h>
227 #include <arpa/inet.h>
228
229 #include "asterisk/utils.h"
230 #include "asterisk/lock.h"
231 #include "asterisk/file.h"
232 #include "asterisk/logger.h"
233 #include "asterisk/channel.h"
234 #include "asterisk/callerid.h"
235 #include "asterisk/pbx.h"
236 #include "asterisk/module.h"
237 #include "asterisk/translate.h"
238 #include "asterisk/features.h"
239 #include "asterisk/options.h"
240 #include "asterisk/cli.h"
241 #include "asterisk/config.h"
242 #include "asterisk/say.h"
243 #include "asterisk/localtime.h"
244
245 static char *app = "Rpt";
246
247 static char *synopsis = "Radio Repeater/Remote Base Control System";
248
249 static char *descrip = 
250 "  Rpt(nodename[|options]):  Radio Remote Link or Remote Base Link Endpoint Process.\n"
251 "\n"
252 "    Not specifying an option puts it in normal endpoint mode (where source\n"
253 "    IP and nodename are verified).\n"
254 "\n"
255 "    Options are as follows:\n"
256 "\n"
257 "        X - Normal endpoint mode WITHOUT security check. Only specify\n"
258 "            this if you have checked security already (like with an IAX2\n"
259 "            user/password or something).\n"
260 "\n"
261 "        Rannounce-string[|timeout[|timeout-destination]] - Amateur Radio\n"
262 "            Reverse Autopatch. Caller is put on hold, and announcement (as\n"
263 "            specified by the 'announce-string') is played on radio system.\n"
264 "            Users of radio system can access autopatch, dial specified\n"
265 "            code, and pick up call. Announce-string is list of names of\n"
266 "            recordings, or \"PARKED\" to substitute code for un-parking,\n"
267 "            or \"NODE\" to substitute node number.\n"
268 "\n"
269 "        P - Phone Control mode. This allows a regular phone user to have\n"
270 "            full control and audio access to the radio system. For the\n"
271 "            user to have DTMF control, the 'phone_functions' parameter\n"
272 "            must be specified for the node in 'rpt.conf'. An additional\n"
273 "            function (cop,6) must be listed so that PTT control is available.\n"
274 "\n"
275 "        D - Dumb Phone Control mode. This allows a regular phone user to\n"
276 "            have full control and audio access to the radio system. In this\n"
277 "            mode, the PTT is activated for the entire length of the call.\n"
278 "            For the user to have DTMF control (not generally recomended in\n"
279 "            this mode), the 'dphone_functions' parameter must be specified\n"
280 "            for the node in 'rpt.conf'. Otherwise no DTMF control will be\n"
281 "            available to the phone user.\n"
282 "\n";
283
284 static unsigned int vmajor = 0;
285 static unsigned int vminor = 47;
286
287 static int debug = 0;  /* FIXME Set this >0 for extra debug output */
288 static int nrpts = 0;
289
290 char *discstr = "!!DISCONNECT!!";
291 static char *remote_rig_ft897="ft897";
292 static char *remote_rig_rbi="rbi";
293
294 #ifdef  OLD_ASTERISK
295 STANDARD_LOCAL_USER;
296 #endif
297
298
299 #define MSWAIT 200
300 #define HANGTIME 5000
301 #define TOTIME 180000
302 #define IDTIME 300000
303 #define MAXRPTS 20
304 #define MAX_STAT_LINKS 32
305 #define POLITEID 30000
306 #define FUNCTDELAY 1500
307
308 static  pthread_t rpt_master_thread;
309
310 struct rpt;
311
312 struct rpt_link
313 {
314         struct rpt_link *next;
315         struct rpt_link *prev;
316         char    mode;                   /* 1 if in tx mode */
317         char    isremote;
318         char    phonemode;
319         char    name[MAXNODESTR];       /* identifier (routing) string */
320         char    lasttx;
321         char    lastrx;
322         char    connected;
323         char    hasconnected;
324         char    outbound;
325         char    disced;
326         char    killme;
327         long    elaptime;
328         long    disctime;
329         long    retrytimer;
330         long    retxtimer;
331         int     retries;
332         int     reconnects;
333         long long connecttime;
334         struct ast_channel *chan;       
335         struct ast_channel *pchan;      
336 } ;
337
338 struct rpt_lstat
339 {
340         struct  rpt_lstat *next;
341         struct  rpt_lstat *prev;
342         char    peer[MAXPEERSTR];
343         char    name[MAXNODESTR];
344         char    mode;
345         char    outbound;
346         char    reconnects;
347         long long       connecttime;
348 } ;
349
350 struct rpt_tele
351 {
352         struct rpt_tele *next;
353         struct rpt_tele *prev;
354         struct rpt *rpt;
355         struct ast_channel *chan;
356         int     mode;
357         struct rpt_link mylink;
358         char param[TELEPARAMSIZE];
359         pthread_t threadid;
360 } ;
361
362 struct function_table_tag
363 {
364         char action[ACTIONSIZE];
365         int (*function)(struct rpt *myrpt, char *param, char *digitbuf, 
366                 int command_source, struct rpt_link *mylink);
367 } ;
368
369 /* Used to store the morse code patterns */
370
371 struct morse_bits
372 {                 
373         int len;
374         int ddcomb;
375 } ;
376
377 struct telem_defaults
378 {
379         char name[20];
380         char value[80];
381 } ;
382
383
384 static struct rpt
385 {
386         ast_mutex_t lock;
387         struct ast_config *cfg;
388         char reload;
389
390         char *name;
391         char *rxchanname;
392         char *txchanname;
393         char *remote;
394
395         struct {
396
397                 const char *ourcontext;
398                 const char *ourcallerid;
399                 const char *acctcode;
400                 const char *ident;
401                 char *tonezone;
402                 char simple;
403                 const char *functions;
404                 const char *link_functions;
405                 const char *phone_functions;
406                 const char *dphone_functions;
407                 const char *nodes;
408                 int hangtime;
409                 int totime;
410                 int idtime;
411                 int tailmessagetime;
412                 int tailsquashedtime;
413                 int duplex;
414                 int politeid;
415                 char *tailmessages[500];
416                 int tailmessagemax;
417                 const char      *memory;
418                 const char      *macro;
419                 const char      *startupmacro;
420                 int iobase;
421                 char funcchar;
422                 char endchar;
423                 char    nobusyout;
424         } p;
425         struct rpt_link links;
426         int unkeytocttimer;
427         char keyed;
428         char exttx;
429         char localtx;
430         char remoterx;
431         char remotetx;
432         char remoteon;
433         char tounkeyed;
434         char tonotify;
435         char enable;
436         char dtmfbuf[MAXDTMF];
437         char macrobuf[MAXMACRO];
438         char rem_dtmfbuf[MAXDTMF];
439         char lastdtmfcommand[MAXDTMF];
440         char cmdnode[50];
441         struct ast_channel *rxchannel,*txchannel;
442         struct ast_channel *pchannel,*txpchannel, *remchannel;
443         struct rpt_tele tele;
444         struct timeval lasttv,curtv;
445         pthread_t rpt_call_thread,rpt_thread;
446         time_t dtmf_time,rem_dtmf_time,dtmf_time_rem;
447         int tailtimer,totimer,idtimer,txconf,conf,callmode,cidx,scantimer,tmsgtimer,skedtimer;
448         int mustid,tailid;
449         int tailevent;
450         int telemrefcount;
451         int dtmfidx,rem_dtmfidx;
452         int dailytxtime,dailykerchunks,totalkerchunks,dailykeyups,totalkeyups,timeouts;
453         int totalexecdcommands, dailyexecdcommands;
454         long    retxtimer;
455         long long totaltxtime;
456         char mydtmf;
457         char exten[AST_MAX_EXTENSION];
458         char freq[MAXREMSTR],rxpl[MAXREMSTR],txpl[MAXREMSTR];
459         char offset;
460         char powerlevel;
461         char txplon;
462         char rxplon;
463         char remmode;
464         char tunerequest;
465         char hfscanmode;
466         int hfscanstatus;
467         char lastlinknode[MAXNODESTR];
468         char stopgen;
469         char patchfarenddisconnect;
470         char patchnoct;
471         char patchquiet;
472         char patchcontext[MAXPATCHCONTEXT];
473         int patchdialtime;
474         int macro_longest;
475         int phone_longestfunc;
476         int dphone_longestfunc;
477         int link_longestfunc;
478         int longestfunc;
479         int longestnode;
480         int threadrestarts;             
481         int tailmessagen;
482         time_t disgorgetime;
483         time_t lastthreadrestarttime;
484         long    macrotimer;
485         char    lastnodewhichkeyedusup[MAXNODESTR];
486 #ifdef  __RPT_NOTCH
487         struct rptfilter
488         {
489                 char    desc[100];
490                 float   x0;
491                 float   x1;
492                 float   x2;
493                 float   y0;
494                 float   y1;
495                 float   y2;
496                 float   gain;
497                 float   const0;
498                 float   const1;
499                 float   const2;
500         } filters[MAXFILTERS];
501 #endif
502 #ifdef  _MDC_DECODE_H_
503         mdc_decoder_t *mdc;
504         unsigned short lastunit;
505 #endif
506 } rpt_vars[MAXRPTS];    
507
508
509 #ifdef  APP_RPT_LOCK_DEBUG
510
511 #warning COMPILING WITH LOCK-DEBUGGING ENABLED!!
512
513 #define MAXLOCKTHREAD 100
514
515 #define rpt_mutex_lock(x) _rpt_mutex_lock(x,myrpt,__LINE__)
516 #define rpt_mutex_unlock(x) _rpt_mutex_unlock(x,myrpt,__LINE__)
517
518 struct lockthread
519 {
520         pthread_t id;
521         int lockcount;
522         int lastlock;
523         int lastunlock;
524 } lockthreads[MAXLOCKTHREAD];
525
526
527 struct by_lightning
528 {
529         int line;
530         struct timeval tv;
531         struct rpt *rpt;
532         struct lockthread lockthread;
533 } lock_ring[32];
534
535
536 int lock_ring_index = 0;
537
538 AST_MUTEX_DEFINE_STATIC(locklock);
539
540 static struct lockthread *get_lockthread(pthread_t id)
541 {
542 int     i;
543
544         for(i = 0; i < MAXLOCKTHREAD; i++)
545         {
546                 if (lockthreads[i].id == id) return(&lockthreads[i]);
547         }
548         return(NULL);
549 }
550
551 static struct lockthread *put_lockthread(pthread_t id)
552 {
553 int     i;
554
555         for(i = 0; i < MAXLOCKTHREAD; i++)
556         {
557                 if (lockthreads[i].id == id)
558                         return(&lockthreads[i]);
559         }
560         for(i = 0; i < MAXLOCKTHREAD; i++)
561         {
562                 if (!lockthreads[i].id)
563                 {
564                         lockthreads[i].lockcount = 0;
565                         lockthreads[i].lastlock = 0;
566                         lockthreads[i].lastunlock = 0;
567                         lockthreads[i].id = id;
568                         return(&lockthreads[i]);
569                 }
570         }
571         return(NULL);
572 }
573
574
575 static void rpt_mutex_spew(void)
576 {
577         struct by_lightning lock_ring_copy[32];
578         int lock_ring_index_copy;
579         int i,j;
580         long long diff;
581         char a[100];
582         struct timeval lasttv;
583
584         ast_mutex_lock(&locklock);
585         memcpy(&lock_ring_copy, &lock_ring, sizeof(lock_ring_copy));
586         lock_ring_index_copy = lock_ring_index;
587         ast_mutex_unlock(&locklock);
588
589         lasttv.tv_sec = lasttv.tv_usec = 0;
590         for(i = 0 ; i < 32 ; i++)
591         {
592                 j = (i + lock_ring_index_copy) % 32;
593                 strftime(a,sizeof(a) - 1,"%m/%d/%Y %H:%M:%S",
594                         localtime(&lock_ring_copy[j].tv.tv_sec));
595                 diff = 0;
596                 if(lasttv.tv_sec)
597                 {
598                         diff = (lock_ring_copy[j].tv.tv_sec - lasttv.tv_sec)
599                                 * 1000000;
600                         diff += (lock_ring_copy[j].tv.tv_usec - lasttv.tv_usec);
601                 }
602                 lasttv.tv_sec = lock_ring_copy[j].tv.tv_sec;
603                 lasttv.tv_usec = lock_ring_copy[j].tv.tv_usec;
604                 if (!lock_ring_copy[j].tv.tv_sec) continue;
605                 if (lock_ring_copy[j].line < 0)
606                 {
607                         ast_log(LOG_NOTICE,"LOCKDEBUG [#%d] UNLOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
608                                 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);
609                 }
610                 else
611                 {
612                         ast_log(LOG_NOTICE,"LOCKDEBUG [#%d] LOCK app_rpt.c:%d node %s pid %x diff %lld us at %s.%06d\n",
613                                 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);
614                 }
615         }
616 }
617
618
619 static void _rpt_mutex_lock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
620 {
621 struct lockthread *t;
622 pthread_t id;
623
624         id = pthread_self();
625         ast_mutex_lock(&locklock);
626         t = put_lockthread(id);
627         if (!t)
628         {
629                 ast_mutex_unlock(&locklock);
630                 return;
631         }
632         if (t->lockcount)
633         {
634                 int lastline = t->lastlock;
635                 ast_mutex_unlock(&locklock);
636                 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);
637                 rpt_mutex_spew();
638                 return;
639         }
640         t->lastlock = line;
641         t->lockcount = 1;
642         gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
643         lock_ring[lock_ring_index].rpt = myrpt;
644         memcpy(&lock_ring[lock_ring_index].lockthread,t,sizeof(struct lockthread));
645         lock_ring[lock_ring_index++].line = line;
646         if(lock_ring_index == 32)
647                 lock_ring_index = 0;
648         ast_mutex_unlock(&locklock);
649         ast_mutex_lock(lockp);
650 }
651
652
653 static void _rpt_mutex_unlock(ast_mutex_t *lockp, struct rpt *myrpt, int line)
654 {
655 struct lockthread *t;
656 pthread_t id;
657
658         id = pthread_self();
659         ast_mutex_lock(&locklock);
660         t = put_lockthread(id);
661         if (!t)
662         {
663                 ast_mutex_unlock(&locklock);
664                 return;
665         }
666         if (!t->lockcount)
667         {
668                 int lastline = t->lastunlock;
669                 ast_mutex_unlock(&locklock);
670                 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);
671                 rpt_mutex_spew();
672                 return;
673         }
674         t->lastunlock = line;
675         t->lockcount = 0;
676         gettimeofday(&lock_ring[lock_ring_index].tv, NULL);
677         lock_ring[lock_ring_index].rpt = myrpt;
678         memcpy(&lock_ring[lock_ring_index].lockthread,t,sizeof(struct lockthread));
679         lock_ring[lock_ring_index++].line = -line;
680         if(lock_ring_index == 32)
681                 lock_ring_index = 0;
682         ast_mutex_unlock(&locklock);
683         ast_mutex_unlock(lockp);
684 }
685
686 #else  /* APP_RPT_LOCK_DEBUG */
687
688 #define rpt_mutex_lock(x) ast_mutex_lock(x)
689 #define rpt_mutex_unlock(x) ast_mutex_unlock(x)
690
691 #endif  /* APP_RPT_LOCK_DEBUG */
692
693 /*
694 * CLI extensions
695 */
696
697 /* Debug mode */
698 static int rpt_do_debug(int fd, int argc, char *argv[]);
699 static int rpt_do_dump(int fd, int argc, char *argv[]);
700 static int rpt_do_stats(int fd, int argc, char *argv[]);
701 static int rpt_do_lstats(int fd, int argc, char *argv[]);
702 static int rpt_do_reload(int fd, int argc, char *argv[]);
703 static int rpt_do_restart(int fd, int argc, char *argv[]);
704
705 static char debug_usage[] =
706 "Usage: rpt debug level {0-7}\n"
707 "       Enables debug messages in app_rpt\n";
708
709 static char dump_usage[] =
710 "Usage: rpt dump <nodename>\n"
711 "       Dumps struct debug info to log\n";
712
713 static char dump_stats[] =
714 "Usage: rpt stats <nodename>\n"
715 "       Dumps node statistics to console\n";
716
717 static char dump_lstats[] =
718 "Usage: rpt lstats <nodename>\n"
719 "       Dumps link statistics to console\n";
720
721 static char reload_usage[] =
722 "Usage: rpt reload\n"
723 "       Reloads app_rpt running config parameters\n";
724
725 static char restart_usage[] =
726 "Usage: rpt restart\n"
727 "       Restarts app_rpt\n";
728
729 static struct ast_cli_entry cli_rpt[] = {
730         { { "rpt", "debug", "level" },
731         rpt_do_debug, "Enable app_rpt debugging",
732         debug_usage },
733
734         { { "rpt", "dump" },
735         rpt_do_dump, "Dump app_rpt structs for debugging",
736         dump_usage },
737
738         { { "rpt", "stats" },
739         rpt_do_stats, "Dump node statistics",
740         dump_stats },
741         { { "rpt", "lstats" },
742         rpt_do_lstats, "Dump link statistics",
743         dump_lstats },
744
745         { { "rpt", "reload" },
746         rpt_do_reload, "Reload app_rpt config",
747         reload_usage },
748
749         { { "rpt", "restart" },
750         rpt_do_restart, "Restart app_rpt",
751         restart_usage },
752 };
753
754 /*
755 * Telemetry defaults
756 */
757
758
759 static struct telem_defaults tele_defs[] = {
760         {"ct1","|t(350,0,100,3072)(500,0,100,3072)(660,0,100,3072)"},
761         {"ct2","|t(660,880,150,3072)"},
762         {"ct3","|t(440,0,150,3072)"},
763         {"ct4","|t(550,0,150,3072)"},
764         {"ct5","|t(660,0,150,3072)"},
765         {"ct6","|t(880,0,150,3072)"},
766         {"ct7","|t(660,440,150,3072)"},
767         {"ct8","|t(700,1100,150,3072)"},
768         {"remotemon","|t(1600,0,75,2048)"},
769         {"remotetx","|t(2000,0,75,2048)(0,0,75,0)(1600,0,75,2048)"},
770         {"cmdmode","|t(900,904,200,2048)"},
771         {"functcomplete","|t(1000,0,100,2048)(0,0,100,0)(1000,0,100,2048)"}
772 } ;
773
774 /*
775 * Forward decl's - these suppress compiler warnings when funcs coded further down the file than thier invokation
776 */
777
778 static int setrbi(struct rpt *myrpt);
779
780
781
782 /*
783 * Define function protos for function table here
784 */
785
786 static int function_ilink(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
787 static int function_autopatchup(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
788 static int function_autopatchdn(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
789 static int function_status(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
790 static int function_cop(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
791 static int function_remote(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
792 static int function_macro(struct rpt *myrpt, char *param, char *digitbuf, int command_source, struct rpt_link *mylink);
793 /*
794 * Function table
795 */
796
797 static struct function_table_tag function_table[] = {
798         {"cop", function_cop},
799         {"autopatchup", function_autopatchup},
800         {"autopatchdn", function_autopatchdn},
801         {"ilink", function_ilink},
802         {"status", function_status},
803         {"remote", function_remote},
804         {"macro", function_macro}
805 } ;
806
807 /*
808 * Break up a delimited string into a table of substrings
809 *
810 * str - delimited string ( will be modified )
811 * strp- list of pointers to substrings (this is built by this function), NULL will be placed at end of list
812 * limit- maximum number of substrings to process
813 */
814         
815
816
817 static int finddelim(char *str, char *strp[], int limit)
818 {
819 int     i,l,inquo;
820
821         inquo = 0;
822         i = 0;
823         strp[i++] = str;
824         if (!*str)
825            {
826                 strp[0] = 0;
827                 return(0);
828            }
829         for(l = 0; *str && (l < limit) ; str++)
830            {
831                 if (*str == QUOTECHR)
832                    {
833                         if (inquo)
834                            {
835                                 *str = 0;
836                                 inquo = 0;
837                            }
838                         else
839                            {
840                                 strp[i - 1] = str + 1;
841                                 inquo = 1;
842                            }
843                 }
844                 if ((*str == DELIMCHR) && (!inquo))
845                 {
846                         *str = 0;
847                         l++;
848                         strp[i++] = str + 1;
849                 }
850            }
851         strp[i] = 0;
852         return(i);
853
854 }
855
856 /*
857 * Match a keyword in a list, and return index of string plus 1 if there was a match,
858 * else return 0. If param is passed in non-null, then it will be set to the first character past the match
859 */
860
861 static int matchkeyword(char *string, char **param, char *keywords[])
862 {
863 int     i,ls;
864         for( i = 0 ; keywords[i] ; i++){
865                 ls = strlen(keywords[i]);
866                 if(!ls){
867                         *param = NULL;
868                         return 0;
869                 }
870                 if(!strncmp(string, keywords[i], ls)){
871                         if(param)
872                                 *param = string + ls;
873                         return i + 1; 
874                 }
875         }
876         param = NULL;
877         return 0;
878 }
879
880 /*
881 * Skip characters in string which are in charlist, and return a pointer to the
882 * first non-matching character
883 */
884
885 static char *skipchars(char *string, char *charlist)
886 {
887 int i;  
888         while(*string){
889                 for(i = 0; charlist[i] ; i++){
890                         if(*string == charlist[i]){
891                                 string++;
892                                 break;
893                         }
894                 }
895                 if(!charlist[i])
896                         return string;
897         }
898         return string;
899 }       
900                                         
901
902
903 static int myatoi(const char *str)
904 {
905 int     ret;
906
907         if (str == NULL) return -1;
908         /* leave this %i alone, non-base-10 input is useful here */
909         if (sscanf(str,"%i",&ret) != 1) return -1;
910         return ret;
911 }
912
913
914 #ifdef  __RPT_NOTCH
915
916 /* rpt filter routine */
917 static void rpt_filter(struct rpt *myrpt, volatile short *buf, int len)
918 {
919 int     i,j;
920 struct  rptfilter *f;
921
922         for(i = 0; i < len; i++)
923         {
924                 for(j = 0; j < MAXFILTERS; j++)
925                 {
926                         f = &myrpt->filters[j];
927                         if (!*f->desc) continue;
928                         f->x0 = f->x1; f->x1 = f->x2;
929                         f->x2 = ((float)buf[i]) / f->gain;
930                         f->y0 = f->y1; f->y1 = f->y2;
931                         f->y2 =   (f->x0 + f->x2) +   f->const0 * f->x1
932                                      + (f->const1 * f->y0) + (f->const2 * f->y1);
933                         buf[i] = (short)f->y2;
934                 }
935         }
936 }
937
938 #endif
939
940 /* Retrieve an int from a config file */
941                                                                                 
942 static int retrieve_astcfgint(struct rpt *myrpt,char *category, char *name, int min, int max, int defl)
943 {
944         const char *var;
945         int ret;
946                                                                                 
947         var = ast_variable_retrieve(myrpt->cfg, category, name);
948         if(var){
949                 ret = myatoi(var);
950                 if(ret < min)
951                         ret = min;
952                 if(ret > max)
953                         ret = max;
954         }
955         else
956                 ret = defl;
957         return ret;
958 }
959
960
961 static void load_rpt_vars(int n,int init)
962 {
963 char *this;
964         const char *val;
965 int     j,longestnode;
966 struct ast_variable *vp;
967 struct ast_config *cfg;
968 #ifdef  __RPT_NOTCH
969 int     i;
970 char *strs[100];
971 #endif
972
973         if (option_verbose > 2)
974                 ast_verbose(VERBOSE_PREFIX_3 "%s config for repeater %s\n",
975                         (init) ? "Loading initial" : "Re-Loading",rpt_vars[n].name);
976         ast_mutex_lock(&rpt_vars[n].lock);
977         if (rpt_vars[n].cfg) ast_config_destroy(rpt_vars[n].cfg);
978         cfg = ast_config_load("rpt.conf");
979         if (!cfg) {
980                 ast_mutex_unlock(&rpt_vars[n].lock);
981                 ast_log(LOG_NOTICE, "Unable to open radio repeater configuration rpt.conf.  Radio Repeater disabled.\n");
982                 pthread_exit(NULL);
983         }
984         rpt_vars[n].cfg = cfg; 
985         this = rpt_vars[n].name;
986         memset(&rpt_vars[n].p,0,sizeof(rpt_vars[n].p));
987         if (init)
988         {
989                 char *cp;
990                 int savearea = (char *)&rpt_vars[n].p - (char *)&rpt_vars[n];
991
992                 cp = (char *) &rpt_vars[n].p;
993                 memset(cp + sizeof(rpt_vars[n].p),0,
994                         sizeof(rpt_vars[n]) - (sizeof(rpt_vars[n].p) + savearea));
995                 rpt_vars[n].tele.next = &rpt_vars[n].tele;
996                 rpt_vars[n].tele.prev = &rpt_vars[n].tele;
997                 rpt_vars[n].rpt_thread = AST_PTHREADT_NULL;
998                 rpt_vars[n].tailmessagen = 0;
999         }
1000 #ifdef  __RPT_NOTCH
1001         /* zot out filters stuff */
1002         memset(&rpt_vars[n].filters,0,sizeof(rpt_vars[n].filters));
1003 #endif
1004         val = ast_variable_retrieve(cfg,this,"context");
1005         if (val) rpt_vars[n].p.ourcontext = val;
1006         else rpt_vars[n].p.ourcontext = this;
1007         val = ast_variable_retrieve(cfg,this,"callerid");
1008         if (val) rpt_vars[n].p.ourcallerid = val;
1009         val = ast_variable_retrieve(cfg,this,"accountcode");
1010         if (val) rpt_vars[n].p.acctcode = val;
1011         val = ast_variable_retrieve(cfg,this,"idrecording");
1012         if (val) rpt_vars[n].p.ident = val;
1013         val = ast_variable_retrieve(cfg,this,"hangtime");
1014         if (val) rpt_vars[n].p.hangtime = atoi(val);
1015                 else rpt_vars[n].p.hangtime = HANGTIME;
1016         val = ast_variable_retrieve(cfg,this,"totime");
1017         if (val) rpt_vars[n].p.totime = atoi(val);
1018                 else rpt_vars[n].p.totime = TOTIME;
1019         rpt_vars[n].p.tailmessagetime = retrieve_astcfgint(&rpt_vars[n],this, "tailmessagetime", 0, 2400000, 0);                
1020         rpt_vars[n].p.tailsquashedtime = retrieve_astcfgint(&rpt_vars[n],this, "tailsquashedtime", 0, 2400000, 0);              
1021         rpt_vars[n].p.duplex = retrieve_astcfgint(&rpt_vars[n],this,"duplex",0,4,2);
1022         rpt_vars[n].p.idtime = retrieve_astcfgint(&rpt_vars[n],this, "idtime", 60000, 2400000, IDTIME); /* Enforce a min max */
1023         rpt_vars[n].p.politeid = retrieve_astcfgint(&rpt_vars[n],this, "politeid", 30000, 300000, POLITEID); /* Enforce a min max */
1024         val = ast_variable_retrieve(cfg,this,"tonezone");
1025         if (val) rpt_vars[n].p.tonezone = ast_strdupa(val);
1026         rpt_vars[n].p.tailmessages[0] = 0;
1027         rpt_vars[n].p.tailmessagemax = 0;
1028         val = ast_variable_retrieve(cfg,this,"tailmessagelist");
1029         if (val) rpt_vars[n].p.tailmessagemax = finddelim(ast_strdupa(val), rpt_vars[n].p.tailmessages, 500);
1030         val = ast_variable_retrieve(cfg,this,"memory");
1031         if (!val) val = MEMORY;
1032         rpt_vars[n].p.memory = val;
1033         val = ast_variable_retrieve(cfg,this,"macro");
1034         if (!val) val = MACRO;
1035         rpt_vars[n].p.macro = val;
1036         val = ast_variable_retrieve(cfg,this,"startup_macro");
1037         if (val) rpt_vars[n].p.startupmacro = val;
1038         val = ast_variable_retrieve(cfg,this,"iobase");
1039         /* do not use atoi() here, we need to be able to have
1040                 the input specified in hex or decimal so we use
1041                 sscanf with a %i */
1042         if ((!val) || (sscanf(val,"%i",&rpt_vars[n].p.iobase) != 1))
1043         rpt_vars[n].p.iobase = DEFAULT_IOBASE;
1044         val = ast_variable_retrieve(cfg,this,"functions");
1045         if (!val)
1046                 {
1047                         val = FUNCTIONS;
1048                         rpt_vars[n].p.simple = 1;
1049                 } 
1050         rpt_vars[n].p.functions = val;
1051         val =  ast_variable_retrieve(cfg,this,"link_functions");
1052         if (val) rpt_vars[n].p.link_functions = val;
1053         else 
1054                 rpt_vars[n].p.link_functions = rpt_vars[n].p.functions;
1055         val = ast_variable_retrieve(cfg,this,"phone_functions");
1056         if (val) rpt_vars[n].p.phone_functions = val;
1057         val = ast_variable_retrieve(cfg,this,"dphone_functions");
1058         if (val) rpt_vars[n].p.dphone_functions = val;
1059         val = ast_variable_retrieve(cfg,this,"funcchar");
1060         if (!val) rpt_vars[n].p.funcchar = FUNCCHAR; else 
1061                 rpt_vars[n].p.funcchar = *val;          
1062         val = ast_variable_retrieve(cfg,this,"endchar");
1063         if (!val) rpt_vars[n].p.endchar = ENDCHAR; else 
1064                 rpt_vars[n].p.endchar = *val;           
1065         val = ast_variable_retrieve(cfg,this,"nobusyout");
1066         if (val) rpt_vars[n].p.nobusyout = ast_true(val);
1067         val = ast_variable_retrieve(cfg,this,"nodes");
1068         if (!val) val = NODES;
1069         rpt_vars[n].p.nodes = val;
1070 #ifdef  __RPT_NOTCH
1071         val = ast_variable_retrieve(cfg,this,"rxnotch");
1072         if (val) {
1073                 i = finddelim(ast_strdupa(val),strs,MAXFILTERS * 2);
1074                 i &= ~1; /* force an even number, rounded down */
1075                 if (i >= 2) for(j = 0; j < i; j += 2)
1076                 {
1077                         rpt_mknotch(atof(strs[j]),atof(strs[j + 1]),
1078                           &rpt_vars[n].filters[j >> 1].gain,
1079                             &rpt_vars[n].filters[j >> 1].const0,
1080                                 &rpt_vars[n].filters[j >> 1].const1,
1081                                     &rpt_vars[n].filters[j >> 1].const2);
1082                         sprintf(rpt_vars[n].filters[j >> 1].desc,"%s Hz, BW = %s",
1083                                 strs[j],strs[j + 1]);
1084                 }
1085
1086         }
1087 #endif
1088         longestnode = 0;
1089
1090         vp = ast_variable_browse(cfg, rpt_vars[n].p.nodes);
1091                 
1092         while(vp){
1093                 j = strlen(vp->name);
1094                 if (j > longestnode)
1095                         longestnode = j;
1096                 vp = vp->next;
1097         }
1098
1099         rpt_vars[n].longestnode = longestnode;
1100                 
1101         /*
1102         * For this repeater, Determine the length of the longest function 
1103         */
1104         rpt_vars[n].longestfunc = 0;
1105         vp = ast_variable_browse(cfg, rpt_vars[n].p.functions);
1106         while(vp){
1107                 j = strlen(vp->name);
1108                 if (j > rpt_vars[n].longestfunc)
1109                         rpt_vars[n].longestfunc = j;
1110                 vp = vp->next;
1111         }
1112         /*
1113         * For this repeater, Determine the length of the longest function 
1114         */
1115         rpt_vars[n].link_longestfunc = 0;
1116         vp = ast_variable_browse(cfg, rpt_vars[n].p.link_functions);
1117         while(vp){
1118                 j = strlen(vp->name);
1119                 if (j > rpt_vars[n].link_longestfunc)
1120                         rpt_vars[n].link_longestfunc = j;
1121                 vp = vp->next;
1122         }
1123         rpt_vars[n].phone_longestfunc = 0;
1124         if (rpt_vars[n].p.phone_functions)
1125         {
1126                 vp = ast_variable_browse(cfg, rpt_vars[n].p.phone_functions);
1127                 while(vp){
1128                         j = strlen(vp->name);
1129                         if (j > rpt_vars[n].phone_longestfunc)
1130                                 rpt_vars[n].phone_longestfunc = j;
1131                         vp = vp->next;
1132                 }
1133         }
1134         rpt_vars[n].dphone_longestfunc = 0;
1135         if (rpt_vars[n].p.dphone_functions)
1136         {
1137                 vp = ast_variable_browse(cfg, rpt_vars[n].p.dphone_functions);
1138                 while(vp){
1139                         j = strlen(vp->name);
1140                         if (j > rpt_vars[n].dphone_longestfunc)
1141                                 rpt_vars[n].dphone_longestfunc = j;
1142                         vp = vp->next;
1143                 }
1144         }
1145         rpt_vars[n].macro_longest = 1;
1146         vp = ast_variable_browse(cfg, rpt_vars[n].p.macro);
1147         while(vp){
1148                 j = strlen(vp->name);
1149                 if (j > rpt_vars[n].macro_longest)
1150                         rpt_vars[n].macro_longest = j;
1151                 vp = vp->next;
1152         }
1153         ast_mutex_unlock(&rpt_vars[n].lock);
1154 }
1155
1156 /*
1157 * Enable or disable debug output at a given level at the console
1158 */
1159                                                                                                                                  
1160 static int rpt_do_debug(int fd, int argc, char *argv[])
1161 {
1162         int newlevel;
1163
1164         if (argc != 4)
1165                 return RESULT_SHOWUSAGE;
1166         newlevel = myatoi(argv[3]);
1167         if((newlevel < 0) || (newlevel > 7))
1168                 return RESULT_SHOWUSAGE;
1169         if(newlevel)
1170                 ast_cli(fd, "app_rpt Debugging enabled, previous level: %d, new level: %d\n", debug, newlevel);
1171         else
1172                 ast_cli(fd, "app_rpt Debugging disabled\n");
1173
1174         debug = newlevel;                                                                                                                          
1175         return RESULT_SUCCESS;
1176 }
1177
1178 /*
1179 * Dump rpt struct debugging onto console
1180 */
1181                                                                                                                                  
1182 static int rpt_do_dump(int fd, int argc, char *argv[])
1183 {
1184         int i;
1185
1186         if (argc != 3)
1187                 return RESULT_SHOWUSAGE;
1188
1189         for(i = 0; i < nrpts; i++)
1190         {
1191                 if (!strcmp(argv[2],rpt_vars[i].name))
1192                 {
1193                         rpt_vars[i].disgorgetime = time(NULL) + 10; /* Do it 10 seconds later */
1194                         ast_cli(fd, "app_rpt struct dump requested for node %s\n",argv[2]);
1195                         return RESULT_SUCCESS;
1196                 }
1197         }
1198         return RESULT_FAILURE;
1199 }
1200
1201 /*
1202 * Dump statistics onto console
1203 */
1204
1205 static int rpt_do_stats(int fd, int argc, char *argv[])
1206 {
1207         int i,j;
1208         int dailytxtime, dailykerchunks;
1209         int totalkerchunks, dailykeyups, totalkeyups, timeouts;
1210         int totalexecdcommands, dailyexecdcommands, hours, minutes, seconds;
1211         long long totaltxtime;
1212         struct  rpt_link *l;
1213         char *listoflinks[MAX_STAT_LINKS];      
1214         char *lastnodewhichkeyedusup, *lastdtmfcommand;
1215         char *tot_state, *ider_state, *patch_state;
1216         char *reverse_patch_state, *enable_state, *input_signal, *called_number;
1217         struct rpt *myrpt;
1218
1219         static char *not_applicable = "N/A";
1220
1221         if(argc != 3)
1222                 return RESULT_SHOWUSAGE;
1223
1224         for(i = 0 ; i <= MAX_STAT_LINKS; i++)
1225                 listoflinks[i] = NULL;
1226
1227         tot_state = ider_state = 
1228         patch_state = reverse_patch_state = 
1229         input_signal = called_number = 
1230         lastdtmfcommand = not_applicable;
1231
1232         for(i = 0; i < nrpts; i++)
1233         {
1234                 if (!strcmp(argv[2],rpt_vars[i].name)){
1235                         /* Make a copy of all stat variables while locked */
1236                         myrpt = &rpt_vars[i];
1237                         rpt_mutex_lock(&myrpt->lock); /* LOCK */
1238
1239                         dailytxtime = myrpt->dailytxtime;
1240                         totaltxtime = myrpt->totaltxtime;
1241                         dailykeyups = myrpt->dailykeyups;
1242                         totalkeyups = myrpt->totalkeyups;
1243                         dailykerchunks = myrpt->dailykerchunks;
1244                         totalkerchunks = myrpt->totalkerchunks;
1245                         dailyexecdcommands = myrpt->dailyexecdcommands;
1246                         totalexecdcommands = myrpt->totalexecdcommands;
1247                         timeouts = myrpt->timeouts;
1248
1249                         /* Traverse the list of connected nodes */
1250                         reverse_patch_state = "DOWN";
1251                         j = 0;
1252                         l = myrpt->links.next;
1253                         while(l != &myrpt->links){
1254                                 if (l->name[0] == '0'){ /* Skip '0' nodes */
1255                                         reverse_patch_state = "UP";
1256                                         l = l->next;
1257                                         continue;
1258                                 }
1259                                 listoflinks[j] = ast_strdupa(l->name);
1260                                 if(listoflinks[j])
1261                                         j++;
1262                                 l = l->next;
1263                         }
1264
1265                         lastnodewhichkeyedusup = ast_strdupa(myrpt->lastnodewhichkeyedusup);                    
1266                         if((!lastnodewhichkeyedusup) || (!strlen(lastnodewhichkeyedusup)))
1267                                 lastnodewhichkeyedusup = not_applicable;
1268
1269                         if(myrpt->keyed)
1270                                 input_signal = "YES";
1271                         else
1272                                 input_signal = "NO";
1273
1274                         if(myrpt->enable)
1275                                 enable_state = "YES";
1276                         else
1277                                 enable_state = "NO";
1278
1279                         if(!myrpt->totimer)
1280                                 tot_state = "TIMED OUT!";
1281                         else if(myrpt->totimer != myrpt->p.totime)
1282                                 tot_state = "ARMED";
1283                         else
1284                                 tot_state = "RESET";
1285
1286                         if(myrpt->tailid)
1287                                 ider_state = "QUEUED IN TAIL";
1288                         else if(myrpt->mustid)
1289                                 ider_state = "QUEUED FOR CLEANUP";
1290                         else
1291                                 ider_state = "CLEAN";
1292
1293                         switch(myrpt->callmode){
1294                                 case 1:
1295                                         patch_state = "DIALING";
1296                                         break;
1297                                 case 2:
1298                                         patch_state = "CONNECTING";
1299                                         break;
1300                                 case 3:
1301                                         patch_state = "UP";
1302                                         break;
1303
1304                                 case 4:
1305                                         patch_state = "CALL FAILED";
1306                                         break;
1307
1308                                 default:
1309                                         patch_state = "DOWN";
1310                         }
1311
1312                         if(strlen(myrpt->exten)){
1313                                 called_number = ast_strdupa(myrpt->exten);
1314                                 if(!called_number)
1315                                         called_number = not_applicable;
1316                         }
1317
1318                         if(strlen(myrpt->lastdtmfcommand)){
1319                                 lastdtmfcommand = ast_strdupa(myrpt->lastdtmfcommand);
1320                                 if(!lastdtmfcommand)
1321                                         lastdtmfcommand = not_applicable;
1322                         }
1323
1324                         rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
1325
1326                         ast_cli(fd, "************************ NODE %s STATISTICS *************************\n\n", myrpt->name);
1327                         ast_cli(fd, "Signal on input..................................: %s\n", input_signal);
1328                         ast_cli(fd, "Transmitter enabled..............................: %s\n", enable_state);
1329                         ast_cli(fd, "Time out timer state.............................: %s\n", tot_state);
1330                         ast_cli(fd, "Time outs since system initialization............: %d\n", timeouts);
1331                         ast_cli(fd, "Identifier state.................................: %s\n", ider_state);
1332                         ast_cli(fd, "Kerchunks today..................................: %d\n", dailykerchunks);
1333                         ast_cli(fd, "Kerchunks since system initialization............: %d\n", totalkerchunks);
1334                         ast_cli(fd, "Keyups today.....................................: %d\n", dailykeyups);
1335                         ast_cli(fd, "Keyups since system initialization...............: %d\n", totalkeyups);
1336                         ast_cli(fd, "DTMF commands today..............................: %d\n", dailyexecdcommands);
1337                         ast_cli(fd, "DTMF commands since system initialization........: %d\n", totalexecdcommands);
1338                         ast_cli(fd, "Last DTMF command executed.......................: %s\n", lastdtmfcommand);
1339
1340                         hours = dailytxtime/3600000;
1341                         dailytxtime %= 3600000;
1342                         minutes = dailytxtime/60000;
1343                         dailytxtime %= 60000;
1344                         seconds = dailytxtime/1000;
1345                         dailytxtime %= 1000;
1346
1347                         ast_cli(fd, "TX time today ...................................: %02d:%02d:%02d.%d\n",
1348                                 hours, minutes, seconds, dailytxtime);
1349
1350                         hours = (int) totaltxtime/3600000;
1351                         totaltxtime %= 3600000;
1352                         minutes = (int) totaltxtime/60000;
1353                         totaltxtime %= 60000;
1354                         seconds = (int)  totaltxtime/1000;
1355                         totaltxtime %= 1000;
1356
1357                         ast_cli(fd, "TX time since system initialization..............: %02d:%02d:%02d.%d\n",
1358                                  hours, minutes, seconds, (int) totaltxtime);
1359                         ast_cli(fd, "Nodes currently connected to us..................: ");
1360                         for(j = 0 ;; j++){
1361                                 if(!listoflinks[j]){
1362                                         if(!j){
1363                                                 ast_cli(fd,"<NONE>");
1364                                         }
1365                                         break;
1366                                 }
1367                                 ast_cli(fd, "%s", listoflinks[j]);
1368                                 if(j % 4 == 3){
1369                                         ast_cli(fd, "\n");
1370                                         ast_cli(fd, "                                                 : ");
1371                                 }
1372                                 else{
1373                                         if(listoflinks[j + 1])
1374                                                 ast_cli(fd, ", ");
1375                                 }
1376                         }
1377                         ast_cli(fd,"\n");
1378
1379                         ast_cli(fd, "Last node which transmitted to us................: %s\n", lastnodewhichkeyedusup);
1380                         ast_cli(fd, "Autopatch state..................................: %s\n", patch_state);
1381                         ast_cli(fd, "Autopatch called number..........................: %s\n", called_number);
1382                         ast_cli(fd, "Reverse patch/IAXRPT connected...................: %s\n\n", reverse_patch_state);
1383
1384                         return RESULT_SUCCESS;
1385                 }
1386         }
1387         return RESULT_FAILURE;
1388 }
1389
1390 /*
1391 * Link stats function
1392 */
1393
1394 static int rpt_do_lstats(int fd, int argc, char *argv[])
1395 {
1396         int i,j;
1397         struct rpt *myrpt;
1398         struct rpt_link *l;
1399         struct rpt_lstat *s,*t;
1400         struct rpt_lstat s_head;
1401         if(argc != 3)
1402                 return RESULT_SHOWUSAGE;
1403
1404         s = NULL;
1405         s_head.next = &s_head;
1406         s_head.prev = &s_head;
1407
1408         for(i = 0; i < nrpts; i++)
1409         {
1410                 if (!strcmp(argv[2],rpt_vars[i].name)){
1411                         /* Make a copy of all stat variables while locked */
1412                         myrpt = &rpt_vars[i];
1413                         rpt_mutex_lock(&myrpt->lock); /* LOCK */
1414                         /* Traverse the list of connected nodes */
1415                         j = 0;
1416                         l = myrpt->links.next;
1417                         while(l != &myrpt->links){
1418                                 if (l->name[0] == '0'){ /* Skip '0' nodes */
1419                                         l = l->next;
1420                                         continue;
1421                                 }
1422                                 if((s = (struct rpt_lstat *) malloc(sizeof(struct rpt_lstat))) == NULL){
1423                                         ast_log(LOG_ERROR, "Malloc failed in rpt_do_lstats\n");
1424                                         rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
1425                                         return RESULT_FAILURE;
1426                                 }
1427                                 memset(s, 0, sizeof(struct rpt_lstat));
1428                                 strncpy(s->name, l->name, MAXREMSTR - 1);
1429                                 pbx_substitute_variables_helper(l->chan, "${IAXPEER(CURRENTCHANNEL)}", s->peer, MAXPEERSTR - 1);
1430                                 s->mode = l->mode;
1431                                 s->outbound = l->outbound;
1432                                 s->reconnects = l->reconnects;
1433                                 s->connecttime = l->connecttime;
1434                                 insque((struct qelem *) s, (struct qelem *) s_head.next);
1435                                 l = l->next;
1436                         }
1437                         rpt_mutex_unlock(&myrpt->lock); /* UNLOCK */
1438                         ast_cli(fd, "NODE      PEER                RECONNECTS  DIRECTION  CONNECT TIME\n");
1439                         ast_cli(fd, "----      ----                ----------  ---------  ------------\n");
1440
1441                         for(s = s_head.next; s != &s_head; s = s->next){
1442                                 int hours, minutes, seconds;
1443                                 long long connecttime = s->connecttime;
1444                                 char conntime[31];
1445                                 hours = (int) connecttime/3600000;
1446                                 connecttime %= 3600000;
1447                                 minutes = (int) connecttime/60000;
1448                                 connecttime %= 60000;
1449                                 seconds = (int)  connecttime/1000;
1450                                 connecttime %= 1000;
1451                                 snprintf(conntime, 30, "%02d:%02d:%02d.%d",
1452                                         hours, minutes, seconds, (int) connecttime);
1453                                 conntime[30] = 0;
1454                                 ast_cli(fd, "%-10s%-20s%-12d%-11s%-30s\n",
1455                                         s->name, s->peer, s->reconnects, (s->outbound)? "OUT":"IN", conntime);
1456                         }       
1457                         /* destroy our local link queue */
1458                         s = s_head.next;
1459                         while(s != &s_head){
1460                                 t = s;
1461                                 s = s->next;
1462                                 remque((struct qelem *)t);
1463                                 free(t);
1464                         }                       
1465                         return RESULT_SUCCESS;
1466                 }
1467         }
1468         return RESULT_FAILURE;
1469 }
1470
1471 /*
1472 * reload vars 
1473 */
1474                                                                                                                                  
1475 static int rpt_do_reload(int fd, int argc, char *argv[])
1476 {
1477 int     n;
1478
1479         if (argc > 2) return RESULT_SHOWUSAGE;
1480
1481         for(n = 0; n < nrpts; n++) rpt_vars[n].reload = 1;
1482
1483         return RESULT_FAILURE;
1484 }
1485
1486 /*
1487 * restart app_rpt
1488 */
1489                                                                                                                                  
1490 static int rpt_do_restart(int fd, int argc, char *argv[])
1491 {
1492 int     i;
1493
1494         if (argc > 2) return RESULT_SHOWUSAGE;
1495         for(i = 0; i < nrpts; i++)
1496         {
1497                 if (rpt_vars[i].rxchannel) ast_softhangup(rpt_vars[i].rxchannel,AST_SOFTHANGUP_DEV);
1498         }
1499         return RESULT_FAILURE;
1500 }
1501
1502 static int play_tone_pair(struct ast_channel *chan, int f1, int f2, int duration, int amplitude)
1503 {
1504         int res;
1505
1506         if ((res = ast_tonepair_start(chan, f1, f2, duration, amplitude)))
1507                 return res;
1508                                                                                                                                             
1509         while(chan->generatordata) {
1510                 if (ast_safe_sleep(chan,1)) return -1;
1511         }
1512
1513         return 0;
1514 }
1515
1516 static int play_tone(struct ast_channel *chan, int freq, int duration, int amplitude)
1517 {
1518         return play_tone_pair(chan, freq, 0, duration, amplitude);
1519 }
1520
1521 static int play_silence(struct ast_channel *chan, int duration)
1522 {
1523         return play_tone_pair(chan, 0, 0, duration, 0);
1524 }
1525
1526
1527 static int send_morse(struct ast_channel *chan, const char *string, int speed, int freq, int amplitude)
1528 {
1529
1530 static struct morse_bits mbits[] = {
1531                 {0, 0}, /* SPACE */
1532                 {0, 0}, 
1533                 {6, 18},/* " */
1534                 {0, 0},
1535                 {7, 72},/* $ */
1536                 {0, 0},
1537                 {0, 0},
1538                 {6, 30},/* ' */
1539                 {5, 13},/* ( */
1540                 {6, 29},/* ) */
1541                 {0, 0},
1542                 {5, 10},/* + */
1543                 {6, 51},/* , */
1544                 {6, 33},/* - */
1545                 {6, 42},/* . */
1546                 {5, 9}, /* / */
1547                 {5, 31},/* 0 */
1548                 {5, 30},/* 1 */
1549                 {5, 28},/* 2 */
1550                 {5, 24},/* 3 */
1551                 {5, 16},/* 4 */
1552                 {5, 0}, /* 5 */
1553                 {5, 1}, /* 6 */
1554                 {5, 3}, /* 7 */
1555                 {5, 7}, /* 8 */
1556                 {5, 15},/* 9 */
1557                 {6, 7}, /* : */
1558                 {6, 21},/* ; */
1559                 {0, 0},
1560                 {5, 33},/* = */
1561                 {0, 0},
1562                 {6, 12},/* ? */
1563                 {0, 0},
1564                 {2, 2}, /* A */
1565                 {4, 1}, /* B */
1566                 {4, 5}, /* C */
1567                 {3, 1}, /* D */
1568                 {1, 0}, /* E */
1569                 {4, 4}, /* F */
1570                 {3, 3}, /* G */
1571                 {4, 0}, /* H */
1572                 {2, 0}, /* I */
1573                 {4, 14},/* J */
1574                 {3, 5}, /* K */
1575                 {4, 2}, /* L */
1576                 {2, 3}, /* M */
1577                 {2, 1}, /* N */
1578                 {3, 7}, /* O */
1579                 {4, 6}, /* P */
1580                 {4, 11},/* Q */
1581                 {3, 2}, /* R */
1582                 {3, 0}, /* S */
1583                 {1, 1}, /* T */
1584                 {3, 4}, /* U */
1585                 {4, 8}, /* V */
1586                 {3, 6}, /* W */
1587                 {4, 9}, /* X */
1588                 {4, 13},/* Y */
1589                 {4, 3}  /* Z */
1590         };
1591
1592
1593         int dottime;
1594         int dashtime;
1595         int intralettertime;
1596         int interlettertime;
1597         int interwordtime;
1598         int len, ddcomb;
1599         int res;
1600         int c;
1601         int i;
1602         int flags;
1603                         
1604         res = 0;
1605         
1606         /* Approximate the dot time from the speed arg. */
1607         
1608         dottime = 900/speed;
1609         
1610         /* Establish timing releationships */
1611         
1612         dashtime = 3 * dottime;
1613         intralettertime = dottime;
1614         interlettertime = dottime * 4 ;
1615         interwordtime = dottime * 7;
1616         
1617         for(;(*string) && (!res); string++){
1618         
1619                 c = *string;
1620                 
1621                 /* Convert lower case to upper case */
1622                 
1623                 if((c >= 'a') && (c <= 'z'))
1624                         c -= 0x20;
1625                 
1626                 /* Can't deal with any char code greater than Z, skip it */
1627                 
1628                 if(c  > 'Z')
1629                         continue;
1630                 
1631                 /* If space char, wait the inter word time */
1632                                         
1633                 if(c == ' '){
1634                         if(!res)
1635                                 res = play_silence(chan, interwordtime);
1636                         continue;
1637                 }
1638                 
1639                 /* Subtract out control char offset to match our table */
1640                 
1641                 c -= 0x20;
1642                 
1643                 /* Get the character data */
1644                 
1645                 len = mbits[c].len;
1646                 ddcomb = mbits[c].ddcomb;
1647                 
1648                 /* Send the character */
1649                 
1650                 for(; len ; len--){
1651                         if(!res)
1652                                 res = play_tone(chan, freq, (ddcomb & 1) ? dashtime : dottime, amplitude);
1653                         if(!res)
1654                                 res = play_silence(chan, intralettertime);
1655                         ddcomb >>= 1;
1656                 }
1657                 
1658                 /* Wait the interletter time */
1659                 
1660                 if(!res)
1661                         res = play_silence(chan, interlettertime - intralettertime);
1662         }
1663         
1664         /* Wait for all the frames to be sent */
1665         
1666         if (!res) 
1667                 res = ast_waitstream(chan, "");
1668         ast_stopstream(chan);
1669         
1670         /*
1671         * Wait for the zaptel driver to physically write the tone blocks to the hardware
1672         */
1673
1674         for(i = 0; i < 20 ; i++){
1675                 flags =  ZT_IOMUX_WRITEEMPTY | ZT_IOMUX_NOWAIT; 
1676                 res = ioctl(chan->fds[0], ZT_IOMUX, &flags);
1677                 if(flags & ZT_IOMUX_WRITEEMPTY)
1678                         break;
1679                 if( ast_safe_sleep(chan, 50)){
1680                         res = -1;
1681                         break;
1682                 }
1683         }
1684
1685         
1686         return res;
1687 }
1688
1689 static int send_tone_telemetry(struct ast_channel *chan, const char *tonestring)
1690 {
1691         char *stringp;
1692         char *tonesubset;
1693         int f1,f2;
1694         int duration;
1695         int amplitude;
1696         int res;
1697         int i;
1698         int flags;
1699         
1700         res = 0;
1701         
1702         stringp = ast_strdupa(tonestring);
1703
1704         for(;tonestring;){
1705                 tonesubset = strsep(&stringp,")");
1706                 if(!tonesubset)
1707                         break;
1708                 if(sscanf(tonesubset,"(%d,%d,%d,%d", &f1, &f2, &duration, &amplitude) != 4)
1709                         break;
1710                 res = play_tone_pair(chan, f1, f2, duration, amplitude);
1711                 if(res)
1712                         break;
1713         }
1714         if(!res)
1715                 res = play_tone_pair(chan, 0, 0, 100, 0); /* This is needed to ensure the last tone segment is timed correctly */
1716         
1717         if (!res) 
1718                 res = ast_waitstream(chan, "");
1719         ast_stopstream(chan);
1720
1721         /*
1722         * Wait for the zaptel driver to physically write the tone blocks to the hardware
1723         */
1724
1725         for(i = 0; i < 20 ; i++){
1726                 flags =  ZT_IOMUX_WRITEEMPTY | ZT_IOMUX_NOWAIT; 
1727                 res = ioctl(chan->fds[0], ZT_IOMUX, &flags);
1728                 if(flags & ZT_IOMUX_WRITEEMPTY)
1729                         break;
1730                 if( ast_safe_sleep(chan, 50)){
1731                         res = -1;
1732                         break;
1733                 }
1734         }
1735                 
1736         return res;
1737                 
1738 }
1739         
1740
1741 static int sayfile(struct ast_channel *mychannel, const char *fname)
1742 {
1743 int     res;
1744
1745         res = ast_streamfile(mychannel, fname, mychannel->language);
1746         if (!res) 
1747                 res = ast_waitstream(mychannel, "");
1748         else
1749                  ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
1750         ast_stopstream(mychannel);
1751         return res;
1752 }
1753
1754 static int saycharstr(struct ast_channel *mychannel,char *str)
1755 {
1756 int     res;
1757
1758         res = ast_say_character_str(mychannel,str,NULL,mychannel->language);
1759         if (!res) 
1760                 res = ast_waitstream(mychannel, "");
1761         else
1762                  ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
1763         ast_stopstream(mychannel);
1764         return res;
1765 }
1766
1767 static int saynum(struct ast_channel *mychannel, int num)
1768 {
1769         int res;
1770         res = ast_say_number(mychannel, num, NULL, mychannel->language, NULL);
1771         if(!res)
1772                 res = ast_waitstream(mychannel, "");
1773         else
1774                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
1775         ast_stopstream(mychannel);
1776         return res;
1777 }
1778
1779
1780 static int telem_any(struct rpt *myrpt,struct ast_channel *chan, const char *entry)
1781 {
1782         int res;
1783         char c;
1784         
1785         static int morsespeed;
1786         static int morsefreq;
1787         static int morseampl;
1788         static int morseidfreq = 0;
1789         static int morseidampl;
1790         static char mcat[] = MORSE;
1791         
1792         res = 0;
1793         
1794         if(!morseidfreq){ /* Get the morse parameters if not already loaded */
1795                 morsespeed = retrieve_astcfgint(myrpt, mcat, "speed", 5, 20, 20);
1796                 morsefreq = retrieve_astcfgint(myrpt, mcat, "frequency", 300, 3000, 800);
1797                 morseampl = retrieve_astcfgint(myrpt, mcat, "amplitude", 200, 8192, 4096);
1798                 morseidampl = retrieve_astcfgint(myrpt, mcat, "idamplitude", 200, 8192, 2048);
1799                 morseidfreq = retrieve_astcfgint(myrpt, mcat, "idfrequency", 300, 3000, 330);   
1800         }
1801         
1802         /* Is it a file, or a tone sequence? */
1803                         
1804         if(entry[0] == '|'){
1805                 c = entry[1];
1806                 if((c >= 'a')&&(c <= 'z'))
1807                         c -= 0x20;
1808         
1809                 switch(c){
1810                         case 'I': /* Morse ID */
1811                                 res = send_morse(chan, entry + 2, morsespeed, morseidfreq, morseidampl);
1812                                 break;
1813                         
1814                         case 'M': /* Morse Message */
1815                                 res = send_morse(chan, entry + 2, morsespeed, morsefreq, morseampl);
1816                                 break;
1817                         
1818                         case 'T': /* Tone sequence */
1819                                 res = send_tone_telemetry(chan, entry + 2);
1820                                 break;
1821                         default:
1822                                 res = -1;
1823                 }
1824         }
1825         else
1826                 res = sayfile(chan, entry); /* File */
1827         return res;
1828 }
1829
1830 /*
1831 * This function looks up a telemetry name in the config file, and does a telemetry response as configured.
1832 *
1833 * 4 types of telemtry are handled: Morse ID, Morse Message, Tone Sequence, and a File containing a recording.
1834 */
1835
1836 static int telem_lookup(struct rpt *myrpt,struct ast_channel *chan, char *node, char *name)
1837 {
1838         
1839         int res;
1840         int i;
1841         const char *entry;
1842         const char *telemetry;
1843         char *telemetry_save;
1844
1845         res = 0;
1846         telemetry_save = NULL;
1847         entry = NULL;
1848         
1849         /* Retrieve the section name for telemetry from the node section */
1850         telemetry = ast_variable_retrieve(myrpt->cfg, node, TELEMETRY);
1851         if(telemetry ){
1852                 telemetry_save = ast_strdupa(telemetry);
1853                 if(!telemetry_save){
1854                         ast_log(LOG_WARNING,"ast_strdupa() failed in telem_lookup()\n");
1855                         return res;
1856                 }
1857                 entry = ast_variable_retrieve(myrpt->cfg, telemetry_save, name);
1858         }
1859         
1860         /* Try to look up the telemetry name */ 
1861
1862         if(!entry){
1863                 /* Telemetry name wasn't found in the config file, use the default */
1864                 for(i = 0; i < sizeof(tele_defs)/sizeof(struct telem_defaults) ; i++){
1865                         if(!strcasecmp(tele_defs[i].name, name))
1866                                 entry = tele_defs[i].value;
1867                 }
1868         }
1869         if(entry){      
1870                 if(strlen(entry))
1871                         telem_any(myrpt,chan, entry);
1872         }
1873         else{
1874                 res = -1;
1875         }
1876         return res;
1877 }
1878
1879 /*
1880 * Retrieve a wait interval
1881 */
1882
1883 static int get_wait_interval(struct rpt *myrpt, int type)
1884 {
1885         int interval;
1886         const char *wait_times;
1887         char *wait_times_save;
1888                                                                                                                   
1889         wait_times_save = NULL;
1890         wait_times = ast_variable_retrieve(myrpt->cfg, myrpt->name, "wait_times");
1891                                                                                                                   
1892         if(wait_times){
1893                 wait_times_save = ast_strdupa(wait_times);
1894                 if(!wait_times_save){
1895                         ast_log(LOG_WARNING, "Out of memory in wait_interval()\n");
1896                         wait_times = NULL;
1897                 }
1898         }
1899                                                                                                                   
1900         switch(type){
1901                 case DLY_TELEM:
1902                         if(wait_times)
1903                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "telemwait", 500, 5000, 1000);
1904                         else
1905                                 interval = 1000;
1906                         break;
1907                                                                                                                   
1908                 case DLY_ID:
1909                         if(wait_times)
1910                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "idwait",250,5000,500);
1911                         else
1912                                 interval = 500;
1913                         break;
1914                                                                                                                   
1915                 case DLY_UNKEY:
1916                         if(wait_times)
1917                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "unkeywait",500,5000,1000);
1918                         else
1919                                 interval = 1000;
1920                         break;
1921                                                                                                                   
1922                 case DLY_CALLTERM:
1923                         if(wait_times)
1924                                 interval = retrieve_astcfgint(myrpt,wait_times_save, "calltermwait",500,5000,1500);
1925                         else
1926                                 interval = 1500;
1927                         break;
1928                                                                                                                   
1929                 default:
1930                         return 0;
1931         }
1932         return interval;
1933 }                                                                                                                  
1934
1935
1936 /*
1937 * Wait a configurable interval of time 
1938 */
1939
1940
1941 static void wait_interval(struct rpt *myrpt, int type, struct ast_channel *chan)
1942 {
1943         int interval;
1944         interval = get_wait_interval(myrpt, type);
1945         if(debug)
1946                 ast_log(LOG_NOTICE," Delay interval = %d\n", interval);
1947         if(interval)
1948                 ast_safe_sleep(chan,interval);
1949         if(debug)
1950                 ast_log(LOG_NOTICE,"Delay complete\n");
1951         return;
1952 }
1953
1954
1955 static void *rpt_tele_thread(void *this)
1956 {
1957 ZT_CONFINFO ci;  /* conference info */
1958 int     res = 0,haslink,hastx,hasremote,imdone = 0, unkeys_queued, x;
1959 struct  rpt_tele *mytele = (struct rpt_tele *)this;
1960 struct  rpt_tele *tlist;
1961 struct  rpt *myrpt;
1962 struct  rpt_link *l,*m,linkbase;
1963 struct  ast_channel *mychannel;
1964         const char *p, *ct;
1965         char *ct_copy, *ident, *nodename;
1966 time_t t;
1967 struct tm localtm;
1968
1969         /* get a pointer to myrpt */
1970         myrpt = mytele->rpt;
1971
1972         /* Snag copies of a few key myrpt variables */
1973         rpt_mutex_lock(&myrpt->lock);
1974         nodename = ast_strdupa(myrpt->name);
1975         ident = ast_strdupa(myrpt->p.ident);
1976         rpt_mutex_unlock(&myrpt->lock);
1977         
1978         /* allocate a pseudo-channel thru asterisk */
1979         mychannel = ast_request("zap",AST_FORMAT_SLINEAR,"pseudo",NULL);
1980         if (!mychannel)
1981         {
1982                 fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
1983                 rpt_mutex_lock(&myrpt->lock);
1984                 remque((struct qelem *)mytele);
1985                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
1986                 rpt_mutex_unlock(&myrpt->lock);
1987                 free(mytele);           
1988                 pthread_exit(NULL);
1989         }
1990         rpt_mutex_lock(&myrpt->lock);
1991         mytele->chan = mychannel; /* Save a copy of the channel so we can access it externally if need be */
1992         rpt_mutex_unlock(&myrpt->lock);
1993         
1994         /* make a conference for the tx */
1995         ci.chan = 0;
1996         /* If there's an ID queued, or tail message queued, */
1997         /* only connect the ID audio to the local tx conference so */
1998         /* linked systems can't hear it */
1999         ci.confno = (((mytele->mode == ID) || (mytele->mode == IDTALKOVER) || (mytele->mode == UNKEY) || 
2000                 (mytele->mode == TAILMSG)) ?
2001                         myrpt->txconf : myrpt->conf);
2002         ci.confmode = ZT_CONF_CONFANN;
2003         /* first put the channel on the conference in announce mode */
2004         if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
2005         {
2006                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2007                 rpt_mutex_lock(&myrpt->lock);
2008                 remque((struct qelem *)mytele);
2009                 rpt_mutex_unlock(&myrpt->lock);
2010                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
2011                 free(mytele);           
2012                 ast_hangup(mychannel);
2013                 pthread_exit(NULL);
2014         }
2015         ast_stopstream(mychannel);
2016         switch(mytele->mode)
2017         {
2018
2019             case ID:
2020             case ID1:
2021                 /* wait a bit */
2022                 wait_interval(myrpt, (mytele->mode == ID) ? DLY_ID : DLY_TELEM,mychannel);
2023                 res = telem_any(myrpt,mychannel, ident); 
2024                 imdone=1;       
2025                 break;
2026                 
2027             case TAILMSG:
2028                 res = ast_streamfile(mychannel, myrpt->p.tailmessages[myrpt->tailmessagen], mychannel->language); 
2029                 break;
2030                 
2031             case IDTALKOVER:
2032                 p = ast_variable_retrieve(myrpt->cfg, nodename, "idtalkover");
2033                 if(p)
2034                         res = telem_any(myrpt,mychannel, p); 
2035                 imdone=1;       
2036                 break;
2037                         
2038             case PROC:
2039                 /* wait a little bit longer */
2040                 wait_interval(myrpt, DLY_TELEM, mychannel);
2041                 res = telem_lookup(myrpt, mychannel, myrpt->name, "patchup");
2042                 if(res < 0){ /* Then default message */
2043                         res = ast_streamfile(mychannel, "rpt/callproceeding", mychannel->language);
2044                 }
2045                 break;
2046             case TERM:
2047                 /* wait a little bit longer */
2048                 wait_interval(myrpt, DLY_CALLTERM, mychannel);
2049                 res = telem_lookup(myrpt, mychannel, myrpt->name, "patchdown");
2050                 if(res < 0){ /* Then default message */
2051                         res = ast_streamfile(mychannel, "rpt/callterminated", mychannel->language);
2052                 }
2053                 break;
2054             case COMPLETE:
2055                 /* wait a little bit */
2056                 wait_interval(myrpt, DLY_TELEM, mychannel);
2057                 res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
2058                 break;
2059             case MACRO_NOTFOUND:
2060                 /* wait a little bit */
2061                 wait_interval(myrpt, DLY_TELEM, mychannel);
2062                 res = ast_streamfile(mychannel, "rpt/macro_notfound", mychannel->language);
2063                 break;
2064             case MACRO_BUSY:
2065                 /* wait a little bit */
2066                 wait_interval(myrpt, DLY_TELEM, mychannel);
2067                 res = ast_streamfile(mychannel, "rpt/macro_busy", mychannel->language);
2068                 break;
2069             case UNKEY:
2070                 if(myrpt->patchnoct && myrpt->callmode){ /* If no CT during patch configured, then don't send one */
2071                         imdone = 1;
2072                         break;
2073                 }
2074                         
2075                 /*
2076                 * Reset the Unkey to CT timer
2077                 */
2078
2079                 x = get_wait_interval(myrpt, DLY_UNKEY);
2080                 rpt_mutex_lock(&myrpt->lock);
2081                 myrpt->unkeytocttimer = x; /* Must be protected as it is changed below */
2082                 rpt_mutex_unlock(&myrpt->lock);
2083
2084                 /*
2085                 * If there's one already queued, don't do another
2086                 */
2087
2088                 tlist = myrpt->tele.next;
2089                 unkeys_queued = 0;
2090                 if (tlist != &myrpt->tele)
2091                 {
2092                         rpt_mutex_lock(&myrpt->lock);
2093                         while(tlist != &myrpt->tele){
2094                                 if (tlist->mode == UNKEY) unkeys_queued++;
2095                                 tlist = tlist->next;
2096                         }
2097                         rpt_mutex_unlock(&myrpt->lock);
2098                 }
2099                 if( unkeys_queued > 1){
2100                         imdone = 1;
2101                         break;
2102                 }
2103
2104                 /* Wait for the telemetry timer to expire */
2105                 /* Periodically check the timer since it can be re-initialized above */
2106                 while(myrpt->unkeytocttimer)
2107                 {
2108                         int ctint;
2109                         if(myrpt->unkeytocttimer > 100)
2110                                 ctint = 100;
2111                         else
2112                                 ctint = myrpt->unkeytocttimer;
2113                         ast_safe_sleep(mychannel, ctint);
2114                         rpt_mutex_lock(&myrpt->lock);
2115                         if(myrpt->unkeytocttimer < ctint)
2116                                 myrpt->unkeytocttimer = 0;
2117                         else
2118                                 myrpt->unkeytocttimer -= ctint;
2119                         rpt_mutex_unlock(&myrpt->lock);
2120                 }
2121         
2122                 /*
2123                 * Now, the carrier on the rptr rx should be gone. 
2124                 * If it re-appeared, then forget about sending the CT
2125                 */
2126                 if(myrpt->keyed){
2127                         imdone = 1;
2128                         break;
2129                 }
2130                 
2131                 rpt_mutex_lock(&myrpt->lock); /* Update the kerchunk counters */
2132                 myrpt->dailykerchunks++;
2133                 myrpt->totalkerchunks++;
2134                 rpt_mutex_unlock(&myrpt->lock);
2135         
2136                 haslink = 0;
2137                 hastx = 0;
2138                 hasremote = 0;          
2139                 l = myrpt->links.next;
2140                 if (l != &myrpt->links)
2141                 {
2142                         rpt_mutex_lock(&myrpt->lock);
2143                         while(l != &myrpt->links)
2144                         {
2145                                 if (l->name[0] == '0')
2146                                 {
2147                                         l = l->next;
2148                                         continue;
2149                                 }
2150                                 haslink = 1;
2151                                 if (l->mode) {
2152                                         hastx++;
2153                                         if (l->isremote) hasremote++;
2154                                 }
2155                                 l = l->next;
2156                         }
2157                         rpt_mutex_unlock(&myrpt->lock);
2158                 }
2159                 if (haslink)
2160                 {
2161
2162                         res = telem_lookup(myrpt,mychannel, myrpt->name, (!hastx) ? "remotemon" : "remotetx");
2163                         if(res)
2164                                 ast_log(LOG_WARNING, "telem_lookup:remotexx failed on %s\n", mychannel->name);
2165                         
2166                 
2167                         /* if in remote cmd mode, indicate it */
2168                         if (myrpt->cmdnode[0])
2169                         {
2170                                 ast_safe_sleep(mychannel,200);
2171                                 res = telem_lookup(myrpt,mychannel, myrpt->name, "cmdmode");
2172                                 if(res)
2173                                         ast_log(LOG_WARNING, "telem_lookup:cmdmode failed on %s\n", mychannel->name);
2174                                 ast_stopstream(mychannel);
2175                         }
2176                 }
2177                 else if((ct = ast_variable_retrieve(myrpt->cfg, nodename, "unlinkedct"))){ /* Unlinked Courtesy Tone */
2178                         ct_copy = ast_strdupa(ct);
2179                         res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
2180                         if(res)
2181                                 ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);               
2182                 }       
2183                 if (hasremote && (!myrpt->cmdnode[0]))
2184                 {
2185                         /* set for all to hear */
2186                         ci.chan = 0;
2187                         ci.confno = myrpt->conf;
2188                         ci.confmode = ZT_CONF_CONFANN;
2189                         /* first put the channel on the conference in announce mode */
2190                         if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
2191                         {
2192                                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2193                                 rpt_mutex_lock(&myrpt->lock);
2194                                 remque((struct qelem *)mytele);
2195                                 rpt_mutex_unlock(&myrpt->lock);
2196                                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
2197                                 free(mytele);           
2198                                 ast_hangup(mychannel);
2199                                 pthread_exit(NULL);
2200                         }
2201                         if((ct = ast_variable_retrieve(myrpt->cfg, nodename, "remotect"))){ /* Unlinked Courtesy Tone */
2202                                 ast_safe_sleep(mychannel,200);
2203                                 ct_copy = ast_strdupa(ct);
2204                                 res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
2205                                 if(res)
2206                                         ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);               
2207                         }       
2208                 }
2209 #ifdef  _MDC_DECODE_H_
2210                 if (myrpt->lastunit)
2211                 {
2212                         char mystr[10];
2213
2214                         ast_safe_sleep(mychannel,200);
2215                         /* set for all to hear */
2216                         ci.chan = 0;
2217                         ci.confno = myrpt->txconf;
2218                         ci.confmode = ZT_CONF_CONFANN;
2219                         /* first put the channel on the conference in announce mode */
2220                         if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
2221                         {
2222                                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2223                                 rpt_mutex_lock(&myrpt->lock);
2224                                 remque((struct qelem *)mytele);
2225                                 rpt_mutex_unlock(&myrpt->lock);
2226                                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
2227                                 free(mytele);           
2228                                 ast_hangup(mychannel);
2229                                 pthread_exit(NULL);
2230                         }
2231                         sprintf(mystr,"%04x",myrpt->lastunit);
2232                         myrpt->lastunit = 0;
2233                         ast_say_character_str(mychannel,mystr,NULL,mychannel->language);
2234                         break;
2235                 }
2236 #endif
2237                 imdone = 1;
2238                 break;
2239             case REMDISC:
2240                 /* wait a little bit */
2241                 wait_interval(myrpt, DLY_TELEM, mychannel);
2242                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2243                 if (!res) 
2244                         res = ast_waitstream(mychannel, "");
2245                 else
2246                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2247                 ast_stopstream(mychannel);
2248                 ast_say_character_str(mychannel,mytele->mylink.name,NULL,mychannel->language);
2249                 res = ast_streamfile(mychannel, ((mytele->mylink.connected) ? 
2250                         "rpt/remote_disc" : "rpt/remote_busy"), mychannel->language);
2251                 break;
2252             case REMALREADY:
2253                 /* wait a little bit */
2254                 wait_interval(myrpt, DLY_TELEM, mychannel);
2255                 res = ast_streamfile(mychannel, "rpt/remote_already", mychannel->language);
2256                 break;
2257             case REMNOTFOUND:
2258                 /* wait a little bit */
2259                 wait_interval(myrpt, DLY_TELEM, mychannel);
2260                 res = ast_streamfile(mychannel, "rpt/remote_notfound", mychannel->language);
2261                 break;
2262             case REMGO:
2263                 /* wait a little bit */
2264                 wait_interval(myrpt, DLY_TELEM, mychannel);
2265                 res = ast_streamfile(mychannel, "rpt/remote_go", mychannel->language);
2266                 break;
2267             case CONNECTED:
2268                 /* wait a little bit */
2269                 wait_interval(myrpt, DLY_TELEM,  mychannel);
2270                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2271                 if (!res) 
2272                         res = ast_waitstream(mychannel, "");
2273                 else
2274                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2275                 ast_stopstream(mychannel);
2276                 ast_say_character_str(mychannel,mytele->mylink.name,NULL,mychannel->language);
2277                 res = ast_streamfile(mychannel, "rpt/connected", mychannel->language);
2278                 break;
2279             case CONNFAIL:
2280                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2281                 if (!res) 
2282                         res = ast_waitstream(mychannel, "");
2283                 else
2284                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2285                 ast_stopstream(mychannel);
2286                 ast_say_character_str(mychannel,mytele->mylink.name,NULL,mychannel->language);
2287                 res = ast_streamfile(mychannel, "rpt/connection_failed", mychannel->language);
2288                 break;
2289             case STATUS:
2290                 /* wait a little bit */
2291                 wait_interval(myrpt, DLY_TELEM, mychannel);
2292                 hastx = 0;
2293                 linkbase.next = &linkbase;
2294                 linkbase.prev = &linkbase;
2295                 rpt_mutex_lock(&myrpt->lock);
2296                 /* make our own list of links */
2297                 l = myrpt->links.next;
2298                 while(l != &myrpt->links)
2299                 {
2300                         if (l->name[0] == '0')
2301                         {
2302                                 l = l->next;
2303                                 continue;
2304                         }
2305                         m = malloc(sizeof(struct rpt_link));
2306                         if (!m)
2307                         {
2308                                 ast_log(LOG_WARNING, "Cannot alloc memory on %s\n", mychannel->name);
2309                                 remque((struct qelem *)mytele);
2310                                 rpt_mutex_unlock(&myrpt->lock);
2311                                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
2312                                 free(mytele);           
2313                                 ast_hangup(mychannel);
2314                                 pthread_exit(NULL);
2315                         }
2316                         memcpy(m,l,sizeof(struct rpt_link));
2317                         m->next = m->prev = NULL;
2318                         insque((struct qelem *)m,(struct qelem *)linkbase.next);
2319                         l = l->next;
2320                 }
2321                 rpt_mutex_unlock(&myrpt->lock);
2322                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2323                 if (!res) 
2324                         res = ast_waitstream(mychannel, "");
2325                 else
2326                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2327                 ast_stopstream(mychannel);
2328                 ast_say_character_str(mychannel,myrpt->name,NULL,mychannel->language);
2329                 if (!res) 
2330                         res = ast_waitstream(mychannel, "");
2331                 else
2332                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2333                 ast_stopstream(mychannel);
2334                 if (myrpt->callmode)
2335                 {
2336                         hastx = 1;
2337                         res = ast_streamfile(mychannel, "rpt/autopatch_on", mychannel->language);
2338                         if (!res) 
2339                                 res = ast_waitstream(mychannel, "");
2340                         else
2341                                  ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2342                         ast_stopstream(mychannel);
2343                 }
2344                 l = linkbase.next;
2345                 while(l != &linkbase)
2346                 {
2347                         hastx = 1;
2348                         res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2349                         if (!res) 
2350                                 res = ast_waitstream(mychannel, "");
2351                         else
2352                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2353                         ast_stopstream(mychannel);
2354                         ast_say_character_str(mychannel,l->name,NULL,mychannel->language);
2355                         if (!res) 
2356                                 res = ast_waitstream(mychannel, "");
2357                         else
2358                                  ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2359                         ast_stopstream(mychannel);
2360                         res = ast_streamfile(mychannel, ((l->mode) ? 
2361                                 "rpt/tranceive" : "rpt/monitor"), mychannel->language);
2362                         if (!res) 
2363                                 res = ast_waitstream(mychannel, "");
2364                         else
2365                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2366                         ast_stopstream(mychannel);
2367                         l = l->next;
2368                 }                       
2369                 if (!hastx)
2370                 {
2371                         res = ast_streamfile(mychannel, "rpt/repeat_only", mychannel->language);
2372                         if (!res) 
2373                                 res = ast_waitstream(mychannel, "");
2374                         else
2375                                  ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2376                         ast_stopstream(mychannel);
2377                 }
2378                 /* destroy our local link queue */
2379                 l = linkbase.next;
2380                 while(l != &linkbase)
2381                 {
2382                         m = l;
2383                         l = l->next;
2384                         remque((struct qelem *)m);
2385                         free(m);
2386                 }                       
2387                 imdone = 1;
2388                 break;
2389
2390             case LASTNODEKEY: /* Identify last node which keyed us up */
2391                 rpt_mutex_lock(&myrpt->lock);
2392                 if(myrpt->lastnodewhichkeyedusup)
2393                         p = ast_strdupa(myrpt->lastnodewhichkeyedusup); /* Make a local copy of the node name */
2394                 else
2395                         p = NULL;
2396                 rpt_mutex_unlock(&myrpt->lock);
2397                 if(!p){
2398                         imdone = 1; /* no node previously keyed us up, or the node which did has been disconnected */
2399                         break;
2400                 }
2401                 wait_interval(myrpt, DLY_TELEM, mychannel);
2402                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2403                 if (!res) 
2404                         res = ast_waitstream(mychannel, "");
2405                 else
2406                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2407                 ast_stopstream(mychannel);
2408                 ast_say_character_str(mychannel, p, NULL, mychannel->language);
2409                 if (!res) 
2410                         res = ast_waitstream(mychannel, "");
2411                 else
2412                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2413                 ast_stopstream(mychannel);
2414                 imdone = 1;
2415                 break;          
2416
2417             case TIMEOUT:
2418                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2419                 if (!res) 
2420                         res = ast_waitstream(mychannel, "");
2421                 else
2422                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2423                 ast_stopstream(mychannel);
2424                 ast_say_character_str(mychannel,myrpt->name,NULL,mychannel->language);
2425                 res = ast_streamfile(mychannel, "rpt/timeout", mychannel->language);
2426                 break;
2427                 
2428             case STATS_TIME:
2429                 wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
2430                 t = time(NULL);
2431                 localtime_r(&t, &localtm);
2432                 /* Say the phase of the day is before the time */
2433                 if((localtm.tm_hour >= 0) && (localtm.tm_hour < 12))
2434                         p = "rpt/goodmorning";
2435                 else if((localtm.tm_hour >= 12) && (localtm.tm_hour < 18))
2436                         p = "rpt/goodafternoon";
2437                 else
2438                         p = "rpt/goodevening";
2439                 if (sayfile(mychannel,p) == -1)
2440                 {
2441                         imdone = 1;
2442                         break;
2443                 }
2444                 /* Say the time is ... */               
2445                 if (sayfile(mychannel,"rpt/thetimeis") == -1)
2446                 {
2447                         imdone = 1;
2448                         break;
2449                 }
2450                 /* Say the time */                              
2451                 res = ast_say_time(mychannel, t, "", mychannel->language);
2452                 if (!res) 
2453                         res = ast_waitstream(mychannel, "");
2454                 ast_stopstream(mychannel);              
2455                 imdone = 1;
2456                 break;
2457             case STATS_VERSION:
2458                 wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
2459                 /* Say "version" */
2460                 if (sayfile(mychannel,"rpt/version") == -1)
2461                 {
2462                         imdone = 1;
2463                         break;
2464                 }
2465                 if(!res) /* Say "X" */
2466                         ast_say_number(mychannel, vmajor, "", mychannel->language, (char *) NULL);
2467                 if (!res) 
2468                         res = ast_waitstream(mychannel, "");
2469                 ast_stopstream(mychannel);      
2470                 if (saycharstr(mychannel,".") == -1)
2471                 {
2472                         imdone = 1;
2473                         break;
2474                 }
2475                 if(!res) /* Say "Y" */
2476                         ast_say_number(mychannel, vminor, "", mychannel->language, (char *) NULL);
2477                 if (!res){
2478                         res = ast_waitstream(mychannel, "");
2479                         ast_stopstream(mychannel);
2480                 }       
2481                 else
2482                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2483                 imdone = 1;
2484                 break;
2485             case ARB_ALPHA:
2486                 wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
2487                 if(mytele->param)
2488                         saycharstr(mychannel, mytele->param);
2489                 imdone = 1;
2490                 break;
2491             case REV_PATCH:
2492                 wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
2493                 if(mytele->param) {
2494
2495                         /* Parts of this section taken from app_parkandannounce */
2496                         char *tpl_working, *tpl_current;
2497                         char *tmp[100], *myparm;
2498                         int looptemp=0,i=0, dres = 0;
2499         
2500
2501                         tpl_working = strdupa(mytele->param);
2502                         myparm = strsep(&tpl_working,",");
2503                         tpl_current=strsep(&tpl_working, ":");
2504
2505                         while(tpl_current && looptemp < sizeof(tmp)) {
2506                                 tmp[looptemp]=tpl_current;
2507                                 looptemp++;
2508                                 tpl_current=strsep(&tpl_working,":");
2509                         }
2510
2511                         for(i=0; i<looptemp; i++) {
2512                                 if(!strcmp(tmp[i], "PARKED")) {
2513                                         ast_say_digits(mychannel, atoi(myparm), "", mychannel->language);
2514                                 } else if(!strcmp(tmp[i], "NODE")) {
2515                                         ast_say_digits(mychannel, atoi(myrpt->name), "", mychannel->language);
2516                                 } else {
2517                                         dres = ast_streamfile(mychannel, tmp[i], mychannel->language);
2518                                         if(!dres) {
2519                                                 dres = ast_waitstream(mychannel, "");
2520                                         } else {
2521                                                 ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", tmp[i], mychannel->name);
2522                                                 dres = 0;
2523                                         }
2524                                 }
2525                         }
2526                 }
2527                 imdone = 1;
2528                 break;
2529             case TEST_TONE:
2530                 imdone = 1;
2531                 myrpt->stopgen = 0;
2532                 if ((res = ast_tonepair_start(mychannel, 1004.0, 0, 99999999, 7200.0))) 
2533                         break;
2534                 while(mychannel->generatordata && (!myrpt->stopgen)) {
2535                         if (ast_safe_sleep(mychannel,1)) break;
2536                         imdone = 1;
2537                         }
2538                 break;
2539             default:
2540                 break;
2541         }
2542         myrpt->stopgen = 0;
2543         if (!imdone)
2544         {
2545                 if (!res) 
2546                         res = ast_waitstream(mychannel, "");
2547                 else {
2548                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2549                         res = 0;
2550                 }
2551         }
2552         ast_stopstream(mychannel);
2553         rpt_mutex_lock(&myrpt->lock);
2554         if (mytele->mode == TAILMSG)
2555         {
2556                 if (!res)
2557                 {
2558                         myrpt->tailmessagen++;
2559                         if(myrpt->tailmessagen >= myrpt->p.tailmessagemax) myrpt->tailmessagen = 0;
2560                 }
2561                 else
2562                 {
2563                         myrpt->tmsgtimer = myrpt->p.tailsquashedtime;
2564                 }
2565         }
2566         remque((struct qelem *)mytele);
2567         rpt_mutex_unlock(&myrpt->lock);
2568         free(mytele);           
2569         ast_hangup(mychannel);
2570 #ifdef  APP_RPT_LOCK_DEBUG
2571         {
2572                 struct lockthread *t;
2573
2574                 sleep(5);
2575                 ast_mutex_lock(&locklock);
2576                 t = get_lockthread(pthread_self());
2577                 if (t) memset(t,0,sizeof(struct lockthread));
2578                 ast_mutex_unlock(&locklock);
2579         }                       
2580 #endif
2581         pthread_exit(NULL);
2582 }
2583
2584 static void rpt_telemetry(struct rpt *myrpt,int mode, void *data)
2585 {
2586 struct rpt_tele *tele;
2587 struct rpt_link *mylink = (struct rpt_link *) data;
2588 int res;
2589 pthread_attr_t attr;
2590
2591         tele = malloc(sizeof(struct rpt_tele));
2592         if (!tele)
2593         {
2594                 ast_log(LOG_WARNING, "Unable to allocate memory\n");
2595                 pthread_exit(NULL);
2596                 return;
2597         }
2598         /* zero it out */
2599         memset((char *)tele,0,sizeof(struct rpt_tele));
2600         tele->rpt = myrpt;
2601         tele->mode = mode;
2602         rpt_mutex_lock(&myrpt->lock);
2603         if((mode == CONNFAIL) || (mode == REMDISC) || (mode == CONNECTED)){
2604                 memset(&tele->mylink,0,sizeof(struct rpt_link));
2605                 if (mylink){
2606                         memcpy(&tele->mylink,mylink,sizeof(struct rpt_link));
2607                 }
2608         }
2609         else if ((mode == ARB_ALPHA) || (mode == REV_PATCH)) {
2610                 strncpy(tele->param, (char *) data, TELEPARAMSIZE - 1);
2611                 tele->param[TELEPARAMSIZE - 1] = 0;
2612         }
2613         insque((struct qelem *)tele, (struct qelem *)myrpt->tele.next);
2614         rpt_mutex_unlock(&myrpt->lock);
2615         pthread_attr_init(&attr);
2616         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2617         res = ast_pthread_create(&tele->threadid,&attr,rpt_tele_thread,(void *) tele);
2618         if(res < 0){
2619                 rpt_mutex_lock(&myrpt->lock);
2620                 remque((struct qlem *) tele); /* We don't like stuck transmitters, remove it from the queue */
2621                 rpt_mutex_unlock(&myrpt->lock); 
2622                 ast_log(LOG_WARNING, "Could not create telemetry thread: %s",strerror(res));
2623         }
2624         return;
2625 }
2626
2627 static void *rpt_call(void *this)
2628 {
2629 ZT_CONFINFO ci;  /* conference info */
2630 struct  rpt *myrpt = (struct rpt *)this;
2631 int     res;
2632 struct  ast_frame wf;
2633 int stopped,congstarted,dialtimer,lastcidx,aborted;
2634 struct ast_channel *mychannel,*genchannel;
2635
2636
2637         myrpt->mydtmf = 0;
2638         /* allocate a pseudo-channel thru asterisk */
2639         mychannel = ast_request("zap",AST_FORMAT_SLINEAR,"pseudo",NULL);
2640         if (!mychannel)
2641         {
2642                 fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
2643                 pthread_exit(NULL);
2644         }
2645         ci.chan = 0;
2646         ci.confno = myrpt->conf; /* use the pseudo conference */
2647         ci.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER
2648                 | ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER; 
2649         /* first put the channel on the conference */
2650         if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
2651         {
2652                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2653                 ast_hangup(mychannel);
2654                 myrpt->callmode = 0;
2655                 pthread_exit(NULL);
2656         }
2657         /* allocate a pseudo-channel thru asterisk */
2658         genchannel = ast_request("zap",AST_FORMAT_SLINEAR,"pseudo",NULL);
2659         if (!genchannel)
2660         {
2661                 fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
2662                 ast_hangup(mychannel);
2663                 pthread_exit(NULL);
2664         }
2665         ci.chan = 0;
2666         ci.confno = myrpt->conf;
2667         ci.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER
2668                 | ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER; 
2669         /* first put the channel on the conference */
2670         if (ioctl(genchannel->fds[0],ZT_SETCONF,&ci) == -1)
2671         {
2672                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2673                 ast_hangup(mychannel);
2674                 ast_hangup(genchannel);
2675                 myrpt->callmode = 0;
2676                 pthread_exit(NULL);
2677         }
2678         if (myrpt->p.tonezone && (tone_zone_set_zone(mychannel->fds[0],myrpt->p.tonezone) == -1))
2679         {
2680                 ast_log(LOG_WARNING, "Unable to set tone zone %s\n",myrpt->p.tonezone);
2681                 ast_hangup(mychannel);
2682                 ast_hangup(genchannel);
2683                 myrpt->callmode = 0;
2684                 pthread_exit(NULL);
2685         }
2686         if (myrpt->p.tonezone && (tone_zone_set_zone(genchannel->fds[0],myrpt->p.tonezone) == -1))
2687         {
2688                 ast_log(LOG_WARNING, "Unable to set tone zone %s\n",myrpt->p.tonezone);
2689                 ast_hangup(mychannel);
2690                 ast_hangup(genchannel);
2691                 myrpt->callmode = 0;
2692                 pthread_exit(NULL);
2693         }
2694         /* start dialtone if patchquiet is 0. Special patch modes don't send dial tone */
2695         if ((!myrpt->patchquiet) && (tone_zone_play_tone(mychannel->fds[0],ZT_TONE_DIALTONE) < 0))
2696         {
2697                 ast_log(LOG_WARNING, "Cannot start dialtone\n");
2698                 ast_hangup(mychannel);
2699                 ast_hangup(genchannel);
2700                 myrpt->callmode = 0;
2701                 pthread_exit(NULL);
2702         }
2703         stopped = 0;
2704         congstarted = 0;
2705         dialtimer = 0;
2706         lastcidx = 0;
2707         aborted = 0;
2708
2709
2710         while ((myrpt->callmode == 1) || (myrpt->callmode == 4))
2711         {
2712
2713                 if((myrpt->patchdialtime)&&(myrpt->callmode == 1)&&(myrpt->cidx != lastcidx)){
2714                         dialtimer = 0;
2715                         lastcidx = myrpt->cidx;
2716                 }               
2717
2718                 if((myrpt->patchdialtime)&&(dialtimer >= myrpt->patchdialtime)){ 
2719                         rpt_mutex_lock(&myrpt->lock);
2720                         aborted = 1;
2721                         myrpt->callmode = 0;
2722                         rpt_mutex_unlock(&myrpt->lock);
2723                         break;
2724                 }
2725         
2726                 if ((!myrpt->patchquiet) && (!stopped) && (myrpt->callmode == 1) && (myrpt->cidx > 0))
2727                 {
2728                         stopped = 1;
2729                         /* stop dial tone */
2730                         tone_zone_play_tone(mychannel->fds[0],-1);
2731                 }
2732                 if (myrpt->callmode == 4)
2733                 {
2734                         if(!congstarted){
2735                                 congstarted = 1;
2736                                 /* start congestion tone */
2737                                 tone_zone_play_tone(mychannel->fds[0],ZT_TONE_CONGESTION);
2738                         }
2739                 }
2740                 res = ast_safe_sleep(mychannel, MSWAIT);
2741                 if (res < 0)
2742                 {
2743                         ast_hangup(mychannel);
2744                         ast_hangup(genchannel);
2745                         rpt_mutex_lock(&myrpt->lock);
2746                         myrpt->callmode = 0;
2747                         rpt_mutex_unlock(&myrpt->lock);
2748                         pthread_exit(NULL);
2749                 }
2750                 dialtimer += MSWAIT;
2751         }
2752         /* stop any tone generation */
2753         tone_zone_play_tone(mychannel->fds[0],-1);
2754         /* end if done */
2755         if (!myrpt->callmode)
2756         {
2757                 ast_hangup(mychannel);
2758                 ast_hangup(genchannel);
2759                 rpt_mutex_lock(&myrpt->lock);
2760                 myrpt->callmode = 0;
2761                 rpt_mutex_unlock(&myrpt->lock);
2762                 if((!myrpt->patchquiet) && aborted)
2763                         rpt_telemetry(myrpt, TERM, NULL);
2764                 pthread_exit(NULL);                     
2765         }
2766
2767         if (myrpt->p.ourcallerid && *myrpt->p.ourcallerid){
2768                 char *name, *loc, *instr;
2769                 instr = strdup(myrpt->p.ourcallerid);
2770                 if(instr){
2771                         ast_callerid_parse(instr, &name, &loc);
2772                         if(loc){
2773                                 if(mychannel->cid.cid_num)
2774                                         free(mychannel->cid.cid_num);
2775                                 mychannel->cid.cid_num = strdup(loc);
2776                         }
2777                         if(name){
2778                                 if(mychannel->cid.cid_name)
2779                                         free(mychannel->cid.cid_name);
2780                                 mychannel->cid.cid_name = strdup(name);
2781                         }
2782                         free(instr);
2783                 }
2784         }
2785
2786         strncpy(mychannel->exten, myrpt->exten, sizeof(mychannel->exten) - 1);
2787         strncpy(mychannel->context, myrpt->patchcontext, sizeof(mychannel->context) - 1);
2788         
2789         if (myrpt->p.acctcode)
2790                 strncpy((char *)mychannel->accountcode, myrpt->p.acctcode, sizeof(mychannel->accountcode) - 1);
2791         mychannel->priority = 1;
2792         ast_channel_undefer_dtmf(mychannel);
2793         if (ast_pbx_start(mychannel) < 0)
2794         {
2795                 ast_log(LOG_WARNING, "Unable to start PBX!!\n");
2796                 ast_hangup(mychannel);
2797                 ast_hangup(genchannel);
2798                 rpt_mutex_lock(&myrpt->lock);
2799                 myrpt->callmode = 0;
2800                 rpt_mutex_unlock(&myrpt->lock);
2801                 pthread_exit(NULL);
2802         }
2803         usleep(10000);
2804         rpt_mutex_lock(&myrpt->lock);
2805         myrpt->callmode = 3;
2806         /* set appropriate conference for the pseudo */
2807         ci.chan = 0;
2808         ci.confno = myrpt->conf;
2809         ci.confmode = (myrpt->p.duplex == 2) ? ZT_CONF_CONFANNMON :
2810                 (ZT_CONF_CONF | ZT_CONF_LISTENER | ZT_CONF_TALKER);
2811         /* first put the channel on the conference in announce mode */
2812         if (ioctl(myrpt->pchannel->fds[0],ZT_SETCONF,&ci) == -1)
2813         {
2814                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2815                 ast_hangup(mychannel);
2816                 ast_hangup(genchannel);
2817                 myrpt->callmode = 0;
2818                 pthread_exit(NULL);
2819         }
2820         while(myrpt->callmode)
2821         {
2822                 if ((!mychannel->pbx) && (myrpt->callmode != 4))
2823                 {
2824                         if(myrpt->patchfarenddisconnect){ /* If patch is setup for far end disconnect */
2825                                 myrpt->callmode = 0;
2826                                 if(!myrpt->patchquiet){
2827                                         rpt_mutex_unlock(&myrpt->lock);
2828                                         rpt_telemetry(myrpt, TERM, NULL);
2829                                         rpt_mutex_lock(&myrpt->lock);
2830                                 }
2831                         }
2832                         else{ /* Send congestion until patch is downed by command */
2833                                 myrpt->callmode = 4;
2834                                 rpt_mutex_unlock(&myrpt->lock);
2835                                 /* start congestion tone */
2836                                 tone_zone_play_tone(genchannel->fds[0],ZT_TONE_CONGESTION);
2837                                 rpt_mutex_lock(&myrpt->lock);
2838                         }
2839                 }
2840                 if (myrpt->mydtmf)
2841                 {
2842                         wf.frametype = AST_FRAME_DTMF;
2843                         wf.subclass = myrpt->mydtmf;
2844                         wf.offset = 0;
2845                         wf.mallocd = 0;
2846                         wf.data = NULL;
2847                         wf.datalen = 0;
2848                         wf.samples = 0;
2849                         rpt_mutex_unlock(&myrpt->lock);
2850                         ast_write(genchannel,&wf); 
2851                         rpt_mutex_lock(&myrpt->lock);
2852                         myrpt->mydtmf = 0;
2853                 }
2854                 rpt_mutex_unlock(&myrpt->lock);
2855                 usleep(MSWAIT * 1000);
2856                 rpt_mutex_lock(&myrpt->lock);
2857         }
2858         rpt_mutex_unlock(&myrpt->lock);
2859         tone_zone_play_tone(genchannel->fds[0],-1);
2860         if (mychannel->pbx) ast_softhangup(mychannel,AST_SOFTHANGUP_DEV);
2861         ast_hangup(genchannel);
2862         rpt_mutex_lock(&myrpt->lock);
2863         myrpt->callmode = 0;
2864         rpt_mutex_unlock(&myrpt->lock);
2865         /* set appropriate conference for the pseudo */
2866         ci.chan = 0;
2867         ci.confno = myrpt->conf;
2868         ci.confmode = ((myrpt->p.duplex == 2) || (myrpt->p.duplex == 4)) ? ZT_CONF_CONFANNMON :
2869                 (ZT_CONF_CONF | ZT_CONF_LISTENER | ZT_CONF_TALKER);
2870         /* first put the channel on the conference in announce mode */
2871         if (ioctl(myrpt->pchannel->fds[0],ZT_SETCONF,&ci) == -1)
2872         {
2873                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2874         }
2875         pthread_exit(NULL);
2876 }
2877
2878 static void send_link_dtmf(struct rpt *myrpt,char c)
2879 {
2880 char    str[300];
2881 struct  ast_frame wf;
2882 struct  rpt_link *l;
2883
2884         snprintf(str, sizeof(str), "D %s %s %d %c", myrpt->cmdnode, myrpt->name, ++(myrpt->dtmfidx), c);
2885         wf.frametype = AST_FRAME_TEXT;
2886         wf.subclass = 0;
2887         wf.offset = 0;
2888         wf.mallocd = 1;
2889         wf.datalen = strlen(str) + 1;
2890         wf.samples = 0;
2891         l = myrpt->links.next;
2892         /* first, see if our dude is there */
2893         while(l != &myrpt->links)
2894         {
2895                 if (l->name[0] == '0') 
2896                 {
2897                         l = l->next;
2898                         continue;
2899                 }
2900                 /* if we found it, write it and were done */
2901                 if (!strcmp(l->name,myrpt->cmdnode))
2902                 {
2903                         wf.data = strdup(str);
2904                         if (l->chan) ast_write(l->chan,&wf);
2905                         return;
2906                 }
2907                 l = l->next;
2908         }
2909         l = myrpt->links.next;
2910         /* if not, give it to everyone */
2911         while(l != &myrpt->links)
2912         {
2913                 wf.data = strdup(str);
2914                 if (l->chan) ast_write(l->chan,&wf);
2915                 l = l->next;
2916         }
2917         return;
2918 }
2919
2920 /*
2921 * Internet linking function 
2922 */
2923
2924 static int function_ilink(struct rpt *myrpt, char *param, char *digits, int command_source, struct rpt_link *mylink)
2925 {
2926
2927         const char *val;
2928         char *s, *s1, *s2, *tele;
2929         char tmp[300], deststr[300] = "",modechange = 0;
2930         char digitbuf[MAXNODESTR];
2931         struct rpt_link *l;
2932         int reconnects = 0;
2933         ZT_CONFINFO ci;  /* conference info */
2934
2935         if(!param)
2936                 return DC_ERROR;
2937                 
2938                         
2939         if (!myrpt->enable)
2940                 return DC_ERROR;
2941
2942         strncpy(digitbuf,digits,MAXNODESTR - 1);
2943
2944         if(debug)
2945                 printf("@@@@ ilink param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
2946                 
2947         switch(myatoi(param)){
2948                 case 1: /* Link off */
2949                         if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
2950                                 strcpy(digitbuf,myrpt->lastlinknode);
2951                         val = ast_variable_retrieve(myrpt->cfg, myrpt->p.nodes, digitbuf);
2952                         if (!val){
2953                                 if(strlen(digitbuf) >= myrpt->longestnode)
2954                                         return DC_ERROR;
2955                                 break;
2956                         }
2957                         strncpy(tmp,val,sizeof(tmp) - 1);
2958                         s = tmp;
2959                         s1 = strsep(&s,",");
2960                         s2 = strsep(&s,",");
2961                         rpt_mutex_lock(&myrpt->lock);
2962                         l = myrpt->links.next;
2963                         /* try to find this one in queue */
2964                         while(l != &myrpt->links){
2965                                 if (l->name[0] == '0') 
2966                                 {
2967                                         l = l->next;
2968                                         continue;
2969                                 }
2970                                 /* if found matching string */
2971                                 if (!strcmp(l->name, digitbuf))
2972                                         break;
2973                                 l = l->next;
2974                         }
2975                         if (l != &myrpt->links){ /* if found */
2976                                 struct  ast_frame wf;
2977                                 strncpy(myrpt->lastlinknode,digitbuf,MAXNODESTR - 1);
2978                                 l->retries = MAX_RETRIES + 1;
2979                                 l->disced = 1;
2980                                 rpt_mutex_unlock(&myrpt->lock);
2981                                 wf.frametype = AST_FRAME_TEXT;
2982                                 wf.subclass = 0;
2983                                 wf.offset = 0;
2984                                 wf.mallocd = 1;
2985                                 wf.datalen = strlen(discstr) + 1;
2986                                 wf.samples = 0;
2987                                 wf.data = strdup(discstr);
2988                                 if (l->chan)
2989                                 {
2990                                         ast_write(l->chan,&wf);
2991                                         if (ast_safe_sleep(l->chan,250) == -1) return DC_ERROR;
2992                                         ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
2993                                 }
2994                                 rpt_telemetry(myrpt, COMPLETE, NULL);
2995                                 return DC_COMPLETE;
2996                         }
2997                         rpt_mutex_unlock(&myrpt->lock); 
2998                         return DC_COMPLETE;
2999                 case 2: /* Link Monitor */
3000                         if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
3001                                 strcpy(digitbuf,myrpt->lastlinknode);
3002                         val = ast_variable_retrieve(myrpt->cfg, myrpt->p.nodes, digitbuf);
3003                         if (!val){
3004                                 if(strlen(digitbuf) >= myrpt->longestnode)
3005                                         return DC_ERROR;
3006                                 break;
3007                         }
3008                         strncpy(tmp,val,sizeof(tmp) - 1);
3009                         s = tmp;
3010                         s1 = strsep(&s,",");
3011                         s2 = strsep(&s,",");
3012                         rpt_mutex_lock(&myrpt->lock);
3013                         l = myrpt->links.next;
3014                         /* try to find this one in queue */
3015                         while(l != &myrpt->links){
3016                                 if (l->name[0] == '0') 
3017                                 {
3018                                         l = l->next;
3019                                         continue;
3020                                 }
3021                                 /* if found matching string */
3022                                 if (!strcmp(l->name, digitbuf))
3023                                         break;
3024                                 l = l->next;
3025                         }
3026                         /* if found */
3027                         if (l != &myrpt->links) 
3028                         {
3029                                 /* if already in this mode, just ignore */
3030                                 if ((!l->mode) || (!l->chan)) {
3031                                         rpt_mutex_unlock(&myrpt->lock);
3032                                         rpt_telemetry(myrpt,REMALREADY,NULL);
3033                                         return DC_COMPLETE;
3034                                         
3035                                 }
3036                                 reconnects = l->reconnects;
3037                                 rpt_mutex_unlock(&myrpt->lock);
3038                                 if (l->chan) ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
3039                                 l->retries = MAX_RETRIES + 1;
3040                                 l->disced = 2;
3041                                 modechange = 1;
3042                         } else
3043                                 rpt_mutex_unlock(&myrpt->lock);
3044                         strncpy(myrpt->lastlinknode,digitbuf,MAXNODESTR - 1);
3045                         /* establish call in monitor mode */
3046                         l = malloc(sizeof(struct rpt_link));
3047                         if (!l){
3048                                 ast_log(LOG_WARNING, "Unable to malloc\n");
3049                                 return DC_ERROR;
3050                         }
3051                         /* zero the silly thing */
3052                         memset((char *)l,0,sizeof(struct rpt_link));
3053                         snprintf(deststr, sizeof(deststr), "IAX2/%s", s1);
3054                         tele = strchr(deststr,'/');
3055                         if (!tele){
3056                                 fprintf(stderr,"link2:Dial number (%s) must be in format tech/number\n",deststr);
3057                                 return DC_ERROR;
3058                         }
3059                         *tele++ = 0;
3060                         l->isremote = (s && ast_true(s));
3061                         strncpy(l->name, digitbuf, MAXNODESTR - 1);
3062                         l->chan = ast_request(deststr,AST_FORMAT_SLINEAR,tele,NULL);
3063                         if (modechange) l->connected = 1;
3064                         if (l->chan){
3065                                 ast_set_read_format(l->chan,AST_FORMAT_SLINEAR);
3066                                 ast_set_write_format(l->chan,AST_FORMAT_SLINEAR);
3067                                 l->chan->whentohangup = 0;
3068                                 l->chan->appl = "Apprpt";
3069                                 l->chan->data = "(Remote Rx)";
3070                                 if (option_verbose > 2)
3071                                         ast_verbose(VERBOSE_PREFIX_3 "rpt (remote) initiating call to %s/%s on %s\n",
3072                                                 deststr,tele,l->chan->name);
3073                                 if(l->chan->cid.cid_num)
3074                                         free(l->chan->cid.cid_num);
3075                                 l->chan->cid.cid_num = strdup(myrpt->name);
3076                                 ast_call(l->chan,tele,0);
3077                         }
3078                         else
3079                         {
3080                                 rpt_telemetry(myrpt,CONNFAIL,l);
3081                                 free(l);
3082                                 if (option_verbose > 2)
3083                                         ast_verbose(VERBOSE_PREFIX_3 "Unable to place call to %s/%s on %s\n",
3084                                                 deststr,tele,l->chan->name);
3085                                 return DC_ERROR;
3086                         }
3087                         /* allocate a pseudo-channel thru asterisk */
3088                         l->pchan = ast_request("zap",AST_FORMAT_SLINEAR,"pseudo",NULL);
3089                         if (!l->pchan){
3090                                 fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
3091                                 ast_hangup(l->chan);
3092                                 free(l);
3093                                 return DC_ERROR;
3094                         }
3095