All better now!
[asterisk/asterisk.git] / apps / app_followme.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * A full-featured Find-Me/Follow-Me Application
5  * 
6  * Copyright (C) 2005-2006, BJ Weschke All Rights Reserved.
7  *
8  * BJ Weschke <bweschke@btwtech.com>
9  *
10  * This code is released by the author with no restrictions on usage.
11  *
12  * See http://www.asterisk.org for more information about
13  * the Asterisk project. Please do not directly contact
14  * any of the maintainers of this project for assistance;
15  * the project provides a web site, mailing lists and IRC
16  * channels for your use.
17  *
18  */
19
20 /*! \file
21  *
22  * \brief Find-Me Follow-Me application
23  *
24  * \author BJ Weschke <bweschke@btwtech.com>
25  *
26  * \ingroup applications
27  */
28
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <signal.h>
35
36 #include "asterisk.h"
37
38 ASTERISK_FILE_VERSION(__FILE__, "$revision$")
39
40 #include "asterisk/lock.h"
41 #include "asterisk/file.h"
42 #include "asterisk/logger.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/options.h"
46 #include "asterisk/module.h"
47 #include "asterisk/translate.h"
48 #include "asterisk/say.h"
49 #include "asterisk/features.h"
50 #include "asterisk/musiconhold.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/manager.h"
53 #include "asterisk/config.h"
54 #include "asterisk/monitor.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/causes.h"
57 #include "asterisk/astdb.h"
58 #include "asterisk/app.h"
59
60 static char *app = "FollowMe";
61 static char *synopsis = 
62 "Find-Me/Follow-Me.";
63 static char *descrip = 
64 "  FollowMe(followmeid|options):\n"
65 "This application performs Find-Me/Follow-Me functionality for the caller\n"
66 "as defined in the profile matching the <followmeid> parameter in\n"
67 "followme.conf. If the specified <followmeid> profile doesn't exist in\n"
68 "followme.conf, execution will be returned to the dialplan and call\n"
69 "execution will continue at the next priority.\n\n"
70 "  Options:\n"
71 "    s    - Playback the incoming status message prior to starting the follow-me step(s)\n"
72 "    a    - Record the caller's name so it can be announced to the callee on each step\n" 
73 "    n    - Playback the unreachable status message if we've run out of steps to reach the\n"
74 "           or the callee has elected not to be reachable.\n" 
75
76
77 LOCAL_USER_DECL;
78
79 struct number {
80         char number[512];       /*!< Phone Number(s) and/or Extension(s) */
81         long timeout;           /*!< Dial Timeout, if used. */
82         int order;              /*!< The order to dial in */
83         AST_LIST_ENTRY(number) entry; /*!< Next Number record */
84 };
85
86 struct ast_call_followme {
87         ast_mutex_t lock;
88         char name[AST_MAX_EXTENSION];   /*!< Name - FollowMeID */
89         char moh[AST_MAX_CONTEXT];      /*!< Music On Hold Class to be used */
90         char context[AST_MAX_CONTEXT];  /*!< Context to dial from */
91         unsigned int active;            /*!< Profile is active (1), or disabled (0). */
92         char takecall[20];              /*!< Digit mapping to take a call */
93         char nextindp[20];              /*!< Digit mapping to decline a call */
94         char callfromprompt[AST_CONFIG_MAX_PATH];
95         char norecordingprompt[AST_CONFIG_MAX_PATH];
96         char optionsprompt[AST_CONFIG_MAX_PATH];
97         char plsholdprompt[AST_CONFIG_MAX_PATH];
98         char statusprompt[AST_CONFIG_MAX_PATH];
99         char sorryprompt[AST_CONFIG_MAX_PATH];
100
101         AST_LIST_HEAD_NOLOCK(numbers, number) numbers;     /*!< Head of the list of follow-me numbers */
102         AST_LIST_HEAD_NOLOCK(blnumbers, number) blnumbers; /*!< Head of the list of black-listed numbers */
103         AST_LIST_HEAD_NOLOCK(wlnumbers, number) wlnumbers; /*!< Head of the list of white-listed numbers */
104         AST_LIST_ENTRY(ast_call_followme) entry;           /*!< Next Follow-Me record */
105 };
106
107 struct fm_args {
108         struct ast_channel *chan;
109         char *mohclass;
110         AST_LIST_HEAD_NOLOCK(cnumbers, number) cnumbers;
111         int status;
112         char context[AST_MAX_CONTEXT];
113         char namerecloc[AST_MAX_CONTEXT];
114         struct ast_channel *outbound;
115         char takecall[20];              /*!< Digit mapping to take a call */
116         char nextindp[20];              /*!< Digit mapping to decline a call */
117         char callfromprompt[AST_CONFIG_MAX_PATH];
118         char norecordingprompt[AST_CONFIG_MAX_PATH];
119         char optionsprompt[AST_CONFIG_MAX_PATH];
120         char plsholdprompt[AST_CONFIG_MAX_PATH];
121         char statusprompt[AST_CONFIG_MAX_PATH];
122         char sorryprompt[AST_CONFIG_MAX_PATH];
123         struct ast_flags followmeflags;
124 };
125
126 struct findme_user {
127         struct ast_channel *ochan;
128         int state;
129         char dialarg[256];
130         char yn[10];
131         int ynidx; 
132         long digts;
133         int cleared;
134         AST_LIST_ENTRY(findme_user) entry;      
135 };
136
137 enum {
138         FOLLOWMEFLAG_STATUSMSG = (1 << 0),
139         FOLLOWMEFLAG_RECORDNAME = (1 << 1),
140         FOLLOWMEFLAG_UNREACHABLEMSG = (1 << 2)
141 };
142
143 AST_APP_OPTIONS(followme_opts, {
144         AST_APP_OPTION('s', FOLLOWMEFLAG_STATUSMSG ),
145         AST_APP_OPTION('a', FOLLOWMEFLAG_RECORDNAME ),
146         AST_APP_OPTION('n', FOLLOWMEFLAG_UNREACHABLEMSG ),
147 });
148
149 static int ynlongest = 0;
150 static char toast[80];
151 static time_t start_time, answer_time, end_time;
152
153 static char *featuredigittostr;
154 static int featuredigittimeout = 5000;          /*!< Feature Digit Timeout */
155 static const char *defaultmoh = "default";      /*!< Default Music-On-Hold Class */
156
157 static char takecall[20] = "1", nextindp[20] = "2";
158 static char callfromprompt[AST_CONFIG_MAX_PATH] = "followme/call-from";
159 static char norecordingprompt[AST_CONFIG_MAX_PATH] = "followme/no-recording";
160 static char optionsprompt[AST_CONFIG_MAX_PATH] = "followme/followme-options";
161 static char plsholdprompt[AST_CONFIG_MAX_PATH] = "followme/pls-hold-while-try";
162 static char statusprompt[AST_CONFIG_MAX_PATH] = "followme/followme-status";
163 static char sorryprompt[AST_CONFIG_MAX_PATH] = "followme/followme-sorry";
164
165
166 static AST_LIST_HEAD_STATIC(followmes, ast_call_followme);
167 AST_LIST_HEAD_NOLOCK(findme_user_listptr, findme_user);
168
169 static void free_numbers(struct ast_call_followme *f)
170 {
171         /* Free numbers attached to the profile */
172         struct number *prev;
173
174         while ((prev = AST_LIST_REMOVE_HEAD(&f->numbers, entry)))
175                 /* Free the number */
176                 free(prev);
177         AST_LIST_HEAD_INIT_NOLOCK(&f->numbers);
178
179         while ((prev = AST_LIST_REMOVE_HEAD(&f->blnumbers, entry)))
180                 /* Free the blacklisted number */
181                 free(prev);
182         AST_LIST_HEAD_INIT_NOLOCK(&f->blnumbers);
183
184         while ((prev = AST_LIST_REMOVE_HEAD(&f->wlnumbers, entry)))
185                 /* Free the whitelisted number */
186                 free(prev);
187         AST_LIST_HEAD_INIT_NOLOCK(&f->wlnumbers);
188         
189 }
190
191
192 static struct ast_call_followme *alloc_profile(const char *fmname)
193 {
194         struct ast_call_followme *f;
195
196         f = ast_calloc(1, sizeof(*f));
197         if (f) {
198                 ast_mutex_init(&f->lock);
199                 ast_copy_string(f->name, fmname, sizeof(f->name));
200                 ast_copy_string(f->moh, "", sizeof(f->moh));
201                 ast_copy_string(f->context, "", sizeof(f->context));
202                 ast_copy_string(f->takecall, takecall, sizeof(f->takecall));
203                 ast_copy_string(f->nextindp, nextindp, sizeof(f->nextindp));
204                 ast_copy_string(f->callfromprompt, callfromprompt, sizeof(f->callfromprompt));
205                 ast_copy_string(f->norecordingprompt, norecordingprompt, sizeof(f->norecordingprompt));
206                 ast_copy_string(f->optionsprompt, optionsprompt, sizeof(f->optionsprompt));
207                 ast_copy_string(f->plsholdprompt, plsholdprompt, sizeof(f->plsholdprompt));
208                 ast_copy_string(f->statusprompt, statusprompt, sizeof(f->statusprompt));
209                 ast_copy_string(f->sorryprompt, sorryprompt, sizeof(f->sorryprompt));
210                 AST_LIST_HEAD_INIT_NOLOCK(&f->numbers);
211                 AST_LIST_HEAD_INIT_NOLOCK(&f->blnumbers);
212                 AST_LIST_HEAD_INIT_NOLOCK(&f->wlnumbers);
213         }
214         return f;
215 }
216
217 static void init_profile(struct ast_call_followme *f)
218 {
219         f->active = 1;
220         ast_copy_string(f->moh, defaultmoh, sizeof(f->moh));
221 }
222
223    
224    
225 static void profile_set_param(struct ast_call_followme *f, const char *param, const char *val, int linenum, int failunknown)
226 {
227
228         if (!strcasecmp(param, "musicclass") || !strcasecmp(param, "musiconhold") || !strcasecmp(param, "music")) 
229                 ast_copy_string(f->moh, val, sizeof(f->moh));
230         else if (!strcasecmp(param, "context")) {
231                 ast_copy_string(f->context, val, sizeof(f->context));
232         } else if (!strcasecmp(param, "takecall")) {
233                 ast_copy_string(f->takecall, val, sizeof(f->takecall));
234         } else if (!strcasecmp(param, "declinecall")) {
235                 ast_copy_string(f->nextindp, val, sizeof(f->nextindp));
236         } else if (!strcasecmp(param, "call-from-prompt")) {
237                 ast_copy_string(f->callfromprompt, val, sizeof(f->callfromprompt));
238         } else if (!strcasecmp(param, "followme-recording-prompt")) {
239                 ast_copy_string(f->norecordingprompt, val, sizeof(f->norecordingprompt));
240         } else if (!strcasecmp(param, "followme-options-prompt")) {
241                 ast_copy_string(f->optionsprompt, val, sizeof(f->optionsprompt));
242         } else if (!strcasecmp(param, "followme-pls-hold-prompt")) {
243                 ast_copy_string(f->plsholdprompt, val, sizeof(f->plsholdprompt));
244         } else if (!strcasecmp(param, "followme-status-prompt")) {
245                 ast_copy_string(f->statusprompt, val, sizeof(f->statusprompt));
246         } else if (!strcasecmp(param, "followme-sorry-prompt")) {
247                 ast_copy_string(f->sorryprompt, val, sizeof(f->sorryprompt));
248         } else if (failunknown) {
249                 if (linenum >= 0)
250                         ast_log(LOG_WARNING, "Unknown keyword in profile '%s': %s at line %d of followme.conf\n", f->name, param, linenum);
251                 else
252                         ast_log(LOG_WARNING, "Unknown keyword in profile '%s': %s\n", f->name, param);
253         }
254 }
255
256 static struct number *create_followme_number(char *number, int timeout, int numorder)
257 {
258         struct number *cur;
259         char *tmp;
260         
261         /* Add a new number */
262
263         cur = ast_calloc(1, sizeof(*cur));
264
265         if (cur) {
266                 cur->timeout = timeout;
267                 if (strchr(number, ',')) { 
268                         tmp = strchr(number, ',');
269                         *tmp = '\0';
270                 }
271                 ast_copy_string(cur->number, number, sizeof(cur->number));
272                 cur->order = numorder;
273                 if (option_debug)
274                         ast_log(LOG_DEBUG, "Created a number, %s, order of , %d, with a timeout of %ld.\n", cur->number, cur->order, cur->timeout);
275         }
276
277         return cur;
278 }
279
280 static int reload_followme(void)
281 {
282         struct ast_call_followme *f;
283         struct ast_config *cfg;
284         char *cat, *tmp;
285         struct ast_variable *var;
286         struct number *cur, *nm;
287         int new, idx;
288         char numberstr[90];
289         int timeout;
290         char *timeoutstr;
291         int numorder;   
292         char *takecallstr;
293         char *declinecallstr;
294         char *tmpstr;
295
296         cfg = ast_config_load("followme.conf");
297         if (!cfg) {
298                 ast_log(LOG_WARNING, "No follow me config file (followme.conf), so no follow me\n");
299                 return 0;
300         }
301
302         AST_LIST_LOCK(&followmes);
303
304         /* Reset Global Var Values */
305         featuredigittimeout = 5000;
306
307         /* Mark all profiles as inactive for the moment */
308         AST_LIST_TRAVERSE(&followmes, f, entry) {
309                 f->active = 0;
310         }
311         featuredigittostr = ast_variable_retrieve(cfg, "general", "featuredigittimeout");
312         
313         if (!ast_strlen_zero(featuredigittostr)) 
314                 if (!scanf("%d", &featuredigittimeout))
315                         featuredigittimeout = 5000;
316
317         takecallstr = ast_variable_retrieve(cfg, "general", "takecall");
318         if (!ast_strlen_zero(takecallstr))
319                 ast_copy_string(takecall, takecallstr, sizeof(takecall));
320         
321         declinecallstr = ast_variable_retrieve(cfg, "general", "declinecall");
322         if (!ast_strlen_zero(declinecallstr))
323                 ast_copy_string(nextindp, declinecallstr, sizeof(nextindp));
324
325         tmpstr = ast_variable_retrieve(cfg, "general", "call-from-prompt");
326         if (!ast_strlen_zero(tmpstr))
327                 ast_copy_string(callfromprompt, tmpstr, sizeof(callfromprompt));
328
329         tmpstr = ast_variable_retrieve(cfg, "general", "followme-norecording-prompt");
330         if (!ast_strlen_zero(tmpstr))
331                 ast_copy_string(norecordingprompt, tmpstr, sizeof(norecordingprompt));
332
333         tmpstr = ast_variable_retrieve(cfg, "general", "followme-options-prompt");
334         if (!ast_strlen_zero(tmpstr))
335                 ast_copy_string(optionsprompt, tmpstr, sizeof(optionsprompt));
336
337         tmpstr = ast_variable_retrieve(cfg, "general", "followme-pls-hold-prompt");
338         if (!ast_strlen_zero(tmpstr))
339                 ast_copy_string(plsholdprompt, tmpstr, sizeof(plsholdprompt));
340
341         tmpstr = ast_variable_retrieve(cfg, "general", "followme-status-prompt");
342         if (!ast_strlen_zero(tmpstr))
343                 ast_copy_string(statusprompt, tmpstr, sizeof(statusprompt));
344
345         tmpstr = ast_variable_retrieve(cfg, "general", "followme-sorry-prompt");
346         if (!ast_strlen_zero(tmpstr))
347                 ast_copy_string(sorryprompt, tmpstr, sizeof(sorryprompt));
348
349         /* Chug through config file */
350         cat = ast_category_browse(cfg, NULL);
351         while(cat) {
352                 /* Define a new profile */
353                 /* Look for an existing one */
354                 AST_LIST_TRAVERSE(&followmes, f, entry) {
355                         if (!strcasecmp(f->name, cat))
356                                 break;
357                 }
358                 if (option_debug)
359                         ast_log(LOG_DEBUG, "New profile %s.\n", cat);
360                 if (!f) {
361                         /* Make one then */
362                         f = alloc_profile(cat);
363                         new = 1;
364                 } else
365                         new = 0;
366         
367                 if (f) {
368                         if (!new)
369                                 ast_mutex_lock(&f->lock);
370                         /* Re-initialize the profile */
371                         init_profile(f);
372                         free_numbers(f);
373                         var = ast_variable_browse(cfg, cat);
374                         while(var) {
375                                 if (!strcasecmp(var->name, "number")) {
376                                         /* Add a new number */
377                                         ast_copy_string(numberstr, var->value, sizeof(numberstr));
378                                         if ((tmp = strchr(numberstr, ','))) {
379                                                 *tmp = '\0';
380                                                 tmp++;
381                                                 timeoutstr = ast_strdupa(tmp);
382                                                 if ((tmp = strchr(timeoutstr, ','))) {
383                                                         *tmp = '\0';
384                                                         tmp++;
385                                                         numorder = atoi(tmp);
386                                                         if (numorder < 0)
387                                                                 numorder = 0;
388                                                 } else 
389                                                         numorder = 0;
390                                                 timeout = atoi(timeoutstr);
391                                                 if (timeout < 0) 
392                                                         timeout = 25;
393                                         } else {
394                                                 timeout = 25;
395                                                 numorder = 0;
396                                         }
397
398                                         if (!numorder) {        
399                                                 idx = 1;
400                                                 AST_LIST_TRAVERSE(&f->numbers, nm, entry) 
401                                                         idx++;
402                                                 numorder = idx;
403                                         }
404                                         cur = create_followme_number(numberstr, timeout, numorder);
405                                         AST_LIST_INSERT_TAIL(&f->numbers, cur, entry);
406                                 } else {
407                                         profile_set_param(f, var->name, var->value, var->lineno, 1);
408                                         if (option_debug)
409                                                 ast_log(LOG_DEBUG, "Logging parameter %s with value %s from lineno %d\n", var->name, var->value, var->lineno);
410                                 }
411                                 var = var->next;
412                         } /* End while(var) loop */
413
414                         if (!new) 
415                                 ast_mutex_unlock(&f->lock);
416                         if (new) {
417                                 AST_LIST_INSERT_HEAD(&followmes, f, entry);
418                         }
419                 }
420                 cat = ast_category_browse(cfg, cat);
421         }
422         ast_config_destroy(cfg);
423
424         AST_LIST_UNLOCK(&followmes);
425
426         return 1;
427 }
428
429 static void clear_caller(struct findme_user *tmpuser)
430 {
431         struct ast_channel *outbound;
432         
433         if (tmpuser && tmpuser->ochan && tmpuser->state >= 0) {
434                 outbound = tmpuser->ochan;
435                 if (!outbound->cdr) {
436                         outbound->cdr = ast_cdr_alloc();
437                         if (outbound->cdr)
438                                 ast_cdr_init(outbound->cdr, outbound);
439                 }
440                 if (outbound->cdr) {
441                         char tmp[256];
442                         snprintf(tmp, 256, "%s/%s", "Local", tmpuser->dialarg);
443                         ast_cdr_setapp(outbound->cdr,"FollowMe",tmp);
444                         ast_cdr_update(outbound);
445                         ast_cdr_start(outbound->cdr);
446                         ast_cdr_end(outbound->cdr);
447                         /* If the cause wasn't handled properly */
448                         if (ast_cdr_disposition(outbound->cdr,outbound->hangupcause))
449                                 ast_cdr_failed(outbound->cdr);
450                 } else
451                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
452                 ast_hangup(tmpuser->ochan);
453         }
454
455 }
456
457 static void clear_calling_tree(struct findme_user_listptr *findme_user_list) 
458 {
459         struct findme_user *tmpuser;
460         
461         AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
462                 clear_caller(tmpuser);
463                 tmpuser->cleared = 1;
464         }
465         
466 }
467
468
469
470 static struct ast_channel *wait_for_winner(struct findme_user_listptr *findme_user_list, struct number *nm, struct ast_channel *caller, char *namerecloc, int *status, struct fm_args *tpargs) 
471 {
472         struct ast_channel *watchers[256];
473         int pos;
474         struct ast_channel *winner;
475         struct ast_frame *f;
476         int ctstatus;
477         int dg;
478         struct findme_user *tmpuser;
479         int *to = ast_calloc(1, sizeof(*to));
480         int livechannels = 0;
481         int tmpto;
482         long totalwait = 0, wtd, towas = *to;
483         char *callfromname;
484         char *pressbuttonname;
485
486         /* ------------ wait_for_winner_channel start --------------- */ 
487
488         callfromname = ast_strdupa(tpargs->callfromprompt);
489         pressbuttonname = ast_strdupa(tpargs->optionsprompt);   
490
491         if (!AST_LIST_EMPTY(findme_user_list))
492         {
493                 if (!caller) {
494                         if (option_verbose > 2)
495                                 ast_verbose(VERBOSE_PREFIX_3 "Original caller hungup. Cleanup.\n");
496                         clear_calling_tree(findme_user_list);
497                         free(to);
498                         return NULL;
499                 }
500                 ctstatus = 0;
501                 totalwait = nm->timeout * 1000;
502                 wtd = 0;
503                 while (!ctstatus) {
504                         *to = 1000;
505                         pos = 1; 
506                         livechannels = 0;
507                         watchers[0] = caller;
508                 
509                         dg = 0; 
510                         winner = NULL;  
511                         AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry) {
512                                 if (tmpuser->state >= 0 && tmpuser->ochan) {
513                                         if (tmpuser->state == 3) {
514                                                 tmpuser->digts += (towas - wtd);
515                                         }
516                                         if (tmpuser->digts && (tmpuser->digts > featuredigittimeout)) {
517                                                 if (option_verbose > 2)
518                                                         ast_verbose(VERBOSE_PREFIX_3 "We've been waiting for digits longer than we should have.\n");
519                                                 if (!ast_strlen_zero(namerecloc)) {
520                                                         tmpuser->state = 1;
521                                                         tmpuser->digts = 0;
522                                                         if (!ast_streamfile(tmpuser->ochan, callfromname, tmpuser->ochan->language)) {
523                                                                 ast_sched_runq(tmpuser->ochan->sched);
524                                                         } else {
525                                                                 ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
526                                                                 free(to);
527                                                                 return NULL;
528                                                         }                                                       
529                                                 } else {
530                                                         tmpuser->state = 2;
531                                                         tmpuser->digts = 0;
532                                                         if (!ast_streamfile(tmpuser->ochan, tpargs->norecordingprompt, tmpuser->ochan->language))
533                                                                 ast_sched_runq(tmpuser->ochan->sched);
534                                                         else {
535                                                                 ast_log(LOG_WARNING, "Unable to playback %s.\n", tpargs->norecordingprompt);
536                                                                 free(to);
537                                                                 return NULL;
538                                                         }
539                                                 }
540                                         }
541                                         if (tmpuser->ochan->stream) {
542                                                 ast_sched_runq(tmpuser->ochan->sched);
543                                                 tmpto = ast_sched_wait(tmpuser->ochan->sched);
544                                                 if (tmpto > 0 && tmpto < *to)
545                                                         *to = tmpto;
546                                                 else if (tmpto < 0 && !tmpuser->ochan->timingfunc) {
547                                                         ast_stopstream(tmpuser->ochan);
548                                                         if (tmpuser->state == 1) {
549                                                                 if (option_verbose > 2)
550                                                                         ast_verbose(VERBOSE_PREFIX_3 "Playback of the call-from file appears to be done.\n");
551                                                                 if (!ast_streamfile(tmpuser->ochan, namerecloc, tmpuser->ochan->language)) {
552                                                                         tmpuser->state = 2;
553                                                                 } else {
554                                                                         ast_log(LOG_NOTICE, "Unable to playback %s. Maybe the caller didn't record their name?\n", namerecloc);
555                                                                         memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
556                                                                         tmpuser->ynidx = 0;
557                                                                         if (!ast_streamfile(tmpuser->ochan, pressbuttonname, tmpuser->ochan->language))
558                                                                                 tmpuser->state = 3;
559                                                                         else {
560                                                                                 ast_log(LOG_WARNING, "Unable to playback %s.\n", pressbuttonname);
561                                                                                 free(to);
562                                                                                 return NULL;
563                                                                         } 
564                                                                 }
565                                                         } else if (tmpuser->state == 2) {
566                                                                 if (option_verbose > 2)
567                                                                         ast_verbose(VERBOSE_PREFIX_3 "Playback of name file appears to be done.\n");
568                                                                 memset(tmpuser->yn, 0, sizeof(tmpuser->yn));
569                                                                 tmpuser->ynidx = 0;
570                                                                 if (!ast_streamfile(tmpuser->ochan, pressbuttonname, tmpuser->ochan->language)) {
571                                                                         tmpuser->state = 3;
572                                                                         
573                                                                 } else {
574                                                                         ast_log(LOG_WARNING, "Unable to playback %s.\n", pressbuttonname);                                                                                free(to);
575                                                                         return NULL;
576                                                                 } 
577                                                         } else if (tmpuser->state == 3) {
578                                                                 if (option_verbose > 2)
579                                                                         ast_verbose(VERBOSE_PREFIX_3 "Playback of the next step file appears to be done.\n");
580                                                                 tmpuser->digts = 0;
581                                                         }
582                                                 }
583                                         }
584                                 watchers[pos++] = tmpuser->ochan;
585                                 livechannels++;
586                                 }
587                         }
588
589                         tmpto = *to;
590                         if (*to < 0) {
591                                 *to = 1000;
592                                 tmpto = 1000;
593                         }
594                         towas = *to;
595                         winner = ast_waitfor_n(watchers, pos, to);
596                         tmpto -= *to;
597                         totalwait -= tmpto;
598                         wtd = *to;      
599                         if (totalwait <= 0) {
600                                 if (option_verbose > 2) 
601                                         ast_verbose(VERBOSE_PREFIX_3 "We've hit our timeout for this step. Drop everyone and move on to the next one. %ld\n", totalwait);
602                                 clear_calling_tree(findme_user_list);
603                                 free(to);
604                                 return NULL;
605                         }
606                         if (winner) {
607                                 /* Need to find out which channel this is */
608                                 dg = 0;
609                                 while ((winner != watchers[dg]) && (dg < 256))
610                                         dg++;
611                                 AST_LIST_TRAVERSE(findme_user_list, tmpuser, entry)
612                                         if (tmpuser->ochan == winner)
613                                                 break;
614                                 f = ast_read(winner);
615                                 if (f) {
616                                         if (f->frametype == AST_FRAME_CONTROL) {
617                                                 switch(f->subclass) {
618                                                 case AST_CONTROL_HANGUP:
619                                                         if (option_verbose > 2)
620                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s received a hangup frame.\n", winner->name);
621                                                         if (dg == 0) {
622                                                                 if (option_verbose > 2)
623                                                                         ast_verbose( VERBOSE_PREFIX_3 "The calling channel hungup. Need to drop everyone else.\n");
624                                                                 clear_calling_tree(findme_user_list);
625                                                                 ctstatus = -1;
626                                                         }
627                                                         break;
628                                                 case AST_CONTROL_ANSWER:
629                                                         if (option_verbose > 2)
630                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", winner->name, caller->name);
631                                                         /* If call has been answered, then the eventual hangup is likely to be normal hangup */ 
632                                                         winner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
633                                                         caller->hangupcause = AST_CAUSE_NORMAL_CLEARING;
634                                                         if (option_verbose > 2)
635                                                                 ast_verbose( VERBOSE_PREFIX_3 "Starting playback of %s\n", callfromname);
636                                                         if (dg > 0) {
637                                                                 if (!ast_strlen_zero(namerecloc)) {
638                                                                         if (!ast_streamfile(winner, callfromname, winner->language)) {
639                                                                                 ast_sched_runq(winner->sched);
640                                                                                 tmpuser->state = 1;
641                                                                         } else {
642                                                                                 ast_log(LOG_WARNING, "Unable to playback %s.\n", callfromname);
643                                                                                 free(to);
644                                                                                 return NULL;
645                                                                         }                               
646                                                                 } else {                        
647                                                                         tmpuser->state = 2;
648                                                                         if (!ast_streamfile(tmpuser->ochan, tpargs->norecordingprompt, tmpuser->ochan->language))
649                                                                                 ast_sched_runq(tmpuser->ochan->sched);
650                                                                         else {
651                                                                                 ast_log(LOG_WARNING, "Unable to playback %s.\n", tpargs->norecordingprompt);
652                                                                                 free(to);
653                                                                                 return NULL;
654                                                                         }
655                                                                 }
656                                                         }
657                                                         break;
658                                                 case AST_CONTROL_BUSY:
659                                                         if (option_verbose > 2)
660                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", winner->name);
661                                                         break;
662                                                 case AST_CONTROL_CONGESTION:
663                                                         if (option_verbose > 2)
664                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", winner->name);
665                                                         break;
666                                                 case AST_CONTROL_RINGING:
667                                                         if (option_verbose > 2)
668                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", winner->name);
669                                                         break;
670                                                 case AST_CONTROL_PROGRESS:
671                                                         if (option_verbose > 2)
672                                                                 ast_verbose ( VERBOSE_PREFIX_3 "%s is making progress passing it to %s\n", winner->name,caller->name);
673                                                         break;
674                                                 case AST_CONTROL_VIDUPDATE:
675                                                         if (option_verbose > 2)
676                                                                 ast_verbose ( VERBOSE_PREFIX_3 "%s requested a video update, passing it to %s\n", winner->name,caller->name);
677                                                         break;
678                                                 case AST_CONTROL_PROCEEDING:
679                                                         if (option_verbose > 2)
680                                                                 ast_verbose ( VERBOSE_PREFIX_3 "%s is proceeding passing it to %s\n", winner->name,caller->name);
681                                                         break;
682                                                 case AST_CONTROL_HOLD:
683                                                         if (option_verbose > 2)
684                                                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s placed on hold\n", winner->name);
685                                                         break;
686                                                 case AST_CONTROL_UNHOLD:
687                                                         if (option_verbose > 2)
688                                                                 ast_verbose(VERBOSE_PREFIX_3 "Call on %s left from hold\n", winner->name);
689                                                         break;
690                                                 case AST_CONTROL_OFFHOOK:
691                                                 case AST_CONTROL_FLASH:
692                                                         /* Ignore going off hook and flash */
693                                                         break;
694                                                 case -1:
695                                                         if (option_verbose > 2)
696                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s stopped sounds\n", winner->name);
697                                                         break;
698                                                 default:
699                                                         if (option_debug)
700                                                                 ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
701                                                         break;
702                                                 }
703                                         } 
704                                         if (tmpuser && tmpuser->state == 3 && f->frametype == AST_FRAME_DTMF) {
705                                                 if (winner->stream)
706                                                         ast_stopstream(winner);
707                                                         tmpuser->digts = 0;
708                                                 if (option_debug)
709                                                         ast_log(LOG_DEBUG, "DTMF received: %c\n",(char) f->subclass);
710                                                 tmpuser->yn[tmpuser->ynidx] = (char) f->subclass;
711                                                 tmpuser->ynidx++;
712                                                 if (option_debug)
713                                                         ast_log(LOG_DEBUG, "DTMF string: %s\n", tmpuser->yn);
714                                                 if (tmpuser->ynidx >= ynlongest) {
715                                                         if (option_debug)
716                                                                 ast_log(LOG_DEBUG, "reached longest possible match - doing evals\n");
717                                                         if (!strcmp(tmpuser->yn, tpargs->takecall)) {
718                                                                 if (option_debug)
719                                                                         ast_log(LOG_DEBUG, "Match to take the call!\n");
720                                                                 free(to);
721                                                                 return tmpuser->ochan;  
722                                                         }
723                                                         if (!strcmp(tmpuser->yn, tpargs->nextindp)) {
724                                                                 if (option_debug)
725                                                                         ast_log(LOG_DEBUG, "Next in dial plan step requested.\n");
726                                                                 *status = 1;
727                                                                 free(to);
728                                                                 return NULL;
729                                                         }       
730
731                                                 }
732                                         }
733                                         
734                                         ast_frfree(f);
735                                 } else {
736                                         if (winner) {
737                                                 if (option_debug)
738                                                         ast_log(LOG_DEBUG, "we didn't get a frame. hanging up. dg is %d\n",dg);                                       
739                                                 if (!dg) {
740                                                         clear_calling_tree(findme_user_list);
741                                                         free(to);
742                                                         return NULL;
743                                                 } else {
744                                                         tmpuser->state = -1;
745                                                         ast_hangup(winner);  
746                                                         livechannels--;
747                                                         if (option_debug)
748                                                                 ast_log(LOG_DEBUG, "live channels left %d\n", livechannels);
749                                                         if (!livechannels) {
750                                                                 if (option_verbose > 2)
751                                                                         ast_verbose(VERBOSE_PREFIX_3 "no live channels left. exiting.\n");
752                                                                 free(to);
753                                                                 return NULL;
754                                                         }
755                                                 }
756                                         }
757                                 }                                       
758                                 
759                         } else
760                                 if (option_debug)
761                                         ast_log(LOG_DEBUG, "timed out waiting for action\n");
762                 }
763                 
764         }
765         else
766         {
767                 if (option_verbose > 2)
768                         ast_verbose(VERBOSE_PREFIX_3 "couldn't reach at this number.\n");
769         }
770         
771         /* --- WAIT FOR WINNER NUMBER END! -----------*/
772         free(to);
773         return NULL;
774 }
775
776 static void findmeexec(void *args)
777 {
778         struct fm_args *tpargs;
779         struct number *nm;
780         struct ast_channel *outbound;
781         struct ast_channel *caller;
782         struct ast_channel *winner = NULL;
783         char dialarg[512];
784         int dg, idx;
785         char *rest, *number;
786         struct findme_user *tmpuser;
787         struct findme_user *fmuser;
788         struct findme_user *headuser;
789         struct findme_user_listptr *findme_user_list;
790         int status;
791
792         findme_user_list = ast_calloc(1, sizeof(*findme_user_list));            
793         AST_LIST_HEAD_INIT_NOLOCK(findme_user_list);
794
795         tpargs = (struct fm_args *)args;
796                         
797         if (!tpargs->chan) 
798                 return;
799         
800
801         /* We're going to figure out what the longest possible string of digits to collect is */
802         ynlongest = 0;
803         if (strlen(tpargs->takecall) > ynlongest)
804                 ynlongest = strlen(tpargs->takecall);
805         if (strlen(tpargs->nextindp) > ynlongest)
806                 ynlongest = strlen(tpargs->nextindp);
807
808         idx = 1;
809         caller = tpargs->chan;
810         AST_LIST_TRAVERSE(&tpargs->cnumbers, nm, entry)
811                 if (nm->order == idx)
812                         break;
813
814         while (nm) {
815
816                 if (option_debug)       
817                         ast_log(LOG_DEBUG, "Number %s timeout %ld\n",nm->number,nm->timeout);
818                 time(&start_time);
819
820                 number = ast_strdupa(nm->number);
821                 if (option_debug)
822                         ast_log(LOG_DEBUG, "examining %s\n", number);
823                 do {
824                         rest = strchr(number, '&');
825                         if (rest) {
826                                 *rest = 0;
827                                 rest++;
828                         }
829
830                         if (!strcmp(tpargs->context, ""))
831                                 sprintf(dialarg, "%s", number);
832                         else
833                                 sprintf(dialarg, "%s@%s", number, tpargs->context);
834                                         
835                         tmpuser = ast_calloc(1, sizeof(*tmpuser));
836                         if (!tmpuser) {
837                                 ast_log(LOG_WARNING, "Out of memory!\n");
838                                 return;
839                         }
840                                         
841                         outbound = ast_request("Local", ast_best_codec(caller->nativeformats), dialarg, &dg);
842                         if (outbound) {
843                                 ast_set_callerid(outbound, caller->cid.cid_num, caller->cid.cid_name, caller->cid.cid_num);
844                                 ast_channel_inherit_variables(tpargs->chan, outbound);
845                                 if (option_verbose > 2)
846                                         ast_verbose(VERBOSE_PREFIX_3 "calling %s\n", dialarg);
847                                 if (!ast_call(outbound,dialarg,0)) {
848                                         tmpuser->ochan = outbound;
849                                         tmpuser->state = 0;
850                                         tmpuser->cleared = 0;
851                                         ast_copy_string(tmpuser->dialarg, dialarg, sizeof(dialarg));
852                                         AST_LIST_INSERT_TAIL(findme_user_list, tmpuser, entry);
853                                 } else {
854                                         if (option_verbose > 2) 
855                                                 ast_verbose(VERBOSE_PREFIX_3 "couldn't reach at this number.\n"); 
856                                         if (outbound) {
857                                                 if (!outbound->cdr) {
858                                                         outbound->cdr = ast_cdr_alloc();
859                                                 }
860                                                 if (outbound->cdr) {
861                                                         ast_cdr_init(outbound->cdr, outbound);
862                                                         char tmp[256];
863                                                         snprintf(tmp, 256, "%s/%s", "Local", dialarg);
864                                                         ast_cdr_setapp(outbound->cdr,"FollowMe",tmp);
865                                                         ast_cdr_update(outbound);
866                                                         ast_cdr_start(outbound->cdr);
867                                                         ast_cdr_end(outbound->cdr);
868                                                         /* If the cause wasn't handled properly */
869                                                         if (ast_cdr_disposition(outbound->cdr,outbound->hangupcause))
870                                                                 ast_cdr_failed(outbound->cdr);
871                                                 } else {
872                                                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
873                                                         ast_hangup(outbound);
874                                                         outbound = NULL;
875                                                 }
876                                         }
877                                                 
878                                 }
879                         } else 
880                                 ast_log(LOG_WARNING, "Unable to allocate a channel for Local/%s cause: %s\n", dialarg, ast_cause2str(dg));
881                                         
882                         number = rest;
883                 } while (number);
884                                 
885                 status = 0;     
886                 if (!AST_LIST_EMPTY(findme_user_list))
887                         winner = wait_for_winner(findme_user_list, nm, caller, tpargs->namerecloc, &status, tpargs);
888                 
889                                         
890                 AST_LIST_TRAVERSE_SAFE_BEGIN(findme_user_list, fmuser, entry) {
891                         if (!fmuser->cleared && fmuser->ochan != winner)
892                                 clear_caller(fmuser);
893                         AST_LIST_REMOVE_CURRENT(findme_user_list, entry);
894                         free(fmuser);
895                 }
896                 AST_LIST_TRAVERSE_SAFE_END
897                 fmuser = NULL;
898                 tmpuser = NULL;
899                 headuser = NULL;        
900                 if (winner)
901                         break;
902
903                 if (!caller) {
904                         tpargs->status = 1;
905                         return; 
906                 }
907
908                 idx++;
909                 AST_LIST_TRAVERSE(&tpargs->cnumbers, nm, entry)
910                         if (nm->order == idx)
911                                 break;
912
913         }
914         free(findme_user_list);
915         if (!winner) 
916                 tpargs->status = 1;
917         else {
918                 tpargs->status = 100;
919                 tpargs->outbound = winner;
920         }
921
922         
923         return;
924                 
925 }
926
927 static int app_exec(struct ast_channel *chan, void *data)
928 {
929         struct fm_args targs;
930         struct ast_bridge_config config;
931         struct ast_call_followme *f;
932         struct number *nm, *newnm;
933         int res = 0;
934         struct localuser *u;
935         char *argstr;
936         char namerecloc[255];
937         int duration = 0;
938         struct ast_channel *caller;
939         struct ast_channel *outbound;
940         
941         AST_DECLARE_APP_ARGS(args,
942                 AST_APP_ARG(followmeid);
943                 AST_APP_ARG(options);
944         );
945         
946         if (!(argstr = ast_strdupa((char *)data))) {
947                 ast_log(LOG_ERROR, "Out of memory!\n");
948                 return -1;
949         }
950
951         if (!data) {
952                 ast_log(LOG_WARNING, "%s requires an argument (followmeid)\n",app);
953                 return -1;
954         }
955
956         LOCAL_USER_ADD(u);
957
958         AST_STANDARD_APP_ARGS(args, argstr);
959
960         if (!ast_strlen_zero(args.followmeid)) 
961         
962                         AST_LIST_LOCK(&followmes);
963                         AST_LIST_TRAVERSE(&followmes, f, entry) {
964                                 if (!strcasecmp(f->name, args.followmeid) && (f->active))
965                                         break;
966                         }
967                         AST_LIST_UNLOCK(&followmes);
968
969                         if (option_debug)
970                                 ast_log(LOG_DEBUG, "New profile %s.\n", args.followmeid);
971                         if (!f)
972                         { 
973                                 ast_log(LOG_WARNING, "Profile requested, %s, not found in the configuration.", args.followmeid);
974                                 res = -1;
975                         }
976                         else
977                         {
978         
979                                 /* XXX TODO: Reinsert the db check value to see whether or not follow-me is on or off */
980
981
982                                 if (args.options) {
983                                         ast_app_parse_options(followme_opts, &targs.followmeflags, NULL, args.options);
984                                 }
985
986                                 /* Lock the profile lock and copy out everything we need to run with before unlocking it again */
987                                 ast_mutex_lock(&f->lock);
988                                 targs.mohclass = ast_strdupa(f->moh);
989                                 ast_copy_string(targs.context, f->context, sizeof(targs.context));
990                                 ast_copy_string(targs.takecall, f->takecall, sizeof(targs.takecall));
991                                 ast_copy_string(targs.nextindp, f->nextindp, sizeof(targs.nextindp));
992                                 ast_copy_string(targs.callfromprompt, f->callfromprompt, sizeof(targs.callfromprompt));
993                                 ast_copy_string(targs.norecordingprompt, f->norecordingprompt, sizeof(targs.norecordingprompt));
994                                 ast_copy_string(targs.optionsprompt, f->optionsprompt, sizeof(targs.optionsprompt));
995                                 ast_copy_string(targs.plsholdprompt, f->plsholdprompt, sizeof(targs.plsholdprompt));
996                                 ast_copy_string(targs.statusprompt, f->statusprompt, sizeof(targs.statusprompt));
997                                 ast_copy_string(targs.sorryprompt, f->sorryprompt, sizeof(targs.sorryprompt));
998                                 /* Copy the numbers we're going to use into another list in case the master list should get modified 
999                                    (and locked) while we're trying to do a follow-me */
1000                                 AST_LIST_HEAD_INIT_NOLOCK(&targs.cnumbers);
1001                                 AST_LIST_TRAVERSE(&f->numbers, nm, entry) {
1002                                         newnm = create_followme_number(nm->number, nm->timeout, nm->order);
1003                                         AST_LIST_INSERT_TAIL(&targs.cnumbers, newnm, entry);
1004                                 }
1005                                 ast_mutex_unlock(&f->lock);
1006
1007                                 if (targs.followmeflags.flags & FOLLOWMEFLAG_STATUSMSG) 
1008                                         ast_stream_and_wait(chan, targs.statusprompt, chan->language, "");
1009
1010                                 snprintf(namerecloc,sizeof(namerecloc),"%s/followme.%s",ast_config_AST_SPOOL_DIR,chan->uniqueid);
1011                                 duration = 5;
1012
1013                                 if (targs.followmeflags.flags & FOLLOWMEFLAG_RECORDNAME) 
1014                                         if (ast_play_and_record(chan, "vm-rec-name", namerecloc, 5, "sln", &duration, 128, 0, NULL) < 0)
1015                                                 goto outrun;
1016
1017                                 /* The following call looks like we're going to playback the file, but we're actually   */
1018                                 /* just checking to see if we *can* play it.                                            */
1019                                 if (ast_streamfile(chan, namerecloc, chan->language))
1020                                         ast_copy_string(namerecloc, "", sizeof(namerecloc));                                    
1021                                 else
1022                                         ast_stopstream(chan);
1023
1024                                 if (ast_streamfile(chan, targs.plsholdprompt, chan->language))
1025                                         goto outrun;
1026                                 if (ast_waitstream(chan, "") < 0)
1027                                         goto outrun;
1028                                 if (!strcmp(targs.mohclass, ""))
1029                                         ast_moh_start(chan, NULL);
1030                                 else
1031                                         ast_moh_start(chan, targs.mohclass);
1032
1033
1034                                 targs.status = 0;
1035                                 targs.chan = chan;
1036
1037                                 ast_copy_string(targs.namerecloc, namerecloc, sizeof(targs.namerecloc));
1038
1039                                 findmeexec(&targs);             
1040                                 
1041                                 AST_LIST_TRAVERSE_SAFE_BEGIN(&targs.cnumbers, nm, entry)        {
1042                                         AST_LIST_REMOVE_CURRENT(&targs.cnumbers, entry);
1043                                         free(nm);
1044                                 }
1045                                 AST_LIST_TRAVERSE_SAFE_END
1046         
1047                                 if (!ast_strlen_zero(namerecloc))
1048                                         unlink(namerecloc);     
1049
1050                                 if (targs.status != 100)
1051                                 {
1052                                         ast_moh_stop(chan);
1053                                         if (targs.followmeflags.flags & FOLLOWMEFLAG_UNREACHABLEMSG) 
1054                                                 ast_stream_and_wait(chan, targs.sorryprompt, chan->language, "");
1055                                         res = 0;
1056                                 }
1057                                 else
1058                                 {
1059                                                         
1060                                         caller = chan;
1061                                         outbound = targs.outbound;
1062                                         /* Bridge the two channels. */
1063
1064                                         memset(&config,0,sizeof(struct ast_bridge_config));
1065                                         ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1066                                         ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
1067                                         ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
1068                                 
1069                                         ast_moh_stop(caller);
1070                                         /* Be sure no generators are left on it */
1071                                         ast_deactivate_generator(caller);
1072                                         /* Make sure channels are compatible */
1073                                         res = ast_channel_make_compatible(caller, outbound);
1074                                         if (res < 0) {
1075                                                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", caller->name, outbound->name);
1076                                                 ast_hangup(outbound);
1077                                                 goto outrun;
1078                                         }
1079                                         time(&answer_time);
1080                                         res = ast_bridge_call(caller,outbound,&config);
1081                                         time(&end_time);
1082                                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - start_time));
1083                                         pbx_builtin_setvar_helper(caller, "DIALEDTIME", toast);
1084                                         snprintf(toast, sizeof(toast), "%ld", (long)(end_time - answer_time));
1085                                         pbx_builtin_setvar_helper(caller, "ANSWEREDTIME", toast);
1086                                         if (outbound)
1087                                                 ast_hangup(outbound);
1088                                         res = 1;
1089                                         
1090                                 }
1091                                 
1092                         }
1093         outrun:
1094         
1095         LOCAL_USER_REMOVE(u);
1096         return res;
1097 }
1098
1099 static int unload_module(void *mod)
1100 {
1101         struct ast_call_followme *f;
1102         /* Free Memory. Yeah! I'm free! */
1103         AST_LIST_TRAVERSE_SAFE_BEGIN(&followmes, f, entry) {
1104                 free_numbers(f);
1105                 AST_LIST_REMOVE_CURRENT(&followmes, entry);
1106                 free(f);
1107         }
1108         AST_LIST_TRAVERSE_SAFE_END
1109         STANDARD_HANGUP_LOCALUSERS;
1110         return ast_unregister_application(app);
1111 }
1112
1113 static int load_module(void *mod)
1114 {
1115         reload_followme();
1116         return ast_register_application(app, app_exec, synopsis, descrip);
1117 }
1118
1119 static const char *description(void)
1120 {
1121         return "Find-Me/Follow-Me Application";
1122 }
1123
1124 static int reload(void *mod)
1125 {
1126         reload_followme();
1127         return 0;       
1128 }
1129
1130 static const char *key(void)
1131 {
1132         return ASTERISK_GPL_KEY;
1133 }
1134
1135 STD_MOD(MOD_1, reload, NULL, NULL);