1 /*
2  * Channel management functions.
3  *
4  * Copyright 2000-2014 Willy Tarreau <w@1wt.eu>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  *
11  */
12 
13 #include <ctype.h>
14 #include <stdarg.h>
15 #include <stdio.h>
16 #include <string.h>
17 
18 #include <haproxy/api.h>
19 #include <haproxy/buf.h>
20 #include <haproxy/channel.h>
21 
22 
23 /* Schedule up to <bytes> more bytes to be forwarded via the channel without
24  * notifying the owner task. Any data pending in the buffer are scheduled to be
25  * sent as well, within the limit of the number of bytes to forward. This must
26  * be the only method to use to schedule bytes to be forwarded. If the requested
27  * number is too large, it is automatically adjusted. The number of bytes taken
28  * into account is returned. Directly touching ->to_forward will cause lockups
29  * when buf->o goes down to zero if nobody is ready to push the remaining data.
30  */
__channel_forward(struct channel * chn,unsigned long long bytes)31 unsigned long long __channel_forward(struct channel *chn, unsigned long long bytes)
32 {
33 	unsigned int budget;
34 	unsigned int forwarded;
35 
36 	/* This is more of a safety measure as it's not supposed to happen in
37 	 * regular code paths.
38 	 */
39 	if (unlikely(chn->to_forward == CHN_INFINITE_FORWARD)) {
40 		c_adv(chn, ci_data(chn));
41 		return bytes;
42 	}
43 
44 	/* Bound the transferred size to a 32-bit count since all our values
45 	 * are 32-bit, and we don't want to reach CHN_INFINITE_FORWARD.
46 	 */
47 	budget = MIN(bytes, CHN_INFINITE_FORWARD - 1);
48 
49 	/* transfer as much as we can of buf->i */
50 	forwarded = MIN(ci_data(chn), budget);
51 	c_adv(chn, forwarded);
52 	budget -= forwarded;
53 
54 	if (!budget)
55 		return forwarded;
56 
57 	/* Now we must ensure chn->to_forward sats below CHN_INFINITE_FORWARD,
58 	 * which also implies it won't overflow. It's less operations in 64-bit.
59 	 */
60 	bytes = (unsigned long long)chn->to_forward + budget;
61 	if (bytes >= CHN_INFINITE_FORWARD)
62 		bytes = CHN_INFINITE_FORWARD - 1;
63 	budget = bytes - chn->to_forward;
64 
65 	chn->to_forward += budget;
66 	forwarded += budget;
67 	return forwarded;
68 }
69 
70 /* writes <len> bytes from message <msg> to the channel's buffer. Returns -1 in
71  * case of success, -2 if the message is larger than the buffer size, or the
72  * number of bytes available otherwise. The send limit is automatically
73  * adjusted to the amount of data written. FIXME-20060521: handle unaligned
74  * data. Note: this function appends data to the buffer's output and possibly
75  * overwrites any pending input data which are assumed not to exist.
76  */
co_inject(struct channel * chn,const char * msg,int len)77 int co_inject(struct channel *chn, const char *msg, int len)
78 {
79 	int max;
80 
81 	if (len == 0)
82 		return -1;
83 
84 	if (len < 0 || len > c_size(chn)) {
85 		/* we can't write this chunk and will never be able to, because
86 		 * it is larger than the buffer. This must be reported as an
87 		 * error. Then we return -2 so that writers that don't care can
88 		 * ignore it and go on, and others can check for this value.
89 		 */
90 		return -2;
91 	}
92 
93 	c_realign_if_empty(chn);
94 	max = b_contig_space(&chn->buf);
95 	if (len > max)
96 		return max;
97 
98 	memcpy(co_tail(chn), msg, len);
99 	b_add(&chn->buf, len);
100 	c_adv(chn, len);
101 	chn->total += len;
102 	return -1;
103 }
104 
105 /* Tries to copy character <c> into the channel's buffer after some length
106  * controls. The chn->o and to_forward pointers are updated. If the channel
107  * input is closed, -2 is returned. If there is not enough room left in the
108  * buffer, -1 is returned. Otherwise the number of bytes copied is returned
109  * (1). Channel flag READ_PARTIAL is updated if some data can be transferred.
110  */
ci_putchr(struct channel * chn,char c)111 int ci_putchr(struct channel *chn, char c)
112 {
113 	if (unlikely(channel_input_closed(chn)))
114 		return -2;
115 
116 	if (!channel_may_recv(chn))
117 		return -1;
118 
119 	*ci_tail(chn) = c;
120 
121 	b_add(&chn->buf, 1);
122 	chn->flags |= CF_READ_PARTIAL;
123 
124 	if (chn->to_forward >= 1) {
125 		if (chn->to_forward != CHN_INFINITE_FORWARD)
126 			chn->to_forward--;
127 		c_adv(chn, 1);
128 	}
129 
130 	chn->total++;
131 	return 1;
132 }
133 
134 /* Tries to copy block <blk> at once into the channel's buffer after length
135  * controls. The chn->o and to_forward pointers are updated. If the channel
136  * input is closed, -2 is returned. If the block is too large for this buffer,
137  * -3 is returned. If there is not enough room left in the buffer, -1 is
138  * returned. Otherwise the number of bytes copied is returned (0 being a valid
139  * number). Channel flag READ_PARTIAL is updated if some data can be
140  * transferred.
141  */
ci_putblk(struct channel * chn,const char * blk,int len)142 int ci_putblk(struct channel *chn, const char *blk, int len)
143 {
144 	int max;
145 
146 	if (unlikely(channel_input_closed(chn)))
147 		return -2;
148 
149 	if (len < 0)
150 		return -3;
151 
152 	max = channel_recv_limit(chn);
153 	if (unlikely(len > max - c_data(chn))) {
154 		/* we can't write this chunk right now because the buffer is
155 		 * almost full or because the block is too large. Returns
156 		 * -3 if block is too large for this buffer. Or -1 if the
157 		 * room left is not large enough.
158 		 */
159 		if (len > max)
160 			return -3;
161 
162 		return -1;
163 	}
164 
165 	if (unlikely(len == 0))
166 		return 0;
167 
168 	/* OK so the data fits in the buffer in one or two blocks */
169 	max = b_contig_space(&chn->buf);
170 	memcpy(ci_tail(chn), blk, MIN(len, max));
171 	if (len > max)
172 		memcpy(c_orig(chn), blk + max, len - max);
173 
174 	b_add(&chn->buf, len);
175 	channel_add_input(chn, len);
176 	return len;
177 }
178 
179 /* Gets one text word out of a channel's buffer from a stream interface.
180  * Return values :
181  *   >0 : number of bytes read. Includes the sep if present before len or end.
182  *   =0 : no sep before end found. <str> is left undefined.
183  *   <0 : no more bytes readable because output is shut.
184  * The channel status is not changed. The caller must call co_skip() to
185  * update it. The line separator is waited for as long as neither the buffer
186  * nor the output are full. If either of them is full, the string may be
187  * returned as is, without the line separator.
188  */
co_getword(const struct channel * chn,char * str,int len,char sep)189 int co_getword(const struct channel *chn, char *str, int len, char sep)
190 {
191 	int ret, max;
192 	char *p;
193 
194 	ret = 0;
195 	max = len;
196 
197 	/* closed or empty + imminent close = -1; empty = 0 */
198 	if (unlikely((chn->flags & CF_SHUTW) || channel_is_empty(chn))) {
199 		if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW))
200 			ret = -1;
201 		goto out;
202 	}
203 
204 	p = co_head(chn);
205 
206 	if (max > co_data(chn)) {
207 		max = co_data(chn);
208 		str[max-1] = 0;
209 	}
210 	while (max) {
211 		*str++ = *p;
212 		ret++;
213 		max--;
214 
215 		if (*p == sep)
216 			break;
217 		p = b_next(&chn->buf, p);
218 	}
219 	if (ret > 0 && ret < len &&
220 	    (ret < co_data(chn) || channel_may_recv(chn)) &&
221 	    *(str-1) != sep &&
222 	    !(chn->flags & (CF_SHUTW|CF_SHUTW_NOW)))
223 		ret = 0;
224  out:
225 	if (max)
226 		*str = 0;
227 	return ret;
228 }
229 
230 /* Gets one text line out of a channel's buffer from a stream interface.
231  * Return values :
232  *   >0 : number of bytes read. Includes the \n if present before len or end.
233  *   =0 : no '\n' before end found. <str> is left undefined.
234  *   <0 : no more bytes readable because output is shut.
235  * The channel status is not changed. The caller must call co_skip() to
236  * update it. The '\n' is waited for as long as neither the buffer nor the
237  * output are full. If either of them is full, the string may be returned
238  * as is, without the '\n'.
239  */
co_getline(const struct channel * chn,char * str,int len)240 int co_getline(const struct channel *chn, char *str, int len)
241 {
242 	int ret, max;
243 	char *p;
244 
245 	ret = 0;
246 	max = len;
247 
248 	/* closed or empty + imminent close = -1; empty = 0 */
249 	if (unlikely((chn->flags & CF_SHUTW) || channel_is_empty(chn))) {
250 		if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW))
251 			ret = -1;
252 		goto out;
253 	}
254 
255 	p = co_head(chn);
256 
257 	if (max > co_data(chn)) {
258 		max = co_data(chn);
259 		str[max-1] = 0;
260 	}
261 	while (max) {
262 		*str++ = *p;
263 		ret++;
264 		max--;
265 
266 		if (*p == '\n')
267 			break;
268 		p = b_next(&chn->buf, p);
269 	}
270 	if (ret > 0 && ret < len &&
271 	    (ret < co_data(chn) || channel_may_recv(chn)) &&
272 	    *(str-1) != '\n' &&
273 	    !(chn->flags & (CF_SHUTW|CF_SHUTW_NOW)))
274 		ret = 0;
275  out:
276 	if (max)
277 		*str = 0;
278 	return ret;
279 }
280 
281 /* Gets one char of data from a channel's buffer,
282  * Return values :
283  *    1 : number of bytes read, equal to requested size.
284  *   =0 : not enough data available. <c> is left undefined.
285  *   <0 : no more bytes readable because output is shut.
286  * The channel status is not changed. The caller must call co_skip() to
287  * update it.
288  */
co_getchar(const struct channel * chn,char * c)289 int co_getchar(const struct channel *chn, char *c)
290 {
291 	if (chn->flags & CF_SHUTW)
292 		return -1;
293 
294 	if (unlikely(co_data(chn) == 0)) {
295 		if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW))
296 			return -1;
297 		return 0;
298 	}
299 
300 	*c = *(co_head(chn));
301 	return 1;
302 }
303 
304 /* Gets one full block of data at once from a channel's buffer, optionally from
305  * a specific offset. Return values :
306  *   >0 : number of bytes read, equal to requested size.
307  *   =0 : not enough data available. <blk> is left undefined.
308  *   <0 : no more bytes readable because output is shut.
309  * The channel status is not changed. The caller must call co_skip() to
310  * update it.
311  */
co_getblk(const struct channel * chn,char * blk,int len,int offset)312 int co_getblk(const struct channel *chn, char *blk, int len, int offset)
313 {
314 	if (chn->flags & CF_SHUTW)
315 		return -1;
316 
317 	if (len + offset > co_data(chn)) {
318 		if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW))
319 			return -1;
320 		return 0;
321 	}
322 
323 	return b_getblk(&chn->buf, blk, len, offset);
324 }
325 
326 /* Gets one or two blocks of data at once from a channel's output buffer.
327  * Return values :
328  *   >0 : number of blocks filled (1 or 2). blk1 is always filled before blk2.
329  *   =0 : not enough data available. <blk*> are left undefined.
330  *   <0 : no more bytes readable because output is shut.
331  * The channel status is not changed. The caller must call co_skip() to
332  * update it. Unused buffers are left in an undefined state.
333  */
co_getblk_nc(const struct channel * chn,const char ** blk1,size_t * len1,const char ** blk2,size_t * len2)334 int co_getblk_nc(const struct channel *chn, const char **blk1, size_t *len1, const char **blk2, size_t *len2)
335 {
336 	if (unlikely(co_data(chn) == 0)) {
337 		if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW))
338 			return -1;
339 		return 0;
340 	}
341 
342 	return b_getblk_nc(&chn->buf, blk1, len1, blk2, len2, 0, co_data(chn));
343 }
344 
345 /* Gets one text line out of a channel's output buffer from a stream interface.
346  * Return values :
347  *   >0 : number of blocks returned (1 or 2). blk1 is always filled before blk2.
348  *   =0 : not enough data available.
349  *   <0 : no more bytes readable because output is shut.
350  * The '\n' is waited for as long as neither the buffer nor the output are
351  * full. If either of them is full, the string may be returned as is, without
352  * the '\n'. Unused buffers are left in an undefined state.
353  */
co_getline_nc(const struct channel * chn,const char ** blk1,size_t * len1,const char ** blk2,size_t * len2)354 int co_getline_nc(const struct channel *chn,
355                   const char **blk1, size_t *len1,
356                   const char **blk2, size_t *len2)
357 {
358 	int retcode;
359 	int l;
360 
361 	retcode = co_getblk_nc(chn, blk1, len1, blk2, len2);
362 	if (unlikely(retcode <= 0))
363 		return retcode;
364 
365 	for (l = 0; l < *len1 && (*blk1)[l] != '\n'; l++);
366 	if (l < *len1 && (*blk1)[l] == '\n') {
367 		*len1 = l + 1;
368 		return 1;
369 	}
370 
371 	if (retcode >= 2) {
372 		for (l = 0; l < *len2 && (*blk2)[l] != '\n'; l++);
373 		if (l < *len2 && (*blk2)[l] == '\n') {
374 			*len2 = l + 1;
375 			return 2;
376 		}
377 	}
378 
379 	if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) {
380 		/* If we have found no LF and the buffer is shut, then
381 		 * the resulting string is made of the concatenation of
382 		 * the pending blocks (1 or 2).
383 		 */
384 		return retcode;
385 	}
386 
387 	/* No LF yet and not shut yet */
388 	return 0;
389 }
390 
391 /* Gets one full block of data at once from a channel's input buffer.
392  * This function can return the data slitted in one or two blocks.
393  * Return values :
394  *   >0 : number of blocks returned (1 or 2). blk1 is always filled before blk2.
395  *   =0 : not enough data available.
396  *   <0 : no more bytes readable because input is shut.
397  */
ci_getblk_nc(const struct channel * chn,char ** blk1,size_t * len1,char ** blk2,size_t * len2)398 int ci_getblk_nc(const struct channel *chn,
399                  char **blk1, size_t *len1,
400                  char **blk2, size_t *len2)
401 {
402 	if (unlikely(ci_data(chn) == 0)) {
403 		if (chn->flags & CF_SHUTR)
404 			return -1;
405 		return 0;
406 	}
407 
408 	if (unlikely(ci_head(chn) + ci_data(chn) > c_wrap(chn))) {
409 		*blk1 = ci_head(chn);
410 		*len1 = c_wrap(chn) - ci_head(chn);
411 		*blk2 = c_orig(chn);
412 		*len2 = ci_data(chn) - *len1;
413 		return 2;
414 	}
415 
416 	*blk1 = ci_head(chn);
417 	*len1 = ci_data(chn);
418 	return 1;
419 }
420 
421 /* Gets one text line out of a channel's input buffer from a stream interface.
422  * Return values :
423  *   >0 : number of blocks returned (1 or 2). blk1 is always filled before blk2.
424  *   =0 : not enough data available.
425  *   <0 : no more bytes readable because output is shut.
426  * The '\n' is waited for as long as neither the buffer nor the input are
427  * full. If either of them is full, the string may be returned as is, without
428  * the '\n'. Unused buffers are left in an undefined state.
429  */
ci_getline_nc(const struct channel * chn,char ** blk1,size_t * len1,char ** blk2,size_t * len2)430 int ci_getline_nc(const struct channel *chn,
431                   char **blk1, size_t *len1,
432                   char **blk2, size_t *len2)
433 {
434 	int retcode;
435 	int l;
436 
437 	retcode = ci_getblk_nc(chn, blk1, len1, blk2, len2);
438 	if (unlikely(retcode <= 0))
439 		return retcode;
440 
441 	for (l = 0; l < *len1 && (*blk1)[l] != '\n'; l++);
442 	if (l < *len1 && (*blk1)[l] == '\n') {
443 		*len1 = l + 1;
444 		return 1;
445 	}
446 
447 	if (retcode >= 2) {
448 		for (l = 0; l < *len2 && (*blk2)[l] != '\n'; l++);
449 		if (l < *len2 && (*blk2)[l] == '\n') {
450 			*len2 = l + 1;
451 			return 2;
452 		}
453 	}
454 
455 	if (chn->flags & CF_SHUTW) {
456 		/* If we have found no LF and the buffer is shut, then
457 		 * the resulting string is made of the concatenation of
458 		 * the pending blocks (1 or 2).
459 		 */
460 		return retcode;
461 	}
462 
463 	/* No LF yet and not shut yet */
464 	return 0;
465 }
466 
467 /* Inserts <str> followed by "\r\n" at position <pos> relative to channel <c>'s
468  * input head. The <len> argument informs about the length of string <str> so
469  * that we don't have to measure it. <str> must be a valid pointer and must not
470  * include the trailing "\r\n".
471  *
472  * The number of bytes added is returned on success. 0 is returned on failure.
473  */
ci_insert_line2(struct channel * c,int pos,const char * str,int len)474 int ci_insert_line2(struct channel *c, int pos, const char *str, int len)
475 {
476 	struct buffer *b = &c->buf;
477 	char *dst = c_ptr(c, pos);
478 	int delta;
479 
480 	delta = len + 2;
481 
482 	if (__b_tail(b) + delta >= b_wrap(b))
483 		return 0;  /* no space left */
484 
485 	if (b_data(b) &&
486 	    b_tail(b) + delta > b_head(b) &&
487 	    b_head(b) >= b_tail(b))
488 		return 0;  /* no space left before wrapping data */
489 
490 	/* first, protect the end of the buffer */
491 	memmove(dst + delta, dst, b_tail(b) - dst);
492 
493 	/* now, copy str over dst */
494 	memcpy(dst, str, len);
495 	dst[len] = '\r';
496 	dst[len + 1] = '\n';
497 
498 	b_add(b, delta);
499 	return delta;
500 }
501 
502 /*
503  * Local variables:
504  *  c-indent-level: 8
505  *  c-basic-offset: 8
506  * End:
507  */
508