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 #include <stdio.h>
41 #include <stdlib.h>
42 #include <unistd.h>
43
44
45 #include "../public/nsapi.h"
46 #include "io.h"
47
48
49
50
51 #define NETBUF_RDTIMEOUT 120
52
53
54
55
56
57 NSAPI_PUBLIC netbuf *netbuf_open(
SYS_NETFD sd,
int sz) {
58 netbuf *buf = (netbuf *) malloc(
sizeof(netbuf));
59
60 buf->rdtimeout =
NETBUF_RDTIMEOUT;
61 buf->pos = sz;
62 buf->cursize = sz;
63 buf->maxsize = sz;
64 buf->sd = sd;
65
66 buf->inbuf =
NULL;
67 buf->errmsg =
NULL;
68
69 return buf;
70 }
71
72
73
74
75
76 NSAPI_PUBLIC void netbuf_close(netbuf *buf) {
77 if(buf->inbuf)
78 free(buf->inbuf);
79 free(buf);
80 }
81
82
83
84
85
86 NSAPI_PUBLIC unsigned char * netbuf_replace(netbuf *buf,
87 unsigned char *inbuf,
int pos,
int cursize,
int maxsize)
88 {
89 unsigned char *oldbuf = buf->inbuf;
90
91 buf->inbuf = inbuf;
92 buf->pos = pos;
93 buf->cursize = cursize;
94 buf->maxsize = maxsize;
95
96 return oldbuf;
97 }
98
99
100
101
102
103 NSAPI_PUBLIC int netbuf_next(netbuf *buf,
int advance) {
104 int n;
105
106 if(!buf->inbuf)
107 buf->inbuf = (
unsigned char *) malloc(buf->maxsize);
108
109 while(
1) {
110 switch(n = net_read(buf->sd, (
char *)(buf->inbuf), buf->maxsize)) {
111
112 case 0:
113 return IO_EOF;
114 case -
1:
115 return IO_ERROR;
116
117
118
119 default:
120 buf->pos = advance;
121 buf->cursize = n;
122 return buf->inbuf[
0];
123 }
124 }
125 }
126
127 NSAPI_PUBLIC int netbuf_getbytes(netbuf *buf,
char *buffer,
int size)
128 {
129 int bytes;
130
131 if (!buf->inbuf) {
132 buf->inbuf = (
unsigned char *) malloc(buf->maxsize);
133 }
else {
134 if (buf->pos < buf->cursize) {
135 int bytes_in_buffer = buf->cursize - buf->pos;
136
137 if (bytes_in_buffer > size)
138 bytes_in_buffer = size;
139
140 memcpy(buffer, &(buf->inbuf[buf->pos]), bytes_in_buffer);
141
142 buf->pos += bytes_in_buffer;
143 return bytes_in_buffer;
144 }
145 }
146
147
148 bytes = net_read(buf->sd, buffer, size);
149 if (bytes ==
0)
150 return NETBUF_EOF;
151 if (bytes <
0) {
152
153 return NETBUF_ERROR;
154 }
155 return bytes;
156 }
157
158
159
160
161
162 NSAPI_PUBLIC int netbuf_grab(netbuf *buf,
int sz) {
163 int n;
164
165 if(!buf->inbuf) {
166 buf->inbuf = (
unsigned char *) malloc(sz);
167 buf->maxsize = sz;
168 }
169 else if(sz > buf->maxsize) {
170 buf->inbuf = (
unsigned char *) realloc(buf->inbuf, sz);
171 buf->maxsize = sz;
172 }
173
174
175 buf->pos =
0;
176 buf->cursize =
0;
177
178 while(
1) {
179 switch(n = net_read(buf->sd, (
char *)(buf->inbuf), sz)) {
180 case 0:
181 return IO_EOF;
182 case -
1: {
183
184 return IO_ERROR;
185 }
186 default:
187 buf->cursize = n;
188 return n;
189 }
190 }
191 }
192