Port Access Control.
[vde.git] / vdetelweb / vdetelweb.c
blob24c269f971a2794bf821f131fd3c95fff00ec237
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 #ifdef SIGSTKFLT
163 { SIGSTKFLT, "SIGSTKFLT", 1 },
164 #endif
165 { SIGIO, "SIGIO", 1 },
166 { SIGPWR, "SIGPWR", 1 },
167 #ifdef SIGUNUSED
168 { SIGUNUSED, "SIGUNUSED", 1 },
169 #endif
170 { 0, NULL, 0 }
173 int i;
174 for(i = 0; signals[i].sig != 0; i++)
175 if(signal(signals[i].sig,
176 signals[i].ignore ? SIG_IGN : sig_handler) < 0)
177 perror("Setting handler");
180 static void usage(char *progname) {
181 fprintf (stderr,"Usage: %s [-w] [-t] [-d] [-n nodename] [-p pidfile] mgmt_socket\n"
182 " %s [--web] [--telnet] [--daemon] [--nodename nodename] [--pidfile pidfile] mgmt_socket\n",progname,progname);
183 exit(-1);
186 void setprompt(char *ctrl,char *nodename)
188 char buf[BUFSIZE];
189 if (nodename==NULL) {
190 struct utsname un;
191 uname(&un);
192 snprintf(buf,BUFSIZE,"VDE2@%s[%s]: ",un.nodename,ctrl);
193 } else
194 snprintf(buf,BUFSIZE,"VDE2@%s[%s]: ",nodename,ctrl);
195 prompt=strdup(buf);
198 int openextravdem(void)
200 struct sockaddr_un sun;
201 int fd,n;
202 char buf[BUFSIZE+1];
203 sun.sun_family=PF_UNIX;
204 snprintf(sun.sun_path,UNIX_PATH_MAX,"%s",mgmt);
205 fd=socket(PF_UNIX,SOCK_STREAM,0);
206 if (connect(fd,(struct sockaddr *)(&sun),sizeof(sun)) < 0) {
207 printlog(LOG_ERR,"Error connecting to the management socket '%s': %s", mgmt, strerror(errno));
208 return(-1);
210 if ((n=read(fd,buf,BUFSIZE))<=0) {
211 printlog(LOG_ERR,"banner %s",strerror(errno));
212 return(-1);
214 return fd;
217 int openvdem(char *mgmt,char *progname, struct netif **nif,char *nodename)
219 struct sockaddr_un sun;
220 int fd,n;
221 char buf[BUFSIZE+1],*line2,*ctrl;
222 sun.sun_family=PF_UNIX;
223 snprintf(sun.sun_path,UNIX_PATH_MAX,"%s",mgmt);
224 fd=socket(PF_UNIX,SOCK_STREAM,0);
225 if (connect(fd,(struct sockaddr *)(&sun),sizeof(sun)) < 0) {
226 printlog(LOG_ERR,"Error connecting to the management socket '%s': %s", mgmt, strerror(errno));
227 exit(-1);
229 if ((n=read(fd,buf,BUFSIZE))<=0) {
230 printlog(LOG_ERR,"Error reading banner from VDE switch: %s",strerror(errno));
231 exit(-1);
233 buf[n]=0;
234 if ((ctrl=rindex(buf,'\n')) != NULL)
235 *ctrl=0;
236 banner=strdup(buf);
237 write(fd,"ds/showinfo\n",13);
238 if ((n=read(fd,buf,BUFSIZE))<=0) {
239 printlog(LOG_ERR,"Error reading ctl socket from VDE switch: %s",strerror(errno));
240 exit(-1);
242 buf[n]=0;
243 if ((line2=index(buf,'\n')) == NULL) {
244 printlog(LOG_ERR,"Error parsing first line of ctl socket information");
245 exit(-1);
247 line2++;
248 if (strncmp(line2,"ctl dir ",8) != 0) {
249 printlog(LOG_ERR,"Error parsing ctl socket information");
250 exit(-1);
252 for(ctrl=line2+8;*ctrl!='\n' && ctrl<buf+n;ctrl++)
254 *ctrl=0;
255 ctrl=line2+8;
256 setprompt(ctrl,nodename);
257 strcat(ctrl,"[0]");
258 *nif=lwip_vdeif_add(lwipstack,ctrl);
259 if (*nif == NULL) {
260 printlog(LOG_ERR,"Cannot connect to the VDE switch");
261 exit(-1);
263 lwip_ifup(*nif);
265 return fd;
268 static void bitno2mask(unsigned char *addr,int bitno,int len)
270 int i;
271 for(i=0;i<len;i++,bitno -= 8) {
272 if (bitno >= 8)
273 addr[i]=255;
274 else if (bitno <= 0)
275 addr[i]=0;
276 else
277 addr[i]=256 - (1<<(8-bitno));
281 static void sockaddr2ip_6addr(struct ip_addr *ipaddrp,unsigned char *addr)
283 IP6_ADDR(ipaddrp,
284 (addr[0]<<8)|addr[1],
285 (addr[2]<<8)|addr[3],
286 (addr[4]<<8)|addr[5],
287 (addr[6]<<8)|addr[7],
288 (addr[8]<<8)|addr[9],
289 (addr[10]<<8)|addr[11],
290 (addr[12]<<8)|addr[13],
291 (addr[14]<<8)|addr[15]);
294 static void readip(char *arg,struct netif *nif,int af)
296 char *bit=rindex(arg,'/');
297 if (bit == 0)
298 printlog(LOG_ERR,"IP addresses must include the netmask i.e. addr/maskbits");
299 else {
300 int bitno=atoi(bit+1);
301 *bit=0;
302 struct addrinfo *res,hint;
303 struct ip_addr ipaddr,netmask;
304 int err;
305 memset(&hint,0,sizeof(hint));
306 hint.ai_family=af;
307 if ((err=getaddrinfo(arg,NULL,&hint,&res))!=0)
308 printlog(LOG_ERR,"IP address %s error %s",arg,gai_strerror(err));
309 else {
310 switch(res->ai_family) {
311 case PF_INET:
313 struct sockaddr_in *in=(struct sockaddr_in *)res->ai_addr;
314 int addrh=ntohl(in->sin_addr.s_addr);
315 unsigned char i,addr[4];
316 for (i=0;i<4;i++,addrh>>=8)
317 addr[3-i]=addrh;
318 IP64_ADDR(&ipaddr, addr[0],addr[1],addr[2],addr[3]);
319 bitno2mask(addr,bitno,4);
320 IP64_MASKADDR(&netmask, addr[0],addr[1],addr[2],addr[3]);
321 lwip_add_addr(nif,&ipaddr,&netmask);
323 break;
324 case PF_INET6:
326 struct sockaddr_in6 *in=(struct sockaddr_in6 *)res->ai_addr;
327 unsigned char *addr=in->sin6_addr.s6_addr;
328 sockaddr2ip_6addr(&ipaddr,addr);
329 bitno2mask(addr,bitno,16);
330 sockaddr2ip_6addr(&netmask,addr);
331 lwip_add_addr(nif,&ipaddr,&netmask);
333 break;
334 default:
335 printlog(LOG_ERR,"Unsupported Address Family: %s",arg);
337 freeaddrinfo(res);
342 static void readdefroute(char *arg,struct netif *nif,int af)
344 struct addrinfo *res,hint;
345 struct ip_addr ipaddr;
346 int err;
347 memset(&hint,0,sizeof(hint));
348 hint.ai_family=af;
349 if ((err=getaddrinfo(arg,NULL,&hint,&res))!=0)
350 printlog(LOG_ERR,"IP address %s error %s",arg,gai_strerror(err));
351 else {
352 switch(res->ai_family) {
353 case PF_INET:
355 struct sockaddr_in *in=(struct sockaddr_in *)res->ai_addr;
356 int addrh=ntohl(in->sin_addr.s_addr);
357 unsigned char i,addr[4];
358 for (i=0;i<4;i++,addrh>>=8)
359 addr[3-i]=addrh;
360 IP64_ADDR(&ipaddr, addr[0],addr[1],addr[2],addr[3]);
361 lwip_add_route(lwipstack,IP_ADDR_ANY,IP_ADDR_ANY,&ipaddr,nif,0);
363 break;
364 case PF_INET6:
366 struct sockaddr_in6 *in=(struct sockaddr_in6 *)res->ai_addr;
367 sockaddr2ip_6addr(&ipaddr,in->sin6_addr.s6_addr);
368 lwip_add_route(lwipstack,IP_ADDR_ANY,IP_ADDR_ANY,&ipaddr,nif,0);
370 break;
371 default:
372 printlog(LOG_ERR,"Unsupported Address Family: %s",arg);
374 freeaddrinfo(res);
378 static void readpassword(char *arg,int unused)
380 passwd=strdup(arg);
383 struct cf {
384 char *tag;
385 void (*f)();
386 int arg;
387 } cft[]= {
388 {"ip4",readip,PF_INET},
389 {"ip6",readip,PF_INET6},
390 {"ip",readip,0},
391 {"defroute4",readdefroute,PF_INET},
392 {"defroute6",readdefroute,PF_INET6},
393 {"defroute",readdefroute,0},
394 {"password",readpassword,0},
395 {NULL,NULL,0}};
397 int readconffile(char *path,struct netif *nif)
399 FILE *f;
400 char buf[BUFSIZE],*s;
401 int line = 0;
403 if (path==NULL)
404 return -1;
405 if((f=fopen(path,"r"))==NULL)
406 return -1;
407 while (fgets(buf,BUFSIZE,f) != NULL)
409 line++;
411 if ((s=rindex(buf,'\n')) != NULL)
412 *s=0;
414 for(s=buf;*s == ' ' || *s == '\t';s++);
416 if (*s != '#' && *s != '\n' && *s != '\0')
418 struct cf *scf;
419 for (scf=cft;scf->tag != NULL;scf++)
420 if(strncmp(s,scf->tag,strlen(scf->tag)) == 0)
422 s+=strlen(scf->tag);
423 for(;*s == ' ' || *s == '\t';s++);
424 if (*s == '=')
425 s++;
426 for(;*s == ' ' || *s == '\t';s++);
427 scf->f(s,nif,scf->arg);
428 break;
430 if (scf->tag == NULL)
431 printlog(LOG_ERR,"Error parsing configuration file: line %d: %s", line, buf);
434 return 0;
437 int addpfd(int fd,voidfun cb)
439 if (npfd < MAXFD) {
440 pfd[npfd].fd=fd;
441 pfd[npfd].events=POLLIN|POLLHUP;
442 pfd[npfd].revents=0;
443 fpfd[npfd]=cb;
444 npfd++;
446 return npfd-1;
449 void delpfd(int fn)
451 int i=fn;
452 for (i=fn;i<npfd-1;i++) {
453 pfd[i]=pfd[i+1];
454 fpfd[i]=fpfd[i+1];
455 status[i]=status[i+1];
457 npfd--;
460 int pfdsearch(int fd)
462 int i;
463 for (i=0;i<npfd && pfd[i].fd!=fd;i++)
465 return i;
468 int setfds(fd_set *rds, fd_set *exc)
470 int i,max=0;
471 FD_ZERO(rds);
472 FD_ZERO(exc);
473 for (i=0;i<npfd;i++) {
474 FD_SET(pfd[i].fd,rds);
475 FD_SET(pfd[i].fd,exc);
476 if (pfd[i].fd>max) max=pfd[i].fd;
478 return max+1;
481 static void save_pidfile(void)
483 if(pidfile[0] != '/')
484 strncat(pidfile_path, pidfile, _POSIX_PATH_MAX - strlen(pidfile_path));
485 else
486 strcpy(pidfile_path, pidfile);
488 int fd = open(pidfile_path,
489 O_WRONLY | O_CREAT | O_EXCL,
490 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
491 FILE *f;
493 if(fd == -1) {
494 printlog(LOG_ERR, "Error in pidfile creation: %s", strerror(errno));
495 exit(1);
498 if((f = fdopen(fd, "w")) == NULL) {
499 printlog(LOG_ERR, "Error in FILE* construction: %s", strerror(errno));
500 exit(1);
503 if(fprintf(f, "%ld\n", (long int)getpid()) <= 0) {
504 printlog(LOG_ERR, "Error in writing pidfile");
505 exit(1);
508 fclose(f);
511 /* this custom version of daemon(3) continue to receive stderr messages
512 * until the end of the startup phase, the foreground process terminates
513 * when stderr gets closed*/
514 static int special_daemon(void)
516 int fd;
517 int errorpipe[2];
518 char buf[256];
519 int n;
521 if (pipe(errorpipe))
522 return -1;
524 switch (fork()) {
525 case -1:
526 return (-1);
527 case 0:
528 break;
529 default:
530 close(errorpipe[1]);
531 while ((n=read(errorpipe[0],buf,128)) > 0) {
532 write(STDERR_FILENO,buf,n);
534 _exit(0);
536 close(errorpipe[0]);
538 if (setsid() == -1)
539 return (-1);
541 (void)chdir("/");
543 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
544 (void)dup2(fd, STDIN_FILENO);
545 (void)dup2(fd, STDOUT_FILENO);
546 (void)dup2(errorpipe[1], STDERR_FILENO);
547 close(errorpipe[1]);
548 if (fd > 2)
549 (void)close (fd);
551 return 0;
554 int main(int argc, char *argv[])
556 struct netif *nif;
557 int vdefd;
558 char *conffile=NULL;
559 char *nodename=NULL;
560 int c;
562 progname=argv[0];
564 while (1) {
565 int option_index = 0;
567 static struct option long_options[] = {
568 {"daemon", 0, 0, 'd'},
569 {"mgmt", 1, 0, 'M'},
570 {"telnet", 0, 0, 't'},
571 {"web", 0, 0, 'w'},
572 {"help",0,0,'h'},
573 {"rcfile",1,0,'f'},
574 {"nodename",1,0,'n'},
575 {"pidfile", 1, 0, 'p'},
576 {0, 0, 0, 0}
578 c = getopt_long_only (argc, argv, "hdwtM:f:n:",
579 long_options, &option_index);
580 if (c == -1)
581 break;
583 switch (c) {
584 case 'M':
585 mgmt=strdup(optarg);
586 break;
587 case 'f':
588 conffile=strdup(optarg);
589 break;
590 case 'n':
591 nodename=strdup(optarg);
592 break;
593 case 't':
594 telnet=1;
595 break;
596 case 'w':
597 web=1;
598 break;
599 case 'd':
600 daemonize=1;
601 break;
602 case 'p':
603 pidfile=strdup(optarg);
604 break;
605 case 'h':
606 usage(argv[0]); //implies exit
607 break;
610 if (optind < argc && mgmt==NULL)
611 mgmt=argv[optind];
613 if (mgmt==NULL) {
614 printlog(LOG_ERR,"mgmt_socket not defined");
615 exit(-1);
617 if (telnet==0 && web==0) {
618 printlog(LOG_ERR,"at least one service option (-t -w) must be specified");
619 exit(-1);
622 atexit(cleanup);
623 setsighandlers();
625 /* saves current path in pidfile_path, because otherwise with daemonize() we
626 * forget it */
627 if(getcwd(pidfile_path, _POSIX_PATH_MAX-1) == NULL) {
628 printlog(LOG_ERR, "getcwd: %s", strerror(errno));
629 exit(1);
631 strcat(pidfile_path, "/");
633 /* call daemon before starting the stack otherwise the stack threads
634 * does not get inherited by the forked process */
635 if (daemonize && special_daemon()) {
636 printlog(LOG_ERR,"daemon: %s",strerror(errno));
637 exit(1);
640 lwipstack=lwip_stack_new();
641 lwip_stack_set(lwipstack);
643 vdefd = openvdem(mgmt, argv[0], &nif, nodename);
645 /* If rcfile is specified, try it and nothing else */
646 if (conffile && readconffile(conffile,nif) < 0)
648 printlog(LOG_ERR, "Error reading configuration file '%s': %s", conffile, strerror(errno));
649 exit(1);
651 /* Else try default ones */
652 else if (!conffile)
654 int rv;
655 char *homedir = getenv("HOME");
656 if (homedir)
658 int len = strlen(homedir) + strlen(USERCONFFILE) + 1;
659 conffile = malloc(len);
660 snprintf(conffile, len, "%s%s", homedir, USERCONFFILE);
661 if ((rv = readconffile(conffile, nif)) >= 0)
662 free(conffile);
664 if (!homedir || rv < 0)
665 rv = readconffile(conffile = ROOTCONFFILE, nif);
667 if (rv < 0)
669 printlog(LOG_ERR, "Error reading configuration file '%s': %s", conffile, strerror(errno));
670 exit(1);
674 /* once here, we're sure we're the true process which will continue as a
675 * server: save PID file if needed */
676 if(pidfile) save_pidfile();
678 if (telnet)
679 telnet_init(vdefd);
680 if (web)
681 web_init(vdefd);
683 if (daemonize) {
684 int fd;
685 if ((fd=open("/dev/null",O_RDWR)) >= 0) {
686 close(STDERR_FILENO);
687 dup2(fd,STDERR_FILENO);
688 close(fd);
689 openlog(basename(argv[0]), LOG_PID, 0);
690 logok=1;
692 printlog(LOG_INFO,"VDETELWEB started");
695 while (1)
697 int n,m,i;
698 fd_set rds,exc;
699 int max=setfds(&rds,&exc);
700 m=lwip_select(max,&rds,NULL,&exc,NULL);
701 for(i=0; m>0 && i<max; i++) {
702 if (FD_ISSET(i,&rds) || FD_ISSET(i,&exc)) {
703 n=pfdsearch(i);
704 fpfd[n](n,i,vdefd);
705 m--;