Plan 9 from Bell Labs’s /usr/web/sources/contrib/mjl/wip/deluge/peer.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include "deluge.h"


Peer *
peernew(int npieces)
{
	Peer *p;

	p = emalloc(sizeof p[0]);
	p->status = 0;
	p->n = -1;
	p->ip = nil;
	p->port = nil;
	memset(p->peerid, 0, sizeof p->peerid);
	p->fd = -1;
	p->pieces = bitnew(npieces, nil);
	p->rate = ratenew(60);
	setisinterested(p, 0);
	setisinteresting(p, 0);
	setischoked(p, 1);
	setischoking(p, 1);
	p->lreq = nil;
	p->rreq = nil;
	p->meta = nil;
	p->dataout = nil;
	p->write = chancreate(sizeof (Msg *), 0);
	p->changed = 0;
	p->lastchange = time(0);
	p->havefirst = 0;
	p->next = nil;

	return p;
}

void
peerfree(Peer *p)
{
	free(p->ip);
	free(p->port);
	bitfree(p->pieces);
	ratefree(p->rate);
	assert(p->lreq == nil);
	assert(p->rreq == nil);
	chanfree(p->write);
	assert(p->meta == nil);
	assert(p->dataout == nil);
	free(p);
}

int
peerlen(Peer *p)
{
	int i;
	for(i = 0; p; p = p->next)
		i++;
	return i;
}

void
peeradd(Peer **fp, Peer *p)
{
	Peer *p2;

	p->next = nil;
	if(*fp == nil){
		*fp = p;
	}else{
		for(p2 = *fp; p2 && p2->next; p2 = p2->next)
			;
		p2->next = p;
	}
}

Peer *
peerpop(Peer **firstp)
{
	Peer *r;

	if(*firstp == nil)
		return nil;
	r = *firstp;
	*firstp = r->next;
	r->next = nil;
	return r;
}


Peer *
peerfind(Peer *p, int n)
{
	while(p){
		if(p->n == n)
			return p;
		p = p->next;
	}
	return nil;
}

Peer *
peermatch(Peer *first, Peer *p)
{
	while(first){
		if(memcmp(first->peerid, p->peerid, Peeridlen) == 0 ||
		    (strcmp(first->ip, p->ip) == 0 && strcmp(first->port, p->port) == 0))
			return first;
		first = first->next;
	}
	return nil;
}

Peer *
peermatchbyip(Peer *first, Peer *p)
{
	while(first){
		if(memcmp(first->peerid, p->peerid, Peeridlen) == 0 || strcmp(first->ip, p->ip) == 0)
			return first;
		first = first->next;
	}
	return nil;
}

void
peersetstatus(Peer *p, uint mask, uint v)
{
	if(v)
		p->status |= mask;
	else
		p->status &= ~mask;
}

void
peerremove(Peer **fp, Peer *p)
{
	Peer *p2;

	if(*fp == p)
		*fp = p->next;
	else
		for(p2 = *fp; p2 && p2->next; p2 = p2->next){
			if(p2->next == p){
				p2->next = p->next;
				return;
			}
		}
	p->next = nil;
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.