BUGFIX: timing error on wirefilter/markov mode. some minor fix on the wirefilter...
[vde.git] / vde-2 / src / wirefilter.c
blob0b417b7bf34c1c831c4286a904f2b048ccfad357
1 /* WIREFILTER (C) 2005 Renzo Davoli
2 * Licensed under the GPLv2
3 * Modified by Ludovico Gardenghi 2005
4 * Modified by Renzo Davoli, Luca Bigliardi 2007
5 * Modified by Renzo Davoli, Luca Raggi 2009 (Markov chain support)
6 * Gauss normal distribution/blinking support, requested and parlty implemented
7 * by Luca Saiu and Jean-Vincent Loddo (Marionnet project)
8 * Gilbert model for packet loss requested by Leandro Galvao.
10 * This filter can be used for testing network protcols.
11 * It is possible to loose, delay or reorder packets.
12 * Options can be set on command line or interactively with a remote interface
13 * on a unix socket (see unixterm).
16 #define _GNU_SOURCE
17 #include <stdio.h>
18 #include <unistd.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <getopt.h>
22 #include <errno.h>
23 #include <libgen.h>
24 #include <syslog.h>
25 #include <fcntl.h>
26 #include <time.h>
27 #include <signal.h>
28 #include <math.h>
29 #include <stdarg.h>
30 #include <limits.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/socket.h>
35 #include <sys/un.h>
37 #include <config.h>
38 #include <vde.h>
39 #include <vdecommon.h>
40 #include <libvdeplug.h>
42 #if defined(VDE_DARWIN) || defined(VDE_FREEBSD)
43 # if defined HAVE_SYSLIMITS_H
44 # include <syslimits.h>
45 # elif defined HAVE_SYS_SYSLIMITS_H
46 # include <sys/syslimits.h>
47 # else
48 # error "No syslimits.h found"
49 # endif
50 #endif
52 #define NPIPES 2
53 #define MAXCONN 3
54 static int alternate_stdin;
55 static int alternate_stdout;
56 #define NPFD NPIPES+NPIPES+MAXCONN+1
57 struct pollfd pfd[NPFD]={[0 ... NPFD-1 ]={.fd=-1}};
58 int outfd[NPIPES];
59 char debuglevel[NPFD];
60 char *progname;
61 char *mgmt;
62 int mgmtmode=0700;
63 #define LR 0
64 #define RL 1
65 #define ALGO_UNIFORM 0
66 #define ALGO_GAUSS_NORMAL 1
67 static char charalgo[]="UN";
68 struct wirevalue {
69 double value;
70 double plus;
71 char alg;
74 #define LOSS 0
75 #define LOSTBURST 1
76 #define DELAY 2
77 #define DDUP 3
78 #define BAND 4
79 #define SPEED 5
80 #define CAPACITY 6
81 #define NOISE 7
82 #define MTU 8
83 #define NUMVALUES 9
85 /* general Markov chain approach */
86 int markov_numnodes=0;
87 int markov_current=0;
88 struct markov_node {
89 char *name;
90 struct wirevalue val[NUMVALUES][2];
92 double *adjmap;
93 #define ADJMAPN(M,I,J,N) (M)[(I)*(N)+(J)]
94 #define ADJMAP(I,J) ADJMAPN(adjmap,(I),(J),markov_numnodes)
95 #define ROT(I,J) (((I)+(J))%markov_numnodes)
96 struct markov_node **markov_nodes;
97 #define WFVAL(N,T,D) (markov_nodes[N]->val[T][D])
98 #define WFADDR(N,T) (markov_nodes[N]->val[T])
99 #define WFNAME(N) (markov_nodes[N]->name)
100 double markov_time=100.0;
101 long long markov_next;
103 /*for the Gilbert model */
104 #define OK_BURST 0
105 #define FAULTY_BURST 1
106 char loss_status[2]; /* Gilbert model Markov chain status */
107 struct timeval nextband[2];
108 struct timeval nextspeed[2];
109 int nofifo;
110 int ndirs; //1 mono directional, 2 bi directional filter (always 2 with -v)
111 int delay_bufsize[2]; //total size of delayed packets
112 char *vdepath[2]; //path of the directly connected switched (via vde_plug)
113 VDECONN *vdeplug[2]; //vde_plug connections (if NULL stdin/stdout)
114 int daemonize; // daemon mode
115 static int logok=0;
116 static char *rcfile;
117 static char *pidfile = NULL;
118 static char pidfile_path[PATH_MAX];
119 static int blinksock;
120 static struct sockaddr_un blinksun;
121 static char *blinkmsg;
122 static char blinkidlen;
124 static void printoutc(int fd, const char *format, ...);
125 /* markov node mgmt */
126 static inline struct markov_node *markov_node_new(void)
128 return calloc(1,sizeof(struct markov_node));
131 static inline void markov_node_free(struct markov_node *old)
133 free(old);
136 static void markov_compute(i)
138 int j;
139 ADJMAP(i,i)=100.0;
140 for (j=1;j<markov_numnodes;j++)
141 ADJMAP(i,i)-=ADJMAP(i,ROT(i,j));
144 static void copyadjmap(int newsize, double *newmap)
146 int i,j;
147 for (i=0;i<newsize;i++) {
148 ADJMAPN(newmap,i,i,newsize)=100.0;
149 for (j=1;j<newsize;j++) {
150 int newj=(i+j)%newsize;
151 if (i<markov_numnodes && newj<markov_numnodes)
152 ADJMAPN(newmap,i,i,newsize)-=
153 (ADJMAPN(newmap,i,newj,newsize) = ADJMAP(i,newj));
158 static void markov_resize(int numnodes)
160 if (numnodes != markov_numnodes) {
161 int i;
162 double *newadjmap=calloc(numnodes*numnodes,sizeof(double));
163 if (numnodes>markov_numnodes) {
164 markov_nodes=realloc(markov_nodes,numnodes*(sizeof(struct markov_node *)));
165 for (i=markov_numnodes;i<numnodes;i++)
166 markov_nodes[i]=markov_node_new();
167 } else {
168 for (i=numnodes;i<markov_numnodes;i++)
169 markov_node_free(markov_nodes[i]);
170 markov_nodes=realloc(markov_nodes,numnodes*(sizeof(struct markov_node *)));
171 if (markov_current >= numnodes)
172 markov_current = 0;
174 copyadjmap(numnodes,newadjmap);
175 if (adjmap)
176 free(adjmap);
177 adjmap=newadjmap;
178 markov_numnodes=numnodes;
182 static int markov_step(int i) {
183 double num=drand48() * 100;
184 int j,k=0;
185 markov_next+=markov_time;
186 for (j=0;j<markov_numnodes;j++) {
187 k=ROT(i,j);
188 double val=ADJMAP(i,ROT(i,j));
189 if (num <= val)
190 break;
191 else
192 num -= val;
194 if (i != k) {
195 for (j=0;j<NPFD;j++) {
196 if (debuglevel[j] > 0) {
197 int fd=pfd[j].fd;
198 if (fd == 0) fd=1;
199 printoutc(fd,"%04d Node %d \"%s\" -> %d \"%s\"",
200 3800+k,
201 i, WFNAME(i)?WFNAME(i):"",
202 k, WFNAME(k)?WFNAME(k):"");
206 return k;
209 static int markovms(void) {
210 if (markov_numnodes > 1) {
211 struct timeval v;
212 gettimeofday(&v,NULL);
213 unsigned long long next=markov_next-(v.tv_sec*1000+v.tv_usec/1000);
214 if (next < 0) next=0;
215 return next;
216 } else
217 return -1;
220 static inline void markov_try(void) {
221 if (markov_numnodes > 1) {
222 struct timeval v;
223 gettimeofday(&v,NULL);
224 if ((markov_next-(v.tv_sec*1000+v.tv_usec/1000)) <= 0)
225 markov_current=markov_step(markov_current);
229 static void markov_start(void) {
230 if (markov_numnodes > 1) {
231 struct timeval v;
232 gettimeofday(&v,NULL);
233 markov_next=v.tv_sec*1000+v.tv_usec/1000;
234 markov_current=markov_step(markov_current);
238 #define BUFSIZE 2048
239 #define MAXCMD 128
240 #define MGMTMODEARG 129
241 #define DAEMONIZEARG 130
242 #define PIDFILEARG 131
243 #define LOGSOCKETARG 132
244 #define LOGIDARG 133
245 #define KILO (1<<10)
246 #define MEGA (1<<20)
247 #define GIGA (1<<30)
249 static inline double max_wirevalue(int node,int tag, int dir)
251 return (WFVAL(node,tag,dir).value + WFVAL(node,tag,dir).plus);
254 static inline double min_wirevalue(int node,int tag, int dir)
256 return (WFVAL(node,tag,dir).value - WFVAL(node,tag,dir).plus);
259 static void initrand()
261 struct timeval v;
262 gettimeofday(&v,NULL);
263 srand48(v.tv_sec ^ v.tv_usec ^ getpid());
266 /*more than 98% inside the bell */
267 #define SIGMA (1.0/3.0)
268 static double compute_wirevalue(int tag, int dir)
270 struct wirevalue *wv=&WFVAL(markov_current,tag,dir);
271 if (wv->plus == 0)
272 return wv->value;
273 switch (wv->alg) {
274 case ALGO_UNIFORM:
275 return wv->value+wv->plus*((drand48()*2.0)-1.0);
276 case ALGO_GAUSS_NORMAL:
278 double x,y,r2;
279 do {
280 x = (2*drand48())-1;
281 y = (2*drand48())-1;
282 r2=x*x+y*y;
283 } while (r2 >= 1.0);
284 return wv->value+wv->plus* SIGMA * x * sqrt ( (-2 * log(r2)) /r2);
286 default:
287 return 0.0;
291 void printlog(int priority, const char *format, ...)
293 va_list arg;
295 va_start (arg, format);
297 if (logok)
298 vsyslog(priority,format,arg);
299 else {
300 fprintf(stderr,"%s: ",progname);
301 vfprintf(stderr,format,arg);
302 fprintf(stderr,"\n");
304 va_end (arg);
307 static int read_wirevalue(char *s, int tag)
309 struct wirevalue *wv;
310 int markov_node=0;
311 double v=0.0;
312 double vplus=0.0;
313 int n;
314 int mult;
315 char algo=ALGO_UNIFORM;
316 n=strlen(s)-1;
317 while ((s[n] == ' ' || s[n] == '\n' || s[n] == '\t') && n>0)
318 s[n--]=0;
319 if (s[n]==']')
321 char *idstr=&s[n];
322 s[n--] = 0;
323 while(s[n]!='[' && n>1)
324 idstr = &s[n--];
325 s[n--] = 0;
326 sscanf(idstr,"%d",&markov_node);
327 if (markov_node < 0 || markov_node >= markov_numnodes)
328 return EINVAL;
330 wv=WFADDR(markov_node,tag);
331 switch (s[n]) {
332 case 'u':
333 case 'U':
334 algo=ALGO_UNIFORM;
335 n--;
336 break;
337 case 'n':
338 case 'N':
339 algo=ALGO_GAUSS_NORMAL;
340 n--;
341 break;
343 switch (s[n]) {
344 case 'k':
345 case 'K':
346 mult=KILO;
347 break;
348 case 'm':
349 case 'M':
350 mult=MEGA;
351 break;
352 case 'g':
353 case 'G':
354 mult=GIGA;
355 break;
356 default:
357 mult=1;
358 break;
360 if ((n=sscanf(s,"%lf+%lf",&v,&vplus)) > 0) {
361 wv[LR].value=wv[RL].value=v*mult;
362 wv[LR].plus=wv[RL].plus=vplus*mult;
363 wv[LR].alg=wv[RL].alg=algo;
364 } else if ((n=sscanf(s,"LR%lf+%lf",&v,&vplus)) > 0) {
365 wv[LR].value=v*mult;
366 wv[LR].plus=vplus*mult;
367 wv[LR].alg=algo;
368 } else if ((n=sscanf(s,"RL%lf+%lf",&v,&vplus)) > 0) {
369 wv[RL].value=v*mult;
370 wv[RL].plus=vplus*mult;
371 wv[RL].alg=algo;
373 return 0;
376 struct packpq {
377 unsigned long long when;
378 int dir;
379 unsigned char *buf;
380 int size;
383 struct packpq **pqh;
384 struct packpq sentinel={0,0,NULL,0};
385 int npq,maxpq;
386 unsigned long long maxwhen;
388 #define PQCHUNK 100
390 static int nextms()
392 if (npq>0) {
393 long long deltat;
394 struct timeval v;
395 gettimeofday(&v,NULL);
396 deltat=pqh[1]->when-(v.tv_sec*1000000+v.tv_usec);
397 return (deltat>0)?(int)(deltat/1000):0;
399 return -1;
402 static inline int outpacket(int dir,const unsigned char *buf,int size)
404 if (blinksock) {
405 snprintf(blinkmsg+blinkidlen,20,"%s %d\n",
406 (ndirs==2)?((dir==0)?"LR":"RL"):"--",
407 size);
408 sendto(blinksock,blinkmsg,strlen(blinkmsg+blinkidlen)+blinkidlen,0,
409 (struct sockaddr *)&blinksun, sizeof(blinksun));
411 if (vdeplug[1-dir])
412 return vde_send(vdeplug[1-dir],buf+2,size-2,0);
413 else
414 return write(outfd[dir],buf,size);
417 int writepacket(int dir,const unsigned char *buf,int size)
419 /* NOISE */
420 if (max_wirevalue(markov_current,NOISE,dir) > 0) {
421 double noiseval=compute_wirevalue(NOISE,dir);
422 int nobit=0;
423 while ((drand48()*8*MEGA) < (size-2)*8*noiseval)
424 nobit++;
425 if (nobit>0) {
426 unsigned char noisedpacket[BUFSIZE];
427 memcpy(noisedpacket,buf,size);
428 while(nobit>0) {
429 int flippedbit=(drand48()*size*8);
430 noisedpacket[(flippedbit >> 3) + 2] ^= 1<<(flippedbit & 0x7);
431 nobit--;
433 return outpacket(dir,noisedpacket,size);
434 } else
435 return outpacket(dir,buf,size);
436 } else
437 return outpacket(dir,buf,size);
440 /* packet queues are priority queues implemented on a heap.
441 * enqueue time = dequeue time = O(log n) max&mean
444 static void packet_dequeue()
446 struct timeval v;
447 gettimeofday(&v,NULL);
448 unsigned long long now=v.tv_sec*1000000+v.tv_usec;
449 while (npq>0 && pqh[1]->when <= now) {
450 struct packpq *old=pqh[npq--];
451 int k=1;
452 delay_bufsize[pqh[1]->dir] -= pqh[1]->size;
453 writepacket(pqh[1]->dir,pqh[1]->buf,pqh[1]->size);
454 free(pqh[1]->buf);
455 free(pqh[1]);
456 while (k<= npq>>1)
458 int j= k<<1;
459 if (j<npq && pqh[j]->when > pqh[j+1]->when) j++;
460 if (old->when <= pqh[j]->when) {
461 break;
462 } else {
463 pqh[k]=pqh[j];k=j;
466 pqh[k]=old;
470 static void packet_enqueue(int dir,const unsigned char *buf,int size,int delms)
472 struct timeval v;
474 /* CAPACITY */
475 /* when bandwidth is limited, packets exceeding capacity are discarded */
476 if (max_wirevalue(markov_current,CAPACITY,dir) > 0) {
477 double capval=compute_wirevalue(CAPACITY,dir);
478 if ((delay_bufsize[dir]+size) > capval)
479 return;
481 /* */
483 struct packpq *new=malloc(sizeof(struct packpq));
484 if (new==NULL) {
485 printlog(LOG_WARNING,"malloc elem %s",strerror(errno));
486 exit (1);
488 gettimeofday(&v,NULL);
489 new->when=v.tv_sec * 1000000 + v.tv_usec + delms * 1000;
490 if (new->when > maxwhen) maxwhen=new->when;
491 if (!nofifo && new->when < maxwhen) new->when=maxwhen;
492 new->dir=dir;
493 new->buf=malloc(size);
494 if (new->buf==NULL) {
495 printlog(LOG_WARNING,"malloc elem buf %s",strerror(errno));
496 exit (1);
498 memcpy(new->buf,buf,size);
499 new->size=size;
500 delay_bufsize[dir]+=size;
501 if (pqh==NULL) {
502 pqh=malloc(PQCHUNK*sizeof(struct packpq *));
503 if (pqh==NULL) {
504 printlog(LOG_WARNING,"malloc %s",strerror(errno));
505 exit (1);
507 pqh[0]=&sentinel; maxpq=PQCHUNK;
509 if (npq >= maxpq) {
510 pqh=realloc(pqh,(maxpq=maxpq+PQCHUNK) * sizeof(struct packpq *));
511 if (pqh==NULL) {
512 printlog(LOG_WARNING,"malloc %s",strerror(errno));
513 exit (1);
516 {int k=++npq;
517 while (new->when < pqh[k>>1]->when) {
518 pqh[k]=pqh[k>>1];
519 k >>= 1;
521 pqh[k]=new;
525 void handle_packet(int dir,const unsigned char *buf,int size)
527 /* MTU */
528 /* if the packet is incosistent with the MTU of the line just drop it */
529 if (min_wirevalue(markov_current,MTU,dir) > 0 && size > min_wirevalue(markov_current,MTU,dir))
530 return;
532 /* LOSS */
533 /* Total packet loss */
534 if (min_wirevalue(markov_current,LOSS,dir) >= 100.0)
535 return;
536 /* probabilistic loss */
537 if (max_wirevalue(markov_current,LOSTBURST,dir) > 0) {
538 /* Gilbert model */
539 double losval=compute_wirevalue(LOSS,dir)/100;
540 double burstlen=compute_wirevalue(LOSTBURST,dir);
541 double alpha=losval / (burstlen*(1-losval));
542 double beta=1.0 / burstlen;
543 switch (loss_status[dir]) {
544 case OK_BURST:
545 if (drand48() < alpha) loss_status[dir]=FAULTY_BURST;
546 break;
547 case FAULTY_BURST:
548 if (drand48() < beta) loss_status[dir]=OK_BURST;
549 break;
551 if (loss_status[dir] != OK_BURST)
552 return;
553 } else {
554 loss_status[dir] = OK_BURST;
555 if (max_wirevalue(markov_current,LOSS,dir) > 0) {
556 /* standard non bursty model */
557 double losval=compute_wirevalue(LOSS,dir)/100;
558 if (drand48() < losval)
559 return;
563 /* DUP */
564 /* times is the number of dup packets */
565 int times=1;
566 if (max_wirevalue(markov_current,DDUP,dir) > 0) {
567 double dupval=compute_wirevalue(DDUP,dir)/100;
568 while (drand48() < dupval)
569 times++;
571 while (times>0) {
572 int banddelay=0;
574 /* SPEED */
575 /* speed limit, if packets arrive too fast, delay the sender */
576 if (max_wirevalue(markov_current,SPEED,dir) > 0) {
577 double speedval=compute_wirevalue(SPEED,dir);
578 if (speedval<=0) return;
579 if (speedval>0) {
580 unsigned int commtime=((unsigned)size)*1000000/((unsigned int)speedval);
581 struct timeval tv;
582 gettimeofday(&tv,NULL);
583 banddelay=commtime/1000;
584 if (timercmp(&tv,&nextspeed[dir], > ))
585 nextspeed[dir]=tv;
586 nextspeed[dir].tv_usec += commtime;
587 nextspeed[dir].tv_sec += nextspeed[dir].tv_usec / 1000000;
588 nextspeed[dir].tv_usec %= 1000000;
592 /* BANDWIDTH */
593 /* band, when band overflows, delay just the delivery */
594 if (max_wirevalue(markov_current,BAND,dir) > 0) {
595 double bandval=compute_wirevalue(BAND,dir);
596 if (bandval<=0) return;
597 if (bandval >0) {
598 unsigned int commtime=((unsigned)size)*1000000/((unsigned int)bandval);
599 struct timeval tv;
600 gettimeofday(&tv,NULL);
601 if (timercmp(&tv,&nextband[dir], > )) {
602 nextband[dir]=tv;
603 banddelay=commtime/1000;
604 } else {
605 timersub(&nextband[dir],&tv,&tv);
606 banddelay=tv.tv_sec*1000 + (tv.tv_usec + commtime)/1000;
608 nextband[dir].tv_usec += commtime;
609 nextband[dir].tv_sec += nextband[dir].tv_usec / 1000000;
610 nextband[dir].tv_usec %= 1000000;
611 } else
612 banddelay=-1;
615 /* DELAY */
616 /* line delay */
617 if (banddelay >= 0) {
618 if (banddelay > 0 || max_wirevalue(markov_current,DELAY,dir) > 0) {
619 double delval=compute_wirevalue(DELAY,dir);
620 delval=(delval >= 0)?delval+banddelay:banddelay;
621 if (delval > 0) {
622 packet_enqueue(dir,buf,size,(int) delval);
623 } else
624 writepacket(dir,buf,size);
625 } else
626 writepacket(dir,buf,size);
628 times--;
632 #define MIN(X,Y) (((X)<(Y))?(X):(Y))
634 static void splitpacket(const unsigned char *buf,int size,int dir)
636 static unsigned char fragment[BUFSIZE][2];
637 static unsigned char *fragp[2];
638 static unsigned int rnx[2],remaining[2];
640 //fprintf(stderr,"%s: splitpacket rnx=%d remaining=%d size=%d\n",progname,rnx[dir],remaining[dir],size);
641 if (size==0) return;
642 if (rnx[dir]>0) {
643 register int amount=MIN(remaining[dir],size);
644 //fprintf(stderr,"%s: fragment amount %d\n",progname,amount);
645 memcpy(fragp[dir],buf,amount);
646 remaining[dir]-=amount;
647 fragp[dir]+=amount;
648 buf+=amount;
649 size-=amount;
650 if (remaining[dir]==0) {
651 //fprintf(stderr,"%s: delivered defrag %d\n",progname,rnx[dir]);
652 handle_packet(dir,fragment[dir],rnx[dir]+2);
653 rnx[dir]=0;
656 while (size > 0) {
657 rnx[dir]=(buf[0]<<8)+buf[1];
658 //fprintf(stderr,"%s: packet %d size %d %x %x dir %d\n",progname,rnx[dir],size-2,buf[0],buf[1],dir);
659 if (rnx[dir]>1521) {
660 printlog(LOG_WARNING,"Packet length error size %d rnx %d",size,rnx[dir]);
661 rnx[dir]=0;
662 return;
664 if (rnx[dir]+2 > size) {
665 //fprintf(stderr,"%s: begin defrag %d\n",progname,rnx[dir]);
666 fragp[dir]=fragment[dir];
667 memcpy(fragp[dir],buf,size);
668 remaining[dir]=rnx[dir]+2-size;
669 fragp[dir]+=size;
670 size=0;
671 } else {
672 handle_packet(dir,buf,rnx[dir]+2);
673 buf+=rnx[dir]+2;
674 size-=rnx[dir]+2;
675 rnx[dir]=0;
680 static void packet_in(int dir)
682 unsigned char buf[BUFSIZE];
683 int n;
684 if(vdeplug[dir]) {
685 n=vde_recv(vdeplug[dir],buf+2,BUFSIZE-2,0);
686 buf[0]=n>>8;
687 buf[1]=n&0xFF;
688 handle_packet(dir,buf,n+2);
689 } else {
690 n=read(pfd[dir].fd,buf,BUFSIZE);
691 if (n == 0)
692 exit (0);
693 splitpacket(buf,n,dir);
697 static int check_open_fifos_n_plugs(struct pollfd *pfd,int *outfd,char *vdepath[],VDECONN *vdeplug[])
699 int ndirs=0;
700 struct stat stfd[NPIPES];
701 char *env_in;
702 char *env_out;
703 env_in=getenv("ALTERNATE_STDIN");
704 env_out=getenv("ALTERNATE_STDOUT");
705 if (env_in != NULL)
706 alternate_stdin=atoi(env_in);
707 if (env_out != NULL)
708 alternate_stdout=atoi(env_out);
709 if (vdepath[0]) { // -v selected
710 if (strcmp(vdepath[0],"-") != 0) {
711 if((vdeplug[LR]=vde_open(vdepath[0],"vde_crosscable",NULL))==NULL){
712 fprintf(stderr,"vdeplug %s: %s\n",vdepath[0],strerror(errno));
713 return -1;
715 pfd[0].fd=vde_datafd(vdeplug[LR]);
716 pfd[0].events=POLLIN | POLLHUP;
718 if (strcmp(vdepath[1],"-") != 0) {
719 if((vdeplug[RL]=vde_open(vdepath[1],"vde_crosscable",NULL))==NULL){
720 fprintf(stderr,"vdeplug %s: %s\n",vdepath[1],strerror(errno));
721 return -1;
723 pfd[1].fd=vde_datafd(vdeplug[RL]);
724 pfd[1].events=POLLIN | POLLHUP;
726 ndirs=2;
728 if (vdeplug[LR] == NULL || vdeplug[RL] == NULL) {
729 if (fstat(STDIN_FILENO,&stfd[STDIN_FILENO]) < 0) {
730 fprintf(stderr,"%s: Error on stdin: %s\n",progname,strerror(errno));
731 return -1;
733 if (fstat(STDOUT_FILENO,&stfd[STDOUT_FILENO]) < 0) {
734 fprintf(stderr,"%s: Error on stdout: %s\n",progname,strerror(errno));
735 return -1;
737 if (!S_ISFIFO(stfd[STDIN_FILENO].st_mode)) {
738 fprintf(stderr,"%s: Error on stdin: %s\n",progname,"it is not a pipe");
739 return -1;
741 if (!S_ISFIFO(stfd[STDOUT_FILENO].st_mode)) {
742 fprintf(stderr,"%s: Error on stdin: %s\n",progname,"it is not a pipe");
743 return -1;
745 if (vdeplug[RL] != NULL) { /* -v -:xxx */
746 pfd[0].fd=STDIN_FILENO;
747 pfd[0].events=POLLIN | POLLHUP;
748 outfd[1]=STDOUT_FILENO;
749 } else if (vdeplug[LR] != NULL) { /* -v xxx:- */
750 pfd[1].fd=STDIN_FILENO;
751 pfd[1].events=POLLIN | POLLHUP;
752 outfd[0]=STDOUT_FILENO;
753 } else if (env_in == NULL || fstat(alternate_stdin,&stfd[0]) < 0) {
754 ndirs=1;
755 pfd[0].fd=STDIN_FILENO;
756 pfd[0].events=POLLIN | POLLHUP;
757 outfd[0]=STDOUT_FILENO;
758 } else {
759 if (fstat(outfd[1],&stfd[1]) < 0) {
760 fprintf(stderr,"%s: Error on secondary out: %s\n",progname,strerror(errno));
761 return -1;
763 if (!S_ISFIFO(stfd[0].st_mode)) {
764 fprintf(stderr,"%s: Error on secondary in: %s\n",progname,"it is not a pipe");
765 return -1;
767 if (!S_ISFIFO(stfd[1].st_mode)) {
768 fprintf(stderr,"%s: Error on secondary out: %s\n",progname,"it is not a pipe");
769 return -1;
771 ndirs=2;
772 pfd[LR].fd=STDIN_FILENO;
773 pfd[LR].events=POLLIN | POLLHUP;
774 outfd[LR]=alternate_stdout;
775 pfd[RL].fd=alternate_stdin;
776 pfd[RL].events=POLLIN | POLLHUP;
777 outfd[RL]=STDOUT_FILENO;
780 return ndirs;
783 static void save_pidfile()
785 if(pidfile[0] != '/')
786 strncat(pidfile_path, pidfile, PATH_MAX - strlen(pidfile_path));
787 else
788 strcpy(pidfile_path, pidfile);
790 int fd = open(pidfile_path,
791 O_WRONLY | O_CREAT | O_EXCL,
792 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
793 FILE *f;
795 if(fd == -1) {
796 printlog(LOG_ERR, "Error in pidfile creation: %s", strerror(errno));
797 exit(1);
800 if((f = fdopen(fd, "w")) == NULL) {
801 printlog(LOG_ERR, "Error in FILE* construction: %s", strerror(errno));
802 exit(1);
805 if(fprintf(f, "%ld\n", (long int)getpid()) <= 0) {
806 printlog(LOG_ERR, "Error in writing pidfile");
807 exit(1);
810 fclose(f);
813 static void cleanup(void)
815 if((pidfile != NULL) && unlink(pidfile_path) < 0) {
816 printlog(LOG_WARNING,"Couldn't remove pidfile '%s': %s", pidfile, strerror(errno));
818 if (vdeplug[LR])
819 vde_close(vdeplug[LR]);
820 if (vdeplug[RL])
821 vde_close(vdeplug[RL]);
822 if (mgmt)
823 unlink(mgmt);
826 static void sig_handler(int sig)
828 /*fprintf(stderr,"Caught signal %d, cleaning up and exiting", sig);*/
829 cleanup();
830 signal(sig, SIG_DFL);
831 kill(getpid(), sig);
834 static void setsighandlers()
836 /* setting signal handlers.
837 * * * sets clean termination for SIGHUP, SIGINT and SIGTERM, and simply
838 * * * ignores all the others signals which could cause termination. */
839 struct { int sig; const char *name; int ignore; } signals[] = {
840 { SIGHUP, "SIGHUP", 0 },
841 { SIGINT, "SIGINT", 0 },
842 { SIGPIPE, "SIGPIPE", 1 },
843 { SIGALRM, "SIGALRM", 1 },
844 { SIGTERM, "SIGTERM", 0 },
845 { SIGUSR1, "SIGUSR1", 1 },
846 { SIGUSR2, "SIGUSR2", 1 },
847 { SIGPROF, "SIGPROF", 1 },
848 { SIGVTALRM, "SIGVTALRM", 1 },
849 #ifdef VDE_LINUX
850 { SIGPOLL, "SIGPOLL", 1 },
851 #ifdef SIGSTKFLT
852 { SIGSTKFLT, "SIGSTKFLT", 1 },
853 #endif
854 { SIGIO, "SIGIO", 1 },
855 { SIGPWR, "SIGPWR", 1 },
856 #ifdef SIGUNUSED
857 { SIGUNUSED, "SIGUNUSED", 1 },
858 #endif
859 #endif
860 #ifdef VDE_DARWIN
861 { SIGXCPU, "SIGXCPU", 1 },
862 { SIGXFSZ, "SIGXFSZ", 1 },
863 #endif
864 { 0, NULL, 0 }
867 int i;
868 for(i = 0; signals[i].sig != 0; i++)
869 if(signal(signals[i].sig,
870 signals[i].ignore ? SIG_IGN : sig_handler) < 0)
871 fprintf(stderr,"%s: Setting handler for %s: %s", progname, signals[i].name,
872 strerror(errno));
875 static int openmgmt(char *mgmt)
877 int mgmtconnfd;
878 struct sockaddr_un sun;
879 int one = 1;
881 if((mgmtconnfd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0){
882 fprintf(stderr,"%s: mgmt socket: %s",progname,strerror(errno));
883 exit(1);
885 if(setsockopt(mgmtconnfd, SOL_SOCKET, SO_REUSEADDR, (char *) &one,
886 sizeof(one)) < 0){
887 fprintf(stderr,"%s: mgmt setsockopt: %s",progname,strerror(errno));
888 exit(1);
890 if(fcntl(mgmtconnfd, F_SETFL, O_NONBLOCK) < 0){
891 fprintf(stderr,"%s: Setting O_NONBLOCK on mgmt fd: %s",progname,strerror(errno));
892 exit(1);
894 sun.sun_family = PF_UNIX;
895 snprintf(sun.sun_path,sizeof(sun.sun_path),"%s",mgmt);
896 if(bind(mgmtconnfd, (struct sockaddr *) &sun, sizeof(sun)) < 0){
897 fprintf(stderr,"%s: mgmt bind %s",progname,strerror(errno));
898 exit(1);
900 chmod(sun.sun_path,mgmtmode);
901 if(listen(mgmtconnfd, 15) < 0){
902 fprintf(stderr,"%s: mgmt listen: %s",progname,strerror(errno));
903 exit(1);
905 return mgmtconnfd;
908 static char header[]="\nVDE wirefilter V.%s\n(C) R.Davoli 2005,2006 - GPLv2\n";
909 static char prompt[]="\nVDEwf$ ";
910 static int newmgmtconn(int fd,struct pollfd *pfd,int nfds)
912 int new;
913 unsigned int len;
914 char buf[MAXCMD];
915 struct sockaddr addr;
916 new = accept(fd, &addr, &len);
917 if(new < 0){
918 printlog(LOG_WARNING,"mgmt accept %s",strerror(errno));
919 return nfds;
921 if (nfds < NPFD) {
922 snprintf(buf,MAXCMD,header,PACKAGE_VERSION);
923 write(new,buf,strlen(buf));
924 write(new,prompt,strlen(prompt));
925 pfd[nfds].fd=new;
926 pfd[nfds].events=POLLIN | POLLHUP;
927 debuglevel[nfds]=0;
928 return ++nfds;
929 } else {
930 printlog(LOG_WARNING,"too many mgmt connections");
931 close (new);
932 return nfds;
936 static void printoutc(int fd, const char *format, ...)
938 va_list arg;
939 char outbuf[MAXCMD+1];
941 va_start (arg, format);
942 vsnprintf(outbuf,MAXCMD,format,arg);
943 strcat(outbuf,"\n");
944 write(fd,outbuf,strlen(outbuf));
947 static int setdelay(int fd,char *s)
949 return read_wirevalue(s,DELAY);
952 static int setloss(int fd,char *s)
954 return read_wirevalue(s,LOSS);
957 static int setlostburst(int fd,char *s)
959 return read_wirevalue(s,LOSTBURST);
962 static int setddup(int fd,char *s)
964 return read_wirevalue(s,DDUP);
967 static int setband(int fd,char *s)
969 return read_wirevalue(s,BAND);
972 static int setnoise(int fd,char *s)
974 return read_wirevalue(s,NOISE);
977 static int setmtu(int fd,char *s)
979 return read_wirevalue(s,MTU);
982 static int setspeed(int fd,char *s)
984 return read_wirevalue(s,SPEED);
987 static int setcapacity(int fd,char *s)
989 return read_wirevalue(s,CAPACITY);
992 static int setfifo(int fd,char *s)
994 int n=atoi(s);
995 if (n==0)
996 nofifo=1;
997 else
998 nofifo=0;
999 return 0;
1002 static int setmarkov_resize(int fd,char *s)
1004 int n=atoi(s);
1005 if (n>0) {
1006 markov_resize(n);
1007 markov_start();
1008 return 0;
1009 } else
1010 return EINVAL;
1013 static int setedge(int fd,char *s)
1015 int x,y;
1016 double weight;
1017 sscanf(s,"%d,%d,%lg",&x,&y,&weight);
1018 if (x>=0 && x<markov_numnodes && y>=0 && y<markov_numnodes) {
1019 ADJMAP(x,y)=weight;
1020 markov_compute(x);
1021 return 0;
1022 } else
1023 return EINVAL;
1026 static int setmarkov_time(int fd,char *s)
1028 double newvalue;
1029 sscanf(s,"%lg",&newvalue);
1030 if (newvalue > 0) {
1031 markov_time=newvalue;
1032 markov_start();
1033 return 0;
1034 } else
1035 return EINVAL;
1038 static int setmarkov_node(int fd,char *s)
1040 int n=atoi(s);
1041 if (n>=0 && n<markov_numnodes) {
1042 markov_current=n;
1043 return 0;
1044 } else
1045 return EINVAL;
1048 static int setmarkov_debug(int fd,char *s)
1050 int n=atoi(s);
1051 if (fd >= 0 && n>=0) {
1052 int i;
1053 if (fd==1) fd=0;
1054 for (i=0;i<NPFD;i++) {
1055 if (pfd[i].fd == fd)
1056 break;
1058 if (i<NPFD) {
1059 debuglevel[i]=n;
1060 return 0;
1061 } else
1062 return EINVAL;
1063 } else
1064 return EINVAL;
1067 static int showcurrent(int fd,char *s)
1069 printoutc(fd, "Current Markov Node %d \"%s\" (0,..,%d)",markov_current,
1070 WFNAME(markov_current)?WFNAME(markov_current):"",
1071 markov_numnodes-1);
1072 return 0;
1075 static int setmarkov_name(int fd,char *s)
1077 int n;
1078 while (strchr(" \t",*s)) s++;
1079 n=atoi(s);
1080 if (n>=0 && n<markov_numnodes) {
1081 while (strchr("0123456789",*s)) s++;
1082 while (strchr(" \t",*s)) s++;
1083 if (*s == ',') s++;
1084 if (s[strlen(s)-1]=='\n')
1085 s[strlen(s)-1]=0;
1086 if (WFNAME(n)) free(WFNAME(n));
1087 if (*s)
1088 WFNAME(n)=strdup(s);
1089 else
1090 WFNAME(n)=0;
1091 return 0;
1092 } else
1093 return EINVAL;
1096 static int logout(int fd,char *s)
1098 return -1;
1101 static int doshutdown(int fd,char *s)
1103 exit(0);
1107 static int help(int fd,char *s)
1109 printoutc(fd, "COMMAND HELP");
1110 printoutc(fd, "------------ ------------");
1111 printoutc(fd, "help print a summary of mgmt commands");
1112 printoutc(fd, "load load a configuration file");
1113 printoutc(fd, "showinfo show status and parameter values");
1114 printoutc(fd, "loss set loss percentage");
1115 printoutc(fd, "lostburst mean length of lost packet bursts");
1116 printoutc(fd, "delay set delay ms");
1117 printoutc(fd, "dup set dup packet percentage");
1118 printoutc(fd, "bandwidth set channel bandwidth bytes/sec");
1119 printoutc(fd, "speed set interface speed bytes/sec");
1120 printoutc(fd, "noise set noise factor bits/Mbyte");
1121 printoutc(fd, "mtu set channel MTU (bytes)");
1122 printoutc(fd, "capacity set channel capacity (bytes)");
1123 printoutc(fd, "fifo set channel fifoness");
1124 printoutc(fd, "shutdown shut the channel down");
1125 printoutc(fd, "logout log out from this mgmt session");
1126 printoutc(fd, "markov-numnodes n markov mode: set number of states");
1127 printoutc(fd, "markov-setnode n markov mode: set current state");
1128 printoutc(fd, "markov-name n,name markov mode: set state's name");
1129 printoutc(fd, "markov-time ms markov mode: transition period");
1130 printoutc(fd, "setedge n1,n2,w markov mode: set edge weight");
1131 printoutc(fd, "showinfo n markov mode: show parameter values");
1132 printoutc(fd, "showedges n markov mode: show edge weights");
1133 printoutc(fd, "showcurrent markov mode: show current state");
1134 printoutc(fd, "markov-debug n markov mode: set debug level");
1135 return 0;
1138 #define CHARALGO(X) (charalgo[(int)(X)])
1139 #define WIREVALUE_X_FIELDS(X) (X)->value,(X)->plus,(charalgo[(int)((X)->alg)])
1140 #define WIREVALUE_FIELDS(N,T,D) WIREVALUE_X_FIELDS(WFADDR(N,T)+D)
1141 static int showinfo(int fd,char *s)
1143 int node=0;
1144 if (*s != 0)
1145 node=atoi(s);
1146 else
1147 node=markov_current;
1148 if (node >= markov_numnodes || node < 0)
1149 return EINVAL;
1150 printoutc(fd, "WireFilter: %sdirectional",(ndirs==2)?"bi":"mono");
1151 if (markov_numnodes > 1) {
1152 printoutc(fd, "Node %d \"%s\" (0,..,%d) Markov-time %lg",node,
1153 WFNAME(node)?WFNAME(node):"",markov_numnodes-1,markov_time);
1155 if (ndirs==2) {
1156 printoutc(fd, "Loss L->R %g+%g%c R->L %g+%g%c",
1157 WIREVALUE_FIELDS(node,LOSS,LR),
1158 WIREVALUE_FIELDS(node,LOSS,RL));
1159 printoutc(fd, "Lburst L->R %g+%g%c R->L %g+%g%c",
1160 WIREVALUE_FIELDS(node,LOSTBURST,LR),
1161 WIREVALUE_FIELDS(node,LOSTBURST,RL));
1162 printoutc(fd, "Delay L->R %g+%g%c R->L %g+%g%c",
1163 WIREVALUE_FIELDS(node,DELAY,LR),
1164 WIREVALUE_FIELDS(node,DELAY,RL));
1165 printoutc(fd, "Dup L->R %g+%g%c R->L %g+%g%c",
1166 WIREVALUE_FIELDS(node,DDUP,LR),
1167 WIREVALUE_FIELDS(node,DDUP,RL));
1168 printoutc(fd, "Bandw L->R %g+%g%c R->L %g+%g%c",
1169 WIREVALUE_FIELDS(node,BAND,LR),
1170 WIREVALUE_FIELDS(node,BAND,RL));
1171 printoutc(fd, "Speed L->R %g+%g%c R->L %g+%g%c",
1172 WIREVALUE_FIELDS(node,SPEED,LR),
1173 WIREVALUE_FIELDS(node,SPEED,RL));
1174 printoutc(fd, "Noise L->R %g+%g%c R->L %g+%g%c",
1175 WIREVALUE_FIELDS(node,NOISE,LR),
1176 WIREVALUE_FIELDS(node,NOISE,RL));
1177 printoutc(fd, "MTU L->R %g R->L %g ",
1178 min_wirevalue(node,MTU,LR),
1179 min_wirevalue(node,MTU,RL));
1180 printoutc(fd, "Cap. L->R %g+%g%c R->L %g+%g%c",
1181 WIREVALUE_FIELDS(node,CAPACITY,LR),
1182 WIREVALUE_FIELDS(node,CAPACITY,RL));
1183 printoutc(fd, "Current Delay Queue size: L->R %d R->L %d ",delay_bufsize[LR],delay_bufsize[RL]);
1184 } else {
1185 printoutc(fd, "Loss %g+%g%c",
1186 WIREVALUE_FIELDS(node,LOSS,0));
1187 printoutc(fd, "Lburst %g+%g%c",
1188 WIREVALUE_FIELDS(node,LOSTBURST,0));
1189 printoutc(fd, "Delay %g+%g%c",
1190 WIREVALUE_FIELDS(node,DELAY,0));
1191 printoutc(fd, "Dup %g+%g%c",
1192 WIREVALUE_FIELDS(node,DDUP,0));
1193 printoutc(fd, "Bandw %g+%g%c",
1194 WIREVALUE_FIELDS(node,BAND,0));
1195 printoutc(fd, "Speed %g+%g%c",
1196 WIREVALUE_FIELDS(node,SPEED,0));
1197 printoutc(fd, "Noise %g+%g%c",
1198 WIREVALUE_FIELDS(node,NOISE,0));
1199 printoutc(fd, "MTU %g", min_wirevalue(node,MTU,0));
1200 printoutc(fd, "Cap. %g+%g%c",
1201 WIREVALUE_FIELDS(node,CAPACITY,0));
1202 printoutc(fd, "Current Delay Queue size: %d",delay_bufsize[0]);
1204 printoutc(fd,"Fifoness %s",(nofifo == 0)?"TRUE":"FALSE");
1205 printoutc(fd,"Waiting packets in delay queues %d",npq);
1206 if (blinksock) {
1207 blinkmsg[(int)blinkidlen]=0;
1208 printoutc(fd,"Blink socket: %s",blinksun.sun_path);
1209 printoutc(fd,"Blink id: %s",blinkmsg);
1211 return 0;
1214 static int showedges(int fd,char *s)
1216 int node=0;
1217 int j;
1218 if (*s != 0)
1219 node=atoi(s);
1220 else
1221 node=markov_current;
1222 if (node >= markov_numnodes || node < 0)
1223 return EINVAL;
1224 for (j=0;j<markov_numnodes;j++)
1225 if (ADJMAP(node,j) != 0)
1226 printoutc(fd, "Edge %-2d->%-2d \"%s\"->\"%s\" weigth %lg",node,j,
1227 WFNAME(node)?WFNAME(node):"",
1228 WFNAME(j)?WFNAME(j):"",
1229 ADJMAP(node,j));
1230 return 0;
1233 static int runscript(int fd,char *path);
1235 #define WITHFILE 0x80
1236 static struct comlist {
1237 char *tag;
1238 int (*fun)(int fd,char *arg);
1239 unsigned char type;
1240 } commandlist [] = {
1241 {"help", help, WITHFILE},
1242 {"showinfo",showinfo, WITHFILE},
1243 {"load",runscript,WITHFILE},
1244 {"delay",setdelay, 0},
1245 {"loss",setloss, 0},
1246 {"lostburst",setlostburst, 0},
1247 {"dup",setddup, 0},
1248 {"bandwidth",setband, 0},
1249 {"band",setband, 0},
1250 {"speed",setspeed, 0},
1251 {"capacity",setcapacity, 0},
1252 {"noise",setnoise, 0},
1253 {"mtu",setmtu, 0},
1254 {"fifo",setfifo, 0},
1255 {"markov-numnodes",setmarkov_resize, 0},
1256 {"markov-setnode",setmarkov_node, 0},
1257 {"markov-name",setmarkov_name, 0},
1258 {"markov-time",setmarkov_time, 0},
1259 {"setedge",setedge, 0},
1260 {"showedges",showedges, WITHFILE},
1261 {"showcurrent",showcurrent, WITHFILE},
1262 {"markov-debug",setmarkov_debug, 0},
1263 {"logout",logout, 0},
1264 {"shutdown",doshutdown, 0}
1267 #define NCL sizeof(commandlist)/sizeof(struct comlist)
1269 static inline void delnl(char *buf)
1271 int len=strlen(buf)-1;
1272 while (len>0 &&
1273 (buf[len]=='\n' || buf[len]==' ' || buf[len]=='\t')) {
1274 buf[len]=0;
1275 len--;
1279 static int handle_cmd(int fd,char *inbuf)
1281 int rv=ENOSYS;
1282 int i;
1283 char *cmd=inbuf;
1284 while (*inbuf == ' ' || *inbuf == '\t' || *inbuf == '\n') inbuf++;
1285 delnl(inbuf);
1286 if (*inbuf != '\0' && *inbuf != '#') {
1287 for (i=0; i<NCL
1288 && strncmp(commandlist[i].tag,inbuf,strlen(commandlist[i].tag))!=0;
1289 i++)
1291 if (i<NCL)
1293 inbuf += strlen(commandlist[i].tag);
1294 while (*inbuf == ' ' || *inbuf == '\t') inbuf++;
1295 if (fd>=0 && commandlist[i].type & WITHFILE)
1296 printoutc(fd,"0000 DATA END WITH '.'");
1297 rv=commandlist[i].fun(fd,inbuf);
1298 if (fd>=0 && commandlist[i].type & WITHFILE)
1299 printoutc(fd,".");
1301 if (fd >= 0)
1302 printoutc(fd,"1%03d %s",rv,strerror(rv));
1303 else if (rv != 0)
1304 printlog(LOG_ERR,"rc command error: %s %s",cmd,strerror(rv));
1305 return rv;
1307 return rv;
1310 static int runscript(int fd,char *path)
1312 FILE *f=fopen(path,"r");
1313 char buf[MAXCMD];
1314 if (f==NULL)
1315 return errno;
1316 else {
1317 while (fgets(buf,MAXCMD,f) != NULL) {
1318 delnl(buf);
1319 if (fd >= 0) {
1320 printoutc(fd,"%s (%s) %s",prompt,path,buf);
1322 handle_cmd(fd, buf);
1324 fclose(f);
1325 return 0;
1329 static int mgmtcommand(int fd)
1331 char buf[MAXCMD+1];
1332 int n,rv;
1333 int outfd=fd;
1334 n = read(fd, buf, MAXCMD);
1335 if (n<0) {
1336 printlog(LOG_WARNING,"read from mgmt %s",strerror(errno));
1337 return 0;
1339 else if (n==0)
1340 return -1;
1341 else {
1342 if (fd==STDIN_FILENO)
1343 outfd=STDOUT_FILENO;
1344 buf[n]=0;
1345 rv=handle_cmd(outfd,buf);
1346 if (rv>=0)
1347 write(outfd,prompt,strlen(prompt));
1348 return rv;
1352 static int delmgmtconn(int i,struct pollfd *pfd,int nfds)
1354 if (i<nfds) {
1355 close(pfd[i].fd);
1356 if (pfd[i].fd == 0) /* close stdin implies exit */
1357 exit(0);
1358 memmove(pfd+i,pfd+i+1,sizeof (struct pollfd) * (nfds-i-1));
1359 memmove(debuglevel+i,debuglevel+i+1,sizeof(char) * (nfds-i-1));
1360 pfd[nfds].fd = -1;
1361 debuglevel[nfds] = 0;
1362 nfds--;
1364 return nfds;
1367 void usage(void)
1369 fprintf(stderr,"Usage: %s OPTIONS\n"
1370 "\t--help|-h\n"
1371 "\t--rcfile|-f Configuration file\n"
1372 "\t--loss|-l loss_percentage\n"
1373 "\t--lostburst|-L lost_packet_burst_len\n"
1374 "\t--delay|-d delay_ms\n"
1375 "\t--dup|-D dup_percentage\n"
1376 "\t--band|-b bandwidth(bytes/s)\n"
1377 "\t--speed|-s interface_speed(bytes/s)\n"
1378 "\t--capacity|-c delay_channel_capacity\n"
1379 "\t--noise|-n noise_bits/megabye\n"
1380 "\t--mtu|-m mtu_size\n"
1381 "\t--nofifo|-N\n"
1382 "\t--mgmt|-M management_socket\n"
1383 "\t--mgmtmode management_permission(octal)\n"
1384 "\t--vde-plug plug1:plug2 | -v plug1:plug2\n"
1385 "\t--daemon\n"
1386 "\t--pidfile pidfile\n"
1387 "\t--blink blinksocket\n"
1388 "\t--blinkid blink_id_string\n"
1389 ,progname);
1390 exit (1);
1393 int main(int argc,char *argv[])
1395 int n;
1396 int npfd;
1397 int option_index;
1398 int mgmtindex=-1;
1399 int consoleindex=-1;
1400 static struct option long_options[] = {
1401 {"help",0 , 0, 'h'},
1402 {"rcfile", 1, 0, 'f'},
1403 {"loss", 1, 0, 'l'},
1404 {"lostburst", 1, 0, 'L'},
1405 {"delay",1 , 0, 'd'},
1406 {"dup",1 , 0, 'D'},
1407 {"band",1 , 0, 'b'},
1408 {"speed",1 , 0, 's'},
1409 {"capacity",1 , 0, 'c'},
1410 {"noise",1 , 0, 'n'},
1411 {"mtu",1 , 0, 'm'},
1412 {"nofifo",0 , 0, 'N'},
1413 {"mgmt", 1, 0, 'M'},
1414 {"mgmtmode", 1, 0, MGMTMODEARG},
1415 {"vde-plug",1,0,'v'},
1416 {"daemon",0 , 0, DAEMONIZEARG},
1417 {"pidfile", 1, 0, PIDFILEARG},
1418 {"blink",1,0,LOGSOCKETARG},
1419 {"blinkid",1,0,LOGIDARG}
1421 progname=basename(argv[0]);
1422 markov_resize(1);
1424 setsighandlers();
1425 atexit(cleanup);
1427 while(1) {
1428 int c;
1429 c = GETOPT_LONG (argc, argv, "hnl:d:M:D:m:b:s:c:v:L:f:",
1430 long_options, &option_index);
1431 if (c<0)
1432 break;
1433 switch (c) {
1434 case 'h':
1435 usage();
1436 break;
1437 case 'f':
1438 rcfile=strdup(optarg);
1439 break;
1440 case 'd':
1441 read_wirevalue(optarg,DELAY);
1442 break;
1443 case 'l':
1444 read_wirevalue(optarg,LOSS);
1445 break;
1446 case 'L':
1447 read_wirevalue(optarg,LOSTBURST);
1448 break;
1449 case 'D':
1450 read_wirevalue(optarg,DDUP);
1451 break;
1452 case 'b':
1453 read_wirevalue(optarg,BAND);
1454 break;
1455 case 'm':
1456 read_wirevalue(optarg,MTU);
1457 break;
1458 case 'n':
1459 read_wirevalue(optarg,NOISE);
1460 break;
1461 case 's':
1462 read_wirevalue(optarg,SPEED);
1463 break;
1464 case 'c':
1465 read_wirevalue(optarg,CAPACITY);
1466 break;
1467 case 'M':
1468 mgmt=strdup(optarg);
1469 break;
1470 case 'N':
1471 nofifo=1;
1472 break;
1473 case 'v':
1475 char *colon;
1476 vdepath[LR]=strdup(optarg);
1477 colon=index(vdepath[LR],':');
1478 if (colon) {
1479 *colon=0;
1480 vdepath[RL]=colon+1;
1481 } else {
1482 fprintf(stderr,"Bad vde_plugs specification.\n");
1483 usage();
1486 case MGMTMODEARG:
1487 sscanf(optarg,"%o",&mgmtmode);
1488 break;
1489 case DAEMONIZEARG:
1490 daemonize=1;
1491 break;
1492 case PIDFILEARG:
1493 pidfile=strdup(optarg);
1494 break;
1495 case LOGSOCKETARG:
1496 blinksun.sun_family = PF_UNIX;
1497 snprintf(blinksun.sun_path,sizeof(blinksun.sun_path),"%s",optarg);
1498 break;
1499 case LOGIDARG:
1500 if (blinkmsg) free(blinkmsg);
1501 blinkidlen=strlen(optarg)+1;
1502 asprintf(&blinkmsg,"%s 12345678901234567890",optarg);
1503 break;
1504 default:
1505 usage();
1506 break;
1509 if (optind < argc)
1510 usage();
1512 if (blinksun.sun_path[0] != 0) {
1513 blinksock=socket(AF_UNIX, SOCK_DGRAM, 0);
1514 if (blinkmsg==NULL) {
1515 blinkidlen=7;
1516 asprintf(&blinkmsg,"%06d 12345678901234567890",getpid());
1520 /* pfd structure:
1521 * monodir: 0 input LR, 1 mgmtctl, >1 mgmt open conn (mgmtindex==ndirs==1)
1522 * bidir on streams: 0 input LR, 1 input RL, 2 mgmtctl, >2 mgmt open conn (mgmtindex==ndirs==2)
1523 * vdeplug xx:xx : 0 input LR, 1 input RL, 2&3 ctlfd, 4 mgmtctl, > 4 mgmt open conn (mgmtindex>ndirs==2) 5 is console
1524 * vdeplug xx:xx : 0 input LR, 1 input RL, 2&3 ctlfd, 4 console (if not -M)
1525 * vdeplug -:xx : 0 input LR(stdin), 1 input RL, 2 ctlfd, 3 mgmtctl, > 3 mgmt open conn (mgmtindex>ndirs==2)
1526 * vdeplug xx:- : 0 input LR, 1 input RL(stdin), 2 ctlfd, 3 mgmtctl, > 3 mgmt open conn (mgmtindex>ndirs==2)
1529 ndirs=check_open_fifos_n_plugs(pfd,outfd,vdepath,vdeplug);
1531 if (ndirs < 0)
1532 usage();
1534 npfd=ndirs;
1536 if (rcfile)
1537 runscript(-1,rcfile);
1538 if (vdeplug[LR]) {
1539 pfd[npfd].fd=vde_ctlfd(vdeplug[LR]);
1540 pfd[npfd].events=POLLIN | POLLHUP;
1541 npfd++;
1543 if (vdeplug[RL]) {
1544 pfd[npfd].fd=vde_ctlfd(vdeplug[RL]);
1545 pfd[npfd].events=POLLIN | POLLHUP;
1546 npfd++;
1549 if(mgmt != NULL) {
1550 int mgmtfd=openmgmt(mgmt);
1551 mgmtindex=npfd;
1552 pfd[mgmtindex].fd=mgmtfd;
1553 pfd[mgmtindex].events=POLLIN | POLLHUP;
1554 npfd++;
1557 if (daemonize) {
1558 openlog(progname, LOG_PID, 0);
1559 logok=1;
1560 } else if (vdeplug[LR] && vdeplug[RL]) { // console mode
1561 consoleindex=npfd;
1562 pfd[npfd].fd=STDIN_FILENO;
1563 pfd[npfd].events=POLLIN | POLLHUP;
1564 npfd++;
1567 /* saves current path in pidfile_path, because otherwise with daemonize() we
1568 * forget it */
1569 if(getcwd(pidfile_path, PATH_MAX-1) == NULL) {
1570 printlog(LOG_ERR, "getcwd: %s", strerror(errno));
1571 exit(1);
1573 strcat(pidfile_path, "/");
1574 if (daemonize && daemon(0, 0)) {
1575 printlog(LOG_ERR,"daemon: %s",strerror(errno));
1576 exit(1);
1579 /* once here, we're sure we're the true process which will continue as a
1580 * server: save PID file if needed */
1581 if(pidfile) save_pidfile();
1583 if (vdepath[LR])
1584 printlog(LOG_INFO,"bidirectional vdeplug filter L=%s R=%s starting...",
1585 (*vdepath[LR])?vdepath[LR]:"DEFAULT_SWITCH",
1586 (*vdepath[RL])?vdepath[RL]:"DEFAULT_SWITCH");
1587 else if (ndirs==2)
1588 printlog(LOG_INFO,"bidirectional filter starting...");
1589 else
1590 printlog(LOG_INFO,"monodirectional filter starting...");
1592 initrand();
1593 while(1) {
1594 int delay=nextms();
1595 int markovdelay=markovms();
1596 if (markovdelay >= 0 &&
1597 (markovdelay < delay || delay < 0)) delay=markovdelay;
1598 pfd[0].events |= POLLIN;
1599 if (WFVAL(markov_current,SPEED,LR).value > 0) {
1600 struct timeval tv;
1601 int speeddelay;
1602 gettimeofday(&tv,NULL);
1603 if (timercmp(&tv, &nextspeed[LR], <)) {
1604 timersub(&nextspeed[LR],&tv,&tv);
1605 speeddelay=tv.tv_sec*1000 + tv.tv_usec/1000;
1606 if (speeddelay > 0) {
1607 pfd[0].events &= ~POLLIN;
1608 if (speeddelay < delay || delay < 0) delay=speeddelay;
1612 if (ndirs > 1) {
1613 pfd[1].events |= POLLIN;
1614 if (WFVAL(markov_current,SPEED,RL).value > 0) {
1615 struct timeval tv;
1616 int speeddelay;
1617 if (timercmp(&tv, &nextspeed[RL], <)) {
1618 gettimeofday(&tv,NULL);
1619 timersub(&nextspeed[RL],&tv,&tv);
1620 speeddelay=tv.tv_sec*1000 + tv.tv_usec/1000;
1621 if (speeddelay > 0) {
1622 pfd[1].events &= ~POLLIN;
1623 if (speeddelay < delay || delay < 0) delay=speeddelay;
1628 n=poll(pfd,npfd,delay);
1629 if (pfd[0].revents & POLLHUP || (ndirs>1 && pfd[1].revents & POLLHUP))
1630 exit(0);
1631 if (pfd[0].revents & POLLIN) {
1632 packet_in(LR); n--;
1634 if (ndirs>1 && pfd[1].revents & POLLIN) {
1635 packet_in(RL); n--;
1637 if (n>0) { // if there are already events to handle (performance: packet switching first)
1638 int mgmtfdstart=consoleindex;
1639 if (mgmtindex >= 0) mgmtfdstart=mgmtindex+1;
1640 if (mgmtfdstart >= 0 && npfd > mgmtfdstart) {
1641 register int i;
1642 for (i=mgmtfdstart;i<npfd;i++) {
1643 if (pfd[i].revents & POLLIN && mgmtcommand(pfd[i].fd) < 0)
1644 pfd[i].revents |= POLLHUP;
1645 if (pfd[i].revents) n--;
1647 for (i=mgmtfdstart;i<npfd;i++) {
1648 if (pfd[i].revents & POLLHUP)
1649 npfd=delmgmtconn(i,pfd,npfd);
1652 if (mgmtindex >= 0) {
1653 if (pfd[mgmtindex].revents != 0) {
1654 npfd=newmgmtconn(pfd[mgmtindex].fd,pfd,npfd);
1655 n--;
1658 /* if (n>0) // if there are already pending events, it means that a ctlfd has hunged up
1659 exit(0);*/
1661 markov_try();
1662 packet_dequeue();