some acknowledgement comments added
[vde.git] / vdetelweb / vdetelweb.c
blob3444220283ecf054f5e330e080e21b896146db1b
1 /*
2 * VDETELWEB: VDE telnet and WEB interface
4 * vdetelweb.c: main
5 *
6 * Copyright 2005,2008 Virtual Square Team University of Bologna - Italy
7 * 2005 written by Renzo Davoli
8 * --pidfile/-p and cleanup management by Mattia Belletti (C) 2004
9 * (copied from vde_switch code).
10 * 2008 updated Renzo Davoli
11 * 2008 sha1sum by Marco Dalla Via
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 * $Id$
30 #include <config.h>
31 #include <stdio.h>
32 #include <signal.h>
33 #include <stdarg.h>
34 #include <syslog.h>
35 #include <errno.h>
36 #include <unistd.h>
37 #include <netdb.h>
38 #include <libgen.h>
39 #include <unistd.h>
40 #include <sys/types.h>
41 #include <sys/socket.h>
42 #include <sys/select.h>
43 #include <sys/poll.h>
44 #include <sys/wait.h>
45 #include <sys/utsname.h>
46 #include <linux/un.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <string.h>
50 #include <getopt.h>
51 #include <sys/stat.h>
52 #include <fcntl.h>
53 #include "vdetelweb.h"
54 #include <lwipv6.h>
56 int daemonize;
57 int telnet;
58 int web;
59 char *mgmt;
60 char *banner;
61 char *progname;
62 char *prompt;
63 int logok;
64 static char *passwd;
65 static char *pidfile = NULL;
66 static char pidfile_path[_POSIX_PATH_MAX];
67 struct stack *lwipstack;
69 #define MAXFD 16
70 #define HASH_SIZE 40
71 int npfd=0;
72 struct pollfd pfd[MAXFD];
73 voidfun fpfd[MAXFD];
74 void *status[MAXFD];
76 #define ROOTCONFFILE "/etc/vde/vdetelwebrc"
78 /* This will be prefixed by getenv("HOME") */
79 #define USERCONFFILE "/.vde/vdetelwebrc"
81 void printlog(int priority, const char *format, ...)
83 va_list arg;
85 va_start (arg, format);
87 if (logok)
88 vsyslog(priority,format,arg);
89 else {
90 fprintf(stderr,"%s: ",progname);
91 vfprintf(stderr,format,arg);
92 fprintf(stderr,"\n");
94 va_end (arg);
98 static void cleanup(void)
100 if (lwipstack)
101 lwip_stack_free(lwipstack);
102 if((pidfile != NULL) && unlink(pidfile_path) < 0) {
103 printlog(LOG_WARNING,"Couldn't remove pidfile '%s': %s", pidfile, strerror(errno));
107 int sha1passwdok(const char *pw) {
108 char buf[HASH_SIZE + 1];
109 int pfd_fc[2];
110 int pfd_cf[2];
111 pid_t pid;
113 pipe(pfd_fc);
114 pipe(pfd_cf);
115 pid = fork();
117 if (!pid) {
118 close(pfd_fc[1]);
119 close(pfd_cf[0]);
120 dup2(pfd_fc[0], STDIN_FILENO);
121 dup2(pfd_cf[1], STDOUT_FILENO);
123 execl("/usr/bin/sha1sum", "/usr/bin/sha1sum", NULL);
124 exit(1);
125 } else {
126 close(pfd_cf[1]);
127 close(pfd_fc[0]);
129 write(pfd_fc[1], pw, strlen(pw));
130 close(pfd_fc[1]);
131 read(pfd_cf[0], buf, sizeof(buf));
132 close(pfd_cf[0]);
134 waitpid(pid, NULL, 0);
135 return (strncmp(buf,passwd,strlen(passwd))==0);
139 static void sig_handler(int sig)
141 cleanup();
142 signal(sig, SIG_DFL);
143 kill(getpid(), sig);
146 static void setsighandlers(void)
148 /* setting signal handlers.
149 * * sets clean termination for SIGHUP, SIGINT and SIGTERM, and simply
150 * * ignores all the others signals which could cause termination. */
151 struct { int sig; const char *name; int ignore; } signals[] = {
152 { SIGHUP, "SIGHUP", 0 },
153 { SIGINT, "SIGINT", 0 },
154 { SIGPIPE, "SIGPIPE", 1 },
155 { SIGALRM, "SIGALRM", 1 },
156 { SIGTERM, "SIGTERM", 0 },
157 { SIGUSR1, "SIGUSR1", 1 },
158 { SIGUSR2, "SIGUSR2", 1 },
159 { SIGPOLL, "SIGPOLL", 1 },
160 { SIGPROF, "SIGPROF", 1 },
161 { SIGVTALRM, "SIGVTALRM", 1 },
162 { SIGSTKFLT, "SIGSTKFLT", 1 },
163 { SIGIO, "SIGIO", 1 },
164 { SIGPWR, "SIGPWR", 1 },
165 { SIGUNUSED, "SIGUNUSED", 1 },
166 { 0, NULL, 0 }
169 int i;
170 for(i = 0; signals[i].sig != 0; i++)
171 if(signal(signals[i].sig,
172 signals[i].ignore ? SIG_IGN : sig_handler) < 0)
173 perror("Setting handler");
176 static void usage(char *progname) {
177 fprintf (stderr,"Usage: %s [-w] [-t] [-d] [-n nodename] [-p pidfile] mgmt_socket\n"
178 " %s [--web] [--telnet] [--daemon] [--nodename nodename] [--pidfile pidfile] mgmt_socket\n",progname,progname);
179 exit(-1);
182 void setprompt(char *ctrl,char *nodename)
184 char buf[BUFSIZE];
185 if (nodename==NULL) {
186 struct utsname un;
187 uname(&un);
188 snprintf(buf,BUFSIZE,"VDE2@%s[%s]: ",un.nodename,ctrl);
189 } else
190 snprintf(buf,BUFSIZE,"VDE2@%s[%s]: ",nodename,ctrl);
191 prompt=strdup(buf);
194 int openextravdem(void)
196 struct sockaddr_un sun;
197 int fd,n;
198 char buf[BUFSIZE+1];
199 sun.sun_family=PF_UNIX;
200 snprintf(sun.sun_path,UNIX_PATH_MAX,"%s",mgmt);
201 fd=socket(PF_UNIX,SOCK_STREAM,0);
202 if (connect(fd,(struct sockaddr *)(&sun),sizeof(sun)) < 0) {
203 printlog(LOG_ERR,"Error connecting to the management socket '%s': %s", mgmt, strerror(errno));
204 return(-1);
206 if ((n=read(fd,buf,BUFSIZE))<=0) {
207 printlog(LOG_ERR,"banner %s",strerror(errno));
208 return(-1);
210 return fd;
213 int openvdem(char *mgmt,char *progname, struct netif **nif,char *nodename)
215 struct sockaddr_un sun;
216 int fd,n;
217 char buf[BUFSIZE+1],*line2,*ctrl;
218 sun.sun_family=PF_UNIX;
219 snprintf(sun.sun_path,UNIX_PATH_MAX,"%s",mgmt);
220 fd=socket(PF_UNIX,SOCK_STREAM,0);
221 if (connect(fd,(struct sockaddr *)(&sun),sizeof(sun)) < 0) {
222 printlog(LOG_ERR,"Error connecting to the management socket '%s': %s", mgmt, strerror(errno));
223 exit(-1);
225 if ((n=read(fd,buf,BUFSIZE))<=0) {
226 printlog(LOG_ERR,"Error reading banner from VDE switch: %s",strerror(errno));
227 exit(-1);
229 buf[n]=0;
230 if ((ctrl=rindex(buf,'\n')) != NULL)
231 *ctrl=0;
232 banner=strdup(buf);
233 write(fd,"ds/showinfo\n",13);
234 if ((n=read(fd,buf,BUFSIZE))<=0) {
235 printlog(LOG_ERR,"Error reading ctl socket from VDE switch: %s",strerror(errno));
236 exit(-1);
238 buf[n]=0;
239 if ((line2=index(buf,'\n')) == NULL) {
240 printlog(LOG_ERR,"Error parsing first line of ctl socket information");
241 exit(-1);
243 line2++;
244 if (strncmp(line2,"ctl dir ",8) != 0) {
245 printlog(LOG_ERR,"Error parsing ctl socket information");
246 exit(-1);
248 for(ctrl=line2+8;*ctrl!='\n' && ctrl<buf+n;ctrl++)
250 *ctrl=0;
251 ctrl=line2+8;
252 setprompt(ctrl,nodename);
253 strcat(ctrl,"[0]");
254 *nif=lwip_vdeif_add(lwipstack,ctrl);
255 if (*nif == NULL) {
256 printlog(LOG_ERR,"Cannot connect to the VDE switch");
257 exit(-1);
259 lwip_ifup(*nif);
261 return fd;
264 static void bitno2mask(unsigned char *addr,int bitno,int len)
266 int i;
267 for(i=0;i<len;i++,bitno -= 8) {
268 if (bitno >= 8)
269 addr[i]=255;
270 else if (bitno <= 0)
271 addr[i]=0;
272 else
273 addr[i]=256 - (1<<(8-bitno));
277 static void sockaddr2ip_6addr(struct ip_addr *ipaddrp,unsigned char *addr)
279 IP6_ADDR(ipaddrp,
280 (addr[0]<<8)|addr[1],
281 (addr[2]<<8)|addr[3],
282 (addr[4]<<8)|addr[5],
283 (addr[6]<<8)|addr[7],
284 (addr[8]<<8)|addr[9],
285 (addr[10]<<8)|addr[11],
286 (addr[12]<<8)|addr[13],
287 (addr[14]<<8)|addr[15]);
290 static void readip(char *arg,struct netif *nif,int af)
292 char *bit=rindex(arg,'/');
293 if (bit == 0)
294 printlog(LOG_ERR,"IP addresses must include the netmask i.e. addr/maskbits");
295 else {
296 int bitno=atoi(bit+1);
297 *bit=0;
298 struct addrinfo *res,hint;
299 struct ip_addr ipaddr,netmask;
300 int err;
301 memset(&hint,0,sizeof(hint));
302 hint.ai_family=af;
303 if ((err=getaddrinfo(arg,NULL,&hint,&res))!=0)
304 printlog(LOG_ERR,"IP address %s error %s",arg,gai_strerror(err));
305 else {
306 switch(res->ai_family) {
307 case PF_INET:
309 struct sockaddr_in *in=(struct sockaddr_in *)res->ai_addr;
310 int addrh=ntohl(in->sin_addr.s_addr);
311 unsigned char i,addr[4];
312 for (i=0;i<4;i++,addrh>>=8)
313 addr[3-i]=addrh;
314 IP64_ADDR(&ipaddr, addr[0],addr[1],addr[2],addr[3]);
315 bitno2mask(addr,bitno,4);
316 IP64_MASKADDR(&netmask, addr[0],addr[1],addr[2],addr[3]);
317 lwip_add_addr(nif,&ipaddr,&netmask);
319 break;
320 case PF_INET6:
322 struct sockaddr_in6 *in=(struct sockaddr_in6 *)res->ai_addr;
323 unsigned char *addr=in->sin6_addr.s6_addr;
324 sockaddr2ip_6addr(&ipaddr,addr);
325 bitno2mask(addr,bitno,16);
326 sockaddr2ip_6addr(&netmask,addr);
327 lwip_add_addr(nif,&ipaddr,&netmask);
329 break;
330 default:
331 printlog(LOG_ERR,"Unsupported Address Family: %s",arg);
333 freeaddrinfo(res);
338 static void readdefroute(char *arg,struct netif *nif,int af)
340 struct addrinfo *res,hint;
341 struct ip_addr ipaddr;
342 int err;
343 memset(&hint,0,sizeof(hint));
344 hint.ai_family=af;
345 if ((err=getaddrinfo(arg,NULL,&hint,&res))!=0)
346 printlog(LOG_ERR,"IP address %s error %s",arg,gai_strerror(err));
347 else {
348 switch(res->ai_family) {
349 case PF_INET:
351 struct sockaddr_in *in=(struct sockaddr_in *)res->ai_addr;
352 int addrh=ntohl(in->sin_addr.s_addr);
353 unsigned char i,addr[4];
354 for (i=0;i<4;i++,addrh>>=8)
355 addr[3-i]=addrh;
356 IP64_ADDR(&ipaddr, addr[0],addr[1],addr[2],addr[3]);
357 lwip_add_route(lwipstack,IP_ADDR_ANY,IP_ADDR_ANY,&ipaddr,nif,0);
359 break;
360 case PF_INET6:
362 struct sockaddr_in6 *in=(struct sockaddr_in6 *)res->ai_addr;
363 sockaddr2ip_6addr(&ipaddr,in->sin6_addr.s6_addr);
364 lwip_add_route(lwipstack,IP_ADDR_ANY,IP_ADDR_ANY,&ipaddr,nif,0);
366 break;
367 default:
368 printlog(LOG_ERR,"Unsupported Address Family: %s",arg);
370 freeaddrinfo(res);
374 static void readpassword(char *arg,int unused)
376 passwd=strdup(arg);
379 struct cf {
380 char *tag;
381 void (*f)();
382 int arg;
383 } cft[]= {
384 {"ip4",readip,PF_INET},
385 {"ip6",readip,PF_INET6},
386 {"ip",readip,0},
387 {"defroute4",readdefroute,PF_INET},
388 {"defroute6",readdefroute,PF_INET6},
389 {"defroute",readdefroute,0},
390 {"password",readpassword,0},
391 {NULL,NULL,0}};
393 int readconffile(char *path,struct netif *nif)
395 FILE *f;
396 char buf[BUFSIZE],*s;
397 int line = 0;
399 if (path==NULL)
400 return -1;
401 if((f=fopen(path,"r"))==NULL)
402 return -1;
403 while (fgets(buf,BUFSIZE,f) != NULL)
405 line++;
407 if ((s=rindex(buf,'\n')) != NULL)
408 *s=0;
410 for(s=buf;*s == ' ' || *s == '\t';s++);
412 if (*s != '#' && *s != '\n' && *s != '\0')
414 struct cf *scf;
415 for (scf=cft;scf->tag != NULL;scf++)
416 if(strncmp(s,scf->tag,strlen(scf->tag)) == 0)
418 s+=strlen(scf->tag);
419 for(;*s == ' ' || *s == '\t';s++);
420 if (*s == '=')
421 s++;
422 for(;*s == ' ' || *s == '\t';s++);
423 scf->f(s,nif,scf->arg);
424 break;
426 if (scf->tag == NULL)
427 printlog(LOG_ERR,"Error parsing configuration file: line %d: %s", line, buf);
430 return 0;
433 int addpfd(int fd,voidfun cb)
435 if (npfd < MAXFD) {
436 pfd[npfd].fd=fd;
437 pfd[npfd].events=POLLIN|POLLHUP;
438 pfd[npfd].revents=0;
439 fpfd[npfd]=cb;
440 npfd++;
442 return npfd-1;
445 void delpfd(int fn)
447 int i=fn;
448 for (i=fn;i<npfd-1;i++) {
449 pfd[i]=pfd[i+1];
450 fpfd[i]=fpfd[i+1];
451 status[i]=status[i+1];
453 npfd--;
456 int pfdsearch(int fd)
458 int i;
459 for (i=0;i<npfd && pfd[i].fd!=fd;i++)
461 return i;
464 int setfds(fd_set *rds, fd_set *exc)
466 int i,max=0;
467 FD_ZERO(rds);
468 FD_ZERO(exc);
469 for (i=0;i<npfd;i++) {
470 FD_SET(pfd[i].fd,rds);
471 FD_SET(pfd[i].fd,exc);
472 if (pfd[i].fd>max) max=pfd[i].fd;
474 return max+1;
477 static void save_pidfile(void)
479 if(pidfile[0] != '/')
480 strncat(pidfile_path, pidfile, _POSIX_PATH_MAX - strlen(pidfile_path));
481 else
482 strcpy(pidfile_path, pidfile);
484 int fd = open(pidfile_path,
485 O_WRONLY | O_CREAT | O_EXCL,
486 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
487 FILE *f;
489 if(fd == -1) {
490 printlog(LOG_ERR, "Error in pidfile creation: %s", strerror(errno));
491 exit(1);
494 if((f = fdopen(fd, "w")) == NULL) {
495 printlog(LOG_ERR, "Error in FILE* construction: %s", strerror(errno));
496 exit(1);
499 if(fprintf(f, "%ld\n", (long int)getpid()) <= 0) {
500 printlog(LOG_ERR, "Error in writing pidfile");
501 exit(1);
504 fclose(f);
507 /* this custom version of daemon(3) continue to receive stderr messages
508 * until the end of the startup phase, the foreground process terminates
509 * when stderr gets closed*/
510 static int special_daemon(void)
512 int fd;
513 int errorpipe[2];
514 char buf[256];
515 int n;
517 if (pipe(errorpipe))
518 return -1;
520 switch (fork()) {
521 case -1:
522 return (-1);
523 case 0:
524 break;
525 default:
526 close(errorpipe[1]);
527 while ((n=read(errorpipe[0],buf,128)) > 0) {
528 write(STDERR_FILENO,buf,n);
530 _exit(0);
532 close(errorpipe[0]);
534 if (setsid() == -1)
535 return (-1);
537 (void)chdir("/");
539 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
540 (void)dup2(fd, STDIN_FILENO);
541 (void)dup2(fd, STDOUT_FILENO);
542 (void)dup2(errorpipe[1], STDERR_FILENO);
543 close(errorpipe[1]);
544 if (fd > 2)
545 (void)close (fd);
547 return 0;
550 int main(int argc, char *argv[])
552 struct netif *nif;
553 int vdefd;
554 char *conffile=NULL;
555 char *nodename=NULL;
556 int c;
558 progname=argv[0];
560 while (1) {
561 int option_index = 0;
563 static struct option long_options[] = {
564 {"daemon", 0, 0, 'd'},
565 {"mgmt", 1, 0, 'M'},
566 {"telnet", 0, 0, 't'},
567 {"web", 0, 0, 'w'},
568 {"help",0,0,'h'},
569 {"rcfile",1,0,'f'},
570 {"nodename",1,0,'n'},
571 {"pidfile", 1, 0, 'p'},
572 {0, 0, 0, 0}
574 c = getopt_long_only (argc, argv, "hdwtM:f:n:",
575 long_options, &option_index);
576 if (c == -1)
577 break;
579 switch (c) {
580 case 'M':
581 mgmt=strdup(optarg);
582 break;
583 case 'f':
584 conffile=strdup(optarg);
585 break;
586 case 'n':
587 nodename=strdup(optarg);
588 break;
589 case 't':
590 telnet=1;
591 break;
592 case 'w':
593 web=1;
594 break;
595 case 'd':
596 daemonize=1;
597 break;
598 case 'p':
599 pidfile=strdup(optarg);
600 break;
601 case 'h':
602 usage(argv[0]); //implies exit
603 break;
606 if (optind < argc && mgmt==NULL)
607 mgmt=argv[optind];
609 if (mgmt==NULL) {
610 printlog(LOG_ERR,"mgmt_socket not defined");
611 exit(-1);
613 if (telnet==0 && web==0) {
614 printlog(LOG_ERR,"at least one service option (-t -w) must be specified");
615 exit(-1);
618 atexit(cleanup);
619 setsighandlers();
621 /* saves current path in pidfile_path, because otherwise with daemonize() we
622 * forget it */
623 if(getcwd(pidfile_path, _POSIX_PATH_MAX-1) == NULL) {
624 printlog(LOG_ERR, "getcwd: %s", strerror(errno));
625 exit(1);
627 strcat(pidfile_path, "/");
629 /* call daemon before starting the stack otherwise the stack threads
630 * does not get inherited by the forked process */
631 if (daemonize && special_daemon()) {
632 printlog(LOG_ERR,"daemon: %s",strerror(errno));
633 exit(1);
636 lwipstack=lwip_stack_new();
637 lwip_stack_set(lwipstack);
639 vdefd = openvdem(mgmt, argv[0], &nif, nodename);
641 /* If rcfile is specified, try it and nothing else */
642 if (conffile && readconffile(conffile,nif) < 0)
644 printlog(LOG_ERR, "Error reading configuration file '%s': %s", conffile, strerror(errno));
645 exit(1);
647 /* Else try default ones */
648 else if (!conffile)
650 int rv;
651 char *homedir = getenv("HOME");
652 if (homedir)
654 int len = strlen(homedir) + strlen(USERCONFFILE) + 1;
655 conffile = malloc(len);
656 snprintf(conffile, len, "%s%s", homedir, USERCONFFILE);
657 if ((rv = readconffile(conffile, nif)) >= 0)
658 free(conffile);
660 if (!homedir || rv < 0)
661 rv = readconffile(conffile = ROOTCONFFILE, nif);
663 if (rv < 0)
665 printlog(LOG_ERR, "Error reading configuration file '%s': %s", conffile, strerror(errno));
666 exit(1);
670 /* once here, we're sure we're the true process which will continue as a
671 * server: save PID file if needed */
672 if(pidfile) save_pidfile();
674 if (telnet)
675 telnet_init(vdefd);
676 if (web)
677 web_init(vdefd);
679 if (daemonize) {
680 int fd;
681 if ((fd=open("/dev/null",O_RDWR)) >= 0) {
682 close(STDERR_FILENO);
683 dup2(fd,STDERR_FILENO);
684 close(fd);
685 openlog(basename(argv[0]), LOG_PID, 0);
686 logok=1;
688 printlog(LOG_INFO,"VDETELWEB started");
691 while (1)
693 int n,m,i;
694 fd_set rds,exc;
695 int max=setfds(&rds,&exc);
696 m=lwip_select(max,&rds,NULL,&exc,NULL);
697 for(i=0; m>0 && i<max; i++) {
698 if (FD_ISSET(i,&rds) || FD_ISSET(i,&exc)) {
699 n=pfdsearch(i);
700 fpfd[n](n,i,vdefd);
701 m--;