Hi.

I've written a simple traffic shaper.
It works pretty well but I don't have tested a lot. I hope you can do.

Bye!!

-- 
Gustavo Chaín Dumit
http://0xff.cl
-- 
Gustavo Chaín Dumit
http://0xff.cl

Attachment: patch
Description: Binary data

#include "defs.h"

unsigned long inline
tv2ms(struct timeval tv)
{
	register unsigned long ms = (tv.tv_sec * 1000)+(tv.tv_usec / 1000); 
	return  ms ? ms : 1;
}

shaper_stats_t stats;
shaper_ops_t   ops;

void
shaper_init(size_t max_speed)
{
#define MIN_SPEED 64
	if (0 < max_speed) {
		max_speed = MAX(MIN_SPEED, max_speed);
		stats.enabled = 1;
	}
	else {
		max_speed = 0;
		stats.enabled = 0;
	}

	stats.max_speed = max_speed / 8 * 1024;
	stats.bytes = 0;
	gettimeofday(&stats.last_time, NULL);
	// TODO: Init mutex
}

void
shaper_update(size_t bytes)
{
	stats.bytes += bytes;
}

int
shaper_eval(void)
{
	static struct timeval now, deltat;
	register unsigned long speed;

#ifndef timersub
#define timersub(a, b, result)                           \
	do {                                                 \
		(result)->tv_sec = (a)->tv_sec - (b)->tv_sec;    \
		(result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
		if ((result)->tv_usec < 0) {                     \
			--(result)->tv_sec;                          \
			(result)->tv_usec += 1000000;                \
		}                                                \
	} while (0)
#endif

	gettimeofday(&now, NULL);
	timersub(&now, &stats.last_time, &deltat);

	// TODO: Mutex Lock
	speed = stats.bytes * 1000 / tv2ms(deltat);
	// TODO: Mutex unLock

	if ( stats.max_speed && (speed > stats.max_speed) ) {
		usleep(tv2ms(deltat));
		return SHAPER_LIMIT;
	}
	
	if (now.tv_sec > stats.last_time.tv_sec ){
		// TODO: Mutex Lock
		stats.last_time = now;
		stats.bytes = 0;
		// TODO: Mutex unLock
	}

	return SHAPER_OK;
}
#ifndef SHAPER_HEADER_INCLUDED
#define SHAPER_HEADER_INCLUDED

#include <sys/time.h>

#define SHAPER_LIMIT -1
#define SHAPER_OK     0

typedef struct {
	size_t            max_speed;
	size_t            bytes;
	struct timeval    last_time;
	int               enabled;
	// TODO: thread lock
} shaper_stats_t;

typedef struct {
	void (*update) (size_t size);
	int  (*eval)   (void);
} shaper_ops_t;

void shaper_init   (size_t max_speed);
void shaper_update (size_t bytes);
int  shaper_eval   (void);

#endif  /* SHAPER_HEADER_INCLUDED */
-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/
_______________________________________________
shttpd-general mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/shttpd-general

Reply via email to