src/log.c \
src/main.c \
src/meta.c \
+ src/net/cache.c \
src/net/handler.c \
src/net/listen.c \
src/net/loop.c \
src/opt/set.c \
src/opt/watch.c \
src/opt/worker.c \
+ src/peer/free.c \
+ src/peer/init.c \
src/pqueue.c \
src/rss/entry.c \
src/rss/footer.c \
PEER_MESSAGE_HASH_REJECT = 23
};
+void peer_free(struct peer*);
int peer_handshake(int,struct peer*);
int peer_init(struct peer**);
--- /dev/null
+#include<net.h>
+
+int net_cache(void **prev, size_t *prev_size, void *p, size_t size) {
+ void *next;
+ size_t next_size;
+
+ next_size = ((*prev)!=NULL) ? size + (*prev_size) : size;
+ next = malloc(next_size);
+ if(NULL==next) { return -1; }
+
+ if((*prev)!=NULL) {
+ memcpy(next,(*prev),(*prev_size));
+ memcpy(&(next[(*prev_size)]),p,size);
+ free((*prev));
+ }
+
+ (*prev) = next;
+ (*prev_size) = next_size;
+
+ return 1;
+}
+
}
if(-1==epoll_ctl(info->epoll_fd,EPOLL_CTL_ADD,conn_sock,&ev)) {
+ peer_free(ev.data.ptr);
perror("epoll_ctl");
return;
}
#include<net.h>
int net_send(int sock, struct peer *info, void *p, size_t size) {
+ void *next;
ssize_t i;
i = send(sock,p,size,0);
- if(i<size) {
- if(i<0) {
- perror("send");
- return -1;
- }
-
- info->out = malloc(size-i);
- if(NULL==info->out) {
- perror("malloc");
- return -1;
- }
-
- memcpy(info->out,p,size);
- info->out_size = size;
- return 0;
- }
+ if(i<size) { goto cache; }
return 1;
+cache:
+ if(net_cache(
+ &(info->out), /* void **prev */
+ &(info->out_size), /* size_t *prev_size */
+ &(p[i]), /* void *p */
+ (size-i) /* size_t size */
+ )<0) { return -1; }
+ return 0;
}
#include<net.h>
-static int cache(struct peer*,void*,size_t);
static void* use_cached(struct peer*,void*,size_t*);
-static int cache(struct peer *info, void *p, size_t size) {
- void *next;
- size_t i;
-
- next_size = (info->in!=NULL) ? size + info->in_size : size;
- next = malloc(next_size);
- if(NULL==next) { return -1; }
-
- memcpy(next,p,size);
- if(info->in!=NULL) {
- memcpy(&(next[size]),info->in,info->in_size);
- free(info->in);
- }
-
- info->in = next;
- info->in_size = next_size;
-
- return 1;
-}
-
int net_wait(int sock, struct peer *info, void *buf, size_t buf_size) {
void *p;
size_t size;
return 1;
cached:
- cache(info,p,i+(buf_size - size));
+ if(net_cache(
+ &(info->in), /* void **prev */
+ &(info->in_size), /* size_t *prev_size */
+ p, /* void *p */
+ i /* size_t size */
+ )<0) { return -1; }
return 0;
}
--- /dev/null
+#include<peer.h>
+
+void peer_free(struct peer *p) {
+ if(p!=NULL) {
+ if(p->out!=NULL) { free(p->out); }
+ if(p->in!=NULL) { free(p->in); }
+
+ free(p);
+ }
+}
--- /dev/null
+#include<peer.h>
+
+int peer_init(struct peer **p) {
+ assert(p!=NULL);
+
+ (*p) = malloc(sizeof(struct peer));
+ if(NULL==(*p)) { return -1; }
+
+ (*p)->handshake = 0;
+ (*p)->choked = 0;
+ (*p)->interested = 0;
+
+ memset((*p)->infohash,0,PEER_INFOHASH_SIZE);
+ memset((*p)->peer_id,0,PEER_PEER_ID_SIZE);
+
+ (*p)->out = NULL;
+ (*p)->out_size = 0;
+
+ (*p)->in = NULL;
+ (*p)->in_size = 0;
+
+ return 1;
+}