Revert Jim's earlier "fix" :)
[asterisk/asterisk.git] / asterisk.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Top level source file for asterisk
5  * 
6  * Copyright (C) 1999-2004, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <unistd.h>
15 #include <stdlib.h>
16 #include <asterisk/logger.h>
17 #include <asterisk/options.h>
18 #include <asterisk/cli.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/ulaw.h>
21 #include <asterisk/alaw.h>
22 #include <asterisk/callerid.h>
23 #include <asterisk/module.h>
24 #include <asterisk/image.h>
25 #include <asterisk/tdd.h>
26 #include <asterisk/term.h>
27 #include <asterisk/manager.h>
28 #include <asterisk/pbx.h>
29 #include <asterisk/enum.h>
30 #include <asterisk/rtp.h>
31 #include <asterisk/app.h>
32 #include <asterisk/lock.h>
33 #include <asterisk/utils.h>
34 #include <asterisk/file.h>
35 #include <sys/resource.h>
36 #include <fcntl.h>
37 #include <stdio.h>
38 #include <signal.h>
39 #include <sched.h>
40 #include <asterisk/io.h>
41 #include <asterisk/lock.h>
42 #include <sys/socket.h>
43 #include <sys/un.h>
44 #include <sys/wait.h>
45 #include <string.h>
46 #include <errno.h>
47 #include <ctype.h>
48 #include "editline/histedit.h"
49 #include "asterisk.h"
50 #include <asterisk/config.h>
51 #include <asterisk/config_pvt.h>
52 #include <sys/resource.h>
53 #include <grp.h>
54 #include <pwd.h>
55
56 #if  defined(__FreeBSD__) || defined( __NetBSD__ ) || defined(SOLARIS)
57 #include <netdb.h>
58 #endif
59
60 #ifndef AF_LOCAL
61 #define AF_LOCAL AF_UNIX
62 #define PF_LOCAL PF_UNIX
63 #endif
64
65 #define AST_MAX_CONNECTS 128
66 #define NUM_MSGS 64
67
68 #define WELCOME_MESSAGE ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n"); \
69                 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n"); \
70                 ast_verbose( "=========================================================================\n")
71
72 int option_verbose=0;
73 int option_debug=0;
74 int option_nofork=0;
75 int option_quiet=0;
76 int option_console=0;
77 int option_highpriority=0;
78 int option_remote=0;
79 int option_exec=0;
80 int option_initcrypto=0;
81 int option_nocolor;
82 int option_dumpcore = 0;
83 int option_cache_record_files = 0;
84 int option_overrideconfig = 0;
85 int option_reconnect = 0;
86 int fully_booted = 0;
87 char record_cache_dir[AST_CACHE_DIR_LEN] = AST_TMP_DIR;
88
89 static int ast_socket = -1;             /* UNIX Socket for allowing remote control */
90 static int ast_consock = -1;            /* UNIX Socket for controlling another asterisk */
91 int ast_mainpid;
92 struct console {
93         int fd;                                 /* File descriptor */
94         int p[2];                               /* Pipe */
95         pthread_t t;                    /* Thread of handler */
96 };
97
98 static struct ast_atexit {
99         void (*func)(void);
100         struct ast_atexit *next;
101 } *atexits = NULL;
102 AST_MUTEX_DEFINE_STATIC(atexitslock);
103
104 time_t ast_startuptime;
105 time_t ast_lastreloadtime;
106
107 static History *el_hist = NULL;
108 static EditLine *el = NULL;
109 static char *remotehostname;
110
111 struct console consoles[AST_MAX_CONNECTS];
112
113 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
114
115 static int ast_el_add_history(char *);
116 static int ast_el_read_history(char *);
117 static int ast_el_write_history(char *);
118
119 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
120 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
121 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
122 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
123 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
124 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
125 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
126 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
127 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
128 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
129 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
130 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
131
132 static char *_argv[256];
133 static int shuttingdown = 0;
134 static int restartnow = 0;
135 static pthread_t consolethread = AST_PTHREADT_NULL;
136
137 int ast_register_atexit(void (*func)(void))
138 {
139         int res = -1;
140         struct ast_atexit *ae;
141         ast_unregister_atexit(func);
142         ae = malloc(sizeof(struct ast_atexit));
143         ast_mutex_lock(&atexitslock);
144         if (ae) {
145                 memset(ae, 0, sizeof(struct ast_atexit));
146                 ae->next = atexits;
147                 ae->func = func;
148                 atexits = ae;
149                 res = 0;
150         }
151         ast_mutex_unlock(&atexitslock);
152         return res;
153 }
154
155 void ast_unregister_atexit(void (*func)(void))
156 {
157         struct ast_atexit *ae, *prev = NULL;
158         ast_mutex_lock(&atexitslock);
159         ae = atexits;
160         while(ae) {
161                 if (ae->func == func) {
162                         if (prev)
163                                 prev->next = ae->next;
164                         else
165                                 atexits = ae->next;
166                         break;
167                 }
168                 prev = ae;
169                 ae = ae->next;
170         }
171         ast_mutex_unlock(&atexitslock);
172 }
173
174 static int fdprint(int fd, const char *s)
175 {
176         return write(fd, s, strlen(s) + 1);
177 }
178
179 /* NULL handler so we can collect the child exit status */
180 static void null_sig_handler(int signal)
181 {
182
183 }
184
185 int ast_safe_system(const char *s)
186 {
187         /* XXX This function needs some optimization work XXX */
188         pid_t pid;
189         int x;
190         int res;
191         struct rusage rusage;
192         int status;
193         void (*prev_handler) = signal(SIGCHLD, null_sig_handler);
194         pid = fork();
195         if (pid == 0) {
196                 /* Close file descriptors and launch system command */
197                 for (x=STDERR_FILENO + 1; x<4096;x++) {
198                         close(x);
199                 }
200                 res = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
201                 exit(1);
202         } else if (pid > 0) {
203                 for(;;) {
204                         res = wait4(pid, &status, 0, &rusage);
205                         if (res > -1) {
206                                 if (WIFEXITED(status))
207                                         res = WEXITSTATUS(status);
208                                 else
209                                         res = -1;
210                                 break;
211                         } else {
212                                 if (errno != EINTR) 
213                                         break;
214                         }
215                 }
216         } else {
217                 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
218                 res = -1;
219         }
220         signal(SIGCHLD, prev_handler);
221         return res;
222 }
223
224 /*
225  * write the string to all attached console clients
226  */
227 static void ast_network_puts(const char *string)
228 {
229         int x;
230         for (x=0;x<AST_MAX_CONNECTS; x++) {
231                 if (consoles[x].fd > -1) 
232                         fdprint(consoles[x].p[1], string);
233         }
234 }
235
236 /*
237  * write the string to the console, and all attached
238  * console clients
239  */
240 void ast_console_puts(const char *string)
241 {
242         fputs(string, stdout);
243         fflush(stdout);
244         ast_network_puts(string);
245 }
246
247 static void network_verboser(const char *s, int pos, int replace, int complete)
248         /* ARGUSED */
249 {
250         if (replace) {
251                 char *t = alloca(strlen(s) + 2);
252                 if (t) {
253                         sprintf(t, "\r%s", s);
254                         if (complete)
255                                 ast_network_puts(t);
256                 } else {
257                         ast_log(LOG_ERROR, "Out of memory\n");
258                         ast_network_puts(s);
259                 }
260         } else {
261                 if (complete)
262                         ast_network_puts(s);
263         }
264 }
265
266 static pthread_t lthread;
267
268 static void *netconsole(void *vconsole)
269 {
270         struct console *con = vconsole;
271         char hostname[256];
272         char tmp[512];
273         int res;
274         struct pollfd fds[2];
275         
276         if (gethostname(hostname, sizeof(hostname)))
277                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
278         snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, ast_mainpid, ASTERISK_VERSION);
279         fdprint(con->fd, tmp);
280         for(;;) {
281                 fds[0].fd = con->fd;
282                 fds[0].events = POLLIN;
283                 fds[1].fd = con->p[0];
284                 fds[1].events = POLLIN;
285
286                 res = poll(fds, 2, -1);
287                 if (res < 0) {
288                         if (errno != EINTR)
289                                 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
290                         continue;
291                 }
292                 if (fds[0].revents) {
293                         res = read(con->fd, tmp, sizeof(tmp));
294                         if (res < 1) {
295                                 break;
296                         }
297                         tmp[res] = 0;
298                         ast_cli_command(con->fd, tmp);
299                 }
300                 if (fds[1].revents) {
301                         res = read(con->p[0], tmp, sizeof(tmp));
302                         if (res < 1) {
303                                 ast_log(LOG_ERROR, "read returned %d\n", res);
304                                 break;
305                         }
306                         res = write(con->fd, tmp, res);
307                         if (res < 1)
308                                 break;
309                 }
310         }
311         if (option_verbose > 2) 
312                 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
313         close(con->fd);
314         close(con->p[0]);
315         close(con->p[1]);
316         con->fd = -1;
317         
318         return NULL;
319 }
320
321 static void *listener(void *unused)
322 {
323         struct sockaddr_un sunaddr;
324         int s;
325         int len;
326         int x;
327         int flags;
328         struct pollfd fds[1];
329         pthread_attr_t attr;
330         pthread_attr_init(&attr);
331         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
332         for(;;) {
333                 if (ast_socket < 0)
334                         return NULL;
335                 fds[0].fd = ast_socket;
336                 fds[0].events= POLLIN;
337                 s = poll(fds, 1, -1);
338                 if (s < 0) {
339                         if (errno != EINTR)
340                                 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
341                         continue;
342                 }
343                 len = sizeof(sunaddr);
344                 s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
345                 if (s < 0) {
346                         if (errno != EINTR)
347                                 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
348                 } else {
349                         for (x=0;x<AST_MAX_CONNECTS;x++) {
350                                 if (consoles[x].fd < 0) {
351                                         if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
352                                                 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
353                                                 consoles[x].fd = -1;
354                                                 fdprint(s, "Server failed to create pipe\n");
355                                                 close(s);
356                                                 break;
357                                         }
358                                         flags = fcntl(consoles[x].p[1], F_GETFL);
359                                         fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
360                                         consoles[x].fd = s;
361                                         if (ast_pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
362                                                 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
363                                                 consoles[x].fd = -1;
364                                                 fdprint(s, "Server failed to spawn thread\n");
365                                                 close(s);
366                                         }
367                                         break;
368                                 }
369                         }
370                         if (x >= AST_MAX_CONNECTS) {
371                                 fdprint(s, "No more connections allowed\n");
372                                 ast_log(LOG_WARNING, "No more connections allowed\n");
373                                 close(s);
374                         } else if (consoles[x].fd > -1) {
375                                 if (option_verbose > 2) 
376                                         ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
377                         }
378                 }
379         }
380         return NULL;
381 }
382
383 static int ast_makesocket(void)
384 {
385         struct sockaddr_un sunaddr;
386         int res;
387         int x;
388         for (x=0;x<AST_MAX_CONNECTS;x++)        
389                 consoles[x].fd = -1;
390         unlink((char *)ast_config_AST_SOCKET);
391         ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
392         if (ast_socket < 0) {
393                 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
394                 return -1;
395         }               
396         memset(&sunaddr, 0, sizeof(sunaddr));
397         sunaddr.sun_family = AF_LOCAL;
398         strncpy(sunaddr.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sunaddr.sun_path)-1);
399         res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
400         if (res) {
401                 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
402                 close(ast_socket);
403                 ast_socket = -1;
404                 return -1;
405         }
406         res = listen(ast_socket, 2);
407         if (res < 0) {
408                 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
409                 close(ast_socket);
410                 ast_socket = -1;
411                 return -1;
412         }
413         ast_register_verbose(network_verboser);
414         ast_pthread_create(&lthread, NULL, listener, NULL);
415         return 0;
416 }
417
418 static int ast_tryconnect(void)
419 {
420         struct sockaddr_un sunaddr;
421         int res;
422         ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
423         if (ast_consock < 0) {
424                 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
425                 return 0;
426         }
427         memset(&sunaddr, 0, sizeof(sunaddr));
428         sunaddr.sun_family = AF_LOCAL;
429         strncpy(sunaddr.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sunaddr.sun_path)-1);
430         res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
431         if (res) {
432                 close(ast_consock);
433                 ast_consock = -1;
434                 return 0;
435         } else
436                 return 1;
437 }
438
439 static void urg_handler(int num)
440 {
441         /* Called by soft_hangup to interrupt the poll, read, or other
442            system call.  We don't actually need to do anything though.  */
443         /* Cannot EVER ast_log from within a signal handler */
444         if (option_debug) 
445                 printf("Urgent handler\n");
446         signal(num, urg_handler);
447         return;
448 }
449
450 static void hup_handler(int num)
451 {
452         if (option_verbose > 1) 
453                 printf("Received HUP signal -- Reloading configs\n");
454         if (restartnow)
455                 execvp(_argv[0], _argv);
456         /* XXX This could deadlock XXX */
457         ast_module_reload(NULL);
458 }
459
460 static void child_handler(int sig)
461 {
462         /* Must not ever ast_log or ast_verbose within signal handler */
463         int n, status;
464
465         /*
466          * Reap all dead children -- not just one
467          */
468         for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
469                 ;
470         if (n == 0 && option_debug)     
471                 printf("Huh?  Child handler, but nobody there?\n");
472 }
473
474 static void set_title(char *text)
475 {
476         /* Set an X-term or screen title */
477         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
478                 fprintf(stdout, "\033]2;%s\007", text);
479 }
480
481 static void set_icon(char *text)
482 {
483         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
484                 fprintf(stdout, "\033]1;%s\007", text);
485 }
486
487 static int set_priority(int pri)
488 {
489         struct sched_param sched;
490         memset(&sched, 0, sizeof(sched));
491         /* We set ourselves to a high priority, that we might pre-empt everything
492            else.  If your PBX has heavy activity on it, this is a good thing.  */
493 #ifdef __linux__
494         if (pri) {  
495                 sched.sched_priority = 10;
496                 if (sched_setscheduler(0, SCHED_RR, &sched)) {
497                         ast_log(LOG_WARNING, "Unable to set high priority\n");
498                         return -1;
499                 } else
500                         if (option_verbose)
501                                 ast_verbose("Set to realtime thread\n");
502         } else {
503                 sched.sched_priority = 0;
504                 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
505                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
506                         return -1;
507                 }
508         }
509 #else
510         if (pri) {
511                 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
512                         ast_log(LOG_WARNING, "Unable to set high priority\n");
513                         return -1;
514                 } else
515                         if (option_verbose)
516                                 ast_verbose("Set to high priority\n");
517         } else {
518                 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
519                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
520                         return -1;
521                 }
522         }
523 #endif
524         return 0;
525 }
526
527 static void ast_run_atexits(void)
528 {
529         struct ast_atexit *ae;
530         ast_mutex_lock(&atexitslock);
531         ae = atexits;
532         while(ae) {
533                 if (ae->func) 
534                         ae->func();
535                 ae = ae->next;
536         }
537         ast_mutex_unlock(&atexitslock);
538 }
539
540 static void quit_handler(int num, int nice, int safeshutdown, int restart)
541 {
542         char filename[80] = "";
543         time_t s,e;
544         int x;
545         if (safeshutdown) {
546                 shuttingdown = 1;
547                 if (!nice) {
548                         /* Begin shutdown routine, hanging up active channels */
549                         ast_begin_shutdown(1);
550                         if (option_verbose && option_console)
551                                 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
552                         time(&s);
553                         for(;;) {
554                                 time(&e);
555                                 /* Wait up to 15 seconds for all channels to go away */
556                                 if ((e - s) > 15)
557                                         break;
558                                 if (!ast_active_channels())
559                                         break;
560                                 if (!shuttingdown)
561                                         break;
562                                 /* Sleep 1/10 of a second */
563                                 usleep(100000);
564                         }
565                 } else {
566                         if (nice < 2)
567                                 ast_begin_shutdown(0);
568                         if (option_verbose && option_console)
569                                 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
570                         for(;;) {
571                                 if (!ast_active_channels())
572                                         break;
573                                 if (!shuttingdown)
574                                         break;
575                                 sleep(1);
576                         }
577                 }
578
579                 if (!shuttingdown) {
580                         if (option_verbose && option_console)
581                                 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
582                         return;
583                 }
584         }
585         if (option_console || option_remote) {
586                 if (getenv("HOME")) 
587                         snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
588                 if (!ast_strlen_zero(filename))
589                         ast_el_write_history(filename);
590                 if (el != NULL)
591                         el_end(el);
592                 if (el_hist != NULL)
593                         history_end(el_hist);
594         }
595         if (option_verbose)
596                 ast_verbose("Executing last minute cleanups\n");
597         ast_run_atexits();
598         /* Called on exit */
599         if (option_verbose && option_console)
600                 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
601         else if (option_debug)
602                 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
603         manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
604         if (ast_socket > -1) {
605                 close(ast_socket);
606                 ast_socket = -1;
607         }
608         if (ast_consock > -1)
609                 close(ast_consock);
610         if (ast_socket > -1)
611                 unlink((char *)ast_config_AST_SOCKET);
612         if (!option_remote) unlink((char *)ast_config_AST_PID);
613         printf(term_quit());
614         if (restart) {
615                 if (option_verbose || option_console)
616                         ast_verbose("Preparing for Asterisk restart...\n");
617                 /* Mark all FD's for closing on exec */
618                 for (x=3;x<32768;x++) {
619                         fcntl(x, F_SETFD, FD_CLOEXEC);
620                 }
621                 if (option_verbose || option_console)
622                         ast_verbose("Restarting Asterisk NOW...\n");
623                 restartnow = 1;
624
625                 /* close logger */
626                 close_logger();
627
628                 /* If there is a consolethread running send it a SIGHUP 
629                    so it can execvp, otherwise we can do it ourselves */
630                 if (consolethread != AST_PTHREADT_NULL) {
631                         pthread_kill(consolethread, SIGHUP);
632                         /* Give the signal handler some time to complete */
633                         sleep(2);
634                 } else
635                         execvp(_argv[0], _argv);
636         
637         } else {
638                 /* close logger */
639                 close_logger();
640         }
641         exit(0);
642 }
643
644 static void __quit_handler(int num)
645 {
646         quit_handler(num, 0, 1, 0);
647 }
648
649 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
650 {
651         const char *c;
652         if (!strncmp(s, cmp, strlen(cmp))) {
653                 c = s + strlen(cmp);
654                 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
655                 return c;
656         }
657         return NULL;
658 }
659
660 static void console_verboser(const char *s, int pos, int replace, int complete)
661 {
662         char tmp[80];
663         const char *c=NULL;
664         /* Return to the beginning of the line */
665         if (!pos) {
666                 fprintf(stdout, "\r");
667                 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
668                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
669                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
670                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
671                         fputs(tmp, stdout);
672         }
673         if (c)
674                 fputs(c + pos,stdout);
675         else
676                 fputs(s + pos,stdout);
677         fflush(stdout);
678         if (complete) {
679                 /* Wake up a poll()ing console */
680                 if (option_console && consolethread != AST_PTHREADT_NULL)
681                         pthread_kill(consolethread, SIGURG);
682         }
683 }
684
685 static int ast_all_zeros(char *s)
686 {
687         while(*s) {
688                 if (*s > 32)
689                         return 0;
690                 s++;  
691         }
692         return 1;
693 }
694
695 static void consolehandler(char *s)
696 {
697         printf(term_end());
698         fflush(stdout);
699         /* Called when readline data is available */
700         if (s && !ast_all_zeros(s))
701                 ast_el_add_history(s);
702         /* Give the console access to the shell */
703         if (s) {
704                 /* The real handler for bang */
705                 if (s[0] == '!') {
706                         if (s[1])
707                                 ast_safe_system(s+1);
708                         else
709                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
710                 } else 
711                 ast_cli_command(STDOUT_FILENO, s);
712         } else
713                 fprintf(stdout, "\nUse \"quit\" to exit\n");
714 }
715
716 static int remoteconsolehandler(char *s)
717 {
718         int ret = 0;
719         /* Called when readline data is available */
720         if (s && !ast_all_zeros(s))
721                 ast_el_add_history(s);
722         /* Give the console access to the shell */
723         if (s) {
724                 /* The real handler for bang */
725                 if (s[0] == '!') {
726                         if (s[1])
727                                 ast_safe_system(s+1);
728                         else
729                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
730                         ret = 1;
731                 }
732                 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
733                     (s[4] == '\0' || isspace(s[4]))) {
734                         quit_handler(0, 0, 0, 0);
735                         ret = 1;
736                 }
737         } else
738                 fprintf(stdout, "\nUse \"quit\" to exit\n");
739
740         return ret;
741 }
742
743 static char quit_help[] = 
744 "Usage: quit\n"
745 "       Exits Asterisk.\n";
746
747 static char abort_halt_help[] = 
748 "Usage: abort shutdown\n"
749 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
750 "       call operations.\n";
751
752 static char shutdown_now_help[] = 
753 "Usage: stop now\n"
754 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
755
756 static char shutdown_gracefully_help[] = 
757 "Usage: stop gracefully\n"
758 "       Causes Asterisk to not accept new calls, and exit when all\n"
759 "       active calls have terminated normally.\n";
760
761 static char shutdown_when_convenient_help[] = 
762 "Usage: stop when convenient\n"
763 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
764
765 static char restart_now_help[] = 
766 "Usage: restart now\n"
767 "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
768 "       restart.\n";
769
770 static char restart_gracefully_help[] = 
771 "Usage: restart gracefully\n"
772 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
773 "       restart when all active calls have ended.\n";
774
775 static char restart_when_convenient_help[] = 
776 "Usage: restart when convenient\n"
777 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
778
779 static char bang_help[] =
780 "Usage: !<command>\n"
781 "       Executes a given shell command\n";
782
783 #if 0
784 static int handle_quit(int fd, int argc, char *argv[])
785 {
786         if (argc != 1)
787                 return RESULT_SHOWUSAGE;
788         quit_handler(0, 0, 1, 0);
789         return RESULT_SUCCESS;
790 }
791 #endif
792
793 static int no_more_quit(int fd, int argc, char *argv[])
794 {
795         if (argc != 1)
796                 return RESULT_SHOWUSAGE;
797         ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
798                     "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
799         return RESULT_SUCCESS;
800 }
801
802 static int handle_shutdown_now(int fd, int argc, char *argv[])
803 {
804         if (argc != 2)
805                 return RESULT_SHOWUSAGE;
806         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
807         return RESULT_SUCCESS;
808 }
809
810 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
811 {
812         if (argc != 2)
813                 return RESULT_SHOWUSAGE;
814         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
815         return RESULT_SUCCESS;
816 }
817
818 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
819 {
820         if (argc != 3)
821                 return RESULT_SHOWUSAGE;
822         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
823         return RESULT_SUCCESS;
824 }
825
826 static int handle_restart_now(int fd, int argc, char *argv[])
827 {
828         if (argc != 2)
829                 return RESULT_SHOWUSAGE;
830         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
831         return RESULT_SUCCESS;
832 }
833
834 static int handle_restart_gracefully(int fd, int argc, char *argv[])
835 {
836         if (argc != 2)
837                 return RESULT_SHOWUSAGE;
838         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
839         return RESULT_SUCCESS;
840 }
841
842 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
843 {
844         if (argc != 3)
845                 return RESULT_SHOWUSAGE;
846         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
847         return RESULT_SUCCESS;
848 }
849
850 static int handle_abort_halt(int fd, int argc, char *argv[])
851 {
852         if (argc != 2)
853                 return RESULT_SHOWUSAGE;
854         ast_cancel_shutdown();
855         shuttingdown = 0;
856         return RESULT_SUCCESS;
857 }
858
859 static int handle_bang(int fd, int argc, char *argv[])
860 {
861         return RESULT_SUCCESS;
862 }
863
864 #define ASTERISK_PROMPT "*CLI> "
865
866 #define ASTERISK_PROMPT2 "%s*CLI> "
867
868 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
869
870 static struct ast_cli_entry quit =      { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
871 static struct ast_cli_entry astexit =   { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
872
873 static struct ast_cli_entry astshutdownnow =    { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
874 static struct ast_cli_entry astshutdowngracefully =     { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
875 static struct ast_cli_entry astshutdownwhenconvenient =         { { "stop", "when","convenient", NULL }, handle_shutdown_when_convenient, "Shut down Asterisk at empty call volume", shutdown_when_convenient_help };
876 static struct ast_cli_entry astrestartnow =     { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
877 static struct ast_cli_entry astrestartgracefully =      { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
878 static struct ast_cli_entry astrestartwhenconvenient=   { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
879 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
880
881 static int ast_el_read_char(EditLine *el, char *cp)
882 {
883         int num_read=0;
884         int lastpos=0;
885         struct pollfd fds[2];
886         int res;
887         int max;
888         char buf[512];
889
890         for (;;) {
891                 max = 1;
892                 fds[0].fd = ast_consock;
893                 fds[0].events = POLLIN;
894                 if (!option_exec) {
895                         fds[1].fd = STDIN_FILENO;
896                         fds[1].events = POLLIN;
897                         max++;
898                 }
899                 res = poll(fds, max, -1);
900                 if (res < 0) {
901                         if (errno == EINTR)
902                                 continue;
903                         ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
904                         break;
905                 }
906
907                 if (!option_exec && fds[1].revents) {
908                         num_read = read(STDIN_FILENO, cp, 1);
909                         if (num_read < 1) {
910                                 break;
911                         } else 
912                                 return (num_read);
913                 }
914                 if (fds[0].revents) {
915                         res = read(ast_consock, buf, sizeof(buf) - 1);
916                         /* if the remote side disappears exit */
917                         if (res < 1) {
918                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
919                                 if (!option_reconnect) {
920                                         quit_handler(0, 0, 0, 0);
921                                 } else {
922                                         int tries;
923                                         int reconnects_per_second = 20;
924                                         fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
925                                         for (tries=0;tries<30 * reconnects_per_second;tries++) {
926                                                 if (ast_tryconnect()) {
927                                                         fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
928                                                         printf(term_quit());
929                                                         WELCOME_MESSAGE;
930                                                         break;
931                                                 } else {
932                                                         usleep(1000000 / reconnects_per_second);
933                                                 }
934                                         }
935                                         if (tries >= 30 * reconnects_per_second) {
936                                                 fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
937                                                 quit_handler(0, 0, 0, 0);
938                                         }
939                                 }
940                         }
941
942                         buf[res] = '\0';
943
944                         if (!option_exec && !lastpos)
945                                 write(STDOUT_FILENO, "\r", 1);
946                         write(STDOUT_FILENO, buf, res);
947                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
948                                 *cp = CC_REFRESH;
949                                 return(1);
950                         } else {
951                                 lastpos = 1;
952                         }
953                 }
954         }
955
956         *cp = '\0';
957         return (0);
958 }
959
960 static char *cli_prompt(EditLine *el)
961 {
962         static char prompt[200];
963         char *pfmt;
964         int color_used=0;
965         char term_code[20];
966
967         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
968                 char *t = pfmt, *p = prompt;
969                 memset(prompt, 0, sizeof(prompt));
970                 while (*t != '\0' && *p < sizeof(prompt)) {
971                         if (*t == '%') {
972                                 char hostname[256];
973                                 int i;
974                                 struct timeval tv;
975                                 struct tm tm;
976 #ifdef linux
977                                 FILE *LOADAVG;
978 #endif
979                                 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
980
981                                 t++;
982                                 switch (*t) {
983                                         case 'C': /* color */
984                                                 t++;
985                                                 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
986                                                         strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
987                                                         t += i - 1;
988                                                 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
989                                                         strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
990                                                         t += i - 1;
991                                                 }
992
993                                                 /* If the color has been reset correctly, then there's no need to reset it later */
994                                                 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
995                                                         color_used = 0;
996                                                 } else {
997                                                         color_used = 1;
998                                                 }
999                                                 break;
1000                                         case 'd': /* date */
1001                                                 memset(&tm, 0, sizeof(struct tm));
1002                                                 gettimeofday(&tv, NULL);
1003                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1004                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
1005                                                 }
1006                                                 break;
1007                                         case 'h': /* hostname */
1008                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1009                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1010                                                 } else {
1011                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1012                                                 }
1013                                                 break;
1014                                         case 'H': /* short hostname */
1015                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1016                                                         for (i=0;i<sizeof(hostname);i++) {
1017                                                                 if (hostname[i] == '.') {
1018                                                                         hostname[i] = '\0';
1019                                                                         break;
1020                                                                 }
1021                                                         }
1022                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1023                                                 } else {
1024                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1025                                                 }
1026                                                 break;
1027 #ifdef linux
1028                                         case 'l': /* load avg */
1029                                                 t++;
1030                                                 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
1031                                                         float avg1, avg2, avg3;
1032                                                         int actproc, totproc, npid, which;
1033                                                         fscanf(LOADAVG, "%f %f %f %d/%d %d",
1034                                                                 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
1035                                                         if (sscanf(t, "%d", &which) == 1) {
1036                                                                 switch (which) {
1037                                                                         case 1:
1038                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1039                                                                                 break;
1040                                                                         case 2:
1041                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1042                                                                                 break;
1043                                                                         case 3:
1044                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1045                                                                                 break;
1046                                                                         case 4:
1047                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1048                                                                                 break;
1049                                                                         case 5:
1050                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1051                                                                                 break;
1052                                                                 }
1053                                                         }
1054                                                 }
1055                                                 break;
1056 #endif
1057                                         case 't': /* time */
1058                                                 memset(&tm, 0, sizeof(struct tm));
1059                                                 gettimeofday(&tv, NULL);
1060                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1061                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1062                                                 }
1063                                                 break;
1064                                         case '#': /* process console or remote? */
1065                                                 if (! option_remote) {
1066                                                         strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1067                                                 } else {
1068                                                         strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1069                                                 }
1070                                                 break;
1071                                         case '%': /* literal % */
1072                                                 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1073                                                 break;
1074                                         case '\0': /* % is last character - prevent bug */
1075                                                 t--;
1076                                                 break;
1077                                 }
1078                                 while (*p != '\0') {
1079                                         p++;
1080                                 }
1081                                 t++;
1082                         } else {
1083                                 *p = *t;
1084                                 p++;
1085                                 t++;
1086                         }
1087                 }
1088                 if (color_used) {
1089                         /* Force colors back to normal at end */
1090                         term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1091                         if (strlen(term_code) > sizeof(prompt) - strlen(prompt)) {
1092                                 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1093                         } else {
1094                                 strncat(p, term_code, sizeof(term_code));
1095                         }
1096                 }
1097         } else if (remotehostname)
1098                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1099         else
1100                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1101
1102         return(prompt); 
1103 }
1104
1105 static char **ast_el_strtoarr(char *buf)
1106 {
1107         char **match_list = NULL, *retstr;
1108         size_t match_list_len;
1109         int matches = 0;
1110
1111         match_list_len = 1;
1112         while ( (retstr = strsep(&buf, " ")) != NULL) {
1113
1114                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1115                         break;
1116                 if (matches + 1 >= match_list_len) {
1117                         match_list_len <<= 1;
1118                         match_list = realloc(match_list, match_list_len * sizeof(char *));
1119                 }
1120
1121                 match_list[matches++] = strdup(retstr);
1122         }
1123
1124         if (!match_list)
1125                 return (char **) NULL;
1126
1127         if (matches>= match_list_len)
1128                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1129
1130         match_list[matches] = (char *) NULL;
1131
1132         return match_list;
1133 }
1134
1135 static int ast_el_sort_compare(const void *i1, const void *i2)
1136 {
1137         char *s1, *s2;
1138
1139         s1 = ((char **)i1)[0];
1140         s2 = ((char **)i2)[0];
1141
1142         return strcasecmp(s1, s2);
1143 }
1144
1145 static int ast_cli_display_match_list(char **matches, int len, int max)
1146 {
1147         int i, idx, limit, count;
1148         int screenwidth = 0;
1149         int numoutput = 0, numoutputline = 0;
1150
1151         screenwidth = ast_get_termcols(STDOUT_FILENO);
1152
1153         /* find out how many entries can be put on one line, with two spaces between strings */
1154         limit = screenwidth / (max + 2);
1155         if (limit == 0)
1156                 limit = 1;
1157
1158         /* how many lines of output */
1159         count = len / limit;
1160         if (count * limit < len)
1161                 count++;
1162
1163         idx = 1;
1164
1165         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1166
1167         for (; count > 0; count--) {
1168                 numoutputline = 0;
1169                 for (i=0; i < limit && matches[idx]; i++, idx++) {
1170
1171                         /* Don't print dupes */
1172                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1173                                 i--;
1174                                 free(matches[idx]);
1175                                 matches[idx] = NULL;
1176                                 continue;
1177                         }
1178
1179                         numoutput++;
1180                         numoutputline++;
1181                         fprintf(stdout, "%-*s  ", max, matches[idx]);
1182                         free(matches[idx]);
1183                         matches[idx] = NULL;
1184                 }
1185                 if (numoutputline > 0)
1186                         fprintf(stdout, "\n");
1187         }
1188
1189         return numoutput;
1190 }
1191
1192
1193 static char *cli_complete(EditLine *el, int ch)
1194 {
1195         int len=0;
1196         char *ptr;
1197         int nummatches = 0;
1198         char **matches;
1199         int retval = CC_ERROR;
1200         char buf[2048];
1201         int res;
1202
1203         LineInfo *lf = (LineInfo *)el_line(el);
1204
1205         *(char *)lf->cursor = '\0';
1206         ptr = (char *)lf->cursor;
1207         if (ptr) {
1208                 while (ptr > lf->buffer) {
1209                         if (isspace(*ptr)) {
1210                                 ptr++;
1211                                 break;
1212                         }
1213                         ptr--;
1214                 }
1215         }
1216
1217         len = lf->cursor - ptr;
1218
1219         if (option_remote) {
1220                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
1221                 fdprint(ast_consock, buf);
1222                 res = read(ast_consock, buf, sizeof(buf));
1223                 buf[res] = '\0';
1224                 nummatches = atoi(buf);
1225
1226                 if (nummatches > 0) {
1227                         char *mbuf;
1228                         int mlen = 0, maxmbuf = 2048;
1229                         /* Start with a 2048 byte buffer */
1230                         mbuf = malloc(maxmbuf);
1231                         if (!mbuf)
1232                                 return (char *)(CC_ERROR);
1233                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1234                         fdprint(ast_consock, buf);
1235                         res = 0;
1236                         mbuf[0] = '\0';
1237                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1238                                 if (mlen + 1024 > maxmbuf) {
1239                                         /* Every step increment buffer 1024 bytes */
1240                                         maxmbuf += 1024;
1241                                         mbuf = realloc(mbuf, maxmbuf);
1242                                         if (!mbuf)
1243                                                 return (char *)(CC_ERROR);
1244                                 }
1245                                 /* Only read 1024 bytes at a time */
1246                                 res = read(ast_consock, mbuf + mlen, 1024);
1247                                 if (res > 0)
1248                                         mlen += res;
1249                         }
1250                         mbuf[mlen] = '\0';
1251
1252                         matches = ast_el_strtoarr(mbuf);
1253                         free(mbuf);
1254                 } else
1255                         matches = (char **) NULL;
1256
1257
1258         } else {
1259
1260                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1261                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1262         }
1263
1264         if (matches) {
1265                 int i;
1266                 int matches_num, maxlen, match_len;
1267
1268                 if (matches[0][0] != '\0') {
1269                         el_deletestr(el, (int) len);
1270                         el_insertstr(el, matches[0]);
1271                         retval = CC_REFRESH;
1272                 }
1273
1274                 if (nummatches == 1) {
1275                         /* Found an exact match */
1276                         el_insertstr(el, " ");
1277                         retval = CC_REFRESH;
1278                 } else {
1279                         /* Must be more than one match */
1280                         for (i=1, maxlen=0; matches[i]; i++) {
1281                                 match_len = strlen(matches[i]);
1282                                 if (match_len > maxlen)
1283                                         maxlen = match_len;
1284                         }
1285                         matches_num = i - 1;
1286                         if (matches_num >1) {
1287                                 fprintf(stdout, "\n");
1288                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1289                                 retval = CC_REDISPLAY;
1290                         } else { 
1291                                 el_insertstr(el," ");
1292                                 retval = CC_REFRESH;
1293                         }
1294                 }
1295         free(matches);
1296         }
1297
1298         return (char *)(long)retval;
1299 }
1300
1301 static int ast_el_initialize(void)
1302 {
1303         HistEvent ev;
1304         char *editor = getenv("AST_EDITOR");
1305
1306         if (el != NULL)
1307                 el_end(el);
1308         if (el_hist != NULL)
1309                 history_end(el_hist);
1310
1311         el = el_init("asterisk", stdin, stdout, stderr);
1312         el_set(el, EL_PROMPT, cli_prompt);
1313
1314         el_set(el, EL_EDITMODE, 1);             
1315         el_set(el, EL_EDITOR, editor ? editor : "emacs");               
1316         el_hist = history_init();
1317         if (!el || !el_hist)
1318                 return -1;
1319
1320         /* setup history with 100 entries */
1321         history(el_hist, &ev, H_SETSIZE, 100);
1322
1323         el_set(el, EL_HIST, history, el_hist);
1324
1325         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1326         /* Bind <tab> to command completion */
1327         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1328         /* Bind ? to command completion */
1329         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1330         /* Bind ^D to redisplay */
1331         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1332
1333         return 0;
1334 }
1335
1336 static int ast_el_add_history(char *buf)
1337 {
1338         HistEvent ev;
1339
1340         if (el_hist == NULL || el == NULL)
1341                 ast_el_initialize();
1342         if (strlen(buf) > 256)
1343                 return 0;
1344         return (history(el_hist, &ev, H_ENTER, buf));
1345 }
1346
1347 static int ast_el_write_history(char *filename)
1348 {
1349         HistEvent ev;
1350
1351         if (el_hist == NULL || el == NULL)
1352                 ast_el_initialize();
1353
1354         return (history(el_hist, &ev, H_SAVE, filename));
1355 }
1356
1357 static int ast_el_read_history(char *filename)
1358 {
1359         char buf[256];
1360         FILE *f;
1361         int ret = -1;
1362
1363         if (el_hist == NULL || el == NULL)
1364                 ast_el_initialize();
1365
1366         if ((f = fopen(filename, "r")) == NULL)
1367                 return ret;
1368
1369         while (!feof(f)) {
1370                 fgets(buf, sizeof(buf), f);
1371                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1372                         continue;
1373                 if (ast_all_zeros(buf))
1374                         continue;
1375                 if ((ret = ast_el_add_history(buf)) == -1)
1376                         break;
1377         }
1378         fclose(f);
1379
1380         return ret;
1381 }
1382
1383 static void ast_remotecontrol(char * data)
1384 {
1385         char buf[80];
1386         int res;
1387         char filename[80] = "";
1388         char *hostname;
1389         char *cpid;
1390         char *version;
1391         int pid;
1392         char tmp[80];
1393         char *stringp=NULL;
1394
1395         char *ebuf;
1396         int num = 0;
1397
1398         read(ast_consock, buf, sizeof(buf));
1399         if (data)
1400                 write(ast_consock, data, strlen(data) + 1);
1401         stringp=buf;
1402         hostname = strsep(&stringp, "/");
1403         cpid = strsep(&stringp, "/");
1404         version = strsep(&stringp, "\n");
1405         if (!version)
1406                 version = "<Version Unknown>";
1407         stringp=hostname;
1408         strsep(&stringp, ".");
1409         if (cpid)
1410                 pid = atoi(cpid);
1411         else
1412                 pid = -1;
1413         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1414         fdprint(ast_consock, tmp);
1415         snprintf(tmp, sizeof(tmp), "set debug atleast %d", option_debug);
1416         fdprint(ast_consock, tmp);
1417         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1418         remotehostname = hostname;
1419         if (getenv("HOME")) 
1420                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1421         if (el_hist == NULL || el == NULL)
1422                 ast_el_initialize();
1423
1424         el_set(el, EL_GETCFN, ast_el_read_char);
1425
1426         if (!ast_strlen_zero(filename))
1427                 ast_el_read_history(filename);
1428
1429         ast_cli_register(&quit);
1430         ast_cli_register(&astexit);
1431 #if 0
1432         ast_cli_register(&astshutdown);
1433 #endif  
1434         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1435                 char tempchar;
1436                 struct pollfd fds[0];
1437                 fds[0].fd = ast_consock;
1438                 fds[0].events = POLLIN;
1439                 fds[0].revents = 0;
1440                 while(poll(fds, 1, 100) > 0) {
1441                         ast_el_read_char(el, &tempchar);
1442                 }
1443                 return;
1444         }
1445         for(;;) {
1446                 ebuf = (char *)el_gets(el, &num);
1447
1448                 if (ebuf && !ast_strlen_zero(ebuf)) {
1449                         if (ebuf[strlen(ebuf)-1] == '\n')
1450                                 ebuf[strlen(ebuf)-1] = '\0';
1451                         if (!remoteconsolehandler(ebuf)) {
1452                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1453                                 if (res < 1) {
1454                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1455                                         break;
1456                                 }
1457                         }
1458                 }
1459         }
1460         printf("\nDisconnected from Asterisk server\n");
1461 }
1462
1463 static int show_version(void)
1464 {
1465         printf("Asterisk " ASTERISK_VERSION "\n");
1466         return 0;
1467 }
1468
1469 static int show_cli_help(void) {
1470         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2004, Digium.\n");
1471         printf("Usage: asterisk [OPTIONS]\n");
1472         printf("Valid Options:\n");
1473         printf("   -V              Display version number and exit\n");
1474         printf("   -C <configfile> Use an alternate configuration file\n");
1475         printf("   -G <group>      Run as a group other than the caller\n");
1476         printf("   -U <user>       Run as a user other than the caller\n");
1477         printf("   -c              Provide console CLI\n");
1478         printf("   -d              Enable extra debugging\n");
1479         printf("   -f              Do not fork\n");
1480         printf("   -g              Dump core in case of a crash\n");
1481         printf("   -h              This help screen\n");
1482         printf("   -i              Initialize crypto keys at startup\n");
1483         printf("   -n              Disable console colorization\n");
1484         printf("   -p              Run as pseudo-realtime thread\n");
1485         printf("   -q              Quiet mode (suppress output)\n");
1486         printf("   -r              Connect to Asterisk on this machine\n");
1487         printf("   -R              Connect to Asterisk, and attempt to reconnect if disconnected\n");
1488         printf("   -t              Record soundfiles in /var/tmp and move them where they belong after they are done.\n");
1489         printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
1490         printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
1491         printf("\n");
1492         return 0;
1493 }
1494
1495 static void ast_readconfig(void) {
1496         struct ast_config *cfg;
1497         struct ast_variable *v;
1498         char *config = ASTCONFPATH;
1499
1500         if (option_overrideconfig == 1) {
1501                 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1502                 if (!cfg)
1503                         ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using builtin defaults\n", ast_config_AST_CONFIG_FILE);
1504         } else {
1505                 cfg = ast_load(config);
1506         }
1507
1508         /* init with buildtime config */
1509         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1510         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1511         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1512         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1513         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1514         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1515         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1516         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1517         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1518         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1519         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1520         
1521         /* no asterisk.conf? no problem, use buildtime config! */
1522         if (!cfg) {
1523                 return;
1524         }
1525         v = ast_variable_browse(cfg, "directories");
1526         while(v) {
1527                 if (!strcasecmp(v->name, "astetcdir")) {
1528                         strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1529                 } else if (!strcasecmp(v->name, "astspooldir")) {
1530                         strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1531                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1532                         strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1533                         snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB),"%s/%s",v->value,"astdb");    
1534                 } else if (!strcasecmp(v->name, "astlogdir")) {
1535                         strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1536                 } else if (!strcasecmp(v->name, "astagidir")) {
1537                         strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1538                 } else if (!strcasecmp(v->name, "astrundir")) {
1539                         snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID),"%s/%s",v->value,"asterisk.pid");    
1540                         snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET),"%s/%s",v->value,"asterisk.ctl");    
1541                         strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1542                 } else if (!strcasecmp(v->name, "astmoddir")) {
1543                         strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1544                 }
1545                 v = v->next;
1546         }
1547         v = ast_variable_browse(cfg, "options");
1548         while(v) {
1549                 if (!strcasecmp(v->name, "verbose")) {
1550                         option_verbose= atoi(v->value);
1551                 } else if (!strcasecmp(v->name, "debug")) {
1552                         option_debug= ast_true(v->value);
1553                 } else if (!strcasecmp(v->name, "nofork")) {
1554                         option_nofork = ast_true(v->value);
1555                 } else if (!strcasecmp(v->name, "quiet")) {
1556                         option_quiet = ast_true(v->value);
1557                 } else if (!strcasecmp(v->name, "console")) {
1558                         option_console = ast_true(v->value);
1559                 } else if (!strcasecmp(v->name, "highpriority")) {
1560                         option_highpriority = ast_true(v->value);
1561                 } else if (!strcasecmp(v->name, "initcrypto")) {
1562                         option_initcrypto = ast_true(v->value);
1563                 } else if (!strcasecmp(v->name, "nocolor")) {
1564                         option_nocolor = ast_true(v->value);
1565                 } else if (!strcasecmp(v->name, "dumpcore")) {
1566                         option_dumpcore = ast_true(v->value);
1567                 } else if (!strcasecmp(v->name, "cache_record_files")) {
1568                         option_cache_record_files = ast_true(v->value);
1569                 }  else if (!strcasecmp(v->name, "record_cache_dir")) {
1570                         strncpy(record_cache_dir,v->value,AST_CACHE_DIR_LEN);
1571                 }
1572                 v = v->next;
1573         }
1574         ast_destroy(cfg);
1575 }
1576
1577 int main(int argc, char *argv[])
1578 {
1579         int c;
1580         char filename[80] = "";
1581         char hostname[256];
1582         char tmp[80];
1583         char * xarg = NULL;
1584         int x;
1585         FILE *f;
1586         sigset_t sigs;
1587         int num;
1588         char *buf;
1589         char *runuser=NULL, *rungroup=NULL;
1590
1591         /* Remember original args for restart */
1592         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1593                 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1594                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1595         }
1596         for (x=0;x<argc;x++)
1597                 _argv[x] = argv[x];
1598         _argv[x] = NULL;
1599
1600         /* if the progname is rasterisk consider it a remote console */
1601         if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1602                 option_remote++;
1603                 option_nofork++;
1604         }
1605         if (gethostname(hostname, sizeof(hostname)))
1606                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1607         ast_mainpid = getpid();
1608         ast_ulaw_init();
1609         ast_alaw_init();
1610         callerid_init();
1611         ast_utils_init();
1612         tdd_init();
1613         if (getenv("HOME")) 
1614                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1615         /* Check if we're root */
1616         /*
1617         if (geteuid()) {
1618                 ast_log(LOG_ERROR, "Must be run as root\n");
1619                 exit(1);
1620         }
1621         */
1622         /* Check for options */
1623         while((c=getopt(argc, argv, "thfdvVqprRgcinx:U:G:C:")) != -1) {
1624                 switch(c) {
1625                 case 'd':
1626                         option_debug++;
1627                         option_nofork++;
1628                         break;
1629                 case 'c':
1630                         option_console++;
1631                         option_nofork++;
1632                         break;
1633                 case 'f':
1634                         option_nofork++;
1635                         break;
1636                 case 'n':
1637                         option_nocolor++;
1638                         break;
1639                 case 'r':
1640                         option_remote++;
1641                         option_nofork++;
1642                         break;
1643                 case 'R':
1644                         option_remote++;
1645                         option_nofork++;
1646                         option_reconnect++;
1647                         break;
1648                 case 'p':
1649                         option_highpriority++;
1650                         break;
1651                 case 'v':
1652                         option_verbose++;
1653                         option_nofork++;
1654                         break;
1655                 case 'q':
1656                         option_quiet++;
1657                         break;
1658                 case 't':
1659                         option_cache_record_files++;
1660                         break;
1661                 case 'x':
1662                         option_exec++;
1663                         xarg = optarg;
1664                         break;
1665                 case 'C':
1666                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE) - 1);
1667                         option_overrideconfig++;
1668                         break;
1669                 case 'i':
1670                         option_initcrypto++;
1671                         break;
1672                 case'g':
1673                         option_dumpcore++;
1674                         break;
1675                 case 'h':
1676                         show_cli_help();
1677                         exit(0);
1678                 case 'V':
1679                         show_version();
1680                         exit(0);
1681                 case 'U':
1682                         runuser = optarg;
1683                         break;
1684                 case 'G':
1685                         rungroup = optarg;
1686                         break;
1687                 case '?':
1688                         exit(1);
1689                 }
1690         }
1691
1692         if (option_dumpcore) {
1693                 struct rlimit l;
1694                 memset(&l, 0, sizeof(l));
1695                 l.rlim_cur = RLIM_INFINITY;
1696                 l.rlim_max = RLIM_INFINITY;
1697                 if (setrlimit(RLIMIT_CORE, &l)) {
1698                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1699                 }
1700         }
1701
1702         if (rungroup) {
1703                 struct group *gr;
1704                 gr = getgrnam(rungroup);
1705                 if (!gr) {
1706                         ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
1707                         exit(1);
1708                 }
1709                 if (setgid(gr->gr_gid)) {
1710                         ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", gr->gr_gid, rungroup);
1711                         exit(1);
1712                 }
1713                 if (option_verbose)
1714                         ast_verbose("Running as group '%s'\n", rungroup);
1715         }
1716
1717         if (set_priority(option_highpriority)) {
1718                 exit(1);
1719         }
1720         if (runuser) {
1721                 struct passwd *pw;
1722                 pw = getpwnam(runuser);
1723                 if (!pw) {
1724                         ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
1725                         exit(1);
1726                 }
1727                 if (setuid(pw->pw_uid)) {
1728                         ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", pw->pw_uid, runuser);
1729                         exit(1);
1730                 }
1731                 if (option_verbose)
1732                         ast_verbose("Running as user '%s'\n", runuser);
1733         }
1734
1735         term_init();
1736         printf(term_end());
1737         fflush(stdout);
1738
1739         if (option_console && !option_verbose) 
1740                 ast_verbose("[ Reading Master Configuration ]");
1741         ast_readconfig();
1742
1743         if (option_console && !option_verbose) 
1744                 ast_verbose("[ Initializing Custom Configuration Options]");
1745         /* custom config setup */
1746         register_config_cli();
1747         read_ast_cust_config();
1748         
1749
1750         if (option_console) {
1751                 if (el_hist == NULL || el == NULL)
1752                         ast_el_initialize();
1753
1754                 if (!ast_strlen_zero(filename))
1755                         ast_el_read_history(filename);
1756         }
1757
1758         if (ast_tryconnect()) {
1759                 /* One is already running */
1760                 if (option_remote) {
1761                         if (option_exec) {
1762                                 ast_remotecontrol(xarg);
1763                                 quit_handler(0, 0, 0, 0);
1764                                 exit(0);
1765                         }
1766                         printf(term_quit());
1767                         ast_register_verbose(console_verboser);
1768                         WELCOME_MESSAGE;
1769                         ast_remotecontrol(NULL);
1770                         quit_handler(0, 0, 0, 0);
1771                         exit(0);
1772                 } else {
1773                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1774                         printf(term_quit());
1775                         exit(1);
1776                 }
1777         } else if (option_remote || option_exec) {
1778                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1779                 printf(term_quit());
1780                 exit(1);
1781         }
1782         /* Blindly write pid file since we couldn't connect */
1783         unlink((char *)ast_config_AST_PID);
1784         f = fopen((char *)ast_config_AST_PID, "w");
1785         if (f) {
1786                 fprintf(f, "%d\n", getpid());
1787                 fclose(f);
1788         } else
1789                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1790
1791         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1792                 daemon(0,0);
1793                 /* Blindly re-write pid file since we are forking */
1794                 unlink((char *)ast_config_AST_PID);
1795                 f = fopen((char *)ast_config_AST_PID, "w");
1796                 if (f) {
1797                         fprintf(f, "%d\n", getpid());
1798                         fclose(f);
1799                 } else
1800                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1801         }
1802
1803         /* Test recursive mutex locking. */
1804         if (test_for_thread_safety())
1805                 ast_verbose("Warning! Asterisk is not thread safe.\n");
1806
1807         ast_makesocket();
1808         sigemptyset(&sigs);
1809         sigaddset(&sigs, SIGHUP);
1810         sigaddset(&sigs, SIGTERM);
1811         sigaddset(&sigs, SIGINT);
1812         sigaddset(&sigs, SIGPIPE);
1813         sigaddset(&sigs, SIGWINCH);
1814         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1815         if (option_console || option_verbose || option_remote)
1816                 ast_register_verbose(console_verboser);
1817         /* Print a welcome message if desired */
1818         if (option_verbose || option_console) {
1819                 WELCOME_MESSAGE;
1820         }
1821         if (option_console && !option_verbose) 
1822                 ast_verbose("[ Booting...");
1823
1824         signal(SIGURG, urg_handler);
1825         signal(SIGINT, __quit_handler);
1826         signal(SIGTERM, __quit_handler);
1827         signal(SIGHUP, hup_handler);
1828         signal(SIGCHLD, child_handler);
1829         signal(SIGPIPE, SIG_IGN);
1830
1831         if (init_logger()) {
1832                 printf(term_quit());
1833                 exit(1);
1834         }
1835         ast_channels_init();
1836         if (init_manager()) {
1837                 printf(term_quit());
1838                 exit(1);
1839         }
1840         ast_rtp_init();
1841         if (ast_image_init()) {
1842                 printf(term_quit());
1843                 exit(1);
1844         }
1845         if (ast_file_init()) {
1846                 printf(term_quit());
1847                 exit(1);
1848         }
1849         if (load_pbx()) {
1850                 printf(term_quit());
1851                 exit(1);
1852         }
1853         if (load_modules()) {
1854                 printf(term_quit());
1855                 exit(1);
1856         }
1857         if (init_framer()) {
1858                 printf(term_quit());
1859                 exit(1);
1860         }
1861         if (astdb_init()) {
1862                 printf(term_quit());
1863                 exit(1);
1864         }
1865         if (ast_enum_init()) {
1866                 printf(term_quit());
1867                 exit(1);
1868         }
1869 #if 0
1870         /* This should no longer be necessary */
1871         /* sync cust config and reload some internals in case a custom config handler binded to them */
1872         read_ast_cust_config();
1873         reload_logger(0);
1874         reload_manager();
1875         ast_enum_reload();
1876         ast_rtp_reload();
1877 #endif
1878
1879
1880         /* We might have the option of showing a console, but for now just
1881            do nothing... */
1882         if (option_console && !option_verbose)
1883                 ast_verbose(" ]\n");
1884         if (option_verbose || option_console)
1885                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1886         if (option_nofork)
1887                 consolethread = pthread_self();
1888         fully_booted = 1;
1889         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1890 #ifdef __AST_DEBUG_MALLOC
1891         __ast_mm_init();
1892 #endif  
1893         time(&ast_startuptime);
1894         ast_cli_register(&astshutdownnow);
1895         ast_cli_register(&astshutdowngracefully);
1896         ast_cli_register(&astrestartnow);
1897         ast_cli_register(&astrestartgracefully);
1898         ast_cli_register(&astrestartwhenconvenient);
1899         ast_cli_register(&astshutdownwhenconvenient);
1900         ast_cli_register(&aborthalt);
1901         ast_cli_register(&astbang);
1902         if (option_console) {
1903                 /* Console stuff now... */
1904                 /* Register our quit function */
1905                 char title[256];
1906                 set_icon("Asterisk");
1907                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1908                 set_title(title);
1909                 ast_cli_register(&quit);
1910                 ast_cli_register(&astexit);
1911
1912                 for (;;) {
1913                         buf = (char *)el_gets(el, &num);
1914                         if (buf) {
1915                                 if (buf[strlen(buf)-1] == '\n')
1916                                         buf[strlen(buf)-1] = '\0';
1917
1918                                 consolehandler((char *)buf);
1919                         } else {
1920                                 if (option_remote)
1921                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1922                         }
1923                 }
1924
1925         } else {
1926                 struct pollfd silly_macos[1];   
1927                 /* Do nothing */
1928                 for(;;) 
1929                         poll(silly_macos,0, -1);
1930         }
1931         return 0;
1932 }