a73307be006e316e777ad4d47b120aa6a32f5ebb
[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, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
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/callerid.h>
22 #include <asterisk/module.h>
23 #include <stdio.h>
24 #include <signal.h>
25 #include <sched.h>
26 #include <pthread.h>
27 #include <sys/socket.h>
28 #include <sys/un.h>
29 #include <sys/select.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <readline/readline.h>
33 #include <readline/history.h>
34 #include "asterisk.h"
35
36 #define AST_MAX_CONNECTS 128
37 #define NUM_MSGS 64
38
39 int option_verbose=0;
40 int option_debug=0;
41 int option_nofork=0;
42 int option_quiet=0;
43 int option_console=0;
44 int option_highpriority=0;
45 int option_remote=0;
46 int option_exec=0;
47 int fully_booted = 0;
48
49 static int ast_socket = -1;             /* UNIX Socket for allowing remote control */
50 static int ast_consock = -1;            /* UNIX Socket for controlling another asterisk */
51 static int mainpid;
52 struct console {
53         int fd;                                 /* File descriptor */
54         int p[2];                               /* Pipe */
55         pthread_t t;                    /* Thread of handler */
56 };
57
58 struct console consoles[AST_MAX_CONNECTS];
59
60 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
61
62 static int fdprint(int fd, char *s)
63 {
64         return write(fd, s, strlen(s) + 1);
65 }
66
67 static void network_verboser(char *s, int pos, int replace, int complete)
68 {
69         int x;
70         for (x=0;x<AST_MAX_CONNECTS; x++) {
71                 if (consoles[x].fd > -1) 
72                         fdprint(consoles[x].p[1], s);
73         }
74 }
75
76 static pthread_t lthread;
77
78 static void *netconsole(void *vconsole)
79 {
80         struct console *con = vconsole;
81         char hostname[256];
82         char tmp[512];
83         int res;
84         int max;
85         fd_set rfds;
86         
87         if (gethostname(hostname, sizeof(hostname)))
88                 strncpy(hostname, "<Unknown>", sizeof(hostname));
89         snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, mainpid, ASTERISK_VERSION);
90         fdprint(con->fd, tmp);
91         for(;;) {
92                 FD_ZERO(&rfds); 
93                 FD_SET(con->fd, &rfds);
94                 FD_SET(con->p[0], &rfds);
95                 max = con->fd;
96                 if (con->p[0] > max)
97                         max = con->p[0];
98                 res = select(max + 1, &rfds, NULL, NULL, NULL);
99                 if (res < 0) {
100                         ast_log(LOG_WARNING, "select returned < 0: %s\n", strerror(errno));
101                         continue;
102                 }
103                 if (FD_ISSET(con->fd, &rfds)) {
104                         res = read(con->fd, tmp, sizeof(tmp));
105                         if (res < 1)
106                                 break;
107                         tmp[res] = 0;
108                         ast_cli_command(con->fd, tmp);
109                 }
110                 if (FD_ISSET(con->p[0], &rfds)) {
111                         res = read(con->p[0], tmp, sizeof(tmp));
112                         if (res < 1) {
113                                 ast_log(LOG_ERROR, "read returned %d\n", res);
114                                 break;
115                         }
116                         res = write(con->fd, tmp, res);
117                         if (res < 1)
118                                 break;
119                 }
120         }
121         if (option_verbose > 2) 
122                 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
123         close(con->fd);
124         close(con->p[0]);
125         close(con->p[1]);
126         con->fd = -1;
127         
128         return NULL;
129 }
130
131 static void *listener(void *unused)
132 {
133         struct sockaddr_un sun;
134         int s;
135         int len;
136         int x;
137         pthread_attr_t attr;
138         pthread_attr_init(&attr);
139         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
140         for(;;) {
141                 len = sizeof(sun);
142                 s = accept(ast_socket, (struct sockaddr *)&sun, &len);
143                 if (s < 0) {
144                         ast_log(LOG_WARNING, "Accept retured %d: %s\n", s, strerror(errno));
145                 } else {
146                         for (x=0;x<AST_MAX_CONNECTS;x++) {
147                                 if (consoles[x].fd < 0) {
148                                         if (pipe(consoles[x].p)) {
149                                                 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
150                                                 consoles[x].fd = -1;
151                                                 fdprint(s, "Server failed to create pipe\n");
152                                                 close(s);
153                                                 break;
154                                         }
155                                         consoles[x].fd = s;
156                                         if (pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
157                                                 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection\n");
158                                                 consoles[x].fd = -1;
159                                                 fdprint(s, "Server failed to spawn thread\n");
160                                                 close(s);
161                                         }
162                                         break;
163                                 }
164                         }
165                         if (x >= AST_MAX_CONNECTS) {
166                                 fdprint(s, "No more connections allowed\n");
167                                 ast_log(LOG_WARNING, "No more connections allowed\n");
168                                 close(s);
169                         } else if (consoles[x].fd > -1) {
170                                 if (option_verbose > 2) 
171                                         ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
172                         }
173                 }
174         }
175         return NULL;
176 }
177
178 static int ast_makesocket(void)
179 {
180         struct sockaddr_un sun;
181         int res;
182         int x;
183         for (x=0;x<AST_MAX_CONNECTS;x++)        
184                 consoles[x].fd = -1;
185         unlink(AST_SOCKET);
186         ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
187         if (ast_socket < 0) {
188                 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
189                 return -1;
190         }               
191         memset(&sun, 0, sizeof(sun));
192         sun.sun_family = AF_LOCAL;
193         strncpy(sun.sun_path, AST_SOCKET, sizeof(sun.sun_path));
194         res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
195         if (res) {
196                 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", AST_SOCKET, strerror(errno));
197                 close(ast_socket);
198                 ast_socket = -1;
199                 return -1;
200         }
201         res = listen(ast_socket, 2);
202         if (res < 0) {
203                 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", AST_SOCKET, strerror(errno));
204                 close(ast_socket);
205                 ast_socket = -1;
206                 return -1;
207         }
208         ast_register_verbose(network_verboser);
209         pthread_create(&lthread, NULL, listener, NULL);
210         return 0;
211 }
212
213 static int ast_tryconnect(void)
214 {
215         struct sockaddr_un sun;
216         int res;
217         ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
218         if (ast_consock < 0) {
219                 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
220                 return 0;
221         }
222         memset(&sun, 0, sizeof(sun));
223         sun.sun_family = AF_LOCAL;
224         strncpy(sun.sun_path, AST_SOCKET, sizeof(sun.sun_path));
225         res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
226         if (res) {
227                 close(ast_consock);
228                 ast_consock = -1;
229                 return 0;
230         } else
231                 return 1;
232 }
233
234 static void urg_handler(int num)
235 {
236         /* Called by soft_hangup to interrupt the select, read, or other
237            system call.  We don't actually need to do anything though.  */
238         if (option_debug) 
239                 ast_log(LOG_DEBUG, "Urgent handler\n");
240         signal(num, urg_handler);
241         return;
242 }
243
244 static void hup_handler(int num)
245 {
246         if (option_verbose > 1) 
247                 ast_verbose(VERBOSE_PREFIX_2 "Received HUP signal -- Reloading configs\n");
248         ast_module_reload();
249 }
250
251
252 static void pipe_handler(int num)
253 {
254         /* Ignore sigpipe */
255 }
256 static void set_title(char *text)
257 {
258         /* Set an X-term or screen title */
259         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
260                 fprintf(stdout, "\033]2;%s\007", text);
261 }
262
263 static void set_icon(char *text)
264 {
265         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
266                 fprintf(stdout, "\033]1;%s\007", text);
267 }
268
269 static int set_priority(int pri)
270 {
271         struct sched_param sched;
272         memset(&sched, 0, sizeof(sched));
273         /* We set ourselves to a high priority, that we might pre-empt everything
274            else.  If your PBX has heavy activity on it, this is a good thing.  */
275         if (pri) {  
276                 sched.sched_priority = 10;
277                 if (sched_setscheduler(0, SCHED_RR, &sched)) {
278                         ast_log(LOG_WARNING, "Unable to set high priority\n");
279                         return -1;
280                 } else
281                         if (option_verbose)
282                                 ast_verbose("Set to realtime thread\n");
283         } else {
284                 sched.sched_priority = 0;
285                 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
286                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
287                         return -1;
288                 }
289         }
290         return 0;
291 }
292
293 static void quit_handler(int num)
294 {
295         char filename[80] = "";
296         if (option_console || option_remote) {
297                 if (getenv("HOME")) 
298                         snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
299                 if (strlen(filename))
300                         write_history(filename);
301                 rl_callback_handler_remove();
302         }
303         /* Called on exit */
304         if (option_verbose && option_console)
305                 ast_verbose("Asterisk ending (%d).\n", num);
306         else if (option_debug)
307                 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
308         if (ast_socket > -1)
309                 close(ast_socket);
310         if (ast_consock > -1)
311                 close(ast_consock);
312         if (ast_socket > -1)
313                 unlink(AST_SOCKET);
314         
315         exit(0);
316 }
317
318 static pthread_t consolethread = -1;
319
320 static void console_verboser(char *s, int pos, int replace, int complete)
321 {
322         /* Return to the beginning of the line */
323         if (!pos)
324                 fprintf(stdout, "\r");
325         fprintf(stdout, s + pos);
326         fflush(stdout);
327         if (complete)
328         /* Wake up a select()ing console */
329                 pthread_kill(consolethread, SIGURG);
330 }
331
332 static void consolehandler(char *s)
333 {
334         /* Called when readline data is available */
335         if (s && strlen(s))
336                 add_history(s);
337         /* Give the console access to the shell */
338         if (s) {
339                 if (s[0] == '!') {
340                         if (s[1])
341                                 system(s+1);
342                         else
343                                 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
344                 } else 
345                 ast_cli_command(STDOUT_FILENO, s);
346                 if (!strcasecmp(s, "help"))
347                         fprintf(stdout, "          !<command>   Executes a given shell command\n");
348         } else
349                 fprintf(stdout, "\nUse \"quit\" to exit\n");
350 }
351
352
353 static char cmd[1024];
354
355 static void remoteconsolehandler(char *s)
356 {
357         /* Called when readline data is available */
358         if (s && strlen(s))
359                 add_history(s);
360         /* Give the console access to the shell */
361         if (s) {
362                 if (s[0] == '!') {
363                         if (s[1])
364                                 system(s+1);
365                         else
366                                 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
367                 } else 
368                 strncpy(cmd, s, sizeof(cmd));
369                 if (!strcasecmp(s, "help"))
370                         fprintf(stdout, "          !<command>   Executes a given shell command\n");
371                 if (!strcasecmp(s, "quit"))
372                         quit_handler(0);
373         } else
374                 fprintf(stdout, "\nUse \"quit\" to exit\n");
375 }
376
377 static char quit_help[] = 
378 "Usage: quit\n"
379 "       Exits Asterisk.\n";
380
381 static char shutdown_help[] = 
382 "Usage: shutdown\n"
383 "       Shuts down a running Asterisk PBX.\n";
384
385 static int handle_quit(int fd, int argc, char *argv[])
386 {
387         if (argc != 1)
388                 return RESULT_SHOWUSAGE;
389         quit_handler(0);
390         return RESULT_SUCCESS;
391 }
392
393 #define ASTERISK_PROMPT "*CLI> "
394
395 #define ASTERISK_PROMPT2 "%s*CLI> "
396
397 static struct ast_cli_entry quit =      { { "quit", NULL }, handle_quit, "Exit Asterisk", quit_help };
398
399 static struct ast_cli_entry astshutdown =       { { "shutdown", NULL }, handle_quit, "Shut down an Asterisk PBX", shutdown_help };
400
401 static char *cli_generator(char *text, int state)
402 {
403         return ast_cli_generator(rl_line_buffer, text, state);
404 }
405
406 static char *console_cli_generator(char *text, int state)
407 {
408         char buf[1024];
409         int res;
410 #if 0
411         fprintf(stderr, "Searching for '%s', %s %d\n", rl_line_buffer, text, state);
412 #endif  
413         snprintf(buf, sizeof(buf),"_COMMAND COMPLETE \"%s\" \"%s\" %d", rl_line_buffer, text, state); 
414         fdprint(ast_consock, buf);
415         res = read(ast_consock, buf, sizeof(buf));
416         buf[res] = '\0';
417 #if 0
418         printf("res is %d, buf is '%s'\n", res, buf);
419 #endif  
420         if (strncmp(buf, "NULL", 4))
421                 return strdup(buf);
422         else
423                 return NULL;
424 }
425
426 static void ast_remotecontrol(char * data)
427 {
428         char buf[80];
429         int res;
430         int max;
431         int lastpos = 0;
432         fd_set rfds;
433         char filename[80] = "";
434         char *hostname;
435         char *cpid;
436         char *version;
437         int pid;
438         char tmp[80];
439         read(ast_consock, buf, sizeof(buf));
440         if (data) {
441                         write(ast_consock, data, strlen(data) + 1);
442                         return;
443         }
444         hostname = strtok(buf, "/");
445         cpid = strtok(NULL, "/");
446         version = strtok(NULL, "/");
447         if (!version)
448                 version = "<Version Unknown>";
449         strtok(hostname, ".");
450         if (cpid)
451                 pid = atoi(cpid);
452         else
453                 pid = -1;
454         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
455         fdprint(ast_consock, tmp);
456         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
457         snprintf(tmp, sizeof(tmp), ASTERISK_PROMPT2, hostname);
458         if (getenv("HOME")) 
459                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
460         if (strlen(filename))
461                 read_history(filename);
462     ast_cli_register(&quit);
463     ast_cli_register(&astshutdown);
464         rl_callback_handler_install(tmp, remoteconsolehandler);
465         rl_completion_entry_function = (Function *)console_cli_generator;
466         for(;;) {
467                 FD_ZERO(&rfds);
468                 FD_SET(ast_consock, &rfds);
469                 FD_SET(STDIN_FILENO, &rfds);
470                 max = ast_consock;
471                 if (STDIN_FILENO > max)
472                         max = STDIN_FILENO;
473                 res = select(max + 1, &rfds, NULL, NULL, NULL);
474                 if (res < 0) {
475                         if (errno == EINTR)
476                                 continue;
477                         ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
478                         break;
479                 }
480                 if (FD_ISSET(STDIN_FILENO, &rfds)) {
481                         rl_callback_read_char();
482                         if (strlen(cmd)) {
483                                 res = write(ast_consock, cmd, strlen(cmd) + 1);
484                                 if (res < 1) {
485                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
486                                         break;
487                                 }
488                                 strcpy(cmd, "");
489                         }
490                 }
491                 if (FD_ISSET(ast_consock, &rfds)) {
492                         res = read(ast_consock, buf, sizeof(buf));
493                         if (res < 1)
494                                 break;
495                         buf[res] = 0;
496                         if (!lastpos)
497                                 write(STDOUT_FILENO, "\r", 2);
498                         write(STDOUT_FILENO, buf, res);
499                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
500                                 rl_forced_update_display();
501                                 lastpos = 0;
502                         } else {
503                                 lastpos = 1;
504                         }
505                 }
506         }
507         printf("\nDisconnected from Asterisk server\n");
508 }
509
510 int main(int argc, char *argv[])
511 {
512         char c;
513         fd_set rfds;
514         int res;
515         int pid;
516         char filename[80] = "";
517         char hostname[256];
518         char * xarg = NULL;
519         sigset_t sigs;
520
521         if (gethostname(hostname, sizeof(hostname)))
522                 strncpy(hostname, "<Unknown>", sizeof(hostname));
523         mainpid = getpid();
524         ast_ulaw_init();
525         callerid_init();
526         if (getenv("HOME")) 
527                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
528         /* Check if we're root */
529         if (geteuid()) {
530                 ast_log(LOG_ERROR, "Must be run as root\n");
531                 exit(1);
532         }
533         /* Check for options */
534         while((c=getopt(argc, argv, "fdvqprcx:")) != EOF) {
535                 switch(c) {
536                 case 'd':
537                         option_debug++;
538                         option_nofork++;
539                         break;
540                 case 'c':
541                         option_console++;
542                         option_nofork++;
543                         break;
544                 case 'f':
545                         option_nofork++;
546                         break;
547                 case 'r':
548                         option_remote++;
549                         option_nofork++;
550                         break;
551                 case 'p':
552                         option_highpriority++;
553                         break;
554                 case 'v':
555                         option_verbose++;
556                         option_nofork++;
557                         break;
558                 case 'q':
559                         option_quiet++;
560                         break;
561                 case 'x':
562                         option_exec++;
563                         xarg = optarg;
564                         break;
565                 case '?':
566                         exit(1);
567                 }
568         }
569         
570         if (ast_tryconnect()) {
571                 /* One is already running */
572                 if (option_remote) {
573                         if (option_exec) {
574                                 ast_remotecontrol(xarg);
575                                 quit_handler(0);
576                                 exit(0);
577                         }
578                         ast_register_verbose(console_verboser);
579                         ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
580                         ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
581                         ast_verbose( "=========================================================================\n");
582                         ast_remotecontrol(NULL);
583                         quit_handler(0);
584                         exit(0);
585                 } else {
586                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", AST_SOCKET);
587                         exit(1);
588                 }
589         } else if (option_remote || option_exec) {
590                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
591                 exit(1);
592         }
593         if (!option_verbose && !option_console && !option_debug) {
594                 pid = fork();
595                 if (pid < 0) {
596                         ast_log(LOG_ERROR, "Unable to fork(): %s\n", strerror(errno));
597                         exit(1);
598                 }
599                 if (pid) 
600                         exit(0);
601         }
602         ast_makesocket();
603         sigemptyset(&sigs);
604         sigaddset(&sigs, SIGHUP);
605         sigaddset(&sigs, SIGTERM);
606         sigaddset(&sigs, SIGINT);
607         sigaddset(&sigs, SIGPIPE);
608         sigaddset(&sigs, SIGWINCH);
609         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
610         if (option_console || option_verbose || option_remote)
611                 ast_register_verbose(console_verboser);
612         /* Print a welcome message if desired */
613         if (option_verbose || option_console) {
614                 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
615                 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
616                 ast_verbose( "=========================================================================\n");
617         }
618         if (option_console && !option_verbose) 
619                 ast_verbose("[ Booting...");
620         signal(SIGURG, urg_handler);
621         signal(SIGINT, quit_handler);
622         signal(SIGTERM, quit_handler);
623         signal(SIGHUP, hup_handler);
624         signal(SIGPIPE, pipe_handler);
625         if (set_priority(option_highpriority))
626                 exit(1);
627         if (init_logger())
628                 exit(1);
629         if (load_pbx())
630                 exit(1);
631         if (load_modules())
632                 exit(1);
633         /* We might have the option of showing a console, but for now just
634            do nothing... */
635         if (option_console && !option_verbose)
636                 ast_verbose(" ]\n");
637         if (option_verbose || option_console)
638                 ast_verbose( "Asterisk Ready.\n");
639         fully_booted = 1;
640         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
641     ast_cli_register(&astshutdown);
642         if (option_console) {
643                 /* Console stuff now... */
644                 /* Register our quit function */
645                 char title[256];
646                 set_icon("Asterisk");
647                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
648                 set_title(title);
649             ast_cli_register(&quit);
650                 consolethread = pthread_self();
651                 if (strlen(filename))
652                         read_history(filename);
653                 rl_callback_handler_install(ASTERISK_PROMPT, consolehandler);
654                 rl_completion_entry_function = (Function *)cli_generator;
655                 for(;;) {
656                         FD_ZERO(&rfds);
657                         FD_SET(STDIN_FILENO, &rfds);
658                         res = select(STDIN_FILENO + 1, &rfds, NULL, NULL, NULL);
659                         if (res > 0) {
660                                 rl_callback_read_char();
661                         } else if (res < 1) {
662                                 rl_forced_update_display();
663                         }
664         
665                 }       
666         } else {
667                 /* Do nothing */
668                 select(0,NULL,NULL,NULL,NULL);
669         }
670         return 0;
671 }