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 if(!buf->sd) {
148 return NETBUF_EOF;
149 }
150
151
152 bytes = net_read(buf->sd, buffer, size);
153 if (bytes ==
0)
154 return NETBUF_EOF;
155 if (bytes <
0) {
156
157 return NETBUF_ERROR;
158 }
159 return bytes;
160 }
161
162
163
164
165
166 NSAPI_PUBLIC int netbuf_grab(netbuf *buf,
int sz) {
167 int n;
168
169 if(!buf->inbuf) {
170 buf->inbuf = (
unsigned char *) malloc(sz);
171 buf->maxsize = sz;
172 }
173 else if(sz > buf->maxsize) {
174 buf->inbuf = (
unsigned char *) realloc(buf->inbuf, sz);
175 buf->maxsize = sz;
176 }
177
178
179 buf->pos =
0;
180 buf->cursize =
0;
181
182 while(
1) {
183 switch(n = net_read(buf->sd, (
char *)(buf->inbuf), sz)) {
184 case 0:
185 return IO_EOF;
186 case -
1: {
187
188 return IO_ERROR;
189 }
190 default:
191 buf->cursize = n;
192 return n;
193 }
194 }
195 }
196