328cc2a6b43ff3edbc6c1477ee49ed58beaa1435
[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 = NULL;
1888
1889         wait_times = ast_variable_retrieve(cfg, myrpt->name, "wait_times");
1890
1891         if (wait_times) {
1892                 wait_times_save = ast_strdupa(wait_times);
1893                 if (!wait_times_save) {
1894                         ast_log(LOG_WARNING, "Out of memory in wait_interval()\n");
1895                         wait_times = NULL;
1896                 }
1897         }
1898
1899         switch (type) {
1900         case DLY_TELEM:
1901                 if (wait_times)
1902                         interval = retrieve_astcfgint(wait_times_save, "telemwait", 500, 5000, 1000);
1903                 else
1904                         interval = 1000;
1905                 break;
1906
1907         case DLY_ID:
1908                 if (wait_times)
1909                         interval = retrieve_astcfgint(wait_times_save, "idwait", 250, 5000, 500);
1910                 else
1911                         interval = 500;
1912                 break;
1913
1914         case DLY_UNKEY:
1915                 if (wait_times)
1916                         interval = retrieve_astcfgint(wait_times_save, "unkeywait", 500, 5000, 1000);
1917                 else
1918                         interval = 1000;
1919                 break;
1920
1921         case DLY_CALLTERM:
1922                 if (wait_times)
1923                         interval = retrieve_astcfgint(wait_times_save, "calltermwait", 500, 5000, 1500);
1924                 else
1925                         interval = 1500;
1926                 break;
1927
1928         default:
1929                 return 0;
1930         }
1931         return interval;
1932 }                                                                                                                 
1933
1934
1935 /*
1936 * Wait a configurable interval of time 
1937 */
1938
1939
1940 static void wait_interval(struct rpt *myrpt, int type, struct ast_channel *chan)
1941 {
1942         int interval;
1943         interval = get_wait_interval(myrpt, type);
1944         if(debug)
1945                 ast_log(LOG_NOTICE," Delay interval = %d\n", interval);
1946         if(interval)
1947                 ast_safe_sleep(chan,interval);
1948         if(debug)
1949                 ast_log(LOG_NOTICE,"Delay complete\n");
1950         return;
1951 }
1952
1953
1954 static void *rpt_tele_thread(void *this)
1955 {
1956 ZT_CONFINFO ci;  /* conference info */
1957 int     res = 0,haslink,hastx,hasremote,imdone = 0, unkeys_queued, x;
1958 struct  rpt_tele *mytele = (struct rpt_tele *)this;
1959 struct  rpt_tele *tlist;
1960 struct  rpt *myrpt;
1961 struct  rpt_link *l,*m,linkbase;
1962 struct  ast_channel *mychannel;
1963         const char *p, *ct;
1964         char *ct_copy, *ident, *nodename;
1965 time_t t;
1966 struct tm localtm;
1967
1968         /* get a pointer to myrpt */
1969         myrpt = mytele->rpt;
1970
1971         /* Snag copies of a few key myrpt variables */
1972         rpt_mutex_lock(&myrpt->lock);
1973         nodename = ast_strdupa(myrpt->name);
1974         ident = ast_strdupa(myrpt->p.ident);
1975         rpt_mutex_unlock(&myrpt->lock);
1976         
1977         /* allocate a pseudo-channel thru asterisk */
1978         mychannel = ast_request("zap",AST_FORMAT_SLINEAR,"pseudo",NULL);
1979         if (!mychannel)
1980         {
1981                 fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
1982                 rpt_mutex_lock(&myrpt->lock);
1983                 remque((struct qelem *)mytele);
1984                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
1985                 rpt_mutex_unlock(&myrpt->lock);
1986                 free(mytele);           
1987                 pthread_exit(NULL);
1988         }
1989         rpt_mutex_lock(&myrpt->lock);
1990         mytele->chan = mychannel; /* Save a copy of the channel so we can access it externally if need be */
1991         rpt_mutex_unlock(&myrpt->lock);
1992         
1993         /* make a conference for the tx */
1994         ci.chan = 0;
1995         /* If there's an ID queued, or tail message queued, */
1996         /* only connect the ID audio to the local tx conference so */
1997         /* linked systems can't hear it */
1998         ci.confno = (((mytele->mode == ID) || (mytele->mode == IDTALKOVER) || (mytele->mode == UNKEY) || 
1999                 (mytele->mode == TAILMSG)) ?
2000                         myrpt->txconf : myrpt->conf);
2001         ci.confmode = ZT_CONF_CONFANN;
2002         /* first put the channel on the conference in announce mode */
2003         if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
2004         {
2005                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2006                 rpt_mutex_lock(&myrpt->lock);
2007                 remque((struct qelem *)mytele);
2008                 rpt_mutex_unlock(&myrpt->lock);
2009                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
2010                 free(mytele);           
2011                 ast_hangup(mychannel);
2012                 pthread_exit(NULL);
2013         }
2014         ast_stopstream(mychannel);
2015         switch(mytele->mode)
2016         {
2017
2018             case ID:
2019             case ID1:
2020                 /* wait a bit */
2021                 wait_interval(myrpt, (mytele->mode == ID) ? DLY_ID : DLY_TELEM,mychannel);
2022                 res = telem_any(myrpt,mychannel, ident); 
2023                 imdone=1;       
2024                 break;
2025                 
2026             case TAILMSG:
2027                 res = ast_streamfile(mychannel, myrpt->p.tailmessages[myrpt->tailmessagen], mychannel->language); 
2028                 break;
2029                 
2030             case IDTALKOVER:
2031                 p = ast_variable_retrieve(myrpt->cfg, nodename, "idtalkover");
2032                 if(p)
2033                         res = telem_any(myrpt,mychannel, p); 
2034                 imdone=1;       
2035                 break;
2036                         
2037             case PROC:
2038                 /* wait a little bit longer */
2039                 wait_interval(myrpt, DLY_TELEM, mychannel);
2040                 res = telem_lookup(myrpt, mychannel, myrpt->name, "patchup");
2041                 if(res < 0){ /* Then default message */
2042                         res = ast_streamfile(mychannel, "rpt/callproceeding", mychannel->language);
2043                 }
2044                 break;
2045             case TERM:
2046                 /* wait a little bit longer */
2047                 wait_interval(myrpt, DLY_CALLTERM, mychannel);
2048                 res = telem_lookup(myrpt, mychannel, myrpt->name, "patchdown");
2049                 if(res < 0){ /* Then default message */
2050                         res = ast_streamfile(mychannel, "rpt/callterminated", mychannel->language);
2051                 }
2052                 break;
2053             case COMPLETE:
2054                 /* wait a little bit */
2055                 wait_interval(myrpt, DLY_TELEM, mychannel);
2056                 res = telem_lookup(myrpt,mychannel, myrpt->name, "functcomplete");
2057                 break;
2058             case MACRO_NOTFOUND:
2059                 /* wait a little bit */
2060                 wait_interval(myrpt, DLY_TELEM, mychannel);
2061                 res = ast_streamfile(mychannel, "rpt/macro_notfound", mychannel->language);
2062                 break;
2063             case MACRO_BUSY:
2064                 /* wait a little bit */
2065                 wait_interval(myrpt, DLY_TELEM, mychannel);
2066                 res = ast_streamfile(mychannel, "rpt/macro_busy", mychannel->language);
2067                 break;
2068             case UNKEY:
2069                 if(myrpt->patchnoct && myrpt->callmode){ /* If no CT during patch configured, then don't send one */
2070                         imdone = 1;
2071                         break;
2072                 }
2073                         
2074                 /*
2075                 * Reset the Unkey to CT timer
2076                 */
2077
2078                 x = get_wait_interval(myrpt, DLY_UNKEY);
2079                 rpt_mutex_lock(&myrpt->lock);
2080                 myrpt->unkeytocttimer = x; /* Must be protected as it is changed below */
2081                 rpt_mutex_unlock(&myrpt->lock);
2082
2083                 /*
2084                 * If there's one already queued, don't do another
2085                 */
2086
2087                 tlist = myrpt->tele.next;
2088                 unkeys_queued = 0;
2089                 if (tlist != &myrpt->tele)
2090                 {
2091                         rpt_mutex_lock(&myrpt->lock);
2092                         while(tlist != &myrpt->tele){
2093                                 if (tlist->mode == UNKEY) unkeys_queued++;
2094                                 tlist = tlist->next;
2095                         }
2096                         rpt_mutex_unlock(&myrpt->lock);
2097                 }
2098                 if( unkeys_queued > 1){
2099                         imdone = 1;
2100                         break;
2101                 }
2102
2103                 /* Wait for the telemetry timer to expire */
2104                 /* Periodically check the timer since it can be re-initialized above */
2105                 while(myrpt->unkeytocttimer)
2106                 {
2107                         int ctint;
2108                         if(myrpt->unkeytocttimer > 100)
2109                                 ctint = 100;
2110                         else
2111                                 ctint = myrpt->unkeytocttimer;
2112                         ast_safe_sleep(mychannel, ctint);
2113                         rpt_mutex_lock(&myrpt->lock);
2114                         if(myrpt->unkeytocttimer < ctint)
2115                                 myrpt->unkeytocttimer = 0;
2116                         else
2117                                 myrpt->unkeytocttimer -= ctint;
2118                         rpt_mutex_unlock(&myrpt->lock);
2119                 }
2120         
2121                 /*
2122                 * Now, the carrier on the rptr rx should be gone. 
2123                 * If it re-appeared, then forget about sending the CT
2124                 */
2125                 if(myrpt->keyed){
2126                         imdone = 1;
2127                         break;
2128                 }
2129                 
2130                 rpt_mutex_lock(&myrpt->lock); /* Update the kerchunk counters */
2131                 myrpt->dailykerchunks++;
2132                 myrpt->totalkerchunks++;
2133                 rpt_mutex_unlock(&myrpt->lock);
2134         
2135                 haslink = 0;
2136                 hastx = 0;
2137                 hasremote = 0;          
2138                 l = myrpt->links.next;
2139                 if (l != &myrpt->links)
2140                 {
2141                         rpt_mutex_lock(&myrpt->lock);
2142                         while(l != &myrpt->links)
2143                         {
2144                                 if (l->name[0] == '0')
2145                                 {
2146                                         l = l->next;
2147                                         continue;
2148                                 }
2149                                 haslink = 1;
2150                                 if (l->mode) {
2151                                         hastx++;
2152                                         if (l->isremote) hasremote++;
2153                                 }
2154                                 l = l->next;
2155                         }
2156                         rpt_mutex_unlock(&myrpt->lock);
2157                 }
2158                 if (haslink)
2159                 {
2160
2161                         res = telem_lookup(myrpt,mychannel, myrpt->name, (!hastx) ? "remotemon" : "remotetx");
2162                         if(res)
2163                                 ast_log(LOG_WARNING, "telem_lookup:remotexx failed on %s\n", mychannel->name);
2164                         
2165                 
2166                         /* if in remote cmd mode, indicate it */
2167                         if (myrpt->cmdnode[0])
2168                         {
2169                                 ast_safe_sleep(mychannel,200);
2170                                 res = telem_lookup(myrpt,mychannel, myrpt->name, "cmdmode");
2171                                 if(res)
2172                                         ast_log(LOG_WARNING, "telem_lookup:cmdmode failed on %s\n", mychannel->name);
2173                                 ast_stopstream(mychannel);
2174                         }
2175                 }
2176                 else if((ct = ast_variable_retrieve(myrpt->cfg, nodename, "unlinkedct"))){ /* Unlinked Courtesy Tone */
2177                         ct_copy = ast_strdupa(ct);
2178                         res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
2179                         if(res)
2180                                 ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);               
2181                 }       
2182                 if (hasremote && (!myrpt->cmdnode[0]))
2183                 {
2184                         /* set for all to hear */
2185                         ci.chan = 0;
2186                         ci.confno = myrpt->conf;
2187                         ci.confmode = ZT_CONF_CONFANN;
2188                         /* first put the channel on the conference in announce mode */
2189                         if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
2190                         {
2191                                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2192                                 rpt_mutex_lock(&myrpt->lock);
2193                                 remque((struct qelem *)mytele);
2194                                 rpt_mutex_unlock(&myrpt->lock);
2195                                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
2196                                 free(mytele);           
2197                                 ast_hangup(mychannel);
2198                                 pthread_exit(NULL);
2199                         }
2200                         if((ct = ast_variable_retrieve(myrpt->cfg, nodename, "remotect"))){ /* Unlinked Courtesy Tone */
2201                                 ast_safe_sleep(mychannel,200);
2202                                 ct_copy = ast_strdupa(ct);
2203                                 res = telem_lookup(myrpt,mychannel, myrpt->name, ct_copy);
2204                                 if(res)
2205                                         ast_log(LOG_WARNING, "telem_lookup:ctx failed on %s\n", mychannel->name);               
2206                         }       
2207                 }
2208 #ifdef  _MDC_DECODE_H_
2209                 if (myrpt->lastunit)
2210                 {
2211                         char mystr[10];
2212
2213                         ast_safe_sleep(mychannel,200);
2214                         /* set for all to hear */
2215                         ci.chan = 0;
2216                         ci.confno = myrpt->txconf;
2217                         ci.confmode = ZT_CONF_CONFANN;
2218                         /* first put the channel on the conference in announce mode */
2219                         if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
2220                         {
2221                                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2222                                 rpt_mutex_lock(&myrpt->lock);
2223                                 remque((struct qelem *)mytele);
2224                                 rpt_mutex_unlock(&myrpt->lock);
2225                                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
2226                                 free(mytele);           
2227                                 ast_hangup(mychannel);
2228                                 pthread_exit(NULL);
2229                         }
2230                         sprintf(mystr,"%04x",myrpt->lastunit);
2231                         myrpt->lastunit = 0;
2232                         ast_say_character_str(mychannel,mystr,NULL,mychannel->language);
2233                         break;
2234                 }
2235 #endif
2236                 imdone = 1;
2237                 break;
2238             case REMDISC:
2239                 /* wait a little bit */
2240                 wait_interval(myrpt, DLY_TELEM, mychannel);
2241                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2242                 if (!res) 
2243                         res = ast_waitstream(mychannel, "");
2244                 else
2245                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2246                 ast_stopstream(mychannel);
2247                 ast_say_character_str(mychannel,mytele->mylink.name,NULL,mychannel->language);
2248                 res = ast_streamfile(mychannel, ((mytele->mylink.connected) ? 
2249                         "rpt/remote_disc" : "rpt/remote_busy"), mychannel->language);
2250                 break;
2251             case REMALREADY:
2252                 /* wait a little bit */
2253                 wait_interval(myrpt, DLY_TELEM, mychannel);
2254                 res = ast_streamfile(mychannel, "rpt/remote_already", mychannel->language);
2255                 break;
2256             case REMNOTFOUND:
2257                 /* wait a little bit */
2258                 wait_interval(myrpt, DLY_TELEM, mychannel);
2259                 res = ast_streamfile(mychannel, "rpt/remote_notfound", mychannel->language);
2260                 break;
2261             case REMGO:
2262                 /* wait a little bit */
2263                 wait_interval(myrpt, DLY_TELEM, mychannel);
2264                 res = ast_streamfile(mychannel, "rpt/remote_go", mychannel->language);
2265                 break;
2266             case CONNECTED:
2267                 /* wait a little bit */
2268                 wait_interval(myrpt, DLY_TELEM,  mychannel);
2269                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2270                 if (!res) 
2271                         res = ast_waitstream(mychannel, "");
2272                 else
2273                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2274                 ast_stopstream(mychannel);
2275                 ast_say_character_str(mychannel,mytele->mylink.name,NULL,mychannel->language);
2276                 res = ast_streamfile(mychannel, "rpt/connected", mychannel->language);
2277                 break;
2278             case CONNFAIL:
2279                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2280                 if (!res) 
2281                         res = ast_waitstream(mychannel, "");
2282                 else
2283                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2284                 ast_stopstream(mychannel);
2285                 ast_say_character_str(mychannel,mytele->mylink.name,NULL,mychannel->language);
2286                 res = ast_streamfile(mychannel, "rpt/connection_failed", mychannel->language);
2287                 break;
2288             case STATUS:
2289                 /* wait a little bit */
2290                 wait_interval(myrpt, DLY_TELEM, mychannel);
2291                 hastx = 0;
2292                 linkbase.next = &linkbase;
2293                 linkbase.prev = &linkbase;
2294                 rpt_mutex_lock(&myrpt->lock);
2295                 /* make our own list of links */
2296                 l = myrpt->links.next;
2297                 while(l != &myrpt->links)
2298                 {
2299                         if (l->name[0] == '0')
2300                         {
2301                                 l = l->next;
2302                                 continue;
2303                         }
2304                         m = malloc(sizeof(struct rpt_link));
2305                         if (!m)
2306                         {
2307                                 ast_log(LOG_WARNING, "Cannot alloc memory on %s\n", mychannel->name);
2308                                 remque((struct qelem *)mytele);
2309                                 rpt_mutex_unlock(&myrpt->lock);
2310                                 ast_log(LOG_NOTICE,"Telemetry thread aborted at line %d, mode: %d\n",__LINE__, mytele->mode); /*@@@@@@@@@@@*/
2311                                 free(mytele);           
2312                                 ast_hangup(mychannel);
2313                                 pthread_exit(NULL);
2314                         }
2315                         memcpy(m,l,sizeof(struct rpt_link));
2316                         m->next = m->prev = NULL;
2317                         insque((struct qelem *)m,(struct qelem *)linkbase.next);
2318                         l = l->next;
2319                 }
2320                 rpt_mutex_unlock(&myrpt->lock);
2321                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2322                 if (!res) 
2323                         res = ast_waitstream(mychannel, "");
2324                 else
2325                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2326                 ast_stopstream(mychannel);
2327                 ast_say_character_str(mychannel,myrpt->name,NULL,mychannel->language);
2328                 if (!res) 
2329                         res = ast_waitstream(mychannel, "");
2330                 else
2331                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2332                 ast_stopstream(mychannel);
2333                 if (myrpt->callmode)
2334                 {
2335                         hastx = 1;
2336                         res = ast_streamfile(mychannel, "rpt/autopatch_on", mychannel->language);
2337                         if (!res) 
2338                                 res = ast_waitstream(mychannel, "");
2339                         else
2340                                  ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2341                         ast_stopstream(mychannel);
2342                 }
2343                 l = linkbase.next;
2344                 while(l != &linkbase)
2345                 {
2346                         hastx = 1;
2347                         res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2348                         if (!res) 
2349                                 res = ast_waitstream(mychannel, "");
2350                         else
2351                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2352                         ast_stopstream(mychannel);
2353                         ast_say_character_str(mychannel,l->name,NULL,mychannel->language);
2354                         if (!res) 
2355                                 res = ast_waitstream(mychannel, "");
2356                         else
2357                                  ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2358                         ast_stopstream(mychannel);
2359                         res = ast_streamfile(mychannel, ((l->mode) ? 
2360                                 "rpt/tranceive" : "rpt/monitor"), mychannel->language);
2361                         if (!res) 
2362                                 res = ast_waitstream(mychannel, "");
2363                         else
2364                                 ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2365                         ast_stopstream(mychannel);
2366                         l = l->next;
2367                 }                       
2368                 if (!hastx)
2369                 {
2370                         res = ast_streamfile(mychannel, "rpt/repeat_only", mychannel->language);
2371                         if (!res) 
2372                                 res = ast_waitstream(mychannel, "");
2373                         else
2374                                  ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2375                         ast_stopstream(mychannel);
2376                 }
2377                 /* destroy our local link queue */
2378                 l = linkbase.next;
2379                 while(l != &linkbase)
2380                 {
2381                         m = l;
2382                         l = l->next;
2383                         remque((struct qelem *)m);
2384                         free(m);
2385                 }                       
2386                 imdone = 1;
2387                 break;
2388
2389             case LASTNODEKEY: /* Identify last node which keyed us up */
2390                 rpt_mutex_lock(&myrpt->lock);
2391                 if(myrpt->lastnodewhichkeyedusup)
2392                         p = ast_strdupa(myrpt->lastnodewhichkeyedusup); /* Make a local copy of the node name */
2393                 else
2394                         p = NULL;
2395                 rpt_mutex_unlock(&myrpt->lock);
2396                 if(!p){
2397                         imdone = 1; /* no node previously keyed us up, or the node which did has been disconnected */
2398                         break;
2399                 }
2400                 wait_interval(myrpt, DLY_TELEM, mychannel);
2401                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2402                 if (!res) 
2403                         res = ast_waitstream(mychannel, "");
2404                 else
2405                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2406                 ast_stopstream(mychannel);
2407                 ast_say_character_str(mychannel, p, NULL, mychannel->language);
2408                 if (!res) 
2409                         res = ast_waitstream(mychannel, "");
2410                 else
2411                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2412                 ast_stopstream(mychannel);
2413                 imdone = 1;
2414                 break;          
2415
2416             case TIMEOUT:
2417                 res = ast_streamfile(mychannel, "rpt/node", mychannel->language);
2418                 if (!res) 
2419                         res = ast_waitstream(mychannel, "");
2420                 else
2421                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2422                 ast_stopstream(mychannel);
2423                 ast_say_character_str(mychannel,myrpt->name,NULL,mychannel->language);
2424                 res = ast_streamfile(mychannel, "rpt/timeout", mychannel->language);
2425                 break;
2426                 
2427             case STATS_TIME:
2428                 wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
2429                 t = time(NULL);
2430                 localtime_r(&t, &localtm);
2431                 /* Say the phase of the day is before the time */
2432                 if((localtm.tm_hour >= 0) && (localtm.tm_hour < 12))
2433                         p = "rpt/goodmorning";
2434                 else if((localtm.tm_hour >= 12) && (localtm.tm_hour < 18))
2435                         p = "rpt/goodafternoon";
2436                 else
2437                         p = "rpt/goodevening";
2438                 if (sayfile(mychannel,p) == -1)
2439                 {
2440                         imdone = 1;
2441                         break;
2442                 }
2443                 /* Say the time is ... */               
2444                 if (sayfile(mychannel,"rpt/thetimeis") == -1)
2445                 {
2446                         imdone = 1;
2447                         break;
2448                 }
2449                 /* Say the time */                              
2450                 res = ast_say_time(mychannel, t, "", mychannel->language);
2451                 if (!res) 
2452                         res = ast_waitstream(mychannel, "");
2453                 ast_stopstream(mychannel);              
2454                 imdone = 1;
2455                 break;
2456             case STATS_VERSION:
2457                 wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
2458                 /* Say "version" */
2459                 if (sayfile(mychannel,"rpt/version") == -1)
2460                 {
2461                         imdone = 1;
2462                         break;
2463                 }
2464                 if(!res) /* Say "X" */
2465                         ast_say_number(mychannel, vmajor, "", mychannel->language, (char *) NULL);
2466                 if (!res) 
2467                         res = ast_waitstream(mychannel, "");
2468                 ast_stopstream(mychannel);      
2469                 if (saycharstr(mychannel,".") == -1)
2470                 {
2471                         imdone = 1;
2472                         break;
2473                 }
2474                 if(!res) /* Say "Y" */
2475                         ast_say_number(mychannel, vminor, "", mychannel->language, (char *) NULL);
2476                 if (!res){
2477                         res = ast_waitstream(mychannel, "");
2478                         ast_stopstream(mychannel);
2479                 }       
2480                 else
2481                          ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2482                 imdone = 1;
2483                 break;
2484             case ARB_ALPHA:
2485                 wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
2486                 if(mytele->param)
2487                         saycharstr(mychannel, mytele->param);
2488                 imdone = 1;
2489                 break;
2490             case REV_PATCH:
2491                 wait_interval(myrpt, DLY_TELEM, mychannel); /* Wait a little bit */
2492                 if(mytele->param) {
2493
2494                         /* Parts of this section taken from app_parkandannounce */
2495                         char *tpl_working, *tpl_current;
2496                         char *tmp[100], *myparm;
2497                         int looptemp=0,i=0, dres = 0;
2498         
2499
2500                         tpl_working = strdupa(mytele->param);
2501                         myparm = strsep(&tpl_working,",");
2502                         tpl_current=strsep(&tpl_working, ":");
2503
2504                         while(tpl_current && looptemp < sizeof(tmp)) {
2505                                 tmp[looptemp]=tpl_current;
2506                                 looptemp++;
2507                                 tpl_current=strsep(&tpl_working,":");
2508                         }
2509
2510                         for(i=0; i<looptemp; i++) {
2511                                 if(!strcmp(tmp[i], "PARKED")) {
2512                                         ast_say_digits(mychannel, atoi(myparm), "", mychannel->language);
2513                                 } else if(!strcmp(tmp[i], "NODE")) {
2514                                         ast_say_digits(mychannel, atoi(myrpt->name), "", mychannel->language);
2515                                 } else {
2516                                         dres = ast_streamfile(mychannel, tmp[i], mychannel->language);
2517                                         if(!dres) {
2518                                                 dres = ast_waitstream(mychannel, "");
2519                                         } else {
2520                                                 ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", tmp[i], mychannel->name);
2521                                                 dres = 0;
2522                                         }
2523                                 }
2524                         }
2525                 }
2526                 imdone = 1;
2527                 break;
2528             case TEST_TONE:
2529                 imdone = 1;
2530                 myrpt->stopgen = 0;
2531                 if ((res = ast_tonepair_start(mychannel, 1004.0, 0, 99999999, 7200.0))) 
2532                         break;
2533                 while(mychannel->generatordata && (!myrpt->stopgen)) {
2534                         if (ast_safe_sleep(mychannel,1)) break;
2535                         imdone = 1;
2536                         }
2537                 break;
2538             default:
2539                 break;
2540         }
2541         myrpt->stopgen = 0;
2542         if (!imdone)
2543         {
2544                 if (!res) 
2545                         res = ast_waitstream(mychannel, "");
2546                 else {
2547                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", mychannel->name);
2548                         res = 0;
2549                 }
2550         }
2551         ast_stopstream(mychannel);
2552         rpt_mutex_lock(&myrpt->lock);
2553         if (mytele->mode == TAILMSG)
2554         {
2555                 if (!res)
2556                 {
2557                         myrpt->tailmessagen++;
2558                         if(myrpt->tailmessagen >= myrpt->p.tailmessagemax) myrpt->tailmessagen = 0;
2559                 }
2560                 else
2561                 {
2562                         myrpt->tmsgtimer = myrpt->p.tailsquashedtime;
2563                 }
2564         }
2565         remque((struct qelem *)mytele);
2566         rpt_mutex_unlock(&myrpt->lock);
2567         free(mytele);           
2568         ast_hangup(mychannel);
2569 #ifdef  APP_RPT_LOCK_DEBUG
2570         {
2571                 struct lockthread *t;
2572
2573                 sleep(5);
2574                 ast_mutex_lock(&locklock);
2575                 t = get_lockthread(pthread_self());
2576                 if (t) memset(t,0,sizeof(struct lockthread));
2577                 ast_mutex_unlock(&locklock);
2578         }                       
2579 #endif
2580         pthread_exit(NULL);
2581 }
2582
2583 static void rpt_telemetry(struct rpt *myrpt,int mode, void *data)
2584 {
2585 struct rpt_tele *tele;
2586 struct rpt_link *mylink = (struct rpt_link *) data;
2587 int res;
2588 pthread_attr_t attr;
2589
2590         tele = malloc(sizeof(struct rpt_tele));
2591         if (!tele)
2592         {
2593                 ast_log(LOG_WARNING, "Unable to allocate memory\n");
2594                 pthread_exit(NULL);
2595                 return;
2596         }
2597         /* zero it out */
2598         memset((char *)tele,0,sizeof(struct rpt_tele));
2599         tele->rpt = myrpt;
2600         tele->mode = mode;
2601         rpt_mutex_lock(&myrpt->lock);
2602         if((mode == CONNFAIL) || (mode == REMDISC) || (mode == CONNECTED)){
2603                 memset(&tele->mylink,0,sizeof(struct rpt_link));
2604                 if (mylink){
2605                         memcpy(&tele->mylink,mylink,sizeof(struct rpt_link));
2606                 }
2607         }
2608         else if ((mode == ARB_ALPHA) || (mode == REV_PATCH)) {
2609                 strncpy(tele->param, (char *) data, TELEPARAMSIZE - 1);
2610                 tele->param[TELEPARAMSIZE - 1] = 0;
2611         }
2612         insque((struct qelem *)tele, (struct qelem *)myrpt->tele.next);
2613         rpt_mutex_unlock(&myrpt->lock);
2614         pthread_attr_init(&attr);
2615         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2616         res = ast_pthread_create(&tele->threadid,&attr,rpt_tele_thread,(void *) tele);
2617         if(res < 0){
2618                 rpt_mutex_lock(&myrpt->lock);
2619                 remque((struct qlem *) tele); /* We don't like stuck transmitters, remove it from the queue */
2620                 rpt_mutex_unlock(&myrpt->lock); 
2621                 ast_log(LOG_WARNING, "Could not create telemetry thread: %s",strerror(res));
2622         }
2623         return;
2624 }
2625
2626 static void *rpt_call(void *this)
2627 {
2628 ZT_CONFINFO ci;  /* conference info */
2629 struct  rpt *myrpt = (struct rpt *)this;
2630 int     res;
2631 struct  ast_frame wf;
2632 int stopped,congstarted,dialtimer,lastcidx,aborted;
2633 struct ast_channel *mychannel,*genchannel;
2634
2635
2636         myrpt->mydtmf = 0;
2637         /* allocate a pseudo-channel thru asterisk */
2638         mychannel = ast_request("zap",AST_FORMAT_SLINEAR,"pseudo",NULL);
2639         if (!mychannel)
2640         {
2641                 fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
2642                 pthread_exit(NULL);
2643         }
2644         ci.chan = 0;
2645         ci.confno = myrpt->conf; /* use the pseudo conference */
2646         ci.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER
2647                 | ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER; 
2648         /* first put the channel on the conference */
2649         if (ioctl(mychannel->fds[0],ZT_SETCONF,&ci) == -1)
2650         {
2651                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2652                 ast_hangup(mychannel);
2653                 myrpt->callmode = 0;
2654                 pthread_exit(NULL);
2655         }
2656         /* allocate a pseudo-channel thru asterisk */
2657         genchannel = ast_request("zap",AST_FORMAT_SLINEAR,"pseudo",NULL);
2658         if (!genchannel)
2659         {
2660                 fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
2661                 ast_hangup(mychannel);
2662                 pthread_exit(NULL);
2663         }
2664         ci.chan = 0;
2665         ci.confno = myrpt->conf;
2666         ci.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER
2667                 | ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER; 
2668         /* first put the channel on the conference */
2669         if (ioctl(genchannel->fds[0],ZT_SETCONF,&ci) == -1)
2670         {
2671                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2672                 ast_hangup(mychannel);
2673                 ast_hangup(genchannel);
2674                 myrpt->callmode = 0;
2675                 pthread_exit(NULL);
2676         }
2677         if (myrpt->p.tonezone && (tone_zone_set_zone(mychannel->fds[0],myrpt->p.tonezone) == -1))
2678         {
2679                 ast_log(LOG_WARNING, "Unable to set tone zone %s\n",myrpt->p.tonezone);
2680                 ast_hangup(mychannel);
2681                 ast_hangup(genchannel);
2682                 myrpt->callmode = 0;
2683                 pthread_exit(NULL);
2684         }
2685         if (myrpt->p.tonezone && (tone_zone_set_zone(genchannel->fds[0],myrpt->p.tonezone) == -1))
2686         {
2687                 ast_log(LOG_WARNING, "Unable to set tone zone %s\n",myrpt->p.tonezone);
2688                 ast_hangup(mychannel);
2689                 ast_hangup(genchannel);
2690                 myrpt->callmode = 0;
2691                 pthread_exit(NULL);
2692         }
2693         /* start dialtone if patchquiet is 0. Special patch modes don't send dial tone */
2694         if ((!myrpt->patchquiet) && (tone_zone_play_tone(mychannel->fds[0],ZT_TONE_DIALTONE) < 0))
2695         {
2696                 ast_log(LOG_WARNING, "Cannot start dialtone\n");
2697                 ast_hangup(mychannel);
2698                 ast_hangup(genchannel);
2699                 myrpt->callmode = 0;
2700                 pthread_exit(NULL);
2701         }
2702         stopped = 0;
2703         congstarted = 0;
2704         dialtimer = 0;
2705         lastcidx = 0;
2706         aborted = 0;
2707
2708
2709         while ((myrpt->callmode == 1) || (myrpt->callmode == 4))
2710         {
2711
2712                 if((myrpt->patchdialtime)&&(myrpt->callmode == 1)&&(myrpt->cidx != lastcidx)){
2713                         dialtimer = 0;
2714                         lastcidx = myrpt->cidx;
2715                 }               
2716
2717                 if((myrpt->patchdialtime)&&(dialtimer >= myrpt->patchdialtime)){ 
2718                         rpt_mutex_lock(&myrpt->lock);
2719                         aborted = 1;
2720                         myrpt->callmode = 0;
2721                         rpt_mutex_unlock(&myrpt->lock);
2722                         break;
2723                 }
2724         
2725                 if ((!myrpt->patchquiet) && (!stopped) && (myrpt->callmode == 1) && (myrpt->cidx > 0))
2726                 {
2727                         stopped = 1;
2728                         /* stop dial tone */
2729                         tone_zone_play_tone(mychannel->fds[0],-1);
2730                 }
2731                 if (myrpt->callmode == 4)
2732                 {
2733                         if(!congstarted){
2734                                 congstarted = 1;
2735                                 /* start congestion tone */
2736                                 tone_zone_play_tone(mychannel->fds[0],ZT_TONE_CONGESTION);
2737                         }
2738                 }
2739                 res = ast_safe_sleep(mychannel, MSWAIT);
2740                 if (res < 0)
2741                 {
2742                         ast_hangup(mychannel);
2743                         ast_hangup(genchannel);
2744                         rpt_mutex_lock(&myrpt->lock);
2745                         myrpt->callmode = 0;
2746                         rpt_mutex_unlock(&myrpt->lock);
2747                         pthread_exit(NULL);
2748                 }
2749                 dialtimer += MSWAIT;
2750         }
2751         /* stop any tone generation */
2752         tone_zone_play_tone(mychannel->fds[0],-1);
2753         /* end if done */
2754         if (!myrpt->callmode)
2755         {
2756                 ast_hangup(mychannel);
2757                 ast_hangup(genchannel);
2758                 rpt_mutex_lock(&myrpt->lock);
2759                 myrpt->callmode = 0;
2760                 rpt_mutex_unlock(&myrpt->lock);
2761                 if((!myrpt->patchquiet) && aborted)
2762                         rpt_telemetry(myrpt, TERM, NULL);
2763                 pthread_exit(NULL);                     
2764         }
2765
2766         if (myrpt->p.ourcallerid && *myrpt->p.ourcallerid){
2767                 char *name, *loc, *instr;
2768                 instr = strdup(myrpt->p.ourcallerid);
2769                 if(instr){
2770                         ast_callerid_parse(instr, &name, &loc);
2771                         if(loc){
2772                                 if(mychannel->cid.cid_num)
2773                                         free(mychannel->cid.cid_num);
2774                                 mychannel->cid.cid_num = strdup(loc);
2775                         }
2776                         if(name){
2777                                 if(mychannel->cid.cid_name)
2778                                         free(mychannel->cid.cid_name);
2779                                 mychannel->cid.cid_name = strdup(name);
2780                         }
2781                         free(instr);
2782                 }
2783         }
2784
2785         strncpy(mychannel->exten, myrpt->exten, sizeof(mychannel->exten) - 1);
2786         strncpy(mychannel->context, myrpt->patchcontext, sizeof(mychannel->context) - 1);
2787         
2788         if (myrpt->p.acctcode)
2789                 strncpy((char *)mychannel->accountcode, myrpt->p.acctcode, sizeof(mychannel->accountcode) - 1);
2790         mychannel->priority = 1;
2791         ast_channel_undefer_dtmf(mychannel);
2792         if (ast_pbx_start(mychannel) < 0)
2793         {
2794                 ast_log(LOG_WARNING, "Unable to start PBX!!\n");
2795                 ast_hangup(mychannel);
2796                 ast_hangup(genchannel);
2797                 rpt_mutex_lock(&myrpt->lock);
2798                 myrpt->callmode = 0;
2799                 rpt_mutex_unlock(&myrpt->lock);
2800                 pthread_exit(NULL);
2801         }
2802         usleep(10000);
2803         rpt_mutex_lock(&myrpt->lock);
2804         myrpt->callmode = 3;
2805         /* set appropriate conference for the pseudo */
2806         ci.chan = 0;
2807         ci.confno = myrpt->conf;
2808         ci.confmode = (myrpt->p.duplex == 2) ? ZT_CONF_CONFANNMON :
2809                 (ZT_CONF_CONF | ZT_CONF_LISTENER | ZT_CONF_TALKER);
2810         /* first put the channel on the conference in announce mode */
2811         if (ioctl(myrpt->pchannel->fds[0],ZT_SETCONF,&ci) == -1)
2812         {
2813                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2814                 ast_hangup(mychannel);
2815                 ast_hangup(genchannel);
2816                 myrpt->callmode = 0;
2817                 pthread_exit(NULL);
2818         }
2819         while(myrpt->callmode)
2820         {
2821                 if ((!mychannel->pbx) && (myrpt->callmode != 4))
2822                 {
2823                         if(myrpt->patchfarenddisconnect){ /* If patch is setup for far end disconnect */
2824                                 myrpt->callmode = 0;
2825                                 if(!myrpt->patchquiet){
2826                                         rpt_mutex_unlock(&myrpt->lock);
2827                                         rpt_telemetry(myrpt, TERM, NULL);
2828                                         rpt_mutex_lock(&myrpt->lock);
2829                                 }
2830                         }
2831                         else{ /* Send congestion until patch is downed by command */
2832                                 myrpt->callmode = 4;
2833                                 rpt_mutex_unlock(&myrpt->lock);
2834                                 /* start congestion tone */
2835                                 tone_zone_play_tone(genchannel->fds[0],ZT_TONE_CONGESTION);
2836                                 rpt_mutex_lock(&myrpt->lock);
2837                         }
2838                 }
2839                 if (myrpt->mydtmf)
2840                 {
2841                         wf.frametype = AST_FRAME_DTMF;
2842                         wf.subclass = myrpt->mydtmf;
2843                         wf.offset = 0;
2844                         wf.mallocd = 0;
2845                         wf.data = NULL;
2846                         wf.datalen = 0;
2847                         wf.samples = 0;
2848                         rpt_mutex_unlock(&myrpt->lock);
2849                         ast_write(genchannel,&wf); 
2850                         rpt_mutex_lock(&myrpt->lock);
2851                         myrpt->mydtmf = 0;
2852                 }
2853                 rpt_mutex_unlock(&myrpt->lock);
2854                 usleep(MSWAIT * 1000);
2855                 rpt_mutex_lock(&myrpt->lock);
2856         }
2857         rpt_mutex_unlock(&myrpt->lock);
2858         tone_zone_play_tone(genchannel->fds[0],-1);
2859         if (mychannel->pbx) ast_softhangup(mychannel,AST_SOFTHANGUP_DEV);
2860         ast_hangup(genchannel);
2861         rpt_mutex_lock(&myrpt->lock);
2862         myrpt->callmode = 0;
2863         rpt_mutex_unlock(&myrpt->lock);
2864         /* set appropriate conference for the pseudo */
2865         ci.chan = 0;
2866         ci.confno = myrpt->conf;
2867         ci.confmode = ((myrpt->p.duplex == 2) || (myrpt->p.duplex == 4)) ? ZT_CONF_CONFANNMON :
2868                 (ZT_CONF_CONF | ZT_CONF_LISTENER | ZT_CONF_TALKER);
2869         /* first put the channel on the conference in announce mode */
2870         if (ioctl(myrpt->pchannel->fds[0],ZT_SETCONF,&ci) == -1)
2871         {
2872                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
2873         }
2874         pthread_exit(NULL);
2875 }
2876
2877 static void send_link_dtmf(struct rpt *myrpt,char c)
2878 {
2879 char    str[300];
2880 struct  ast_frame wf;
2881 struct  rpt_link *l;
2882
2883         snprintf(str, sizeof(str), "D %s %s %d %c", myrpt->cmdnode, myrpt->name, ++(myrpt->dtmfidx), c);
2884         wf.frametype = AST_FRAME_TEXT;
2885         wf.subclass = 0;
2886         wf.offset = 0;
2887         wf.mallocd = 1;
2888         wf.datalen = strlen(str) + 1;
2889         wf.samples = 0;
2890         l = myrpt->links.next;
2891         /* first, see if our dude is there */
2892         while(l != &myrpt->links)
2893         {
2894                 if (l->name[0] == '0') 
2895                 {
2896                         l = l->next;
2897                         continue;
2898                 }
2899                 /* if we found it, write it and were done */
2900                 if (!strcmp(l->name,myrpt->cmdnode))
2901                 {
2902                         wf.data = strdup(str);
2903                         if (l->chan) ast_write(l->chan,&wf);
2904                         return;
2905                 }
2906                 l = l->next;
2907         }
2908         l = myrpt->links.next;
2909         /* if not, give it to everyone */
2910         while(l != &myrpt->links)
2911         {
2912                 wf.data = strdup(str);
2913                 if (l->chan) ast_write(l->chan,&wf);
2914                 l = l->next;
2915         }
2916         return;
2917 }
2918
2919 /*
2920 * Internet linking function 
2921 */
2922
2923 static int function_ilink(struct rpt *myrpt, char *param, char *digits, int command_source, struct rpt_link *mylink)
2924 {
2925
2926         const char *val;
2927         char *s, *s1, *s2, *tele;
2928         char tmp[300], deststr[300] = "",modechange = 0;
2929         char digitbuf[MAXNODESTR];
2930         struct rpt_link *l;
2931         int reconnects = 0;
2932         ZT_CONFINFO ci;  /* conference info */
2933
2934         if(!param)
2935                 return DC_ERROR;
2936                 
2937                         
2938         if (!myrpt->enable)
2939                 return DC_ERROR;
2940
2941         strncpy(digitbuf,digits,MAXNODESTR - 1);
2942
2943         if(debug)
2944                 printf("@@@@ ilink param = %s, digitbuf = %s\n", (param)? param : "(null)", digitbuf);
2945                 
2946         switch(myatoi(param)){
2947                 case 1: /* Link off */
2948                         if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
2949                                 strcpy(digitbuf,myrpt->lastlinknode);
2950                         val = ast_variable_retrieve(myrpt->cfg, myrpt->p.nodes, digitbuf);
2951                         if (!val){
2952                                 if(strlen(digitbuf) >= myrpt->longestnode)
2953                                         return DC_ERROR;
2954                                 break;
2955                         }
2956                         strncpy(tmp,val,sizeof(tmp) - 1);
2957                         s = tmp;
2958                         s1 = strsep(&s,",");
2959                         s2 = strsep(&s,",");
2960                         rpt_mutex_lock(&myrpt->lock);
2961                         l = myrpt->links.next;
2962                         /* try to find this one in queue */
2963                         while(l != &myrpt->links){
2964                                 if (l->name[0] == '0') 
2965                                 {
2966                                         l = l->next;
2967                                         continue;
2968                                 }
2969                                 /* if found matching string */
2970                                 if (!strcmp(l->name, digitbuf))
2971                                         break;
2972                                 l = l->next;
2973                         }
2974                         if (l != &myrpt->links){ /* if found */
2975                                 struct  ast_frame wf;
2976                                 strncpy(myrpt->lastlinknode,digitbuf,MAXNODESTR - 1);
2977                                 l->retries = MAX_RETRIES + 1;
2978                                 l->disced = 1;
2979                                 rpt_mutex_unlock(&myrpt->lock);
2980                                 wf.frametype = AST_FRAME_TEXT;
2981                                 wf.subclass = 0;
2982                                 wf.offset = 0;
2983                                 wf.mallocd = 1;
2984                                 wf.datalen = strlen(discstr) + 1;
2985                                 wf.samples = 0;
2986                                 wf.data = strdup(discstr);
2987                                 if (l->chan)
2988                                 {
2989                                         ast_write(l->chan,&wf);
2990                                         if (ast_safe_sleep(l->chan,250) == -1) return DC_ERROR;
2991                                         ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
2992                                 }
2993                                 rpt_telemetry(myrpt, COMPLETE, NULL);
2994                                 return DC_COMPLETE;
2995                         }
2996                         rpt_mutex_unlock(&myrpt->lock); 
2997                         return DC_COMPLETE;
2998                 case 2: /* Link Monitor */
2999                         if ((digitbuf[0] == '0') && (myrpt->lastlinknode[0]))
3000                                 strcpy(digitbuf,myrpt->lastlinknode);
3001                         val = ast_variable_retrieve(myrpt->cfg, myrpt->p.nodes, digitbuf);
3002                         if (!val){
3003                                 if(strlen(digitbuf) >= myrpt->longestnode)
3004                                         return DC_ERROR;
3005                                 break;
3006                         }
3007                         strncpy(tmp,val,sizeof(tmp) - 1);
3008                         s = tmp;
3009                         s1 = strsep(&s,",");
3010                         s2 = strsep(&s,",");
3011                         rpt_mutex_lock(&myrpt->lock);
3012                         l = myrpt->links.next;
3013                         /* try to find this one in queue */
3014                         while(l != &myrpt->links){
3015                                 if (l->name[0] == '0') 
3016                                 {
3017                                         l = l->next;
3018                                         continue;
3019                                 }
3020                                 /* if found matching string */
3021                                 if (!strcmp(l->name, digitbuf))
3022                                         break;
3023                                 l = l->next;
3024                         }
3025                         /* if found */
3026                         if (l != &myrpt->links) 
3027                         {
3028                                 /* if already in this mode, just ignore */
3029                                 if ((!l->mode) || (!l->chan)) {
3030                                         rpt_mutex_unlock(&myrpt->lock);
3031                                         rpt_telemetry(myrpt,REMALREADY,NULL);
3032                                         return DC_COMPLETE;
3033                                         
3034                                 }
3035                                 reconnects = l->reconnects;
3036                                 rpt_mutex_unlock(&myrpt->lock);
3037                                 if (l->chan) ast_softhangup(l->chan,AST_SOFTHANGUP_DEV);
3038                                 l->retries = MAX_RETRIES + 1;
3039                                 l->disced = 2;
3040                                 modechange = 1;
3041                         } else
3042                                 rpt_mutex_unlock(&myrpt->lock);
3043                         strncpy(myrpt->lastlinknode,digitbuf,MAXNODESTR - 1);
3044                         /* establish call in monitor mode */
3045                         l = malloc(sizeof(struct rpt_link));
3046                         if (!l){
3047                                 ast_log(LOG_WARNING, "Unable to malloc\n");
3048                                 return DC_ERROR;
3049                         }
3050                         /* zero the silly thing */
3051                         memset((char *)l,0,sizeof(struct rpt_link));
3052                         snprintf(deststr, sizeof(deststr), "IAX2/%s", s1);
3053                         tele = strchr(deststr,'/');
3054                         if (!tele){
3055                                 fprintf(stderr,"link2:Dial number (%s) must be in format tech/number\n",deststr);
3056                                 return DC_ERROR;
3057                         }
3058                         *tele++ = 0;
3059                         l->isremote = (s && ast_true(s));
3060                         strncpy(l->name, digitbuf, MAXNODESTR - 1);
3061                         l->chan = ast_request(deststr,AST_FORMAT_SLINEAR,tele,NULL);
3062                         if (modechange) l->connected = 1;
3063                         if (l->chan){
3064                                 ast_set_read_format(l->chan,AST_FORMAT_SLINEAR);
3065                                 ast_set_write_format(l->chan,AST_FORMAT_SLINEAR);
3066                                 l->chan->whentohangup = 0;
3067                                 l->chan->appl = "Apprpt";
3068                                 l->chan->data = "(Remote Rx)";
3069                                 if (option_verbose > 2)
3070                                         ast_verbose(VERBOSE_PREFIX_3 "rpt (remote) initiating call to %s/%s on %s\n",
3071                                                 deststr,tele,l->chan->name);
3072                                 if(l->chan->cid.cid_num)
3073                                         free(l->chan->cid.cid_num);
3074                                 l->chan->cid.cid_num = strdup(myrpt->name);
3075                                 ast_call(l->chan,tele,0);
3076                         }
3077                         else
3078                         {
3079                                 rpt_telemetry(myrpt,CONNFAIL,l);
3080                                 free(l);
3081                                 if (option_verbose > 2)
3082                                         ast_verbose(VERBOSE_PREFIX_3 "Unable to place call to %s/%s on %s\n",
3083                                                 deststr,tele,l->chan->name);
3084                                 return DC_ERROR;
3085                         }
3086                         /* allocate a pseudo-channel thru asterisk */
3087                         l->pchan = ast_request("zap",AST_FORMAT_SLINEAR,"pseudo",NULL);
3088                         if (!l->pchan){
3089                                 fprintf(stderr,"rpt:Sorry unable to obtain pseudo channel\n");
3090                                 ast_hangup(l->chan);
3091                                 free(l);
3092                                 return DC_ERROR;
3093                         }
3094                         ast_set_read_format(l->pchan,AST_FORMAT_SLINEAR);
3095                         ast_set_write_format(l->pchan,AST_FORMAT_SLINEAR);
3096                         /* make a conference for the pseudo-one */
3097                         ci.chan = 0;
3098                         ci.confno = myrpt->conf;
3099                         ci.confmode = ZT_CONF_CONF | ZT_CONF_LISTENER | ZT_CONF_TALKER;
3100                         /* first put the channel on the conference in proper mode */
3101                         if (ioctl(l->pchan->fds[0],ZT_SETCONF,&ci) == -1)
3102                         {
3103                                 ast_log(LOG_WARNING, "Unable to set conference mode to Announce\n");
3104                                 ast_hangup(l->chan);
3105                                 ast_hangup(l->pchan);
3106                                 free(l);
3107                                 return DC_ERROR;
3108                         }