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