1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
#include <u.h>
#include <libc.h>
#include <draw.h>
#include <event.h>
#include "plumb.h"
typedef struct EQueue EQueue;
struct EQueue
{
int id;
char *buf;
int nbuf;
EQueue *next;
};
static EQueue *equeue;
static Lock eqlock;
static
int
partial(int id, Event *e, uchar *b, int n)
{
EQueue *eq, *p;
int nmore;
lock(&eqlock);
for(eq = equeue; eq != nil; eq = eq->next)
if(eq->id == id)
break;
unlock(&eqlock);
if(eq == nil)
return 0;
/* partial message exists for this id */
eq->buf = realloc(eq->buf, eq->nbuf+n);
if(eq->buf == nil)
drawerror(display, "eplumb: cannot allocate buffer");
memmove(eq->buf+eq->nbuf, b, n);
eq->nbuf += n;
e->v = plumbunpackpartial((char*)eq->buf, eq->nbuf, &nmore);
if(nmore == 0){ /* no more to read in this message */
lock(&eqlock);
if(eq == equeue)
equeue = eq->next;
else{
for(p = equeue; p!=nil && p->next!=eq; p = p->next)
;
if(p == nil)
drawerror(display, "eplumb: bad event queue");
p->next = eq->next;
}
unlock(&eqlock);
free(eq->buf);
free(eq);
}
return 1;
}
static
void
addpartial(int id, char *b, int n)
{
EQueue *eq;
eq = malloc(sizeof(EQueue));
if(eq == nil)
return;
eq->id = id;
eq->nbuf = n;
eq->buf = malloc(n);
if(eq->buf == nil){
free(eq);
return;
}
memmove(eq->buf, b, n);
lock(&eqlock);
eq->next = equeue;
equeue = eq;
unlock(&eqlock);
}
static
int
plumbevent(int id, Event *e, uchar *b, int n)
{
int nmore;
if(partial(id, e, b, n) == 0){
/* no partial message already waiting for this id */
e->v = plumbunpackpartial((char*)b, n, &nmore);
if(nmore > 0) /* incomplete message */
addpartial(id, (char*)b, n);
}
if(e->v == nil)
return 0;
return id;
}
int
eplumb(int key, char *port)
{
int fd;
fd = plumbopen(port, OREAD|OCEXEC);
if(fd < 0)
return -1;
return estartfn(key, fd, 8192, plumbevent);
}
|