blob: c459e76a9a4cedb6bcf45fb763c5fce942deb7e3 [file] [log] [blame]
Christopher Faulet99eff652019-08-11 23:11:30 +02001/*
2 * FastCGI mux-demux for connections
3 *
4 * Copyright (C) 2019 HAProxy Technologies, Christopher Faulet <cfaulet@haproxy.com>
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 <common/cfgparse.h>
14#include <common/config.h>
15#include <common/fcgi.h>
16#include <common/h1.h>
17#include <common/htx.h>
18#include <common/initcall.h>
19#include <common/ist.h>
20#include <common/mini-clist.h>
21#include <common/net_helper.h>
22
23#include <types/proxy.h>
24#include <types/session.h>
25
26#include <proto/connection.h>
27#include <proto/fcgi-app.h>
28#include <proto/h1_htx.h>
29#include <proto/http_htx.h>
30#include <proto/log.h>
31#include <proto/session.h>
32#include <proto/ssl_sock.h>
33#include <proto/stream.h>
34#include <proto/stream_interface.h>
35
36/* FCGI Connection flags (32 bits) */
37#define FCGI_CF_NONE 0x00000000
38
39/* Flags indicating why writing to the mux is blockes */
40#define FCGI_CF_MUX_MALLOC 0x00000001 /* mux is blocked on lack connection's mux buffer */
41#define FCGI_CF_MUX_MFULL 0x00000002 /* mux is blocked on connection's mux buffer full */
42#define FCGI_CF_MUX_BLOCK_ANY 0x00000003 /* mux is blocked on connection's mux buffer full */
43
44/* Flags indicating why writing to the demux is blocked.
45 * The first two ones directly affect the ability for the mux to receive data
46 * from the connection. The other ones affect the mux's ability to demux
47 * received data.
48 */
49#define FCGI_CF_DEM_DALLOC 0x00000004 /* demux blocked on lack of connection's demux buffer */
50#define FCGI_CF_DEM_DFULL 0x00000008 /* demux blocked on connection's demux buffer full */
51#define FCGI_CF_DEM_MROOM 0x00000010 /* demux blocked on lack of room in mux buffer */
52#define FCGI_CF_DEM_SALLOC 0x00000020 /* demux blocked on lack of stream's rx buffer */
53#define FCGI_CF_DEM_SFULL 0x00000040 /* demux blocked on stream request buffer full */
54#define FCGI_CF_DEM_TOOMANY 0x00000080 /* demux blocked waiting for some conn_streams to leave */
55#define FCGI_CF_DEM_BLOCK_ANY 0x000000F0 /* aggregate of the demux flags above except DALLOC/DFULL */
56
57/* Other flags */
58#define FCGI_CF_MPXS_CONNS 0x00000100 /* connection multiplexing is supported */
59#define FCGI_CF_ABRTS_SENT 0x00000200 /* a record ABORT was successfully sent to all active streams */
60#define FCGI_CF_ABRTS_FAILED 0x00000400 /* failed to abort processing of all streams */
61#define FCGI_CF_WAIT_FOR_HS 0x00000800 /* We did check that at least a stream was waiting for handshake */
62#define FCGI_CF_KEEP_CONN 0x00001000 /* HAproxy is responsible to close the connection */
63#define FCGI_CF_GET_VALUES 0x00002000 /* retrieve settings */
64
65/* FCGI connection state (fcgi_conn->state) */
66enum fcgi_conn_st {
67 FCGI_CS_INIT = 0, /* init done, waiting for sending GET_VALUES record */
68 FCGI_CS_SETTINGS, /* GET_VALUES sent, waiting for the GET_VALUES_RESULT record */
69 FCGI_CS_RECORD_H, /* GET_VALUES_RESULT received, waiting for a record header */
70 FCGI_CS_RECORD_D, /* Record header OK, waiting for a record data */
71 FCGI_CS_RECORD_P, /* Record processed, remains the padding */
72 FCGI_CS_CLOSED, /* abort requests if necessary and close the connection ASAP */
73 FCGI_CS_ENTRIES
74} __attribute__((packed));
75
76/* 32 buffers: one for the ring's root, rest for the mbuf itself */
77#define FCGI_C_MBUF_CNT 32
78
79/* FCGI connection descriptor */
80struct fcgi_conn {
81 struct connection *conn;
82
83 enum fcgi_conn_st state; /* FCGI connection state */
84 int16_t max_id; /* highest ID known on this connection, <0 before mgmt records */
85 uint32_t streams_limit; /* maximum number of concurrent streams the peer supports */
86 uint32_t flags; /* Connection flags: FCGI_CF_* */
87
88 int16_t dsi; /* dmux stream ID (<0 = idle ) */
89 uint16_t drl; /* demux record length (if dsi >= 0) */
90 uint8_t drt; /* demux record type (if dsi >= 0) */
91 uint8_t drp; /* demux record padding (if dsi >= 0) */
92
93 struct buffer dbuf; /* demux buffer */
94 struct buffer mbuf[FCGI_C_MBUF_CNT]; /* mux buffers (ring) */
95
96 int timeout; /* idle timeout duration in ticks */
97 int shut_timeout; /* idle timeout duration in ticks after shutdown */
98 unsigned int nb_streams; /* number of streams in the tree */
99 unsigned int nb_cs; /* number of attached conn_streams */
100 unsigned int nb_reserved; /* number of reserved streams */
101 unsigned int stream_cnt; /* total number of streams seen */
102
103 struct proxy *proxy; /* the proxy this connection was created for */
104 struct fcgi_app *app; /* FCGI application used by this mux */
105 struct task *task; /* timeout management task */
106 struct eb_root streams_by_id; /* all active streams by their ID */
107
108 struct list send_list; /* list of blocked streams requesting to send */
109 struct list sending_list; /* list of fcgi_strm scheduled to send data */
110
111 struct buffer_wait buf_wait; /* Wait list for buffer allocation */
112 struct wait_event wait_event; /* To be used if we're waiting for I/Os */
113};
114
115
116/* FCGI stream state, in fcgi_strm->state */
117enum fcgi_strm_st {
118 FCGI_SS_IDLE = 0,
119 FCGI_SS_OPEN,
120 FCGI_SS_HREM, // half-closed(remote)
121 FCGI_SS_HLOC, // half-closed(local)
122 FCGI_SS_ERROR,
123 FCGI_SS_CLOSED,
124 FCGI_SS_ENTRIES
125} __attribute__((packed));
126
127
128/* FCGI stream flags (32 bits) */
129#define FCGI_SF_NONE 0x00000000
130#define FCGI_SF_ES_RCVD 0x00000001 /* end-of-stream received (empty STDOUT or EDN_REQUEST record) */
131#define FCGI_SF_ES_SENT 0x00000002 /* end-of-strem sent (empty STDIN record) */
132#define FCGI_SF_ABRT_SENT 0x00000004 /* abort sent (ABORT_REQUEST record) */
133
134/* Stream flags indicating the reason the stream is blocked */
135#define FCGI_SF_BLK_MBUSY 0x00000010 /* blocked waiting for mux access (transient) */
136#define FCGI_SF_BLK_MROOM 0x00000020 /* blocked waiting for room in the mux */
137#define FCGI_SF_BLK_ANY 0x00000030 /* any of the reasons above */
138
139#define FCGI_SF_BEGIN_SENT 0x00000100 /* a BEGIN_REQUEST record was sent for this stream */
140#define FCGI_SF_OUTGOING_DATA 0x00000200 /* set whenever we've seen outgoing data */
141
142#define FCGI_SF_WANT_SHUTR 0x00001000 /* a stream couldn't shutr() (mux full/busy) */
143#define FCGI_SF_WANT_SHUTW 0x00002000 /* a stream couldn't shutw() (mux full/busy) */
144#define FCGI_SF_KILL_CONN 0x00004000 /* kill the whole connection with this stream */
145
146/* Other flags */
147#define FCGI_SF_HAVE_I_TLR 0x00010000 /* Set during input process to know the trailers were processed */
148
149/* FCGI stream descriptor */
150struct fcgi_strm {
151 struct conn_stream *cs;
152 struct session *sess;
153 struct fcgi_conn *fconn;
154
155 int32_t id; /* stream ID */
156
157 uint32_t flags; /* Connection flags: FCGI_SF_* */
158 enum fcgi_strm_st state; /* FCGI stream state */
159 int proto_status; /* FCGI_PS_* */
160
161 struct h1m h1m; /* response parser state for H1 */
162
163 struct buffer rxbuf; /* receive buffer, always valid (buf_empty or real buffer) */
164
165 struct eb32_node by_id; /* place in fcgi_conn's streams_by_id */
166 struct wait_event wait_event; /* Wait list, when we're attempting to send an ABORT but we can't send */
167 struct wait_event *recv_wait; /* Address of the wait_event the conn_stream associated is waiting on */
168 struct wait_event *send_wait; /* Address of the wait_event the conn_stream associated is waiting on */
169 struct list send_list; /* To be used when adding in fcgi_conn->send_list */
170 struct list sending_list; /* To be used when adding in fcgi_conn->sending_list */
171};
172
173/* Flags representing all default FCGI parameters */
174#define FCGI_SP_CGI_GATEWAY 0x00000001
175#define FCGI_SP_DOC_ROOT 0x00000002
176#define FCGI_SP_SCRIPT_NAME 0x00000004
177#define FCGI_SP_PATH_INFO 0x00000008
178#define FCGI_SP_REQ_URI 0x00000010
179#define FCGI_SP_REQ_METH 0x00000020
180#define FCGI_SP_REQ_QS 0x00000040
181#define FCGI_SP_SRV_PORT 0x00000080
182#define FCGI_SP_SRV_PROTO 0x00000100
183#define FCGI_SP_SRV_NAME 0x00000200
184#define FCGI_SP_REM_ADDR 0x00000400
185#define FCGI_SP_REM_PORT 0x00000800
186#define FCGI_SP_SCRIPT_FILE 0x00001000
187#define FCGI_SP_PATH_TRANS 0x00002000
188#define FCGI_SP_CONT_LEN 0x00004000
189#define FCGI_SP_HTTPS 0x00008000
190#define FCGI_SP_MASK 0x0000FFFF
191#define FCGI_SP_URI_MASK (FCGI_SP_SCRIPT_NAME|FCGI_SP_PATH_INFO|FCGI_SP_REQ_QS)
192
193/* FCGI parameters used when PARAMS record is sent */
194struct fcgi_strm_params {
195 uint32_t mask;
196 struct ist docroot;
197 struct ist scriptname;
198 struct ist pathinfo;
199 struct ist meth;
200 struct ist uri;
201 struct ist vsn;
202 struct ist qs;
203 struct ist srv_name;
204 struct ist srv_port;
205 struct ist rem_addr;
206 struct ist rem_port;
207 struct ist cont_len;
208 int https;
209 struct buffer *p;
210};
211
212/* Maximum amount of data we're OK with re-aligning for buffer optimizations */
213#define MAX_DATA_REALIGN 1024
214
215/* FCGI connection and stream pools */
216DECLARE_STATIC_POOL(pool_head_fcgi_conn, "fcgi_conn", sizeof(struct fcgi_conn));
217DECLARE_STATIC_POOL(pool_head_fcgi_strm, "fcgi_strm", sizeof(struct fcgi_strm));
218
219static struct task *fcgi_timeout_task(struct task *t, void *context, unsigned short state);
220static int fcgi_process(struct fcgi_conn *fconn);
221static struct task *fcgi_io_cb(struct task *t, void *ctx, unsigned short state);
222static inline struct fcgi_strm *fcgi_conn_st_by_id(struct fcgi_conn *fconn, int id);
223static struct task *fcgi_deferred_shut(struct task *t, void *ctx, unsigned short state);
224static struct fcgi_strm *fcgi_conn_stream_new(struct fcgi_conn *fconn, struct conn_stream *cs, struct session *sess);
225static void fcgi_strm_alert(struct fcgi_strm *fstrm);
226static int fcgi_strm_send_abort(struct fcgi_conn *fconn, struct fcgi_strm *fstrm);
227
228/* a dmumy management stream */
229static const struct fcgi_strm *fcgi_mgmt_stream = &(const struct fcgi_strm){
230 .cs = NULL,
231 .fconn = NULL,
232 .state = FCGI_SS_CLOSED,
233 .flags = FCGI_SF_NONE,
234 .id = 0,
235};
236
237/* and a dummy idle stream for use with any unknown stream */
238static const struct fcgi_strm *fcgi_unknown_stream = &(const struct fcgi_strm){
239 .cs = NULL,
240 .fconn = NULL,
241 .state = FCGI_SS_IDLE,
242 .flags = FCGI_SF_NONE,
243 .id = 0,
244};
245
246
247/*****************************************************/
248/* functions below are for dynamic buffer management */
249/*****************************************************/
250
251/* Indicates whether or not the we may call the fcgi_recv() function to attempt
252 * to receive data into the buffer and/or demux pending data. The condition is
253 * a bit complex due to some API limits for now. The rules are the following :
254 * - if an error or a shutdown was detected on the connection and the buffer
255 * is empty, we must not attempt to receive
256 * - if the demux buf failed to be allocated, we must not try to receive and
257 * we know there is nothing pending
258 * - if no flag indicates a blocking condition, we may attempt to receive,
259 * regardless of whether the demux buffer is full or not, so that only
260 * de demux part decides whether or not to block. This is needed because
261 * the connection API indeed prevents us from re-enabling receipt that is
262 * already enabled in a polled state, so we must always immediately stop
263 * as soon as the demux can't proceed so as never to hit an end of read
264 * with data pending in the buffers.
265 * - otherwise must may not attempt
266 */
267static inline int fcgi_recv_allowed(const struct fcgi_conn *fconn)
268{
269 if (b_data(&fconn->dbuf) == 0 &&
270 (fconn->state == FCGI_CS_CLOSED ||
271 fconn->conn->flags & CO_FL_ERROR ||
272 conn_xprt_read0_pending(fconn->conn)))
273 return 0;
274
275 if (!(fconn->flags & FCGI_CF_DEM_DALLOC) &&
276 !(fconn->flags & FCGI_CF_DEM_BLOCK_ANY))
277 return 1;
278
279 return 0;
280}
281
282/* Restarts reading on the connection if it was not enabled */
283static inline void fcgi_conn_restart_reading(const struct fcgi_conn *fconn, int consider_buffer)
284{
285 if (!fcgi_recv_allowed(fconn))
286 return;
287 if ((!consider_buffer || !b_data(&fconn->dbuf)) &&
288 (fconn->wait_event.events & SUB_RETRY_RECV))
289 return;
290 tasklet_wakeup(fconn->wait_event.tasklet);
291}
292
293
294/* Tries to grab a buffer and to re-enable processing on mux <target>. The
295 * fcgi_conn flags are used to figure what buffer was requested. It returns 1 if
296 * the allocation succeeds, in which case the connection is woken up, or 0 if
297 * it's impossible to wake up and we prefer to be woken up later.
298 */
299static int fcgi_buf_available(void *target)
300{
301 struct fcgi_conn *fconn = target;
302 struct fcgi_strm *fstrm;
303
304 if ((fconn->flags & FCGI_CF_DEM_DALLOC) && b_alloc_margin(&fconn->dbuf, 0)) {
305 fconn->flags &= ~FCGI_CF_DEM_DALLOC;
306 fcgi_conn_restart_reading(fconn, 1);
307 return 1;
308 }
309
310 if ((fconn->flags & FCGI_CF_MUX_MALLOC) && b_alloc_margin(br_tail(fconn->mbuf), 0)) {
311 fconn->flags &= ~FCGI_CF_MUX_MALLOC;
312
313 if (fconn->flags & FCGI_CF_DEM_MROOM) {
314 fconn->flags &= ~FCGI_CF_DEM_MROOM;
315 fcgi_conn_restart_reading(fconn, 1);
316 }
317 return 1;
318 }
319
320 if ((fconn->flags & FCGI_CF_DEM_SALLOC) &&
321 (fstrm = fcgi_conn_st_by_id(fconn, fconn->dsi)) && fstrm->cs &&
322 b_alloc_margin(&fstrm->rxbuf, 0)) {
323 fconn->flags &= ~FCGI_CF_DEM_SALLOC;
324 fcgi_conn_restart_reading(fconn, 1);
325 return 1;
326 }
327
328 return 0;
329}
330
331static inline struct buffer *fcgi_get_buf(struct fcgi_conn *fconn, struct buffer *bptr)
332{
333 struct buffer *buf = NULL;
334
335 if (likely(!LIST_ADDED(&fconn->buf_wait.list)) &&
336 unlikely((buf = b_alloc_margin(bptr, 0)) == NULL)) {
337 fconn->buf_wait.target = fconn;
338 fconn->buf_wait.wakeup_cb = fcgi_buf_available;
339 HA_SPIN_LOCK(BUF_WQ_LOCK, &buffer_wq_lock);
340 LIST_ADDQ(&buffer_wq, &fconn->buf_wait.list);
341 HA_SPIN_UNLOCK(BUF_WQ_LOCK, &buffer_wq_lock);
342 __conn_xprt_stop_recv(fconn->conn);
343 }
344 return buf;
345}
346
347static inline void fcgi_release_buf(struct fcgi_conn *fconn, struct buffer *bptr)
348{
349 if (bptr->size) {
350 b_free(bptr);
351 offer_buffers(NULL, tasks_run_queue);
352 }
353}
354
355static inline void fcgi_release_mbuf(struct fcgi_conn *fconn)
356{
357 struct buffer *buf;
358 unsigned int count = 0;
359
360 while (b_size(buf = br_head_pick(fconn->mbuf))) {
361 b_free(buf);
362 count++;
363 }
364 if (count)
365 offer_buffers(NULL, tasks_run_queue);
366}
367
368/* Returns the number of allocatable outgoing streams for the connection taking
369 * the number reserved streams into account.
370 */
371static inline int fcgi_streams_left(const struct fcgi_conn *fconn)
372{
373 int ret;
374
375 ret = (unsigned int)(0x7FFF - fconn->max_id) - fconn->nb_reserved - 1;
376 if (ret < 0)
377 ret = 0;
378 return ret;
379}
380
381/* Returns the number of streams in use on a connection to figure if it's
382 * idle or not. We check nb_cs and not nb_streams as the caller will want
383 * to know if it was the last one after a detach().
384 */
385static int fcgi_used_streams(struct connection *conn)
386{
387 struct fcgi_conn *fconn = conn->ctx;
388
389 return fconn->nb_cs;
390}
391
392/* Returns the number of concurrent streams available on the connection */
393static int fcgi_avail_streams(struct connection *conn)
394{
395 struct server *srv = objt_server(conn->target);
396 struct fcgi_conn *fconn = conn->ctx;
397 int ret1, ret2;
398
399 /* Don't open new stream if the connection is closed */
400 if (fconn->state == FCGI_CS_CLOSED)
401 return 0;
402
403 /* May be negative if this setting has changed */
404 ret1 = (fconn->streams_limit - fconn->nb_streams);
405
406 /* we must also consider the limit imposed by stream IDs */
407 ret2 = fcgi_streams_left(fconn);
408 ret1 = MIN(ret1, ret2);
409 if (ret1 > 0 && srv && srv->max_reuse >= 0) {
410 ret2 = ((fconn->stream_cnt <= srv->max_reuse) ? srv->max_reuse - fconn->stream_cnt + 1: 0);
411 ret1 = MIN(ret1, ret2);
412 }
413 return ret1;
414}
415
416/*****************************************************************/
417/* functions below are dedicated to the mux setup and management */
418/*****************************************************************/
419
420/* Initializes the mux once it's attached. Only outgoing connections are
421 * supported. So the context is already initialized before installing the
422 * mux. <input> is always used as Input buffer and may contain data. It is the
423 * caller responsibility to not reuse it anymore. Returns < 0 on error.
424 */
425static int fcgi_init(struct connection *conn, struct proxy *px, struct session *sess,
426 struct buffer *input)
427{
428 struct fcgi_conn *fconn;
429 struct fcgi_strm *fstrm;
430 struct fcgi_app *app = get_px_fcgi_app(px);
431 struct task *t = NULL;
432
433 if (!app)
434 goto fail_conn;
435
436 fconn = pool_alloc(pool_head_fcgi_conn);
437 if (!fconn)
438 goto fail_conn;
439
440 fconn->shut_timeout = fconn->timeout = px->timeout.server;
441 if (tick_isset(px->timeout.serverfin))
442 fconn->shut_timeout = px->timeout.serverfin;
443
444 fconn->flags = FCGI_CF_NONE;
445
446 /* Retrieve usefull info from the FCGI app */
447 if (app->flags & FCGI_APP_FL_KEEP_CONN)
448 fconn->flags |= FCGI_CF_KEEP_CONN;
449 if (app->flags & FCGI_APP_FL_GET_VALUES)
450 fconn->flags |= FCGI_CF_GET_VALUES;
451 if (app->flags & FCGI_APP_FL_MPXS_CONNS)
452 fconn->flags |= FCGI_CF_MPXS_CONNS;
453
454 fconn->proxy = px;
455 fconn->app = app;
456 fconn->task = NULL;
457 if (tick_isset(fconn->timeout)) {
458 t = task_new(tid_bit);
459 if (!t)
460 goto fail;
461
462 fconn->task = t;
463 t->process = fcgi_timeout_task;
464 t->context = fconn;
465 t->expire = tick_add(now_ms, fconn->timeout);
466 }
467
468 fconn->wait_event.tasklet = tasklet_new();
469 if (!fconn->wait_event.tasklet)
470 goto fail;
471 fconn->wait_event.tasklet->process = fcgi_io_cb;
472 fconn->wait_event.tasklet->context = fconn;
473 fconn->wait_event.events = 0;
474
475 /* Initialise the context. */
476 fconn->state = FCGI_CS_INIT;
477 fconn->conn = conn;
478 fconn->streams_limit = app->maxreqs;
479 fconn->max_id = -1;
480 fconn->nb_streams = 0;
481 fconn->nb_cs = 0;
482 fconn->nb_reserved = 0;
483 fconn->stream_cnt = 0;
484
485 fconn->dbuf = *input;
486 fconn->dsi = -1;
487
488 br_init(fconn->mbuf, sizeof(fconn->mbuf) / sizeof(fconn->mbuf[0]));
489 fconn->streams_by_id = EB_ROOT;
490 LIST_INIT(&fconn->send_list);
491 LIST_INIT(&fconn->sending_list);
492 LIST_INIT(&fconn->buf_wait.list);
493
494 if (t)
495 task_queue(t);
496
497 /* FIXME: this is temporary, for outgoing connections we need to
498 * immediately allocate a stream until the code is modified so that the
499 * caller calls ->attach(). For now the outgoing cs is stored as
500 * conn->ctx by the caller.
501 */
502 fstrm = fcgi_conn_stream_new(fconn, conn->ctx, sess);
503 if (!fstrm)
504 goto fail;
505
506 conn->ctx = fconn;
507
508 /* Repare to read something */
509 fcgi_conn_restart_reading(fconn, 1);
510 return 0;
511
512 fail:
513 task_destroy(t);
514 if (fconn->wait_event.tasklet)
515 tasklet_free(fconn->wait_event.tasklet);
516 pool_free(pool_head_fcgi_conn, fconn);
517 fail_conn:
518 return -1;
519}
520
521/* Returns the next allocatable outgoing stream ID for the FCGI connection, or
522 * -1 if no more is allocatable.
523 */
524static inline int32_t fcgi_conn_get_next_sid(const struct fcgi_conn *fconn)
525{
526 int32_t id = (fconn->max_id + 1) | 1;
527
528 if ((id & 0x80000000U))
529 id = -1;
530 return id;
531}
532
533/* Returns the stream associated with id <id> or NULL if not found */
534static inline struct fcgi_strm *fcgi_conn_st_by_id(struct fcgi_conn *fconn, int id)
535{
536 struct eb32_node *node;
537
538 if (id == 0)
539 return (struct fcgi_strm *)fcgi_mgmt_stream;
540
541 if (id > fconn->max_id)
542 return (struct fcgi_strm *)fcgi_unknown_stream;
543
544 node = eb32_lookup(&fconn->streams_by_id, id);
545 if (!node)
546 return (struct fcgi_strm *)fcgi_unknown_stream;
547 return container_of(node, struct fcgi_strm, by_id);
548}
549
550
551/* Release function. This one should be called to free all resources allocated
552 * to the mux.
553 */
554static void fcgi_release(struct fcgi_conn *fconn)
555{
556 struct connection *conn = NULL;;
557
558 if (fconn) {
559 /* The connection must be attached to this mux to be released */
560 if (fconn->conn && fconn->conn->ctx == fconn)
561 conn = fconn->conn;
562
563 if (LIST_ADDED(&fconn->buf_wait.list)) {
564 HA_SPIN_LOCK(BUF_WQ_LOCK, &buffer_wq_lock);
565 LIST_DEL(&fconn->buf_wait.list);
566 HA_SPIN_UNLOCK(BUF_WQ_LOCK, &buffer_wq_lock);
567 }
568
569 fcgi_release_buf(fconn, &fconn->dbuf);
570 fcgi_release_mbuf(fconn);
571
572 if (fconn->task) {
573 fconn->task->context = NULL;
574 task_wakeup(fconn->task, TASK_WOKEN_OTHER);
575 fconn->task = NULL;
576 }
577 if (fconn->wait_event.tasklet)
578 tasklet_free(fconn->wait_event.tasklet);
Christopher Fauleta99db932019-09-18 11:11:46 +0200579 if (conn && fconn->wait_event.events != 0)
Christopher Faulet99eff652019-08-11 23:11:30 +0200580 conn->xprt->unsubscribe(conn, conn->xprt_ctx, fconn->wait_event.events,
581 &fconn->wait_event);
582 }
583
584 if (conn) {
585 conn->mux = NULL;
586 conn->ctx = NULL;
587
588 conn_stop_tracking(conn);
589 conn_full_close(conn);
590 if (conn->destroy_cb)
591 conn->destroy_cb(conn);
592 conn_free(conn);
593 }
594}
595
596
597/* Retruns true if the FCGI connection must be release */
598static inline int fcgi_conn_is_dead(struct fcgi_conn *fconn)
599{
600 if (eb_is_empty(&fconn->streams_by_id) && /* don't close if streams exist */
601 (!(fconn->flags & FCGI_CF_KEEP_CONN) || /* don't keep the connection alive */
602 (fconn->conn->flags & CO_FL_ERROR) || /* errors close immediately */
603 (fconn->state == FCGI_CS_CLOSED && !fconn->task) ||/* a timeout stroke earlier */
604 (!(fconn->conn->owner)) || /* Nobody's left to take care of the connection, drop it now */
605 (!br_data(fconn->mbuf) && /* mux buffer empty, also process clean events below */
606 conn_xprt_read0_pending(fconn->conn))))
607 return 1;
608 return 0;
609}
610
611
612/********************************************************/
613/* functions below are for the FCGI protocol processing */
614/********************************************************/
615
Christopher Faulet99eff652019-08-11 23:11:30 +0200616/* Marks an error on the stream. */
617static inline void fcgi_strm_error(struct fcgi_strm *fstrm)
618{
619 if (fstrm->id && fstrm->state != FCGI_SS_ERROR) {
620 if (fstrm->state < FCGI_SS_ERROR)
621 fstrm->state = FCGI_SS_ERROR;
622 if (fstrm->cs)
623 cs_set_error(fstrm->cs);
624 }
625}
626
627/* Attempts to notify the data layer of recv availability */
628static void fcgi_strm_notify_recv(struct fcgi_strm *fstrm)
629{
630 struct wait_event *sw;
631
632 if (fstrm->recv_wait) {
633 sw = fstrm->recv_wait;
634 sw->events &= ~SUB_RETRY_RECV;
635 tasklet_wakeup(sw->tasklet);
636 fstrm->recv_wait = NULL;
637 }
638}
639
640/* Attempts to notify the data layer of send availability */
641static void fcgi_strm_notify_send(struct fcgi_strm *fstrm)
642{
643 struct wait_event *sw;
644
645 if (fstrm->send_wait && !LIST_ADDED(&fstrm->sending_list)) {
646 sw = fstrm->send_wait;
647 sw->events &= ~SUB_RETRY_SEND;
648 LIST_ADDQ(&fstrm->fconn->sending_list, &fstrm->sending_list);
649 tasklet_wakeup(sw->tasklet);
650 }
651}
652
653/* Alerts the data layer, trying to wake it up by all means, following
654 * this sequence :
655 * - if the fcgi stream' data layer is subscribed to recv, then it's woken up
656 * for recv
657 * - if its subscribed to send, then it's woken up for send
658 * - if it was subscribed to neither, its ->wake() callback is called
659 * It is safe to call this function with a closed stream which doesn't have a
660 * conn_stream anymore.
661 */
662static void fcgi_strm_alert(struct fcgi_strm *fstrm)
663{
664 if (fstrm->recv_wait || fstrm->send_wait) {
665 fcgi_strm_notify_recv(fstrm);
666 fcgi_strm_notify_send(fstrm);
667 }
668 else if (fstrm->cs && fstrm->cs->data_cb->wake != NULL)
669 fstrm->cs->data_cb->wake(fstrm->cs);
670}
671
672/* Writes the 16-bit record size <len> at address <record> */
673static inline void fcgi_set_record_size(void *record, uint16_t len)
674{
675 uint8_t *out = (record + 4);
676
677 *out = (len >> 8);
678 *(out + 1) = (len & 0xff);
679}
680
681/* Writes the 16-bit stream id <id> at address <record> */
682static inline void fcgi_set_record_id(void *record, uint16_t id)
683{
684 uint8_t *out = (record + 2);
685
686 *out = (id >> 8);
687 *(out + 1) = (id & 0xff);
688}
689
690/* Marks a FCGI stream as CLOSED and decrement the number of active streams for
691 * its connection if the stream was not yet closed. Please use this exclusively
692 * before closing a stream to ensure stream count is well maintained.
693 */
694static inline void fcgi_strm_close(struct fcgi_strm *fstrm)
695{
696 if (fstrm->state != FCGI_SS_CLOSED) {
697 fstrm->fconn->nb_streams--;
698 if (!fstrm->id)
699 fstrm->fconn->nb_reserved--;
700 if (fstrm->cs) {
701 if (!(fstrm->cs->flags & CS_FL_EOS) && !b_data(&fstrm->rxbuf))
702 fcgi_strm_notify_recv(fstrm);
703 }
704 }
705 fstrm->state = FCGI_SS_CLOSED;
706}
707
708/* Detaches a FCGI stream from its FCGI connection and releases it to the
709 * fcgi_strm pool.
710 */
711static void fcgi_strm_destroy(struct fcgi_strm *fstrm)
712{
713 fcgi_strm_close(fstrm);
714 eb32_delete(&fstrm->by_id);
715 if (b_size(&fstrm->rxbuf)) {
716 b_free(&fstrm->rxbuf);
717 offer_buffers(NULL, tasks_run_queue);
718 }
719 if (fstrm->send_wait != NULL)
720 fstrm->send_wait->events &= ~SUB_RETRY_SEND;
721 if (fstrm->recv_wait != NULL)
722 fstrm->recv_wait->events &= ~SUB_RETRY_RECV;
723 /* There's no need to explicitly call unsubscribe here, the only
724 * reference left would be in the fconn send_list/fctl_list, and if
725 * we're in it, we're getting out anyway
726 */
727 LIST_DEL_INIT(&fstrm->send_list);
728 if (LIST_ADDED(&fstrm->sending_list)) {
729 tasklet_remove_from_tasklet_list(fstrm->send_wait->tasklet);
730 LIST_DEL_INIT(&fstrm->sending_list);
731 }
732 tasklet_free(fstrm->wait_event.tasklet);
733 pool_free(pool_head_fcgi_strm, fstrm);
734}
735
736/* Allocates a new stream <id> for connection <fconn> and adds it into fconn's
737 * stream tree. In case of error, nothing is added and NULL is returned. The
738 * causes of errors can be any failed memory allocation. The caller is
739 * responsible for checking if the connection may support an extra stream prior
740 * to calling this function.
741 */
742static struct fcgi_strm *fcgi_strm_new(struct fcgi_conn *fconn, int id)
743{
744 struct fcgi_strm *fstrm;
745
746 fstrm = pool_alloc(pool_head_fcgi_strm);
747 if (!fstrm)
748 goto out;
749
750 fstrm->wait_event.tasklet = tasklet_new();
751 if (!fstrm->wait_event.tasklet) {
752 pool_free(pool_head_fcgi_strm, fstrm);
753 goto out;
754 }
755 fstrm->send_wait = NULL;
756 fstrm->recv_wait = NULL;
757 fstrm->wait_event.tasklet->process = fcgi_deferred_shut;
758 fstrm->wait_event.tasklet->context = fstrm;
759 fstrm->wait_event.events = 0;
760 LIST_INIT(&fstrm->send_list);
761 LIST_INIT(&fstrm->sending_list);
762 fstrm->fconn = fconn;
763 fstrm->cs = NULL;
764 fstrm->flags = FCGI_SF_NONE;
765 fstrm->proto_status = 0;
766 fstrm->state = FCGI_SS_IDLE;
767 fstrm->rxbuf = BUF_NULL;
768
769 h1m_init_res(&fstrm->h1m);
770 fstrm->h1m.err_pos = -1; // don't care about errors on the request path
771 fstrm->h1m.flags |= (H1_MF_NO_PHDR|H1_MF_CLEAN_CONN_HDR);
772
773 fstrm->by_id.key = fstrm->id = id;
774 if (id > 0)
775 fconn->max_id = id;
776 else
777 fconn->nb_reserved++;
778
779 eb32_insert(&fconn->streams_by_id, &fstrm->by_id);
780 fconn->nb_streams++;
781 fconn->stream_cnt++;
782
783 return fstrm;
784
785 out:
786 return NULL;
787}
788
789/* Allocates a new stream associated to conn_stream <cs> on the FCGI connection
790 * <fconn> and returns it, or NULL in case of memory allocation error or if the
791 * highest possible stream ID was reached.
792 */
793static struct fcgi_strm *fcgi_conn_stream_new(struct fcgi_conn *fconn, struct conn_stream *cs,
794 struct session *sess)
795{
796 struct fcgi_strm *fstrm = NULL;
797
798 if (fconn->nb_streams >= fconn->streams_limit)
799 goto out;
800
801 if (fcgi_streams_left(fconn) < 1)
802 goto out;
803
804 /* Defer choosing the ID until we send the first message to create the stream */
805 fstrm = fcgi_strm_new(fconn, 0);
806 if (!fstrm)
807 goto out;
808
809 fstrm->cs = cs;
810 fstrm->sess = sess;
811 cs->ctx = fstrm;
812 fconn->nb_cs++;
813
814 out:
815 return fstrm;
816}
817
818/* Wakes a specific stream and assign its conn_stream some CS_FL_* flags among
819 * CS_FL_ERR_PENDING and CS_FL_ERROR if needed. The stream's state is
820 * automatically updated accordingly. If the stream is orphaned, it is
821 * destroyed.
822 */
823static void fcgi_strm_wake_one_stream(struct fcgi_strm *fstrm)
824{
825 if (!fstrm->cs) {
826 /* this stream was already orphaned */
827 fcgi_strm_destroy(fstrm);
828 return;
829 }
830
831 if (conn_xprt_read0_pending(fstrm->fconn->conn)) {
832 if (fstrm->state == FCGI_SS_OPEN)
833 fstrm->state = FCGI_SS_HREM;
834 else if (fstrm->state == FCGI_SS_HLOC)
835 fcgi_strm_close(fstrm);
836 }
837
838 if ((fstrm->fconn->state == FCGI_CS_CLOSED || fstrm->fconn->conn->flags & CO_FL_ERROR)) {
839 fstrm->cs->flags |= CS_FL_ERR_PENDING;
840 if (fstrm->cs->flags & CS_FL_EOS)
841 fstrm->cs->flags |= CS_FL_ERROR;
842 if (fstrm->state < FCGI_SS_ERROR)
843 fstrm->state = FCGI_SS_ERROR;
844 }
845
846 fcgi_strm_alert(fstrm);
847}
848
849/* Wakes unassigned streams (ID == 0) attached to the connection. */
850static void fcgi_wake_unassigned_streams(struct fcgi_conn *fconn)
851{
852 struct eb32_node *node;
853 struct fcgi_strm *fstrm;
854
855 node = eb32_lookup(&fconn->streams_by_id, 0);
856 while (node) {
857 fstrm = container_of(node, struct fcgi_strm, by_id);
858 if (fstrm->id > 0)
859 break;
860 node = eb32_next(node);
861 fcgi_strm_wake_one_stream(fstrm);
862 }
863}
864
865/* Wakes the streams attached to the connection, whose id is greater than <last>
866 * or unassigned.
867 */
868static void fcgi_wake_some_streams(struct fcgi_conn *fconn, int last)
869{
870 struct eb32_node *node;
871 struct fcgi_strm *fstrm;
872
873 /* Wake all streams with ID > last */
874 node = eb32_lookup_ge(&fconn->streams_by_id, last + 1);
875 while (node) {
876 fstrm = container_of(node, struct fcgi_strm, by_id);
877 node = eb32_next(node);
878 fcgi_strm_wake_one_stream(fstrm);
879 }
880 fcgi_wake_unassigned_streams(fconn);
881}
882
883static int fcgi_set_default_param(struct fcgi_conn *fconn, struct fcgi_strm *fstrm,
884 struct htx *htx, struct htx_sl *sl,
885 struct fcgi_strm_params *params)
886{
887 struct connection *cli_conn = objt_conn(fstrm->sess->origin);
888 struct ist p;
889
890 if (!sl)
891 goto error;
892
893 if (!(params->mask & FCGI_SP_DOC_ROOT))
894 params->docroot = fconn->app->docroot;
895
896 if (!(params->mask & FCGI_SP_REQ_METH)) {
897 p = htx_sl_req_meth(sl);
898 params->meth = ist2(b_tail(params->p), p.len);
899 chunk_memcat(params->p, p.ptr, p.len);
900 }
901 if (!(params->mask & FCGI_SP_REQ_URI)) {
902 p = htx_sl_req_uri(sl);
903 params->uri = ist2(b_tail(params->p), p.len);
904 chunk_memcat(params->p, p.ptr, p.len);
905 }
906 if (!(params->mask & FCGI_SP_SRV_PROTO)) {
907 p = htx_sl_req_vsn(sl);
908 params->vsn = ist2(b_tail(params->p), p.len);
909 chunk_memcat(params->p, p.ptr, p.len);
910 }
911 if (!(params->mask & FCGI_SP_SRV_PORT)) {
912 char *end;
913 int port = 0;
914 if (conn_get_dst(cli_conn))
915 port = get_host_port(cli_conn->dst);
916 end = ultoa_o(port, b_tail(params->p), b_room(params->p));
917 if (!end)
918 goto error;
919 params->srv_port = ist2(b_tail(params->p), end - b_tail(params->p));
920 params->p->data += params->srv_port.len;
921 }
922 if (!(params->mask & FCGI_SP_SRV_NAME)) {
923 /* If no Host header found, use the server address to fill
924 * srv_name */
925 if (!istlen(params->srv_name)) {
926 char *ptr = NULL;
927
928 if (conn_get_dst(cli_conn))
929 if (addr_to_str(cli_conn->dst, b_tail(params->p), b_room(params->p)) != -1)
930 ptr = b_tail(params->p);
931 if (ptr) {
932 params->srv_name = ist2(ptr, strlen(ptr));
933 params->p->data += params->srv_name.len;
934 }
935 }
936 }
937 if (!(params->mask & FCGI_SP_REM_ADDR)) {
938 char *ptr = NULL;
939
940 if (conn_get_src(cli_conn))
941 if (addr_to_str(cli_conn->src, b_tail(params->p), b_room(params->p)) != -1)
942 ptr = b_tail(params->p);
943 if (ptr) {
944 params->rem_addr = ist2(ptr, strlen(ptr));
945 params->p->data += params->rem_addr.len;
946 }
947 }
948 if (!(params->mask & FCGI_SP_REM_PORT)) {
949 char *end;
950 int port = 0;
951 if (conn_get_src(cli_conn))
952 port = get_host_port(cli_conn->src);
953 end = ultoa_o(port, b_tail(params->p), b_room(params->p));
954 if (!end)
955 goto error;
956 params->rem_port = ist2(b_tail(params->p), end - b_tail(params->p));
957 params->p->data += params->rem_port.len;
958 }
959 if (!(params->mask & FCGI_SP_CONT_LEN)) {
960 struct htx_blk *blk;
961 enum htx_blk_type type;
962 char *end;
963 size_t len = 0;
964
965 for (blk = htx_get_head_blk(htx); blk; blk = htx_get_next_blk(htx, blk)) {
966 type = htx_get_blk_type(blk);
967
968 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
969 break;
970 if (type == HTX_BLK_DATA)
971 len += htx_get_blksz(blk);
972 }
973 end = ultoa_o(len, b_tail(params->p), b_room(params->p));
974 if (!end)
975 goto error;
976 params->cont_len = ist2(b_tail(params->p), end - b_tail(params->p));
977 params->p->data += params->cont_len.len;
978 }
Christopher Fauletd66700a2019-09-17 13:46:47 +0200979#ifdef USE_OPENSSL
Christopher Faulet99eff652019-08-11 23:11:30 +0200980 if (!(params->mask & FCGI_SP_HTTPS)) {
981 params->https = ssl_sock_is_ssl(cli_conn);
982 }
Christopher Fauletd66700a2019-09-17 13:46:47 +0200983#endif
Christopher Faulet99eff652019-08-11 23:11:30 +0200984 if ((params->mask & FCGI_SP_URI_MASK) != FCGI_SP_URI_MASK) {
985 /* one of scriptname, pathinfo or query_string is no set */
986 struct ist path = http_get_path(params->uri);
987 int len;
988
989 /* Decode the path. it must first be copied to keep the URI
990 * untouched.
991 */
992 chunk_memcat(params->p, path.ptr, path.len);
993 path.ptr = b_tail(params->p) - path.len;
994 path.ptr[path.len] = '\0';
995 len = url_decode(path.ptr);
996 if (len < 0)
997 goto error;
998 path.len = len;
999
1000 /* No scrit_name set but no valid path ==> error */
1001 if (!(params->mask & FCGI_SP_SCRIPT_NAME) && !istlen(path))
1002 goto error;
1003
1004 /* Find limit between the path and the query-string */
1005 for (len = 0; len < path.len && *(path.ptr + len) != '?'; len++);
1006
1007 /* If there is a query-string, Set it if not already set */
1008 if (!(params->mask & FCGI_SP_REQ_QS) && len < path.len)
1009 params->qs = ist2(path.ptr+len+1, path.len-len-1);
1010
1011 /* If the script_name is set, don't try to deduce the path_info
1012 * too. The opposite is not true.
1013 */
1014 if (params->mask & FCGI_SP_SCRIPT_NAME) {
1015 params->mask |= FCGI_SP_PATH_INFO;
1016 goto end;
1017 }
1018
1019 /* script_name not set, preset it with the path for now */
1020 params->scriptname = ist2(path.ptr, len);
1021
1022 /* If there is no regex to match the pathinfo, just to the last
1023 * part and see if the index must be used.
1024 */
1025 if (!fconn->app->pathinfo_re)
1026 goto check_index;
1027
1028 /* The regex does not match, just to the last part and see if
1029 * the index must be used.
1030 */
1031 if (!regex_exec_match2(fconn->app->pathinfo_re, path.ptr, len, MAX_MATCH, pmatch, 0))
1032 goto check_index;
1033
1034 /* We must have at least 2 captures, otherwise we do nothing and
1035 * jump to the last part. Only first 2 ones will be considered
1036 */
1037 if (pmatch[1].rm_so == -1 || pmatch[1].rm_eo == -1 ||
1038 pmatch[2].rm_so == -1 || pmatch[2].rm_eo == -1)
1039 goto check_index;
1040
1041 /* Finally we can set the script_name and the path_info */
1042 params->scriptname = ist2(path.ptr + pmatch[1].rm_so, pmatch[1].rm_eo - pmatch[1].rm_so);
1043 params->pathinfo = ist2(path.ptr + pmatch[2].rm_so, pmatch[2].rm_eo - pmatch[2].rm_so);
1044
1045 check_index:
1046 len = params->scriptname.len;
1047 /* the script_name if finished by a '/' so we can add the index
1048 * part, if any.
1049 */
1050 if (istlen(fconn->app->index) && params->scriptname.ptr[len-1] == '/') {
1051 struct ist sn = params->scriptname;
1052
1053 params->scriptname = ist2(b_tail(params->p), len+fconn->app->index.len);
1054 chunk_memcat(params->p, sn.ptr, sn.len);
1055 chunk_memcat(params->p, fconn->app->index.ptr, fconn->app->index.len);
1056 }
1057 }
1058
1059 end:
1060 return 1;
1061 error:
1062 return 0;
1063}
1064
1065static int fcgi_encode_default_param(struct fcgi_conn *fconn, struct fcgi_strm *fstrm,
1066 struct fcgi_strm_params *params, struct buffer *outbuf, int flag)
1067{
1068 struct fcgi_param p;
1069
1070 if (params->mask & flag)
1071 return 1;
1072
1073 chunk_reset(&trash);
1074
1075 switch (flag) {
1076 case FCGI_SP_CGI_GATEWAY:
1077 p.n = ist("GATEWAY_INTERFACE");
1078 p.v = ist("CGI/1.1");
1079 goto encode;
1080 case FCGI_SP_DOC_ROOT:
1081 p.n = ist("DOCUMENT_ROOT");
1082 p.v = params->docroot;
1083 goto encode;
1084 case FCGI_SP_SCRIPT_NAME:
1085 p.n = ist("SCRIPT_NAME");
1086 p.v = params->scriptname;
1087 goto encode;
1088 case FCGI_SP_PATH_INFO:
1089 p.n = ist("PATH_INFO");
1090 p.v = params->pathinfo;
1091 goto encode;
1092 case FCGI_SP_REQ_URI:
1093 p.n = ist("REQUEST_URI");
1094 p.v = params->uri;
1095 goto encode;
1096 case FCGI_SP_REQ_METH:
1097 p.n = ist("REQUEST_METHOD");
1098 p.v = params->meth;
1099 goto encode;
1100 case FCGI_SP_REQ_QS:
1101 p.n = ist("QUERY_STRING");
1102 p.v = params->qs;
1103 goto encode;
1104 case FCGI_SP_SRV_NAME:
1105 p.n = ist("SERVER_NAME");
1106 p.v = params->srv_name;
1107 goto encode;
1108 case FCGI_SP_SRV_PORT:
1109 p.n = ist("SERVER_PORT");
1110 p.v = params->srv_port;
1111 goto encode;
1112 case FCGI_SP_SRV_PROTO:
1113 p.n = ist("SERVER_PROTOCOL");
1114 p.v = params->vsn;
1115 goto encode;
1116 case FCGI_SP_REM_ADDR:
1117 p.n = ist("REMOTE_ADDR");
1118 p.v = params->rem_addr;
1119 goto encode;
1120 case FCGI_SP_REM_PORT:
1121 p.n = ist("REMOTE_PORT");
1122 p.v = params->rem_port;
1123 goto encode;
1124 case FCGI_SP_SCRIPT_FILE:
1125 p.n = ist("SCRIPT_FILENAME");
1126 chunk_memcat(&trash, params->docroot.ptr, params->docroot.len);
1127 chunk_memcat(&trash, params->scriptname.ptr, params->scriptname.len);
1128 p.v = ist2(b_head(&trash), b_data(&trash));
1129 goto encode;
1130 case FCGI_SP_PATH_TRANS:
1131 if (!istlen(params->pathinfo))
1132 goto skip;
1133 p.n = ist("PATH_TRANSLATED");
1134 chunk_memcat(&trash, params->docroot.ptr, params->docroot.len);
1135 chunk_memcat(&trash, params->pathinfo.ptr, params->pathinfo.len);
1136 p.v = ist2(b_head(&trash), b_data(&trash));
1137 goto encode;
1138 case FCGI_SP_CONT_LEN:
1139 p.n = ist("CONTENT_LENGTH");
1140 p.v = params->cont_len;
1141 goto encode;
1142 case FCGI_SP_HTTPS:
1143 if (!params->https)
1144 goto skip;
1145 p.n = ist("HTTPS");
1146 p.v = ist("on");
1147 goto encode;
1148 default:
1149 goto skip;
1150 }
1151
1152 encode:
1153 if (!istlen(p.v))
1154 goto skip;
1155 if (!fcgi_encode_param(outbuf, &p))
1156 return 0;
1157 skip:
1158 params->mask |= flag;
1159 return 1;
1160}
1161
1162/* Sends a GET_VALUES record. Returns > 0 on success, 0 if it couldn't do
1163 * anything. It is highly unexpected, but if the record is larger than a buffer
1164 * and cannot be encoded in one time, an error is triggered and the connection is
1165 * closed. GET_VALUES record cannot be split.
1166 */
1167static int fcgi_conn_send_get_values(struct fcgi_conn *fconn)
1168{
1169 struct buffer outbuf;
1170 struct buffer *mbuf;
1171 struct fcgi_param max_reqs = { .n = ist("FCGI_MAX_REQS"), .v = ist("")};
1172 struct fcgi_param mpxs_conns = { .n = ist("FCGI_MPXS_CONNS"), .v = ist("")};
1173 int ret;
1174
1175 mbuf = br_tail(fconn->mbuf);
1176 retry:
1177 if (!fcgi_get_buf(fconn, mbuf)) {
1178 fconn->flags |= FCGI_CF_MUX_MALLOC;
1179 fconn->flags |= FCGI_CF_DEM_MROOM;
1180 return 0;
1181 }
1182
1183 while (1) {
1184 outbuf = b_make(b_tail(mbuf), b_contig_space(mbuf), 0, 0);
1185 if (outbuf.size >= 8 || !b_space_wraps(mbuf))
1186 break;
1187 realign_again:
1188 b_slow_realign(mbuf, trash.area, b_data(mbuf));
1189 }
1190
1191 if (outbuf.size < 8)
1192 goto full;
1193
1194 /* vsn: 1(FCGI_VERSION), type: (9)FCGI_GET_VALUES, id: 0x0000,
1195 * len: 0x0000 (fill later), padding: 0x00, rsv: 0x00 */
1196 memcpy(outbuf.area, "\x01\x09\x00\x00\x00\x00\x00\x00", 8);
1197 outbuf.data = 8;
1198
1199 /* Note: Don't send the param FCGI_MAX_CONNS because its value cannot be
1200 * handled by HAProxy.
1201 */
1202 if (!fcgi_encode_param(&outbuf, &max_reqs) || !fcgi_encode_param(&outbuf, &mpxs_conns))
1203 goto full;
1204
1205 /* update the record's size now */
1206 fcgi_set_record_size(outbuf.area, outbuf.data - 8);
1207 b_add(mbuf, outbuf.data);
1208 ret = 1;
1209
1210 end:
1211 return ret;
1212 full:
1213 /* Too large to be encoded. For GET_VALUES records, it is an error */
1214 if (!b_data(mbuf))
1215 goto fail;
1216
1217 if ((mbuf = br_tail_add(fconn->mbuf)) != NULL)
1218 goto retry;
1219 fconn->flags |= FCGI_CF_MUX_MFULL;
1220 fconn->flags |= FCGI_CF_DEM_MROOM;
1221 ret = 0;
1222 goto end;
1223 fail:
1224 fconn->state = FCGI_CS_CLOSED;
1225 ret = 0;
1226 goto end;
1227}
1228
1229/* Processes a GET_VALUES_RESULT record. Returns > 0 on success, 0 if it
1230 * couldn't do anything. It is highly unexpected, but if the record is larger
1231 * than a buffer and cannot be decoded in one time, an error is triggered and
1232 * the connection is closed. GET_VALUES_RESULT record cannot be split.
1233 */
1234static int fcgi_conn_handle_values_result(struct fcgi_conn *fconn)
1235{
1236 struct buffer inbuf;
1237 struct buffer *dbuf;
1238 size_t offset;
1239
1240 dbuf = &fconn->dbuf;
1241
1242 /* Record too large to be fully decoded */
1243 if (b_size(dbuf) < (fconn->drl + fconn->drp))
1244 goto fail;
1245
1246 /* process full record only */
1247 if (b_data(dbuf) < (fconn->drl + fconn->drp))
1248 return 0;
1249
1250 if (unlikely(b_contig_data(dbuf, b_head_ofs(dbuf)) < fconn->drl)) {
1251 /* Realign the dmux buffer if the record wraps. It is unexpected
1252 * at this stage because it should be the first record received
1253 * from the FCGI application.
1254 */
1255 b_slow_realign(dbuf, trash.area, 0);
1256 }
1257
1258 inbuf = b_make(b_head(dbuf), b_data(dbuf), 0, fconn->drl);
1259
1260 for (offset = 0; offset < b_data(&inbuf); ) {
1261 struct fcgi_param p;
1262 size_t ret;
1263
1264 ret = fcgi_aligned_decode_param(&inbuf, offset, &p);
1265 if (!ret) {
1266 /* name or value too large to be decoded at once */
1267 goto fail;
1268 }
1269 offset += ret;
1270
1271 if (isteqi(p.n, ist("FCGI_MPXS_CONNS"))) {
1272 if (isteq(p.v, ist("1")))
1273 fconn->flags |= FCGI_CF_MPXS_CONNS;
1274 else
1275 fconn->flags &= ~FCGI_CF_MPXS_CONNS;
1276 }
1277 else if (isteqi(p.n, ist("FCGI_MAX_REQS"))) {
1278 fconn->streams_limit = strl2ui(p.v.ptr, p.v.len);
1279 }
1280 /*
1281 * Ignore all other params
1282 */
1283 }
1284
1285 /* Reset the number of concurrent streams supported if the FCGI
1286 * application does not support connection multiplexing
1287 */
1288 if (!(fconn->flags & FCGI_CF_MPXS_CONNS))
1289 fconn->streams_limit = 1;
1290
1291 /* We must be sure to have read exactly the announced record length, no
1292 * more no less
1293 */
1294 if (offset != fconn->drl)
1295 goto fail;
1296
1297 b_del(&fconn->dbuf, fconn->drl + fconn->drp);
1298 fconn->drl = 0;
1299 fconn->drp = 0;
1300 fconn->state = FCGI_CS_RECORD_H;
1301 fcgi_wake_unassigned_streams(fconn);
1302 return 1;
1303 fail:
1304 fconn->state = FCGI_CS_CLOSED;
1305 return 0;
1306}
1307
1308/* Sends an ABORT_REQUEST record for each active streams. Closed streams are
1309 * excluded, as the streams which already received the end-of-stream. It returns
1310 * > 0 if the record was sent tp all streams. Otherwise it returns 0.
1311 */
1312static int fcgi_conn_send_aborts(struct fcgi_conn *fconn)
1313{
1314 struct eb32_node *node;
1315 struct fcgi_strm *fstrm;
1316
1317 node = eb32_lookup_ge(&fconn->streams_by_id, 1);
1318 while (node) {
1319 fstrm = container_of(node, struct fcgi_strm, by_id);
1320 node = eb32_next(node);
1321 if (fstrm->state != FCGI_SS_CLOSED &&
1322 !(fstrm->flags & (FCGI_SF_ES_RCVD|FCGI_SF_ABRT_SENT)) &&
1323 !fcgi_strm_send_abort(fconn, fstrm))
1324 return 0;
1325 }
1326 fconn->flags |= FCGI_CF_ABRTS_SENT;
1327 return 1;
1328}
1329
1330/* Sends a BEGIN_REQUEST record. It returns > 0 on success, 0 if it couldn't do
1331 * anything. BEGIN_REQUEST record cannot be split. So we wait to have enough
1332 * space to proceed. It is small enough to be encoded in an empty buffer.
1333 */
1334static int fcgi_strm_send_begin_request(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1335{
1336 struct buffer outbuf;
1337 struct buffer *mbuf;
1338 struct fcgi_begin_request rec = { .role = FCGI_RESPONDER, .flags = 0};
1339 int ret;
1340
1341 mbuf = br_tail(fconn->mbuf);
1342 retry:
1343 if (!fcgi_get_buf(fconn, mbuf)) {
1344 fconn->flags |= FCGI_CF_MUX_MALLOC;
1345 fconn->flags |= FCGI_CF_DEM_MROOM;
1346 return 0;
1347 }
1348
1349 while (1) {
1350 outbuf = b_make(b_tail(mbuf), b_contig_space(mbuf), 0, 0);
1351 if (outbuf.size >= 8 || !b_space_wraps(mbuf))
1352 break;
1353 realign_again:
1354 b_slow_realign(mbuf, trash.area, b_data(mbuf));
1355 }
1356
1357 if (outbuf.size < 8)
1358 goto full;
1359
1360 /* vsn: 1(FCGI_VERSION), type: (1)FCGI_BEGIN_REQUEST, id: fstrm->id,
1361 * len: 0x0008, padding: 0x00, rsv: 0x00 */
1362 memcpy(outbuf.area, "\x01\x01\x00\x00\x00\x08\x00\x00", 8);
1363 fcgi_set_record_id(outbuf.area, fstrm->id);
1364 outbuf.data = 8;
1365
1366 if (fconn->flags & FCGI_CF_KEEP_CONN)
1367 rec.flags |= FCGI_KEEP_CONN;
1368 if (!fcgi_encode_begin_request(&outbuf, &rec))
1369 goto full;
1370
1371 /* commit the record */
1372 b_add(mbuf, outbuf.data);
1373 fstrm->flags |= FCGI_SF_BEGIN_SENT;
1374 fstrm->state = FCGI_SS_OPEN;
1375
1376 ret = 1;
1377
1378 end:
1379 return ret;
1380 full:
1381 if ((mbuf = br_tail_add(fconn->mbuf)) != NULL)
1382 goto retry;
1383 fconn->flags |= FCGI_CF_MUX_MFULL;
1384 fstrm->flags |= FCGI_SF_BLK_MROOM;
1385 ret = 0;
1386 goto end;
1387}
1388
1389/* Sends an empty record of type <rtype>. It returns > 0 on success, 0 if it
1390 * couldn't do anything. Empty record cannot be split. So we wait to have enough
1391 * space to proceed. It is small enough to be encoded in an empty buffer.
1392 */
1393static int fcgi_strm_send_empty_record(struct fcgi_conn *fconn, struct fcgi_strm *fstrm,
1394 enum fcgi_record_type rtype)
1395{
1396 struct buffer outbuf;
1397 struct buffer *mbuf;
1398 int ret;
1399
1400 mbuf = br_tail(fconn->mbuf);
1401 retry:
1402 if (!fcgi_get_buf(fconn, mbuf)) {
1403 fconn->flags |= FCGI_CF_MUX_MALLOC;
1404 fconn->flags |= FCGI_CF_DEM_MROOM;
1405 return 0;
1406 }
1407
1408 while (1) {
1409 outbuf = b_make(b_tail(mbuf), b_contig_space(mbuf), 0, 0);
1410 if (outbuf.size >= 8 || !b_space_wraps(mbuf))
1411 break;
1412 realign_again:
1413 b_slow_realign(mbuf, trash.area, b_data(mbuf));
1414 }
1415
1416 if (outbuf.size < 8)
1417 goto full;
1418
1419 /* vsn: 1(FCGI_VERSION), type: rtype, id: fstrm->id,
1420 * len: 0x0000, padding: 0x00, rsv: 0x00 */
1421 memcpy(outbuf.area, "\x01\x05\x00\x00\x00\x00\x00\x00", 8);
1422 outbuf.area[1] = rtype;
1423 fcgi_set_record_id(outbuf.area, fstrm->id);
1424 outbuf.data = 8;
1425
1426 /* commit the record */
1427 b_add(mbuf, outbuf.data);
1428 ret = 1;
1429
1430 end:
1431 return ret;
1432 full:
1433 if ((mbuf = br_tail_add(fconn->mbuf)) != NULL)
1434 goto retry;
1435 fconn->flags |= FCGI_CF_MUX_MFULL;
1436 fstrm->flags |= FCGI_SF_BLK_MROOM;
1437 ret = 0;
1438 goto end;
1439}
1440
1441
1442/* Sends an empty PARAMS record. It relies on fcgi_strm_send_empty_record(). It
1443 * marks the end of params.
1444 */
1445static int fcgi_strm_send_empty_params(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1446{
1447 return fcgi_strm_send_empty_record(fconn, fstrm, FCGI_PARAMS);
1448}
1449
1450/* Sends an empty STDIN record. It relies on fcgi_strm_send_empty_record(). It
1451 * marks the end of input. On success, all the request was successfully sent.
1452 */
1453static int fcgi_strm_send_empty_stdin(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1454{
1455 int ret;
1456
1457 ret = fcgi_strm_send_empty_record(fconn, fstrm, FCGI_STDIN);
1458 if (ret)
1459 fstrm->flags |= FCGI_SF_ES_SENT;
1460 return ret;
1461}
1462
1463/* Sends an ABORT_REQUEST record. It relies on fcgi_strm_send_empty_record(). It
1464 * stops the request processing.
1465 */
1466static int fcgi_strm_send_abort(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1467{
1468 int ret;
1469
1470 ret = fcgi_strm_send_empty_record(fconn, fstrm, FCGI_ABORT_REQUEST);
1471 if (ret)
1472 fstrm->flags |= FCGI_SF_ABRT_SENT;
1473 return ret;
1474}
1475
1476/* Sends a PARAMS record. Returns > 0 on success, 0 if it couldn't do
1477 * anything. If there are too much K/V params to be encoded in a PARAMS record,
1478 * several records are sent. However, a K/V param cannot be split between 2
1479 * records.
1480 */
1481static size_t fcgi_strm_send_params(struct fcgi_conn *fconn, struct fcgi_strm *fstrm,
1482 struct htx *htx)
1483{
1484 struct buffer outbuf;
1485 struct buffer *mbuf;
1486 struct htx_blk *blk;
1487 struct htx_sl *sl = NULL;
1488 struct fcgi_strm_params params;
1489 size_t total = 0;
1490
1491 memset(&params, 0, sizeof(params));
1492 params.p = get_trash_chunk();
1493
1494 mbuf = br_tail(fconn->mbuf);
1495 retry:
1496 if (!fcgi_get_buf(fconn, mbuf)) {
1497 fconn->flags |= FCGI_CF_MUX_MALLOC;
1498 fconn->flags |= FCGI_CF_DEM_MROOM;
1499 return 0;
1500 }
1501
1502 while (1) {
1503 outbuf = b_make(b_tail(mbuf), b_contig_space(mbuf), 0, 0);
1504 if (outbuf.size >= 8 || !b_space_wraps(mbuf))
1505 break;
1506 realign_again:
1507 b_slow_realign(mbuf, trash.area, b_data(mbuf));
1508 }
1509
1510 if (outbuf.size < 8)
1511 goto full;
1512
1513 /* vsn: 1(FCGI_VERSION), type: (4)FCGI_PARAMS, id: fstrm->id,
1514 * len: 0x0000 (fill later), padding: 0x00, rsv: 0x00 */
1515 memcpy(outbuf.area, "\x01\x04\x00\x00\x00\x00\x00\x00", 8);
1516 fcgi_set_record_id(outbuf.area, fstrm->id);
1517 outbuf.data = 8;
1518
1519 blk = htx_get_head_blk(htx);
1520 while (blk) {
1521 enum htx_blk_type type;
1522 uint32_t size = htx_get_blksz(blk);
1523 struct fcgi_param p;
1524
1525 type = htx_get_blk_type(blk);
1526 switch (type) {
1527 case HTX_BLK_REQ_SL:
1528 sl = htx_get_blk_ptr(htx, blk);
1529 if (sl->info.req.meth == HTTP_METH_HEAD)
1530 fstrm->h1m.flags |= H1_MF_METH_HEAD;
1531 if (sl->flags & HTX_SL_F_VER_11)
1532 fstrm->h1m.flags |= H1_MF_VER_11;
1533 break;
1534
1535 case HTX_BLK_HDR:
1536 p.n = htx_get_blk_name(htx, blk);
1537 p.v = htx_get_blk_value(htx, blk);
1538
1539 if (istmatch(p.n, ist(":fcgi-"))) {
1540 p.n.ptr += 6;
1541 p.n.len -= 6;
1542 if (isteq(p.n, ist("gateway_interface")))
1543 params.mask |= FCGI_SP_CGI_GATEWAY;
1544 else if (isteq(p.n, ist("document_root"))) {
1545 params.mask |= FCGI_SP_DOC_ROOT;
1546 params.docroot = p.v;
1547 }
1548 else if (isteq(p.n, ist("script_name"))) {
1549 params.mask |= FCGI_SP_SCRIPT_NAME;
1550 params.scriptname = p.v;
1551 }
1552 else if (isteq(p.n, ist("path_info"))) {
1553 params.mask |= FCGI_SP_PATH_INFO;
1554 params.pathinfo = p.v;
1555 }
1556 else if (isteq(p.n, ist("request_uri"))) {
1557 params.mask |= FCGI_SP_REQ_URI;
1558 params.uri = p.v;
1559 }
1560 else if (isteq(p.n, ist("request_meth")))
1561 params.mask |= FCGI_SP_REQ_METH;
1562 else if (isteq(p.n, ist("query_string")))
1563 params.mask |= FCGI_SP_REQ_QS;
1564 else if (isteq(p.n, ist("server_name")))
1565 params.mask |= FCGI_SP_SRV_NAME;
1566 else if (isteq(p.n, ist("server_port")))
1567 params.mask |= FCGI_SP_SRV_PORT;
1568 else if (isteq(p.n, ist("server_protocol")))
1569 params.mask |= FCGI_SP_SRV_PROTO;
1570 else if (isteq(p.n, ist("remote_addr")))
1571 params.mask |= FCGI_SP_REM_ADDR;
1572 else if (isteq(p.n, ist("remote_port")))
1573 params.mask |= FCGI_SP_REM_PORT;
1574 else if (isteq(p.n, ist("script_filename")))
1575 params.mask |= FCGI_SP_SCRIPT_FILE;
1576 else if (isteq(p.n, ist("path_translated")))
1577 params.mask |= FCGI_SP_PATH_TRANS;
1578 else if (isteq(p.n, ist("https")))
1579 params.mask |= FCGI_SP_HTTPS;
1580 }
1581 else if (isteq(p.n, ist("content-length"))) {
1582 p.n = ist("CONTENT_LENGTH");
1583 params.mask |= FCGI_SP_CONT_LEN;
1584 }
1585 else if (isteq(p.n, ist("content-type")))
1586 p.n = ist("CONTENT_TYPE");
1587 else {
1588 if (isteq(p.n, ist("host")))
1589 params.srv_name = p.v;
1590
Christopher Faulet67d58092019-10-02 10:51:38 +02001591 /* Skip header if same name is used to add the server name */
1592 if (fconn->proxy->server_id_hdr_name &&
1593 isteq(p.n, ist2(fconn->proxy->server_id_hdr_name, fconn->proxy->server_id_hdr_len)))
1594 break;
1595
Christopher Faulet99eff652019-08-11 23:11:30 +02001596 memcpy(trash.area, "http_", 5);
1597 memcpy(trash.area+5, p.n.ptr, p.n.len);
1598 p.n = ist2(trash.area, p.n.len+5);
1599 }
1600
1601 if (!fcgi_encode_param(&outbuf, &p)) {
1602 if (b_space_wraps(mbuf))
1603 goto realign_again;
1604 if (outbuf.data == 8)
1605 goto full;
1606 goto done;
1607 }
1608 break;
1609
1610 case HTX_BLK_EOH:
Christopher Faulet72ba6cd2019-09-24 16:20:05 +02001611 if (fconn->proxy->server_id_hdr_name) {
1612 struct server *srv = objt_server(fconn->conn->target);
1613
1614 if (!srv)
1615 goto done;
1616
1617 memcpy(trash.area, "http_", 5);
1618 memcpy(trash.area+5, fconn->proxy->server_id_hdr_name, fconn->proxy->server_id_hdr_len);
1619 p.n = ist2(trash.area, fconn->proxy->server_id_hdr_len+5);
1620 p.v = ist(srv->id);
1621
1622 if (!fcgi_encode_param(&outbuf, &p)) {
1623 if (b_space_wraps(mbuf))
1624 goto realign_again;
1625 if (outbuf.data == 8)
1626 goto full;
1627 }
1628 }
Christopher Faulet99eff652019-08-11 23:11:30 +02001629 goto done;
1630
1631 default:
1632 break;
1633 }
1634 total += size;
1635 blk = htx_remove_blk(htx, blk);
1636 }
1637
1638 done:
1639 if (!fcgi_set_default_param(fconn, fstrm, htx, sl, &params))
1640 goto error;
1641
1642 if (!fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_CGI_GATEWAY) ||
1643 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_DOC_ROOT) ||
1644 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SCRIPT_NAME) ||
1645 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_PATH_INFO) ||
1646 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REQ_URI) ||
1647 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REQ_METH) ||
1648 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REQ_QS) ||
1649 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SRV_NAME) ||
1650 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SRV_PORT) ||
1651 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SRV_PROTO) ||
1652 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REM_ADDR) ||
1653 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REM_PORT) ||
1654 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SCRIPT_FILE) ||
1655 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_PATH_TRANS) ||
1656 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_CONT_LEN) ||
1657 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_HTTPS))
1658 goto error;
1659
1660 /* update the record's size */
1661 fcgi_set_record_size(outbuf.area, outbuf.data - 8);
1662 b_add(mbuf, outbuf.data);
1663
1664 end:
1665 return total;
1666 full:
1667 if ((mbuf = br_tail_add(fconn->mbuf)) != NULL)
1668 goto retry;
1669 fconn->flags |= FCGI_CF_MUX_MFULL;
1670 fstrm->flags |= FCGI_SF_BLK_MROOM;
1671 if (total)
1672 goto error;
1673 goto end;
1674
1675 error:
1676 htx->flags |= HTX_FL_PROCESSING_ERROR;
1677 fcgi_strm_error(fstrm);
1678 goto end;
1679}
1680
1681/* Sends a STDIN record. Returns > 0 on success, 0 if it couldn't do
1682 * anything. STDIN records contain the request body.
1683 */
1684static size_t fcgi_strm_send_stdin(struct fcgi_conn *fconn, struct fcgi_strm *fstrm,
1685 struct htx *htx, size_t count, struct buffer *buf)
1686{
1687 struct buffer outbuf;
1688 struct buffer *mbuf;
1689 struct htx_blk *blk;
1690 enum htx_blk_type type;
1691 uint32_t size;
1692 size_t total = 0;
1693
1694 if (!count)
1695 goto end;
1696
1697 mbuf = br_tail(fconn->mbuf);
1698 retry:
1699 if (!fcgi_get_buf(fconn, mbuf)) {
1700 fconn->flags |= FCGI_CF_MUX_MALLOC;
1701 fconn->flags |= FCGI_CF_DEM_MROOM;
1702 return 0;
1703 }
1704
1705 /* Perform some optimizations to reduce the number of buffer copies.
1706 * First, if the mux's buffer is empty and the htx area contains exactly
1707 * one data block of the same size as the requested count, and this
1708 * count fits within the record size, then it's possible to simply swap
1709 * the caller's buffer with the mux's output buffer and adjust offsets
1710 * and length to match the entire DATA HTX block in the middle. In this
1711 * case we perform a true zero-copy operation from end-to-end. This is
1712 * the situation that happens all the time with large files. Second, if
1713 * this is not possible, but the mux's output buffer is empty, we still
1714 * have an opportunity to avoid the copy to the intermediary buffer, by
1715 * making the intermediary buffer's area point to the output buffer's
1716 * area. In this case we want to skip the HTX header to make sure that
1717 * copies remain aligned and that this operation remains possible all
1718 * the time. This goes for headers, data blocks and any data extracted
1719 * from the HTX blocks.
1720 */
1721 blk = htx_get_head_blk(htx);
1722 if (!blk)
1723 goto end;
1724 type = htx_get_blk_type(blk);
1725 size = htx_get_blksz(blk);
1726 if (unlikely(size == count && htx_nbblks(htx) == 1 && type == HTX_BLK_DATA)) {
1727 void *old_area = mbuf->area;
1728
1729 if (b_data(mbuf)) {
1730 /* Too bad there are data left there. We're willing to memcpy/memmove
1731 * up to 1/4 of the buffer, which means that it's OK to copy a large
1732 * record into a buffer containing few data if it needs to be realigned,
1733 * and that it's also OK to copy few data without realigning. Otherwise
1734 * we'll pretend the mbuf is full and wait for it to become empty.
1735 */
1736 if (size + 8 <= b_room(mbuf) &&
1737 (b_data(mbuf) <= b_size(mbuf) / 4 ||
1738 (size <= b_size(mbuf) / 4 && size + 8 <= b_contig_space(mbuf))))
1739 goto copy;
1740
1741 if ((mbuf = br_tail_add(fconn->mbuf)) != NULL)
1742 goto retry;
1743
1744 fconn->flags |= FCGI_CF_MUX_MFULL;
1745 fstrm->flags |= FCGI_SF_BLK_MROOM;
1746 goto end;
1747 }
1748
1749 /* map a FCGI record to the HTX block so that we can put the
1750 * record header there.
1751 */
1752 *mbuf = b_make(buf->area, buf->size, sizeof(struct htx) + blk->addr - 8, size + 8);
1753 outbuf.area = b_head(mbuf);
1754
1755 /* prepend a FCGI record header just before the DATA block */
1756 memcpy(outbuf.area, "\x01\x05\x00\x00\x00\x00\x00\x00", 8);
1757 fcgi_set_record_id(outbuf.area, fstrm->id);
1758 fcgi_set_record_size(outbuf.area, size);
1759
1760 /* and exchange with our old area */
1761 buf->area = old_area;
1762 buf->data = buf->head = 0;
1763 total += size;
1764 goto end;
1765 }
1766
1767 copy:
1768 while (1) {
1769 outbuf = b_make(b_tail(mbuf), b_contig_space(mbuf), 0, 0);
1770 if (outbuf.size >= 8 || !b_space_wraps(mbuf))
1771 break;
1772 realign_again:
1773 b_slow_realign(mbuf, trash.area, b_data(mbuf));
1774 }
1775
1776 if (outbuf.size < 8)
1777 goto full;
1778
1779 /* vsn: 1(FCGI_VERSION), type: (5)FCGI_STDIN, id: fstrm->id,
1780 * len: 0x0000 (fill later), padding: 0x00, rsv: 0x00 */
1781 memcpy(outbuf.area, "\x01\x05\x00\x00\x00\x00\x00\x00", 8);
1782 fcgi_set_record_id(outbuf.area, fstrm->id);
1783 outbuf.data = 8;
1784
1785 blk = htx_get_head_blk(htx);
1786 while (blk && count) {
1787 enum htx_blk_type type = htx_get_blk_type(blk);
1788 uint32_t size = htx_get_blksz(blk);
1789 struct ist v;
1790
1791 switch (type) {
1792 case HTX_BLK_DATA:
1793 v = htx_get_blk_value(htx, blk);
1794 if (v.len > count)
1795 v.len = count;
1796
1797 if (v.len > b_room(&outbuf)) {
1798 /* It doesn't fit at once. If it at least fits once split and
1799 * the amount of data to move is low, let's defragment the
1800 * buffer now.
1801 */
1802 if (b_space_wraps(mbuf) &&
1803 b_data(&outbuf) + v.len <= b_room(mbuf) &&
1804 b_data(mbuf) <= MAX_DATA_REALIGN)
1805 goto realign_again;
1806 v.len = b_room(&outbuf);
1807 }
1808 if (!v.len || !chunk_memcat(&outbuf, v.ptr, v.len)) {
1809 if (outbuf.data == 8)
1810 goto full;
1811 goto done;
1812 }
1813 if (v.len != size) {
1814 total += v.len;
1815 count -= v.len;
1816 htx_cut_data_blk(htx, blk, v.len);
1817 goto done;
1818 }
1819 break;
1820
1821 case HTX_BLK_EOM:
1822 goto done;
1823
1824 default:
1825 break;
1826 }
1827 total += size;
1828 count -= size;
1829 blk = htx_remove_blk(htx, blk);
1830 }
1831
1832 done:
1833 /* update the record's size */
1834 fcgi_set_record_size(outbuf.area, outbuf.data - 8);
1835 b_add(mbuf, outbuf.data);
1836
1837 end:
1838 return total;
1839 full:
1840 if ((mbuf = br_tail_add(fconn->mbuf)) != NULL)
1841 goto retry;
1842 fconn->flags |= FCGI_CF_MUX_MFULL;
1843 fstrm->flags |= FCGI_SF_BLK_MROOM;
1844 goto end;
1845}
1846
1847/* Processes a STDOUT record. Returns > 0 on success, 0 if it couldn't do
1848 * anything. STDOUT records contain the entire response. All the content is
1849 * copied in the stream's rxbuf. The parsing will be handled in fcgi_rcv_buf().
1850 */
1851static int fcgi_strm_handle_stdout(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1852{
1853 struct buffer *dbuf;
1854 size_t ret;
1855 size_t max;
1856
1857 dbuf = &fconn->dbuf;
1858
1859 /* Only padding remains */
1860 if (fconn->state == FCGI_CS_RECORD_P)
1861 goto end_transfer;
1862
1863 if (b_data(dbuf) < (fconn->drl + fconn->drp) &&
1864 b_size(dbuf) > (fconn->drl + fconn->drp) &&
1865 buf_room_for_htx_data(dbuf))
1866 goto fail; // incomplete record
1867
1868 if (!fcgi_get_buf(fconn, &fstrm->rxbuf)) {
1869 fconn->flags |= FCGI_CF_DEM_SALLOC;
1870 return 0;
1871 }
1872
1873 /*max = MIN(b_room(&fstrm->rxbuf), fconn->drl);*/
1874 max = buf_room_for_htx_data(&fstrm->rxbuf);
1875 if (!b_data(&fstrm->rxbuf))
1876 fstrm->rxbuf.head = sizeof(struct htx);
1877 if (max > fconn->drl)
1878 max = fconn->drl;
1879
1880 ret = b_xfer(&fstrm->rxbuf, dbuf, max);
1881 if (!ret)
1882 goto fail;
1883 fconn->drl -= ret;
1884
1885 if (!buf_room_for_htx_data(&fstrm->rxbuf))
1886 fconn->flags |= FCGI_CF_DEM_SFULL;
1887
1888 if (fconn->drl)
1889 goto fail;
1890
1891 end_transfer:
1892 fconn->drl += fconn->drp;
1893 fconn->drp = 0;
1894 ret = MIN(b_data(&fconn->dbuf), fconn->drl);
1895 b_del(&fconn->dbuf, ret);
1896 fconn->drl -= ret;
1897 if (fconn->drl)
1898 goto fail;
1899
1900 fconn->state = FCGI_CS_RECORD_H;
1901 return 1;
1902 fail:
1903 return 0;
1904}
1905
1906
1907/* Processes an empty STDOUT. Returns > 0 on success, 0 if it couldn't do
1908 * anything. It only skip the padding in fact, there is no payload for such
1909 * records. It makrs the end of the response.
1910 */
1911static int fcgi_strm_handle_empty_stdout(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1912{
1913 int ret;
1914
1915 fconn->state = FCGI_CS_RECORD_P;
1916 fconn->drl += fconn->drp;
1917 fconn->drp = 0;
1918 ret = MIN(b_data(&fconn->dbuf), fconn->drl);
1919 b_del(&fconn->dbuf, ret);
1920 fconn->drl -= ret;
1921 if (fconn->drl)
1922 return 0;
1923 fconn->state = FCGI_CS_RECORD_H;
1924 fstrm->state |= FCGI_SF_ES_RCVD;
1925 return 1;
1926}
1927
1928/* Processes a STDERR record. Returns > 0 on success, 0 if it couldn't do
1929 * anything.
1930 */
1931static int fcgi_strm_handle_stderr(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1932{
1933 struct buffer *dbuf;
1934 struct buffer tag;
1935 size_t ret;
1936
1937 dbuf = &fconn->dbuf;
1938
1939 /* Only padding remains */
1940 if (fconn->state == FCGI_CS_RECORD_P)
1941 goto end_transfer;
1942
1943 if (b_data(dbuf) < (fconn->drl + fconn->drp) &&
1944 b_size(dbuf) > (fconn->drl + fconn->drp) &&
1945 buf_room_for_htx_data(dbuf))
1946 goto fail; // incomplete record
1947
1948 chunk_reset(&trash);
1949 ret = b_xfer(&trash, dbuf, MIN(b_room(&trash), fconn->drl));
1950 if (!ret)
1951 goto fail;
1952 fconn->drl -= ret;
1953
1954 trash.area[ret] = '\n';
1955 trash.area[ret+1] = '\0';
1956 tag.area = fconn->app->name; tag.data = strlen(fconn->app->name);
Christopher Fauletc45791a2019-09-24 14:30:46 +02001957 app_log(&fconn->app->logsrvs, &tag, LOG_ERR, "%s", trash.area);
Christopher Faulet99eff652019-08-11 23:11:30 +02001958
1959 if (fconn->drl)
1960 goto fail;
1961
1962 end_transfer:
1963 fconn->drl += fconn->drp;
1964 fconn->drp = 0;
1965 ret = MIN(b_data(&fconn->dbuf), fconn->drl);
1966 b_del(&fconn->dbuf, ret);
1967 fconn->drl -= ret;
1968 if (fconn->drl)
1969 goto fail;
1970 fconn->state = FCGI_CS_RECORD_H;
1971 return 1;
1972 fail:
1973 return 0;
1974}
1975
1976/* Processes an END_REQUEST record. Returns > 0 on success, 0 if it couldn't do
1977 * anything. If the empty STDOUT record is not already received, this one marks
1978 * the end of the response. It is highly unexpected, but if the record is larger
1979 * than a buffer and cannot be decoded in one time, an error is triggered and
1980 * the connection is closed. END_REQUEST record cannot be split.
1981 */
1982static int fcgi_strm_handle_end_request(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1983{
1984 struct buffer inbuf;
1985 struct buffer *dbuf;
1986 struct fcgi_end_request endreq;
1987
1988 dbuf = &fconn->dbuf;
1989
1990 /* Record too large to be fully decoded */
1991 if (b_size(dbuf) < (fconn->drl + fconn->drp))
1992 goto fail;
1993
1994 /* process full record only */
1995 if (b_data(dbuf) < (fconn->drl + fconn->drp))
1996 return 0;
1997
1998 if (unlikely(b_contig_data(dbuf, b_head_ofs(dbuf)) < fconn->drl)) {
1999 /* Realign the dmux buffer if the record wraps. It is unexpected
2000 * at this stage because it should be the first record received
2001 * from the FCGI application.
2002 */
2003 b_slow_realign(dbuf, trash.area, 0);
2004 }
2005
2006 inbuf = b_make(b_head(dbuf), b_data(dbuf), 0, fconn->drl);
2007
2008 if (!fcgi_decode_end_request(&inbuf, 0, &endreq))
2009 goto fail;
2010
2011 fstrm->flags |= FCGI_SF_ES_RCVD;
2012 fstrm->proto_status = endreq.errcode;
2013 fcgi_strm_close(fstrm);
2014
2015 b_del(&fconn->dbuf, fconn->drl + fconn->drp);
2016 fconn->drl = 0;
2017 fconn->drp = 0;
2018 fconn->state = FCGI_CS_RECORD_H;
2019 return 1;
2020
2021 fail:
2022 fcgi_strm_error(fstrm);
2023 return 0;
2024}
2025
2026/* process Rx records to be demultiplexed */
2027static void fcgi_process_demux(struct fcgi_conn *fconn)
2028{
2029 struct fcgi_strm *fstrm = NULL, *tmp_fstrm;
2030 struct fcgi_header hdr;
2031 int ret;
2032
2033 if (fconn->state == FCGI_CS_CLOSED)
2034 return;
2035
2036 if (unlikely(fconn->state < FCGI_CS_RECORD_H)) {
2037 if (fconn->state == FCGI_CS_INIT)
2038 return;
2039 if (fconn->state == FCGI_CS_SETTINGS) {
2040 /* ensure that what is pending is a valid GET_VALUES_RESULT record. */
2041 ret = fcgi_decode_record_hdr(&fconn->dbuf, 0, &hdr);
2042 if (!ret)
2043 goto fail;
2044 b_del(&fconn->dbuf, ret);
2045
2046 if (hdr.id || (hdr.type != FCGI_GET_VALUES_RESULT && hdr.type != FCGI_UNKNOWN_TYPE)) {
2047 fconn->state = FCGI_CS_CLOSED;
2048 goto fail;
2049 }
2050 goto new_record;
2051 }
2052 }
2053
2054 /* process as many incoming frames as possible below */
2055 while (b_data(&fconn->dbuf)) {
2056
2057 if (fconn->state == FCGI_CS_CLOSED)
2058 break;
2059
2060 if (fconn->state == FCGI_CS_RECORD_H) {
2061 ret = fcgi_decode_record_hdr(&fconn->dbuf, 0, &hdr);
2062 if (!ret)
2063 break;
2064 b_del(&fconn->dbuf, ret);
2065
2066 new_record:
2067 fconn->dsi = hdr.id;
2068 fconn->drt = hdr.type;
2069 fconn->drl = hdr.len;
2070 fconn->drp = hdr.padding;
2071 fconn->state = FCGI_CS_RECORD_D;
2072 }
2073
2074 /* Only FCGI_CS_RECORD_D or FCGI_CS_RECORD_P */
2075 tmp_fstrm = fcgi_conn_st_by_id(fconn, fconn->dsi);
2076
2077 if (tmp_fstrm != fstrm && fstrm && fstrm->cs &&
2078 (b_data(&fstrm->rxbuf) ||
2079 conn_xprt_read0_pending(fconn->conn) ||
2080 fstrm->state == FCGI_SS_CLOSED ||
2081 (fstrm->flags & FCGI_SF_ES_RCVD) ||
2082 (fstrm->cs->flags & (CS_FL_ERROR|CS_FL_ERR_PENDING|CS_FL_EOS)))) {
2083 /* we may have to signal the upper layers */
2084 fstrm->cs->flags |= CS_FL_RCV_MORE;
2085 fcgi_strm_notify_recv(fstrm);
2086 }
2087 fstrm = tmp_fstrm;
2088
2089 if (fstrm->state == FCGI_SS_CLOSED && fconn->dsi != 0) {
2090 /* ignore all record for closed streams */
2091 goto ignore_record;
2092 }
2093 if (fstrm->state == FCGI_SS_IDLE) {
2094 /* ignore all record for unknown streams */
2095 goto ignore_record;
2096 }
2097
2098 switch (fconn->drt) {
2099 case FCGI_GET_VALUES_RESULT:
2100 ret = fcgi_conn_handle_values_result(fconn);
2101 break;
2102
2103 case FCGI_STDOUT:
2104 if (fstrm->flags & FCGI_SF_ES_RCVD)
2105 goto ignore_record;
2106
2107 if (fconn->drl)
2108 ret = fcgi_strm_handle_stdout(fconn, fstrm);
2109 else
2110 ret = fcgi_strm_handle_empty_stdout(fconn, fstrm);
2111 break;
2112
2113 case FCGI_STDERR:
2114 ret = fcgi_strm_handle_stderr(fconn, fstrm);
2115 break;
2116
2117 case FCGI_END_REQUEST:
2118 ret = fcgi_strm_handle_end_request(fconn, fstrm);
2119 break;
2120
2121 /* implement all extra frame types here */
2122 default:
2123 ignore_record:
2124 /* drop records that we ignore. They may be
2125 * larger than the buffer so we drain all of
2126 * their contents until we reach the end.
2127 */
2128 fconn->state = FCGI_CS_RECORD_P;
2129 fconn->drl += fconn->drp;
2130 fconn->drp = 0;
2131 ret = MIN(b_data(&fconn->dbuf), fconn->drl);
2132 b_del(&fconn->dbuf, ret);
2133 fconn->drl -= ret;
2134 ret = (fconn->drl == 0);
2135 }
2136
2137 /* error or missing data condition met above ? */
2138 if (ret <= 0)
2139 break;
2140
2141 if (fconn->state != FCGI_CS_RECORD_H && !(fconn->drl+fconn->drp))
2142 fconn->state = FCGI_CS_RECORD_H;
2143 }
2144
2145 fail:
2146 /* we can go here on missing data, blocked response or error */
2147 if (fstrm && fstrm->cs &&
2148 (b_data(&fstrm->rxbuf) ||
2149 conn_xprt_read0_pending(fconn->conn) ||
2150 fstrm->state == FCGI_SS_CLOSED ||
2151 (fstrm->flags & FCGI_SF_ES_RCVD) ||
2152 (fstrm->cs->flags & (CS_FL_ERROR|CS_FL_ERR_PENDING|CS_FL_EOS)))) {
2153 /* we may have to signal the upper layers */
2154 fstrm->cs->flags |= CS_FL_RCV_MORE;
2155 fcgi_strm_notify_recv(fstrm);
2156 }
2157
2158 fcgi_conn_restart_reading(fconn, 0);
2159}
2160
2161/* process Tx records from streams to be multiplexed. Returns > 0 if it reached
2162 * the end.
2163 */
2164static int fcgi_process_mux(struct fcgi_conn *fconn)
2165{
2166 struct fcgi_strm *fstrm, *fstrm_back;
2167
2168 if (unlikely(fconn->state < FCGI_CS_RECORD_H)) {
2169 if (unlikely(fconn->state == FCGI_CS_INIT)) {
2170 if (!(fconn->flags & FCGI_CF_GET_VALUES)) {
2171 fconn->state = FCGI_CS_RECORD_H;
2172 fcgi_wake_unassigned_streams(fconn);
2173 goto mux;
2174 }
2175 if (unlikely(!fcgi_conn_send_get_values(fconn)))
2176 goto fail;
2177 fconn->state = FCGI_CS_SETTINGS;
2178 }
2179 /* need to wait for the other side */
2180 if (fconn->state < FCGI_CS_RECORD_H)
2181 return 1;
2182 }
2183
2184 mux:
2185 list_for_each_entry_safe(fstrm, fstrm_back, &fconn->send_list, send_list) {
2186 if (fconn->state == FCGI_CS_CLOSED || fconn->flags & FCGI_CF_MUX_BLOCK_ANY)
2187 break;
2188
2189 if (LIST_ADDED(&fstrm->sending_list))
2190 continue;
2191
2192 /* For some reason, the upper layer failed to subsribe again,
2193 * so remove it from the send_list
2194 */
2195 if (!fstrm->send_wait) {
2196 LIST_DEL_INIT(&fstrm->send_list);
2197 continue;
2198 }
2199 fstrm->flags &= ~FCGI_SF_BLK_ANY;
2200 fstrm->send_wait->events &= ~SUB_RETRY_SEND;
2201 LIST_ADDQ(&fconn->sending_list, &fstrm->sending_list);
2202 tasklet_wakeup(fstrm->send_wait->tasklet);
2203 }
2204
2205 fail:
2206 if (fconn->state == FCGI_CS_CLOSED) {
2207 if (fconn->stream_cnt - fconn->nb_reserved > 0) {
2208 fcgi_conn_send_aborts(fconn);
2209 if (fconn->flags & FCGI_CF_MUX_BLOCK_ANY)
2210 return 0;
2211 }
2212 }
2213 return 1;
2214}
2215
2216
2217/* Attempt to read data, and subscribe if none available.
2218 * The function returns 1 if data has been received, otherwise zero.
2219 */
2220static int fcgi_recv(struct fcgi_conn *fconn)
2221{
2222 struct connection *conn = fconn->conn;
2223 struct buffer *buf;
2224 int max;
2225 size_t ret;
2226
2227 if (fconn->wait_event.events & SUB_RETRY_RECV)
2228 return (b_data(&fconn->dbuf));
2229
2230 if (!fcgi_recv_allowed(fconn))
2231 return 1;
2232
2233 buf = fcgi_get_buf(fconn, &fconn->dbuf);
2234 if (!buf) {
2235 fconn->flags |= FCGI_CF_DEM_DALLOC;
2236 return 0;
2237 }
2238
2239 b_realign_if_empty(buf);
2240 if (!b_data(buf)) {
2241 /* try to pre-align the buffer like the
2242 * rxbufs will be to optimize memory copies. We'll make
2243 * sure that the frame header lands at the end of the
2244 * HTX block to alias it upon recv. We cannot use the
2245 * head because rcv_buf() will realign the buffer if
2246 * it's empty. Thus we cheat and pretend we already
2247 * have a few bytes there.
2248 */
2249 max = buf_room_for_htx_data(buf) + (fconn->state == FCGI_CS_RECORD_H ? 8 : 0);
2250 buf->head = sizeof(struct htx) - (fconn->state == FCGI_CS_RECORD_H ? 8 : 0);
2251 }
2252 else
2253 max = buf_room_for_htx_data(buf);
2254
2255 ret = max ? conn->xprt->rcv_buf(conn, conn->xprt_ctx, buf, max, 0) : 0;
2256
2257 if (max && !ret && fcgi_recv_allowed(fconn))
2258 conn->xprt->subscribe(conn, conn->xprt_ctx, SUB_RETRY_RECV, &fconn->wait_event);
2259
2260 if (!b_data(buf)) {
2261 fcgi_release_buf(fconn, &fconn->dbuf);
2262 return (conn->flags & CO_FL_ERROR || conn_xprt_read0_pending(conn));
2263 }
2264
2265 if (ret == max)
2266 fconn->flags |= FCGI_CF_DEM_DFULL;
2267
2268 return !!ret || (conn->flags & CO_FL_ERROR) || conn_xprt_read0_pending(conn);
2269}
2270
2271
2272/* Try to send data if possible.
2273 * The function returns 1 if data have been sent, otherwise zero.
2274 */
2275static int fcgi_send(struct fcgi_conn *fconn)
2276{
2277 struct connection *conn = fconn->conn;
2278 int done;
2279 int sent = 0;
2280
2281 if (conn->flags & CO_FL_ERROR)
2282 return 1;
2283
2284
2285 if (conn->flags & (CO_FL_HANDSHAKE|CO_FL_WAIT_L4_CONN|CO_FL_WAIT_L6_CONN)) {
2286 /* a handshake was requested */
2287 goto schedule;
2288 }
2289
2290 /* This loop is quite simple : it tries to fill as much as it can from
2291 * pending streams into the existing buffer until it's reportedly full
2292 * or the end of send requests is reached. Then it tries to send this
2293 * buffer's contents out, marks it not full if at least one byte could
2294 * be sent, and tries again.
2295 *
2296 * The snd_buf() function normally takes a "flags" argument which may
2297 * be made of a combination of CO_SFL_MSG_MORE to indicate that more
2298 * data immediately comes and CO_SFL_STREAMER to indicate that the
2299 * connection is streaming lots of data (used to increase TLS record
2300 * size at the expense of latency). The former can be sent any time
2301 * there's a buffer full flag, as it indicates at least one stream
2302 * attempted to send and failed so there are pending data. An
2303 * alternative would be to set it as long as there's an active stream
2304 * but that would be problematic for ACKs until we have an absolute
2305 * guarantee that all waiters have at least one byte to send. The
2306 * latter should possibly not be set for now.
2307 */
2308
2309 done = 0;
2310 while (!done) {
2311 unsigned int flags = 0;
2312 unsigned int released = 0;
2313 struct buffer *buf;
2314
2315 /* fill as much as we can into the current buffer */
2316 while (((fconn->flags & (FCGI_CF_MUX_MFULL|FCGI_CF_MUX_MALLOC)) == 0) && !done)
2317 done = fcgi_process_mux(fconn);
2318
2319 if (fconn->flags & FCGI_CF_MUX_MALLOC)
2320 done = 1; // we won't go further without extra buffers
2321
2322 if (conn->flags & CO_FL_ERROR)
2323 break;
2324
2325 if (fconn->flags & (FCGI_CF_MUX_MFULL | FCGI_CF_DEM_MROOM))
2326 flags |= CO_SFL_MSG_MORE;
2327
2328 for (buf = br_head(fconn->mbuf); b_size(buf); buf = br_del_head(fconn->mbuf)) {
2329 if (b_data(buf)) {
2330 int ret;
2331
2332 ret = conn->xprt->snd_buf(conn, conn->xprt_ctx, buf, b_data(buf), flags);
2333 if (!ret) {
2334 done = 1;
2335 break;
2336 }
2337 sent = 1;
2338 b_del(buf, ret);
2339 if (b_data(buf)) {
2340 done = 1;
2341 break;
2342 }
2343 }
2344 b_free(buf);
2345 released++;
2346 }
2347
2348 if (released)
2349 offer_buffers(NULL, tasks_run_queue);
2350
2351 /* wrote at least one byte, the buffer is not full anymore */
2352 fconn->flags &= ~(FCGI_CF_MUX_MFULL | FCGI_CF_DEM_MROOM);
2353 }
2354
2355 if (conn->flags & CO_FL_SOCK_WR_SH) {
2356 /* output closed, nothing to send, clear the buffer to release it */
2357 b_reset(br_tail(fconn->mbuf));
2358 }
2359 /* We're not full anymore, so we can wake any task that are waiting
2360 * for us.
2361 */
2362 if (!(fconn->flags & (FCGI_CF_MUX_MFULL | FCGI_CF_DEM_MROOM))) {
2363 struct fcgi_strm *fstrm;
2364
2365 list_for_each_entry(fstrm, &fconn->send_list, send_list) {
2366 if (fconn->state == FCGI_CS_CLOSED || fconn->flags & FCGI_CF_MUX_BLOCK_ANY)
2367 break;
2368
2369 if (LIST_ADDED(&fstrm->sending_list))
2370 continue;
2371
2372 /* For some reason, the upper layer failed to subsribe again,
2373 * so remove it from the send_list
2374 */
2375 if (!fstrm->send_wait) {
2376 LIST_DEL_INIT(&fstrm->send_list);
2377 continue;
2378 }
2379 fstrm->flags &= ~FCGI_SF_BLK_ANY;
2380 fstrm->send_wait->events &= ~SUB_RETRY_SEND;
2381 tasklet_wakeup(fstrm->send_wait->tasklet);
2382 LIST_ADDQ(&fconn->sending_list, &fstrm->sending_list);
2383 }
2384 }
2385 /* We're done, no more to send */
2386 if (!br_data(fconn->mbuf))
2387 return sent;
2388schedule:
2389 if (!(conn->flags & CO_FL_ERROR) && !(fconn->wait_event.events & SUB_RETRY_SEND))
2390 conn->xprt->subscribe(conn, conn->xprt_ctx, SUB_RETRY_SEND, &fconn->wait_event);
2391
2392 return sent;
2393}
2394
2395/* this is the tasklet referenced in fconn->wait_event.tasklet */
2396static struct task *fcgi_io_cb(struct task *t, void *ctx, unsigned short status)
2397{
2398 struct fcgi_conn *fconn = ctx;
2399 int ret = 0;
2400
2401 if (!(fconn->wait_event.events & SUB_RETRY_SEND))
2402 ret = fcgi_send(fconn);
2403 if (!(fconn->wait_event.events & SUB_RETRY_RECV))
2404 ret |= fcgi_recv(fconn);
2405 if (ret || b_data(&fconn->dbuf))
2406 fcgi_process(fconn);
2407 return NULL;
2408}
2409
2410/* callback called on any event by the connection handler.
2411 * It applies changes and returns zero, or < 0 if it wants immediate
2412 * destruction of the connection (which normally doesn not happen in FCGI).
2413 */
2414static int fcgi_process(struct fcgi_conn *fconn)
2415{
2416 struct connection *conn = fconn->conn;
2417
2418 if (b_data(&fconn->dbuf) && !(fconn->flags & FCGI_CF_DEM_BLOCK_ANY)) {
2419 fcgi_process_demux(fconn);
2420
2421 if (fconn->state == FCGI_CS_CLOSED || conn->flags & CO_FL_ERROR)
2422 b_reset(&fconn->dbuf);
2423
2424 if (buf_room_for_htx_data(&fconn->dbuf))
2425 fconn->flags &= ~FCGI_CF_DEM_DFULL;
2426 }
2427 fcgi_send(fconn);
2428
2429 if (unlikely(fconn->proxy->state == PR_STSTOPPED)) {
2430 /* frontend is stopping, reload likely in progress, let's try
2431 * to announce a graceful shutdown if not yet done. We don't
2432 * care if it fails, it will be tried again later.
2433 */
2434 if (!(fconn->flags & (FCGI_CF_ABRTS_SENT|FCGI_CF_ABRTS_FAILED))) {
2435 if (fconn->stream_cnt - fconn->nb_reserved > 0)
2436 fcgi_conn_send_aborts(fconn);
2437 }
2438 }
2439
2440 /*
2441 * If we received early data, and the handshake is done, wake
2442 * any stream that was waiting for it.
2443 */
2444 if (!(fconn->flags & FCGI_CF_WAIT_FOR_HS) &&
2445 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE | CO_FL_EARLY_DATA)) == CO_FL_EARLY_DATA) {
2446 struct eb32_node *node;
2447 struct fcgi_strm *fstrm;
2448
2449 fconn->flags |= FCGI_CF_WAIT_FOR_HS;
2450 node = eb32_lookup_ge(&fconn->streams_by_id, 1);
2451
2452 while (node) {
2453 fstrm = container_of(node, struct fcgi_strm, by_id);
2454 if (fstrm->cs && fstrm->cs->flags & CS_FL_WAIT_FOR_HS)
2455 fcgi_strm_notify_recv(fstrm);
2456 node = eb32_next(node);
2457 }
2458 }
2459
2460 if ((conn->flags & CO_FL_ERROR) || conn_xprt_read0_pending(conn) ||
2461 fconn->state == FCGI_CS_CLOSED || (fconn->flags & FCGI_CF_ABRTS_FAILED) ||
2462 eb_is_empty(&fconn->streams_by_id)) {
2463 fcgi_wake_some_streams(fconn, 0);
2464
2465 if (eb_is_empty(&fconn->streams_by_id)) {
2466 /* no more stream, kill the connection now */
2467 fcgi_release(fconn);
2468 return -1;
2469 }
2470 }
2471
2472 if (!b_data(&fconn->dbuf))
2473 fcgi_release_buf(fconn, &fconn->dbuf);
2474
2475 if ((conn->flags & CO_FL_SOCK_WR_SH) ||
2476 fconn->state == FCGI_CS_CLOSED || (fconn->flags & FCGI_CF_ABRTS_FAILED) ||
2477 (!br_data(fconn->mbuf) && ((fconn->flags & FCGI_CF_MUX_BLOCK_ANY) || LIST_ISEMPTY(&fconn->send_list))))
2478 fcgi_release_mbuf(fconn);
2479
2480 if (fconn->task) {
2481 fconn->task->expire = tick_add(now_ms, (fconn->state == FCGI_CS_CLOSED ? fconn->shut_timeout : fconn->timeout));
2482 task_queue(fconn->task);
2483 }
2484
2485 fcgi_send(fconn);
2486 return 0;
2487}
2488
2489
2490/* wake-up function called by the connection layer (mux_ops.wake) */
2491static int fcgi_wake(struct connection *conn)
2492{
2493 struct fcgi_conn *fconn = conn->ctx;
2494
2495 return (fcgi_process(fconn));
2496}
2497
2498/* Connection timeout management. The principle is that if there's no receipt
2499 * nor sending for a certain amount of time, the connection is closed. If the
2500 * MUX buffer still has lying data or is not allocatable, the connection is
2501 * immediately killed. If it's allocatable and empty, we attempt to send a
2502 * GOAWAY frame.
2503 */
2504static struct task *fcgi_timeout_task(struct task *t, void *context, unsigned short state)
2505{
2506 struct fcgi_conn *fconn = context;
2507 int expired = tick_is_expired(t->expire, now_ms);
2508
2509 if (!expired && fconn)
2510 return t;
2511
2512 task_destroy(t);
2513
2514 if (!fconn) {
2515 /* resources were already deleted */
2516 return NULL;
2517 }
2518
2519 fconn->task = NULL;
2520 fconn->state = FCGI_CS_CLOSED;
2521 fcgi_wake_some_streams(fconn, 0);
2522
2523 if (br_data(fconn->mbuf)) {
2524 /* don't even try to send aborts, the buffer is stuck */
2525 fconn->flags |= FCGI_CF_ABRTS_FAILED;
2526 goto end;
2527 }
2528
2529 /* try to send but no need to insist */
2530 if (!fcgi_conn_send_aborts(fconn))
2531 fconn->flags |= FCGI_CF_ABRTS_FAILED;
2532
2533 if (br_data(fconn->mbuf) && !(fconn->flags & FCGI_CF_ABRTS_FAILED) &&
2534 conn_xprt_ready(fconn->conn)) {
2535 unsigned int released = 0;
2536 struct buffer *buf;
2537
2538 for (buf = br_head(fconn->mbuf); b_size(buf); buf = br_del_head(fconn->mbuf)) {
2539 if (b_data(buf)) {
2540 int ret = fconn->conn->xprt->snd_buf(fconn->conn, fconn->conn->xprt_ctx,
2541 buf, b_data(buf), 0);
2542 if (!ret)
2543 break;
2544 b_del(buf, ret);
2545 if (b_data(buf))
2546 break;
2547 b_free(buf);
2548 released++;
2549 }
2550 }
2551
2552 if (released)
2553 offer_buffers(NULL, tasks_run_queue);
2554 }
2555
2556 end:
2557 /* either we can release everything now or it will be done later once
2558 * the last stream closes.
2559 */
2560 if (eb_is_empty(&fconn->streams_by_id))
2561 fcgi_release(fconn);
2562
2563 return NULL;
2564}
2565
2566
2567/*******************************************/
2568/* functions below are used by the streams */
2569/*******************************************/
2570
2571/* Append the description of what is present in error snapshot <es> into <out>.
2572 * The description must be small enough to always fit in a buffer. The output
2573 * buffer may be the trash so the trash must not be used inside this function.
2574 */
2575static void fcgi_show_error_snapshot(struct buffer *out, const struct error_snapshot *es)
2576{
2577 chunk_appendf(out,
2578 " FCGI connection flags 0x%08x, FCGI stream flags 0x%08x\n"
2579 " H1 msg state %s(%d), H1 msg flags 0x%08x\n"
2580 " H1 chunk len %lld bytes, H1 body len %lld bytes :\n",
2581 es->ctx.h1.c_flags, es->ctx.h1.s_flags,
2582 h1m_state_str(es->ctx.h1.state), es->ctx.h1.state,
2583 es->ctx.h1.m_flags, es->ctx.h1.m_clen, es->ctx.h1.m_blen);
2584}
2585/*
2586 * Capture a bad response and archive it in the proxy's structure. By default
2587 * it tries to report the error position as h1m->err_pos. However if this one is
2588 * not set, it will then report h1m->next, which is the last known parsing
2589 * point. The function is able to deal with wrapping buffers. It always displays
2590 * buffers as a contiguous area starting at buf->p. The direction is determined
2591 * thanks to the h1m's flags.
2592 */
2593static void fcgi_strm_capture_bad_message(struct fcgi_conn *fconn, struct fcgi_strm *fstrm,
2594 struct h1m *h1m, struct buffer *buf)
2595{
2596 struct session *sess = fstrm->sess;
2597 struct proxy *proxy = fconn->proxy;
2598 struct proxy *other_end = sess->fe;
2599 union error_snapshot_ctx ctx;
2600
2601 /* http-specific part now */
2602 ctx.h1.state = h1m->state;
2603 ctx.h1.c_flags = fconn->flags;
2604 ctx.h1.s_flags = fstrm->flags;
2605 ctx.h1.m_flags = h1m->flags;
2606 ctx.h1.m_clen = h1m->curr_len;
2607 ctx.h1.m_blen = h1m->body_len;
2608
2609 proxy_capture_error(proxy, 1, other_end, fconn->conn->target, sess, buf, 0, 0,
2610 (h1m->err_pos >= 0) ? h1m->err_pos : h1m->next,
2611 &ctx, fcgi_show_error_snapshot);
2612}
2613
2614static size_t fcgi_strm_parse_headers(struct fcgi_strm *fstrm, struct h1m *h1m, struct htx *htx,
2615 struct buffer *buf, size_t *ofs, size_t max)
2616{
2617 int ret;
2618
2619 ret = h1_parse_msg_hdrs(h1m, NULL, htx, buf, *ofs, max);
2620 if (!ret) {
2621 if (htx->flags & HTX_FL_PARSING_ERROR) {
2622 fcgi_strm_error(fstrm);
2623 fcgi_strm_capture_bad_message(fstrm->fconn, fstrm, h1m, buf);
2624 }
2625 goto end;
2626 }
2627
2628 *ofs += ret;
2629 end:
2630 return ret;
2631
2632}
2633
Christopher Fauletaf542632019-10-01 21:52:49 +02002634static size_t fcgi_strm_parse_data(struct fcgi_strm *fstrm, struct h1m *h1m, struct htx **htx,
Christopher Faulet99eff652019-08-11 23:11:30 +02002635 struct buffer *buf, size_t *ofs, size_t max, struct buffer *htxbuf)
2636{
2637 int ret;
2638
2639 ret = h1_parse_msg_data(h1m, htx, buf, *ofs, max, htxbuf);
2640 if (ret <= 0) {
Christopher Fauletaf542632019-10-01 21:52:49 +02002641 if ((*htx)->flags & HTX_FL_PARSING_ERROR) {
Christopher Faulet99eff652019-08-11 23:11:30 +02002642 fcgi_strm_error(fstrm);
2643 fcgi_strm_capture_bad_message(fstrm->fconn, fstrm, h1m, buf);
2644 }
2645 goto end;
2646 }
2647 *ofs += ret;
2648 end:
2649 return ret;
2650}
2651
2652static size_t fcgi_strm_parse_trailers(struct fcgi_strm *fstrm, struct h1m *h1m, struct htx *htx,
2653 struct buffer *buf, size_t *ofs, size_t max)
2654{
2655 int ret;
2656
2657 ret = h1_parse_msg_tlrs(h1m, htx, buf, *ofs, max);
2658 if (ret <= 0) {
2659 if (htx->flags & HTX_FL_PARSING_ERROR) {
2660 fcgi_strm_error(fstrm);
2661 fcgi_strm_capture_bad_message(fstrm->fconn, fstrm, h1m, buf);
2662 }
2663 goto end;
2664 }
2665 *ofs += ret;
2666 fstrm->flags |= FCGI_SF_HAVE_I_TLR;
2667 end:
2668 return ret;
2669}
2670
2671static size_t fcgi_strm_add_eom(struct fcgi_strm *fstrm, struct h1m *h1m, struct htx *htx,
2672 size_t max)
2673{
2674 if (max < sizeof(struct htx_blk) + 1 || !htx_add_endof(htx, HTX_BLK_EOM))
2675 return 0;
2676
2677 h1m->state = H1_MSG_DONE;
2678 return (sizeof(struct htx_blk) + 1);
2679}
2680
2681static size_t fcgi_strm_parse_response(struct fcgi_strm *fstrm, struct buffer *buf, size_t count)
2682{
2683 struct htx *htx;
2684 struct h1m *h1m = &fstrm->h1m;
2685 size_t ret, data, total = 0;
2686
2687 htx = htx_from_buf(buf);
2688 data = htx->data;
2689 if (fstrm->state == FCGI_SS_ERROR)
2690 goto end;
2691
2692 do {
2693 size_t used = htx_used_space(htx);
2694
2695 if (h1m->state <= H1_MSG_LAST_LF) {
2696 ret = fcgi_strm_parse_headers(fstrm, h1m, htx, &fstrm->rxbuf, &total, count);
2697 if (!ret)
2698 break;
2699 if ((h1m->flags & (H1_MF_VER_11|H1_MF_XFER_LEN)) == H1_MF_VER_11) {
2700 struct htx_blk *blk = htx_get_head_blk(htx);
2701 struct htx_sl *sl;
2702
2703 if (!blk)
2704 break;
2705 sl = htx_get_blk_ptr(htx, blk);
2706 sl->flags |= HTX_SL_F_XFER_LEN;
2707 htx->extra = 0;
2708 }
2709 }
2710 else if (h1m->state < H1_MSG_TRAILERS) {
Christopher Fauletaf542632019-10-01 21:52:49 +02002711 ret = fcgi_strm_parse_data(fstrm, h1m, &htx, &fstrm->rxbuf, &total, count, buf);
Christopher Faulet99eff652019-08-11 23:11:30 +02002712 if (!ret)
2713 break;
2714 }
2715 else if (h1m->state == H1_MSG_TRAILERS) {
2716 if (!(fstrm->flags & FCGI_SF_HAVE_I_TLR)) {
2717 ret = fcgi_strm_parse_trailers(fstrm, h1m, htx, &fstrm->rxbuf, &total, count);
2718 if (!ret)
2719 break;
2720 }
2721 else if (!fcgi_strm_add_eom(fstrm, h1m, htx, count))
2722 break;
2723 }
2724 else if (h1m->state == H1_MSG_DONE) {
2725 if (b_data(&fstrm->rxbuf) > total) {
2726 htx->flags |= HTX_FL_PARSING_ERROR;
2727 fcgi_strm_error(fstrm);
2728 }
2729 break;
2730 }
2731 else if (h1m->state == H1_MSG_TUNNEL) {
Christopher Fauletaf542632019-10-01 21:52:49 +02002732 ret = fcgi_strm_parse_data(fstrm, h1m, &htx, &fstrm->rxbuf, &total, count, buf);
Christopher Faulet99eff652019-08-11 23:11:30 +02002733 if (fstrm->state != FCGI_SS_ERROR &&
2734 (fstrm->flags & FCGI_SF_ES_RCVD) && b_data(&fstrm->rxbuf) == total) {
2735 if ((h1m->flags & (H1_MF_VER_11|H1_MF_XFER_LEN)) == H1_MF_VER_11) {
2736 if (!fcgi_strm_add_eom(fstrm, h1m, htx, count))
2737 break;
2738 }
2739 else {
2740 h1m->state = H1_MSG_DONE;
2741 break;
2742 }
2743 }
2744 if (!ret)
2745 break;
2746 }
2747 else {
2748 htx->flags |= HTX_FL_PROCESSING_ERROR;
2749 fcgi_strm_error(fstrm);
2750 break;
2751 }
2752
2753 count -= htx_used_space(htx) - used;
2754 } while (fstrm->state != FCGI_SS_ERROR/* /\*fstrm->state == FCGI_SS_OPEN && *\/count */);
2755
2756 if (fstrm->state == FCGI_SS_ERROR) {
2757 b_reset(&fstrm->rxbuf);
2758 htx_to_buf(htx, buf);
2759 return 0;
2760 }
2761
2762 b_del(&fstrm->rxbuf, total);
2763
2764 end:
2765 htx_to_buf(htx, buf);
2766 ret = htx->data - data;
2767 return ret;
2768}
2769
2770/*
2771 * Attach a new stream to a connection
2772 * (Used for outgoing connections)
2773 */
2774static struct conn_stream *fcgi_attach(struct connection *conn, struct session *sess)
2775{
2776 struct conn_stream *cs;
2777 struct fcgi_strm *fstrm;
2778 struct fcgi_conn *fconn = conn->ctx;
2779
2780 cs = cs_new(conn);
2781 if (!cs)
2782 return NULL;
2783 fstrm = fcgi_conn_stream_new(fconn, cs, sess);
2784 if (!fstrm) {
2785 cs_free(cs);
2786 return NULL;
2787 }
2788 return cs;
2789}
2790
2791/* Retrieves the first valid conn_stream from this connection, or returns NULL.
2792 * We have to scan because we may have some orphan streams. It might be
2793 * beneficial to scan backwards from the end to reduce the likeliness to find
2794 * orphans.
2795 */
2796static const struct conn_stream *fcgi_get_first_cs(const struct connection *conn)
2797{
2798 struct fcgi_conn *fconn = conn->ctx;
2799 struct fcgi_strm *fstrm;
2800 struct eb32_node *node;
2801
2802 node = eb32_first(&fconn->streams_by_id);
2803 while (node) {
2804 fstrm = container_of(node, struct fcgi_strm, by_id);
2805 if (fstrm->cs)
2806 return fstrm->cs;
2807 node = eb32_next(node);
2808 }
2809 return NULL;
2810}
2811
2812/*
2813 * Destroy the mux and the associated connection, if it is no longer used
2814 */
2815static void fcgi_destroy(void *ctx)
2816{
2817 struct fcgi_conn *fconn = ctx;
2818
2819 if (eb_is_empty(&fconn->streams_by_id) || !fconn->conn || fconn->conn->ctx != fconn)
2820 fcgi_release(fconn);
2821}
2822
2823/*
2824 * Detach the stream from the connection and possibly release the connection.
2825 */
2826static void fcgi_detach(struct conn_stream *cs)
2827{
2828 struct fcgi_strm *fstrm = cs->ctx;
2829 struct fcgi_conn *fconn;
2830 struct session *sess;
2831
2832 cs->ctx = NULL;
2833 if (!fstrm)
2834 return;
2835
2836 /* The stream is about to die, so no need to attempt to run its task */
2837 if (LIST_ADDED(&fstrm->sending_list) &&
2838 fstrm->send_wait != &fstrm->wait_event) {
2839 tasklet_remove_from_tasklet_list(fstrm->send_wait->tasklet);
2840 LIST_DEL_INIT(&fstrm->sending_list);
2841 /*
2842 * At this point, the stream_interface is supposed to have called
2843 * fcgi_unsubscribe(), so the only way there's still a
2844 * subscription that came from the stream_interface (as we
2845 * can subscribe ourself, in fcgi_do_shutw() and fcgi_do_shutr(),
2846 * without the stream_interface involved) is that we subscribed
2847 * for sending, we woke the tasklet up and removed the
2848 * SUB_RETRY_SEND flag, so the stream_interface would not
2849 * know it has to unsubscribe for send, but the tasklet hasn't
2850 * run yet. Make sure to handle that by explicitely setting
2851 * send_wait to NULL, as nothing else will do it for us.
2852 */
2853 fstrm->send_wait = NULL;
2854 }
2855
2856 sess = fstrm->sess;
2857 fconn = fstrm->fconn;
2858 fstrm->cs = NULL;
2859 fconn->nb_cs--;
2860
2861 if (fstrm->proto_status == FCGI_PS_CANT_MPX_CONN) {
2862 fconn->flags &= ~FCGI_CF_MPXS_CONNS;
2863 fconn->streams_limit = 1;
2864 }
2865 else if (fstrm->proto_status == FCGI_PS_OVERLOADED ||
2866 fstrm->proto_status == FCGI_PS_UNKNOWN_ROLE) {
2867 fconn->flags &= ~FCGI_CF_KEEP_CONN;
2868 fconn->state = FCGI_CS_CLOSED;
2869 }
2870
2871 /* this stream may be blocked waiting for some data to leave, so orphan
2872 * it in this case.
2873 */
2874 if (!(cs->conn->flags & CO_FL_ERROR) &&
2875 (fconn->state != FCGI_CS_CLOSED) &&
2876 (fstrm->flags & (FCGI_SF_BLK_MBUSY|FCGI_SF_BLK_MROOM)) && (fstrm->send_wait || fstrm->recv_wait))
2877 return;
2878
2879 if ((fconn->flags & FCGI_CF_DEM_BLOCK_ANY && fstrm->id == fconn->dsi)) {
2880 /* unblock the connection if it was blocked on this stream. */
2881 fconn->flags &= ~FCGI_CF_DEM_BLOCK_ANY;
2882 fcgi_conn_restart_reading(fconn, 1);
2883 }
2884
2885 fcgi_strm_destroy(fstrm);
2886
2887 if (!(fconn->conn->flags & (CO_FL_ERROR|CO_FL_SOCK_RD_SH|CO_FL_SOCK_WR_SH)) &&
2888 !(fconn->flags & FCGI_CF_KEEP_CONN)) {
2889 if (!fconn->conn->owner) {
2890 fconn->conn->owner = sess;
2891 if (!session_add_conn(sess, fconn->conn, fconn->conn->target)) {
2892 fconn->conn->owner = NULL;
2893 if (eb_is_empty(&fconn->streams_by_id)) {
2894 if (!srv_add_to_idle_list(objt_server(fconn->conn->target), fconn->conn))
2895 /* The server doesn't want it, let's kill the connection right away */
2896 fconn->conn->mux->destroy(fconn->conn);
2897 return;
2898 }
2899 }
2900 }
2901 if (eb_is_empty(&fconn->streams_by_id)) {
2902 if (session_check_idle_conn(fconn->conn->owner, fconn->conn) != 0)
2903 /* At this point either the connection is destroyed,
2904 or it's been added to the server idle list, just stop */
2905 return;
2906 }
2907 /* Never ever allow to reuse a connection from a non-reuse backend */
2908 if ((fconn->proxy->options & PR_O_REUSE_MASK) == PR_O_REUSE_NEVR)
2909 fconn->conn->flags |= CO_FL_PRIVATE;
2910 if (!LIST_ADDED(&fconn->conn->list) && fconn->nb_streams < fconn->streams_limit) {
2911 struct server *srv = objt_server(fconn->conn->target);
2912
2913 if (srv) {
2914 if (fconn->conn->flags & CO_FL_PRIVATE)
2915 LIST_ADD(&srv->priv_conns[tid], &fconn->conn->list);
2916 else
2917 LIST_ADD(&srv->idle_conns[tid], &fconn->conn->list);
2918 }
2919 }
2920 }
2921
2922 /* We don't want to close right now unless we're removing the last
2923 * stream, and either the connection is in error, or it reached the ID
2924 * already specified in a GOAWAY frame received or sent (as seen by
2925 * last_sid >= 0).
2926 */
2927 if (fcgi_conn_is_dead(fconn)) {
2928 /* no more stream will come, kill it now */
2929 fcgi_release(fconn);
2930 }
2931 else if (fconn->task) {
2932 fconn->task->expire = tick_add(now_ms, (fconn->state == FCGI_CS_CLOSED ? fconn->shut_timeout : fconn->timeout));
2933 task_queue(fconn->task);
2934 }
2935}
2936
2937
2938/* Performs a synchronous or asynchronous shutr(). */
2939static void fcgi_do_shutr(struct fcgi_strm *fstrm)
2940{
2941 struct fcgi_conn *fconn = fstrm->fconn;
2942 struct wait_event *sw = &fstrm->wait_event;
2943
2944 if (fstrm->state == FCGI_SS_CLOSED)
2945 goto done;
2946
2947 /* a connstream may require us to immediately kill the whole connection
2948 * for example because of a "tcp-request content reject" rule that is
2949 * normally used to limit abuse.
2950 */
2951 if ((fstrm->flags & FCGI_SF_KILL_CONN) &&
2952 !(fconn->flags & (FCGI_CF_ABRTS_SENT|FCGI_CF_ABRTS_FAILED)))
2953 fconn->state = FCGI_CS_CLOSED;
2954 else if (fstrm->flags & FCGI_SF_BEGIN_SENT) {
2955 if (!(fstrm->flags & (FCGI_SF_ES_SENT|FCGI_SF_ABRT_SENT)) &&
2956 !fcgi_strm_send_abort(fconn, fstrm))
2957 goto add_to_list;
2958 }
2959
2960 fcgi_strm_close(fstrm);
2961
2962 if (!(fconn->wait_event.events & SUB_RETRY_SEND))
2963 tasklet_wakeup(fconn->wait_event.tasklet);
2964 done:
2965 fstrm->flags &= ~FCGI_SF_WANT_SHUTR;
2966 return;
2967
2968 add_to_list:
2969 if (!LIST_ADDED(&fstrm->send_list)) {
2970 sw->events |= SUB_RETRY_SEND;
2971 if (fstrm->flags & (FCGI_SF_BLK_MBUSY|FCGI_SF_BLK_MROOM)) {
2972 fstrm->send_wait = sw;
2973 LIST_ADDQ(&fconn->send_list, &fstrm->send_list);
2974 }
2975 }
2976 /* Let the handler know we want shutr */
2977 fstrm->flags |= FCGI_SF_WANT_SHUTR;
2978 return;
2979}
2980
2981/* Performs a synchronous or asynchronous shutw(). */
2982static void fcgi_do_shutw(struct fcgi_strm *fstrm)
2983{
2984 struct fcgi_conn *fconn = fstrm->fconn;
2985 struct wait_event *sw = &fstrm->wait_event;
2986
2987 if (fstrm->state != FCGI_SS_HLOC || fstrm->state == FCGI_SS_CLOSED)
2988 goto done;
2989
2990 if (fstrm->state != FCGI_SS_ERROR && (fstrm->flags & FCGI_SF_BEGIN_SENT)) {
2991 if (!(fstrm->flags & (FCGI_SF_ES_SENT|FCGI_SF_ABRT_SENT)) &&
2992 !fcgi_strm_send_abort(fconn, fstrm))
2993 goto add_to_list;
2994
2995 if (fstrm->state == FCGI_SS_HREM)
2996 fcgi_strm_close(fstrm);
2997 else
2998 fstrm->state = FCGI_SS_HLOC;
2999 } else {
3000 /* a connstream may require us to immediately kill the whole connection
3001 * for example because of a "tcp-request content reject" rule that is
3002 * normally used to limit abuse.
3003 */
3004 if ((fstrm->flags & FCGI_SF_KILL_CONN) &&
3005 !(fconn->flags & (FCGI_CF_ABRTS_SENT|FCGI_CF_ABRTS_FAILED)))
3006 fconn->state = FCGI_CS_CLOSED;
3007
3008 fcgi_strm_close(fstrm);
3009 }
3010
3011 if (!(fconn->wait_event.events & SUB_RETRY_SEND))
3012 tasklet_wakeup(fconn->wait_event.tasklet);
3013 done:
3014 fstrm->flags &= ~FCGI_SF_WANT_SHUTW;
3015 return;
3016
3017 add_to_list:
3018 if (!LIST_ADDED(&fstrm->send_list)) {
3019 sw->events |= SUB_RETRY_SEND;
3020 if (fstrm->flags & (FCGI_SF_BLK_MBUSY|FCGI_SF_BLK_MROOM)) {
3021 fstrm->send_wait = sw;
3022 LIST_ADDQ(&fconn->send_list, &fstrm->send_list);
3023 }
3024 }
3025 /* let the handler know we want to shutw */
3026 fstrm->flags |= FCGI_SF_WANT_SHUTW;
3027 return;
3028}
3029
3030/* This is the tasklet referenced in fstrm->wait_event.tasklet, it is used for
3031 * deferred shutdowns when the fcgi_detach() was done but the mux buffer was full
3032 * and prevented the last frame from being emitted.
3033 */
3034static struct task *fcgi_deferred_shut(struct task *t, void *ctx, unsigned short state)
3035{
3036 struct fcgi_strm *fstrm = ctx;
3037 struct fcgi_conn *fconn = fstrm->fconn;
3038
3039 LIST_DEL_INIT(&fstrm->sending_list);
3040 if (fstrm->flags & FCGI_SF_WANT_SHUTW)
3041 fcgi_do_shutw(fstrm);
3042
3043 if (fstrm->flags & FCGI_SF_WANT_SHUTR)
3044 fcgi_do_shutr(fstrm);
3045
3046 if (!(fstrm->flags & (FCGI_SF_WANT_SHUTR|FCGI_SF_WANT_SHUTW))) {
3047 /* We're done trying to send, remove ourself from the send_list */
3048 LIST_DEL_INIT(&fstrm->send_list);
3049
3050 if (!fstrm->cs) {
3051 fcgi_strm_destroy(fstrm);
3052 if (fcgi_conn_is_dead(fconn))
3053 fcgi_release(fconn);
3054 }
3055 }
3056
3057 return NULL;
3058}
3059
3060/* shutr() called by the conn_stream (mux_ops.shutr) */
3061static void fcgi_shutr(struct conn_stream *cs, enum cs_shr_mode mode)
3062{
3063 struct fcgi_strm *fstrm = cs->ctx;
3064
3065 if (cs->flags & CS_FL_KILL_CONN)
3066 fstrm->flags |= FCGI_SF_KILL_CONN;
3067
3068 if (!mode)
3069 return;
3070
3071 fcgi_do_shutr(fstrm);
3072}
3073
3074/* shutw() called by the conn_stream (mux_ops.shutw) */
3075static void fcgi_shutw(struct conn_stream *cs, enum cs_shw_mode mode)
3076{
3077 struct fcgi_strm *fstrm = cs->ctx;
3078
3079 if (cs->flags & CS_FL_KILL_CONN)
3080 fstrm->flags |= FCGI_SF_KILL_CONN;
3081
3082 fcgi_do_shutw(fstrm);
3083}
3084
3085/* Called from the upper layer, to subscribe to events, such as being able to send.
3086 * The <param> argument here is supposed to be a pointer to a wait_event struct
3087 * which will be passed to fstrm->recv_wait or fstrm->send_wait depending on the
3088 * event_type. The event_type must only be a combination of SUB_RETRY_RECV and
3089 * SUB_RETRY_SEND, other values will lead to -1 being returned. It always
3090 * returns 0 except for the error above.
3091 */
3092static int fcgi_subscribe(struct conn_stream *cs, int event_type, void *param)
3093{
3094 struct wait_event *sw;
3095 struct fcgi_strm *fstrm = cs->ctx;
3096 struct fcgi_conn *fconn = fstrm->fconn;
3097
3098 if (event_type & SUB_RETRY_RECV) {
3099 sw = param;
3100 BUG_ON(fstrm->recv_wait != NULL || (sw->events & SUB_RETRY_RECV));
3101 sw->events |= SUB_RETRY_RECV;
3102 fstrm->recv_wait = sw;
3103 event_type &= ~SUB_RETRY_RECV;
3104 }
3105 if (event_type & SUB_RETRY_SEND) {
3106 sw = param;
3107 BUG_ON(fstrm->send_wait != NULL || (sw->events & SUB_RETRY_SEND));
3108 sw->events |= SUB_RETRY_SEND;
3109 fstrm->send_wait = sw;
3110 if (!LIST_ADDED(&fstrm->send_list))
3111 LIST_ADDQ(&fconn->send_list, &fstrm->send_list);
3112 event_type &= ~SUB_RETRY_SEND;
3113 }
3114 if (event_type != 0)
3115 return -1;
3116 return 0;
3117}
3118
3119/* Called from the upper layer, to unsubscribe some events (undo fcgi_subscribe).
3120 * The <param> argument here is supposed to be a pointer to the same wait_event
3121 * struct that was passed to fcgi_subscribe() otherwise nothing will be changed.
3122 * It always returns zero.
3123 */
3124static int fcgi_unsubscribe(struct conn_stream *cs, int event_type, void *param)
3125{
3126 struct wait_event *sw;
3127 struct fcgi_strm *fstrm = cs->ctx;
3128
3129 if (event_type & SUB_RETRY_RECV) {
3130 sw = param;
3131 BUG_ON(fstrm->recv_wait != sw);
3132 sw->events &= ~SUB_RETRY_RECV;
3133 fstrm->recv_wait = NULL;
3134 }
3135 if (event_type & SUB_RETRY_SEND) {
3136 sw = param;
3137 BUG_ON(fstrm->send_wait != sw);
3138 LIST_DEL(&fstrm->send_list);
3139 LIST_INIT(&fstrm->send_list);
3140 sw->events &= ~SUB_RETRY_SEND;
3141 /* We were about to send, make sure it does not happen */
3142 if (LIST_ADDED(&fstrm->sending_list) && fstrm->send_wait != &fstrm->wait_event) {
3143 tasklet_remove_from_tasklet_list(fstrm->send_wait->tasklet);
3144 LIST_DEL_INIT(&fstrm->sending_list);
3145 }
3146 fstrm->send_wait = NULL;
3147 }
3148 return 0;
3149}
3150
3151/* Called from the upper layer, to receive data */
3152static size_t fcgi_rcv_buf(struct conn_stream *cs, struct buffer *buf, size_t count, int flags)
3153{
3154 struct fcgi_strm *fstrm = cs->ctx;
3155 struct fcgi_conn *fconn = fstrm->fconn;
3156 size_t ret = 0;
3157
3158 if (!(fconn->flags & FCGI_CF_DEM_SALLOC))
3159 ret = fcgi_strm_parse_response(fstrm, buf, count);
3160
3161 if (b_data(&fstrm->rxbuf))
3162 cs->flags |= (CS_FL_RCV_MORE | CS_FL_WANT_ROOM);
3163 else {
3164 cs->flags &= ~(CS_FL_RCV_MORE | CS_FL_WANT_ROOM);
3165 if (fstrm->state == FCGI_SS_ERROR || fstrm->h1m.state == H1_MSG_DONE) {
3166 cs->flags |= CS_FL_EOI;
3167 if (!(fstrm->h1m.flags & (H1_MF_VER_11|H1_MF_XFER_LEN)))
3168 cs->flags |= CS_FL_EOS;
3169 }
3170 if (conn_xprt_read0_pending(fconn->conn))
3171 cs->flags |= CS_FL_EOS;
3172 if (cs->flags & CS_FL_ERR_PENDING)
3173 cs->flags |= CS_FL_ERROR;
3174 fcgi_release_buf(fconn, &fstrm->rxbuf);
3175 }
3176
3177 if (ret && fconn->dsi == fstrm->id) {
3178 /* demux is blocking on this stream's buffer */
3179 fconn->flags &= ~FCGI_CF_DEM_SFULL;
3180 fcgi_conn_restart_reading(fconn, 1);
3181 }
3182
3183 return ret;
3184}
3185
3186
3187/* stops all senders of this connection for example when the mux buffer is full.
3188 * They are moved from the sending_list to send_list.
3189 */
3190static void fcgi_stop_senders(struct fcgi_conn *fconn)
3191{
3192 struct fcgi_strm *fstrm, *fstrm_back;
3193
3194 list_for_each_entry_safe(fstrm, fstrm_back, &fconn->sending_list, sending_list) {
3195 LIST_DEL_INIT(&fstrm->sending_list);
3196 tasklet_remove_from_tasklet_list(fstrm->send_wait->tasklet);
3197 fstrm->send_wait->events |= SUB_RETRY_SEND;
3198 }
3199}
3200
3201
3202/* Called from the upper layer, to send data from buffer <buf> for no more than
3203 * <count> bytes. Returns the number of bytes effectively sent. Some status
3204 * flags may be updated on the conn_stream.
3205 */
3206static size_t fcgi_snd_buf(struct conn_stream *cs, struct buffer *buf, size_t count, int flags)
3207{
3208 struct fcgi_strm *fstrm = cs->ctx;
3209 struct fcgi_conn *fconn = fstrm->fconn;
3210 size_t total = 0;
3211 size_t ret;
3212 struct htx *htx = NULL;
3213 struct htx_sl *sl;
3214 struct htx_blk *blk;
3215 uint32_t bsize;
3216
3217 /* If we were not just woken because we wanted to send but couldn't,
3218 * and there's somebody else that is waiting to send, do nothing,
3219 * we will subscribe later and be put at the end of the list
3220 */
3221 if (!LIST_ADDED(&fstrm->sending_list) && !LIST_ISEMPTY(&fconn->send_list))
3222 return 0;
3223 LIST_DEL_INIT(&fstrm->sending_list);
3224
3225 /* We couldn't set it to NULL before, because we needed it in case
3226 * we had to cancel the tasklet
3227 */
3228 fstrm->send_wait = NULL;
3229
3230 if (fconn->state < FCGI_CS_RECORD_H)
3231 return 0;
3232
3233 htx = htxbuf(buf);
3234 if (fstrm->id == 0) {
3235 int32_t id = fcgi_conn_get_next_sid(fconn);
3236
3237 if (id < 0) {
3238 fcgi_strm_close(fstrm);
3239 cs->flags |= CS_FL_ERROR;
3240 return 0;
3241 }
3242
3243 eb32_delete(&fstrm->by_id);
3244 fstrm->by_id.key = fstrm->id = id;
3245 fconn->max_id = id;
3246 fconn->nb_reserved--;
3247 eb32_insert(&fconn->streams_by_id, &fstrm->by_id);
3248
3249
3250 /* Check if length of the body is known or if the message is
3251 * full. Otherwise, the request is invalid.
3252 */
3253 sl = http_get_stline(htx);
3254 if (!sl || (!(sl->flags & HTX_SL_F_CLEN) && (htx_get_tail_type(htx) != HTX_BLK_EOM))) {
3255 htx->flags |= HTX_FL_PARSING_ERROR;
3256 fcgi_strm_error(fstrm);
3257 goto done;
3258 }
3259 }
3260
3261 if (!(fstrm->flags & FCGI_SF_BEGIN_SENT)) {
3262 if (!fcgi_strm_send_begin_request(fconn, fstrm))
3263 goto done;
3264 }
3265
3266 if (!(fstrm->flags & FCGI_SF_OUTGOING_DATA) && count)
3267 fstrm->flags |= FCGI_SF_OUTGOING_DATA;
3268
3269 while (fstrm->state < FCGI_SS_HLOC && !(fconn->flags & FCGI_SF_BLK_ANY) &&
3270 count && !htx_is_empty(htx)) {
3271 blk = htx_get_head_blk(htx);
William Lallemand13ed9fa2019-09-25 21:21:57 +02003272 ALREADY_CHECKED(blk);
Christopher Faulet99eff652019-08-11 23:11:30 +02003273 bsize = htx_get_blksz(blk);
3274
3275 switch (htx_get_blk_type(blk)) {
3276 case HTX_BLK_REQ_SL:
3277 case HTX_BLK_HDR:
3278 ret = fcgi_strm_send_params(fconn, fstrm, htx);
3279 if (!ret) {
3280 goto done;
3281 }
3282 total += ret;
3283 count -= ret;
3284 break;
3285
3286 case HTX_BLK_EOH:
3287 ret = fcgi_strm_send_empty_params(fconn, fstrm);
3288 if (!ret)
3289 goto done;
3290 goto remove_blk;
3291
3292 case HTX_BLK_DATA:
3293 ret = fcgi_strm_send_stdin(fconn, fstrm, htx, count, buf);
3294 if (ret > 0) {
3295 htx = htx_from_buf(buf);
3296 total += ret;
3297 count -= ret;
3298 if (ret < bsize)
3299 goto done;
3300 }
3301 break;
3302
3303 case HTX_BLK_EOM:
3304 ret = fcgi_strm_send_empty_stdin(fconn, fstrm);
3305 if (!ret)
3306 goto done;
3307 goto remove_blk;
3308
3309 default:
3310 remove_blk:
3311 htx_remove_blk(htx, blk);
3312 total += bsize;
3313 count -= bsize;
3314 break;
3315 }
3316 }
3317
3318 done:
3319 if (fstrm->state >= FCGI_SS_HLOC) {
3320 /* trim any possibly pending data after we close (extra CR-LF,
3321 * unprocessed trailers, abnormal extra data, ...)
3322 */
3323 total += count;
3324 count = 0;
3325 }
3326
3327 if (fstrm->state == FCGI_SS_ERROR) {
3328 cs_set_error(cs);
3329 if (!(fstrm->flags & FCGI_SF_BEGIN_SENT) || fcgi_strm_send_abort(fconn, fstrm))
3330 fcgi_strm_close(fstrm);
3331 }
3332
3333 if (htx)
3334 htx_to_buf(htx, buf);
3335
3336 /* The mux is full, cancel the pending tasks */
3337 if ((fconn->flags & FCGI_CF_MUX_BLOCK_ANY) || (fstrm->flags & FCGI_SF_BLK_MBUSY))
3338 fcgi_stop_senders(fconn);
3339
3340 if (total > 0) {
3341 if (!(fconn->wait_event.events & SUB_RETRY_SEND))
3342 tasklet_wakeup(fconn->wait_event.tasklet);
3343
3344 /* Ok we managed to send something, leave the send_list */
3345 LIST_DEL_INIT(&fstrm->send_list);
3346 }
3347 return total;
3348}
3349
3350/* for debugging with CLI's "show fd" command */
3351static void fcgi_show_fd(struct buffer *msg, struct connection *conn)
3352{
3353 struct fcgi_conn *fconn = conn->ctx;
3354 struct fcgi_strm *fstrm = NULL;
3355 struct eb32_node *node;
3356 int send_cnt = 0;
3357 int tree_cnt = 0;
3358 int orph_cnt = 0;
3359 struct buffer *hmbuf, *tmbuf;
3360
3361 if (!fconn)
3362 return;
3363
3364 list_for_each_entry(fstrm, &fconn->send_list, send_list)
3365 send_cnt++;
3366
3367 fstrm = NULL;
3368 node = eb32_first(&fconn->streams_by_id);
3369 while (node) {
3370 fstrm = container_of(node, struct fcgi_strm, by_id);
3371 tree_cnt++;
3372 if (!fstrm->cs)
3373 orph_cnt++;
3374 node = eb32_next(node);
3375 }
3376
3377 hmbuf = br_head(fconn->mbuf);
3378 tmbuf = br_tail(fconn->mbuf);
3379 chunk_appendf(msg, " fconn.st0=%d .maxid=%d .flg=0x%04x .nbst=%u"
3380 " .nbcs=%u .send_cnt=%d .tree_cnt=%d .orph_cnt=%d .sub=%d "
3381 ".dsi=%d .dbuf=%u@%p+%u/%u .mbuf=[%u..%u|%u],h=[%u@%p+%u/%u],t=[%u@%p+%u/%u]",
3382 fconn->state, fconn->max_id, fconn->flags,
3383 fconn->nb_streams, fconn->nb_cs, send_cnt, tree_cnt, orph_cnt,
3384 fconn->wait_event.events, fconn->dsi,
3385 (unsigned int)b_data(&fconn->dbuf), b_orig(&fconn->dbuf),
3386 (unsigned int)b_head_ofs(&fconn->dbuf), (unsigned int)b_size(&fconn->dbuf),
3387 br_head_idx(fconn->mbuf), br_tail_idx(fconn->mbuf), br_size(fconn->mbuf),
3388 (unsigned int)b_data(hmbuf), b_orig(hmbuf),
3389 (unsigned int)b_head_ofs(hmbuf), (unsigned int)b_size(hmbuf),
3390 (unsigned int)b_data(tmbuf), b_orig(tmbuf),
3391 (unsigned int)b_head_ofs(tmbuf), (unsigned int)b_size(tmbuf));
3392
3393 if (fstrm) {
3394 chunk_appendf(msg, " last_fstrm=%p .id=%d .flg=0x%04x .rxbuf=%u@%p+%u/%u .cs=%p",
3395 fstrm, fstrm->id, fstrm->flags,
3396 (unsigned int)b_data(&fstrm->rxbuf), b_orig(&fstrm->rxbuf),
3397 (unsigned int)b_head_ofs(&fstrm->rxbuf), (unsigned int)b_size(&fstrm->rxbuf),
3398 fstrm->cs);
3399 if (fstrm->cs)
3400 chunk_appendf(msg, " .cs.flg=0x%08x .cs.data=%p",
3401 fstrm->cs->flags, fstrm->cs->data);
3402 }
3403}
3404
3405/****************************************/
3406/* MUX initialization and instanciation */
3407/****************************************/
3408
3409/* The mux operations */
3410static const struct mux_ops mux_fcgi_ops = {
3411 .init = fcgi_init,
3412 .wake = fcgi_wake,
3413 .attach = fcgi_attach,
3414 .get_first_cs = fcgi_get_first_cs,
3415 .detach = fcgi_detach,
3416 .destroy = fcgi_destroy,
3417 .avail_streams = fcgi_avail_streams,
3418 .used_streams = fcgi_used_streams,
3419 .rcv_buf = fcgi_rcv_buf,
3420 .snd_buf = fcgi_snd_buf,
3421 .subscribe = fcgi_subscribe,
3422 .unsubscribe = fcgi_unsubscribe,
3423 .shutr = fcgi_shutr,
3424 .shutw = fcgi_shutw,
3425 .show_fd = fcgi_show_fd,
3426 .flags = MX_FL_HTX,
3427 .name = "FCGI",
3428};
3429
3430
3431/* this mux registers FCGI proto */
3432static struct mux_proto_list mux_proto_fcgi =
3433{ .token = IST("fcgi"), .mode = PROTO_MODE_HTTP, .side = PROTO_SIDE_BE, .mux = &mux_fcgi_ops };
3434
3435INITCALL1(STG_REGISTER, register_mux_proto, &mux_proto_fcgi);
3436
3437/*
3438 * Local variables:
3439 * c-indent-level: 8
3440 * c-basic-offset: 8
3441 * End:
3442 */