blob: d0fdde43568ed7f179d02c96b54908531566e820 [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
1591 memcpy(trash.area, "http_", 5);
1592 memcpy(trash.area+5, p.n.ptr, p.n.len);
1593 p.n = ist2(trash.area, p.n.len+5);
1594 }
1595
1596 if (!fcgi_encode_param(&outbuf, &p)) {
1597 if (b_space_wraps(mbuf))
1598 goto realign_again;
1599 if (outbuf.data == 8)
1600 goto full;
1601 goto done;
1602 }
1603 break;
1604
1605 case HTX_BLK_EOH:
Christopher Faulet72ba6cd2019-09-24 16:20:05 +02001606 if (fconn->proxy->server_id_hdr_name) {
1607 struct server *srv = objt_server(fconn->conn->target);
1608
1609 if (!srv)
1610 goto done;
1611
1612 memcpy(trash.area, "http_", 5);
1613 memcpy(trash.area+5, fconn->proxy->server_id_hdr_name, fconn->proxy->server_id_hdr_len);
1614 p.n = ist2(trash.area, fconn->proxy->server_id_hdr_len+5);
1615 p.v = ist(srv->id);
1616
1617 if (!fcgi_encode_param(&outbuf, &p)) {
1618 if (b_space_wraps(mbuf))
1619 goto realign_again;
1620 if (outbuf.data == 8)
1621 goto full;
1622 }
1623 }
Christopher Faulet99eff652019-08-11 23:11:30 +02001624 goto done;
1625
1626 default:
1627 break;
1628 }
1629 total += size;
1630 blk = htx_remove_blk(htx, blk);
1631 }
1632
1633 done:
1634 if (!fcgi_set_default_param(fconn, fstrm, htx, sl, &params))
1635 goto error;
1636
1637 if (!fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_CGI_GATEWAY) ||
1638 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_DOC_ROOT) ||
1639 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SCRIPT_NAME) ||
1640 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_PATH_INFO) ||
1641 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REQ_URI) ||
1642 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REQ_METH) ||
1643 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REQ_QS) ||
1644 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SRV_NAME) ||
1645 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SRV_PORT) ||
1646 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SRV_PROTO) ||
1647 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REM_ADDR) ||
1648 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_REM_PORT) ||
1649 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_SCRIPT_FILE) ||
1650 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_PATH_TRANS) ||
1651 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_CONT_LEN) ||
1652 !fcgi_encode_default_param(fconn, fstrm, &params, &outbuf, FCGI_SP_HTTPS))
1653 goto error;
1654
1655 /* update the record's size */
1656 fcgi_set_record_size(outbuf.area, outbuf.data - 8);
1657 b_add(mbuf, outbuf.data);
1658
1659 end:
1660 return total;
1661 full:
1662 if ((mbuf = br_tail_add(fconn->mbuf)) != NULL)
1663 goto retry;
1664 fconn->flags |= FCGI_CF_MUX_MFULL;
1665 fstrm->flags |= FCGI_SF_BLK_MROOM;
1666 if (total)
1667 goto error;
1668 goto end;
1669
1670 error:
1671 htx->flags |= HTX_FL_PROCESSING_ERROR;
1672 fcgi_strm_error(fstrm);
1673 goto end;
1674}
1675
1676/* Sends a STDIN record. Returns > 0 on success, 0 if it couldn't do
1677 * anything. STDIN records contain the request body.
1678 */
1679static size_t fcgi_strm_send_stdin(struct fcgi_conn *fconn, struct fcgi_strm *fstrm,
1680 struct htx *htx, size_t count, struct buffer *buf)
1681{
1682 struct buffer outbuf;
1683 struct buffer *mbuf;
1684 struct htx_blk *blk;
1685 enum htx_blk_type type;
1686 uint32_t size;
1687 size_t total = 0;
1688
1689 if (!count)
1690 goto end;
1691
1692 mbuf = br_tail(fconn->mbuf);
1693 retry:
1694 if (!fcgi_get_buf(fconn, mbuf)) {
1695 fconn->flags |= FCGI_CF_MUX_MALLOC;
1696 fconn->flags |= FCGI_CF_DEM_MROOM;
1697 return 0;
1698 }
1699
1700 /* Perform some optimizations to reduce the number of buffer copies.
1701 * First, if the mux's buffer is empty and the htx area contains exactly
1702 * one data block of the same size as the requested count, and this
1703 * count fits within the record size, then it's possible to simply swap
1704 * the caller's buffer with the mux's output buffer and adjust offsets
1705 * and length to match the entire DATA HTX block in the middle. In this
1706 * case we perform a true zero-copy operation from end-to-end. This is
1707 * the situation that happens all the time with large files. Second, if
1708 * this is not possible, but the mux's output buffer is empty, we still
1709 * have an opportunity to avoid the copy to the intermediary buffer, by
1710 * making the intermediary buffer's area point to the output buffer's
1711 * area. In this case we want to skip the HTX header to make sure that
1712 * copies remain aligned and that this operation remains possible all
1713 * the time. This goes for headers, data blocks and any data extracted
1714 * from the HTX blocks.
1715 */
1716 blk = htx_get_head_blk(htx);
1717 if (!blk)
1718 goto end;
1719 type = htx_get_blk_type(blk);
1720 size = htx_get_blksz(blk);
1721 if (unlikely(size == count && htx_nbblks(htx) == 1 && type == HTX_BLK_DATA)) {
1722 void *old_area = mbuf->area;
1723
1724 if (b_data(mbuf)) {
1725 /* Too bad there are data left there. We're willing to memcpy/memmove
1726 * up to 1/4 of the buffer, which means that it's OK to copy a large
1727 * record into a buffer containing few data if it needs to be realigned,
1728 * and that it's also OK to copy few data without realigning. Otherwise
1729 * we'll pretend the mbuf is full and wait for it to become empty.
1730 */
1731 if (size + 8 <= b_room(mbuf) &&
1732 (b_data(mbuf) <= b_size(mbuf) / 4 ||
1733 (size <= b_size(mbuf) / 4 && size + 8 <= b_contig_space(mbuf))))
1734 goto copy;
1735
1736 if ((mbuf = br_tail_add(fconn->mbuf)) != NULL)
1737 goto retry;
1738
1739 fconn->flags |= FCGI_CF_MUX_MFULL;
1740 fstrm->flags |= FCGI_SF_BLK_MROOM;
1741 goto end;
1742 }
1743
1744 /* map a FCGI record to the HTX block so that we can put the
1745 * record header there.
1746 */
1747 *mbuf = b_make(buf->area, buf->size, sizeof(struct htx) + blk->addr - 8, size + 8);
1748 outbuf.area = b_head(mbuf);
1749
1750 /* prepend a FCGI record header just before the DATA block */
1751 memcpy(outbuf.area, "\x01\x05\x00\x00\x00\x00\x00\x00", 8);
1752 fcgi_set_record_id(outbuf.area, fstrm->id);
1753 fcgi_set_record_size(outbuf.area, size);
1754
1755 /* and exchange with our old area */
1756 buf->area = old_area;
1757 buf->data = buf->head = 0;
1758 total += size;
1759 goto end;
1760 }
1761
1762 copy:
1763 while (1) {
1764 outbuf = b_make(b_tail(mbuf), b_contig_space(mbuf), 0, 0);
1765 if (outbuf.size >= 8 || !b_space_wraps(mbuf))
1766 break;
1767 realign_again:
1768 b_slow_realign(mbuf, trash.area, b_data(mbuf));
1769 }
1770
1771 if (outbuf.size < 8)
1772 goto full;
1773
1774 /* vsn: 1(FCGI_VERSION), type: (5)FCGI_STDIN, id: fstrm->id,
1775 * len: 0x0000 (fill later), padding: 0x00, rsv: 0x00 */
1776 memcpy(outbuf.area, "\x01\x05\x00\x00\x00\x00\x00\x00", 8);
1777 fcgi_set_record_id(outbuf.area, fstrm->id);
1778 outbuf.data = 8;
1779
1780 blk = htx_get_head_blk(htx);
1781 while (blk && count) {
1782 enum htx_blk_type type = htx_get_blk_type(blk);
1783 uint32_t size = htx_get_blksz(blk);
1784 struct ist v;
1785
1786 switch (type) {
1787 case HTX_BLK_DATA:
1788 v = htx_get_blk_value(htx, blk);
1789 if (v.len > count)
1790 v.len = count;
1791
1792 if (v.len > b_room(&outbuf)) {
1793 /* It doesn't fit at once. If it at least fits once split and
1794 * the amount of data to move is low, let's defragment the
1795 * buffer now.
1796 */
1797 if (b_space_wraps(mbuf) &&
1798 b_data(&outbuf) + v.len <= b_room(mbuf) &&
1799 b_data(mbuf) <= MAX_DATA_REALIGN)
1800 goto realign_again;
1801 v.len = b_room(&outbuf);
1802 }
1803 if (!v.len || !chunk_memcat(&outbuf, v.ptr, v.len)) {
1804 if (outbuf.data == 8)
1805 goto full;
1806 goto done;
1807 }
1808 if (v.len != size) {
1809 total += v.len;
1810 count -= v.len;
1811 htx_cut_data_blk(htx, blk, v.len);
1812 goto done;
1813 }
1814 break;
1815
1816 case HTX_BLK_EOM:
1817 goto done;
1818
1819 default:
1820 break;
1821 }
1822 total += size;
1823 count -= size;
1824 blk = htx_remove_blk(htx, blk);
1825 }
1826
1827 done:
1828 /* update the record's size */
1829 fcgi_set_record_size(outbuf.area, outbuf.data - 8);
1830 b_add(mbuf, outbuf.data);
1831
1832 end:
1833 return total;
1834 full:
1835 if ((mbuf = br_tail_add(fconn->mbuf)) != NULL)
1836 goto retry;
1837 fconn->flags |= FCGI_CF_MUX_MFULL;
1838 fstrm->flags |= FCGI_SF_BLK_MROOM;
1839 goto end;
1840}
1841
1842/* Processes a STDOUT record. Returns > 0 on success, 0 if it couldn't do
1843 * anything. STDOUT records contain the entire response. All the content is
1844 * copied in the stream's rxbuf. The parsing will be handled in fcgi_rcv_buf().
1845 */
1846static int fcgi_strm_handle_stdout(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1847{
1848 struct buffer *dbuf;
1849 size_t ret;
1850 size_t max;
1851
1852 dbuf = &fconn->dbuf;
1853
1854 /* Only padding remains */
1855 if (fconn->state == FCGI_CS_RECORD_P)
1856 goto end_transfer;
1857
1858 if (b_data(dbuf) < (fconn->drl + fconn->drp) &&
1859 b_size(dbuf) > (fconn->drl + fconn->drp) &&
1860 buf_room_for_htx_data(dbuf))
1861 goto fail; // incomplete record
1862
1863 if (!fcgi_get_buf(fconn, &fstrm->rxbuf)) {
1864 fconn->flags |= FCGI_CF_DEM_SALLOC;
1865 return 0;
1866 }
1867
1868 /*max = MIN(b_room(&fstrm->rxbuf), fconn->drl);*/
1869 max = buf_room_for_htx_data(&fstrm->rxbuf);
1870 if (!b_data(&fstrm->rxbuf))
1871 fstrm->rxbuf.head = sizeof(struct htx);
1872 if (max > fconn->drl)
1873 max = fconn->drl;
1874
1875 ret = b_xfer(&fstrm->rxbuf, dbuf, max);
1876 if (!ret)
1877 goto fail;
1878 fconn->drl -= ret;
1879
1880 if (!buf_room_for_htx_data(&fstrm->rxbuf))
1881 fconn->flags |= FCGI_CF_DEM_SFULL;
1882
1883 if (fconn->drl)
1884 goto fail;
1885
1886 end_transfer:
1887 fconn->drl += fconn->drp;
1888 fconn->drp = 0;
1889 ret = MIN(b_data(&fconn->dbuf), fconn->drl);
1890 b_del(&fconn->dbuf, ret);
1891 fconn->drl -= ret;
1892 if (fconn->drl)
1893 goto fail;
1894
1895 fconn->state = FCGI_CS_RECORD_H;
1896 return 1;
1897 fail:
1898 return 0;
1899}
1900
1901
1902/* Processes an empty STDOUT. Returns > 0 on success, 0 if it couldn't do
1903 * anything. It only skip the padding in fact, there is no payload for such
1904 * records. It makrs the end of the response.
1905 */
1906static int fcgi_strm_handle_empty_stdout(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1907{
1908 int ret;
1909
1910 fconn->state = FCGI_CS_RECORD_P;
1911 fconn->drl += fconn->drp;
1912 fconn->drp = 0;
1913 ret = MIN(b_data(&fconn->dbuf), fconn->drl);
1914 b_del(&fconn->dbuf, ret);
1915 fconn->drl -= ret;
1916 if (fconn->drl)
1917 return 0;
1918 fconn->state = FCGI_CS_RECORD_H;
1919 fstrm->state |= FCGI_SF_ES_RCVD;
1920 return 1;
1921}
1922
1923/* Processes a STDERR record. Returns > 0 on success, 0 if it couldn't do
1924 * anything.
1925 */
1926static int fcgi_strm_handle_stderr(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1927{
1928 struct buffer *dbuf;
1929 struct buffer tag;
1930 size_t ret;
1931
1932 dbuf = &fconn->dbuf;
1933
1934 /* Only padding remains */
1935 if (fconn->state == FCGI_CS_RECORD_P)
1936 goto end_transfer;
1937
1938 if (b_data(dbuf) < (fconn->drl + fconn->drp) &&
1939 b_size(dbuf) > (fconn->drl + fconn->drp) &&
1940 buf_room_for_htx_data(dbuf))
1941 goto fail; // incomplete record
1942
1943 chunk_reset(&trash);
1944 ret = b_xfer(&trash, dbuf, MIN(b_room(&trash), fconn->drl));
1945 if (!ret)
1946 goto fail;
1947 fconn->drl -= ret;
1948
1949 trash.area[ret] = '\n';
1950 trash.area[ret+1] = '\0';
1951 tag.area = fconn->app->name; tag.data = strlen(fconn->app->name);
Christopher Fauletc45791a2019-09-24 14:30:46 +02001952 app_log(&fconn->app->logsrvs, &tag, LOG_ERR, "%s", trash.area);
Christopher Faulet99eff652019-08-11 23:11:30 +02001953
1954 if (fconn->drl)
1955 goto fail;
1956
1957 end_transfer:
1958 fconn->drl += fconn->drp;
1959 fconn->drp = 0;
1960 ret = MIN(b_data(&fconn->dbuf), fconn->drl);
1961 b_del(&fconn->dbuf, ret);
1962 fconn->drl -= ret;
1963 if (fconn->drl)
1964 goto fail;
1965 fconn->state = FCGI_CS_RECORD_H;
1966 return 1;
1967 fail:
1968 return 0;
1969}
1970
1971/* Processes an END_REQUEST record. Returns > 0 on success, 0 if it couldn't do
1972 * anything. If the empty STDOUT record is not already received, this one marks
1973 * the end of the response. It is highly unexpected, but if the record is larger
1974 * than a buffer and cannot be decoded in one time, an error is triggered and
1975 * the connection is closed. END_REQUEST record cannot be split.
1976 */
1977static int fcgi_strm_handle_end_request(struct fcgi_conn *fconn, struct fcgi_strm *fstrm)
1978{
1979 struct buffer inbuf;
1980 struct buffer *dbuf;
1981 struct fcgi_end_request endreq;
1982
1983 dbuf = &fconn->dbuf;
1984
1985 /* Record too large to be fully decoded */
1986 if (b_size(dbuf) < (fconn->drl + fconn->drp))
1987 goto fail;
1988
1989 /* process full record only */
1990 if (b_data(dbuf) < (fconn->drl + fconn->drp))
1991 return 0;
1992
1993 if (unlikely(b_contig_data(dbuf, b_head_ofs(dbuf)) < fconn->drl)) {
1994 /* Realign the dmux buffer if the record wraps. It is unexpected
1995 * at this stage because it should be the first record received
1996 * from the FCGI application.
1997 */
1998 b_slow_realign(dbuf, trash.area, 0);
1999 }
2000
2001 inbuf = b_make(b_head(dbuf), b_data(dbuf), 0, fconn->drl);
2002
2003 if (!fcgi_decode_end_request(&inbuf, 0, &endreq))
2004 goto fail;
2005
2006 fstrm->flags |= FCGI_SF_ES_RCVD;
2007 fstrm->proto_status = endreq.errcode;
2008 fcgi_strm_close(fstrm);
2009
2010 b_del(&fconn->dbuf, fconn->drl + fconn->drp);
2011 fconn->drl = 0;
2012 fconn->drp = 0;
2013 fconn->state = FCGI_CS_RECORD_H;
2014 return 1;
2015
2016 fail:
2017 fcgi_strm_error(fstrm);
2018 return 0;
2019}
2020
2021/* process Rx records to be demultiplexed */
2022static void fcgi_process_demux(struct fcgi_conn *fconn)
2023{
2024 struct fcgi_strm *fstrm = NULL, *tmp_fstrm;
2025 struct fcgi_header hdr;
2026 int ret;
2027
2028 if (fconn->state == FCGI_CS_CLOSED)
2029 return;
2030
2031 if (unlikely(fconn->state < FCGI_CS_RECORD_H)) {
2032 if (fconn->state == FCGI_CS_INIT)
2033 return;
2034 if (fconn->state == FCGI_CS_SETTINGS) {
2035 /* ensure that what is pending is a valid GET_VALUES_RESULT record. */
2036 ret = fcgi_decode_record_hdr(&fconn->dbuf, 0, &hdr);
2037 if (!ret)
2038 goto fail;
2039 b_del(&fconn->dbuf, ret);
2040
2041 if (hdr.id || (hdr.type != FCGI_GET_VALUES_RESULT && hdr.type != FCGI_UNKNOWN_TYPE)) {
2042 fconn->state = FCGI_CS_CLOSED;
2043 goto fail;
2044 }
2045 goto new_record;
2046 }
2047 }
2048
2049 /* process as many incoming frames as possible below */
2050 while (b_data(&fconn->dbuf)) {
2051
2052 if (fconn->state == FCGI_CS_CLOSED)
2053 break;
2054
2055 if (fconn->state == FCGI_CS_RECORD_H) {
2056 ret = fcgi_decode_record_hdr(&fconn->dbuf, 0, &hdr);
2057 if (!ret)
2058 break;
2059 b_del(&fconn->dbuf, ret);
2060
2061 new_record:
2062 fconn->dsi = hdr.id;
2063 fconn->drt = hdr.type;
2064 fconn->drl = hdr.len;
2065 fconn->drp = hdr.padding;
2066 fconn->state = FCGI_CS_RECORD_D;
2067 }
2068
2069 /* Only FCGI_CS_RECORD_D or FCGI_CS_RECORD_P */
2070 tmp_fstrm = fcgi_conn_st_by_id(fconn, fconn->dsi);
2071
2072 if (tmp_fstrm != fstrm && fstrm && fstrm->cs &&
2073 (b_data(&fstrm->rxbuf) ||
2074 conn_xprt_read0_pending(fconn->conn) ||
2075 fstrm->state == FCGI_SS_CLOSED ||
2076 (fstrm->flags & FCGI_SF_ES_RCVD) ||
2077 (fstrm->cs->flags & (CS_FL_ERROR|CS_FL_ERR_PENDING|CS_FL_EOS)))) {
2078 /* we may have to signal the upper layers */
2079 fstrm->cs->flags |= CS_FL_RCV_MORE;
2080 fcgi_strm_notify_recv(fstrm);
2081 }
2082 fstrm = tmp_fstrm;
2083
2084 if (fstrm->state == FCGI_SS_CLOSED && fconn->dsi != 0) {
2085 /* ignore all record for closed streams */
2086 goto ignore_record;
2087 }
2088 if (fstrm->state == FCGI_SS_IDLE) {
2089 /* ignore all record for unknown streams */
2090 goto ignore_record;
2091 }
2092
2093 switch (fconn->drt) {
2094 case FCGI_GET_VALUES_RESULT:
2095 ret = fcgi_conn_handle_values_result(fconn);
2096 break;
2097
2098 case FCGI_STDOUT:
2099 if (fstrm->flags & FCGI_SF_ES_RCVD)
2100 goto ignore_record;
2101
2102 if (fconn->drl)
2103 ret = fcgi_strm_handle_stdout(fconn, fstrm);
2104 else
2105 ret = fcgi_strm_handle_empty_stdout(fconn, fstrm);
2106 break;
2107
2108 case FCGI_STDERR:
2109 ret = fcgi_strm_handle_stderr(fconn, fstrm);
2110 break;
2111
2112 case FCGI_END_REQUEST:
2113 ret = fcgi_strm_handle_end_request(fconn, fstrm);
2114 break;
2115
2116 /* implement all extra frame types here */
2117 default:
2118 ignore_record:
2119 /* drop records that we ignore. They may be
2120 * larger than the buffer so we drain all of
2121 * their contents until we reach the end.
2122 */
2123 fconn->state = FCGI_CS_RECORD_P;
2124 fconn->drl += fconn->drp;
2125 fconn->drp = 0;
2126 ret = MIN(b_data(&fconn->dbuf), fconn->drl);
2127 b_del(&fconn->dbuf, ret);
2128 fconn->drl -= ret;
2129 ret = (fconn->drl == 0);
2130 }
2131
2132 /* error or missing data condition met above ? */
2133 if (ret <= 0)
2134 break;
2135
2136 if (fconn->state != FCGI_CS_RECORD_H && !(fconn->drl+fconn->drp))
2137 fconn->state = FCGI_CS_RECORD_H;
2138 }
2139
2140 fail:
2141 /* we can go here on missing data, blocked response or error */
2142 if (fstrm && fstrm->cs &&
2143 (b_data(&fstrm->rxbuf) ||
2144 conn_xprt_read0_pending(fconn->conn) ||
2145 fstrm->state == FCGI_SS_CLOSED ||
2146 (fstrm->flags & FCGI_SF_ES_RCVD) ||
2147 (fstrm->cs->flags & (CS_FL_ERROR|CS_FL_ERR_PENDING|CS_FL_EOS)))) {
2148 /* we may have to signal the upper layers */
2149 fstrm->cs->flags |= CS_FL_RCV_MORE;
2150 fcgi_strm_notify_recv(fstrm);
2151 }
2152
2153 fcgi_conn_restart_reading(fconn, 0);
2154}
2155
2156/* process Tx records from streams to be multiplexed. Returns > 0 if it reached
2157 * the end.
2158 */
2159static int fcgi_process_mux(struct fcgi_conn *fconn)
2160{
2161 struct fcgi_strm *fstrm, *fstrm_back;
2162
2163 if (unlikely(fconn->state < FCGI_CS_RECORD_H)) {
2164 if (unlikely(fconn->state == FCGI_CS_INIT)) {
2165 if (!(fconn->flags & FCGI_CF_GET_VALUES)) {
2166 fconn->state = FCGI_CS_RECORD_H;
2167 fcgi_wake_unassigned_streams(fconn);
2168 goto mux;
2169 }
2170 if (unlikely(!fcgi_conn_send_get_values(fconn)))
2171 goto fail;
2172 fconn->state = FCGI_CS_SETTINGS;
2173 }
2174 /* need to wait for the other side */
2175 if (fconn->state < FCGI_CS_RECORD_H)
2176 return 1;
2177 }
2178
2179 mux:
2180 list_for_each_entry_safe(fstrm, fstrm_back, &fconn->send_list, send_list) {
2181 if (fconn->state == FCGI_CS_CLOSED || fconn->flags & FCGI_CF_MUX_BLOCK_ANY)
2182 break;
2183
2184 if (LIST_ADDED(&fstrm->sending_list))
2185 continue;
2186
2187 /* For some reason, the upper layer failed to subsribe again,
2188 * so remove it from the send_list
2189 */
2190 if (!fstrm->send_wait) {
2191 LIST_DEL_INIT(&fstrm->send_list);
2192 continue;
2193 }
2194 fstrm->flags &= ~FCGI_SF_BLK_ANY;
2195 fstrm->send_wait->events &= ~SUB_RETRY_SEND;
2196 LIST_ADDQ(&fconn->sending_list, &fstrm->sending_list);
2197 tasklet_wakeup(fstrm->send_wait->tasklet);
2198 }
2199
2200 fail:
2201 if (fconn->state == FCGI_CS_CLOSED) {
2202 if (fconn->stream_cnt - fconn->nb_reserved > 0) {
2203 fcgi_conn_send_aborts(fconn);
2204 if (fconn->flags & FCGI_CF_MUX_BLOCK_ANY)
2205 return 0;
2206 }
2207 }
2208 return 1;
2209}
2210
2211
2212/* Attempt to read data, and subscribe if none available.
2213 * The function returns 1 if data has been received, otherwise zero.
2214 */
2215static int fcgi_recv(struct fcgi_conn *fconn)
2216{
2217 struct connection *conn = fconn->conn;
2218 struct buffer *buf;
2219 int max;
2220 size_t ret;
2221
2222 if (fconn->wait_event.events & SUB_RETRY_RECV)
2223 return (b_data(&fconn->dbuf));
2224
2225 if (!fcgi_recv_allowed(fconn))
2226 return 1;
2227
2228 buf = fcgi_get_buf(fconn, &fconn->dbuf);
2229 if (!buf) {
2230 fconn->flags |= FCGI_CF_DEM_DALLOC;
2231 return 0;
2232 }
2233
2234 b_realign_if_empty(buf);
2235 if (!b_data(buf)) {
2236 /* try to pre-align the buffer like the
2237 * rxbufs will be to optimize memory copies. We'll make
2238 * sure that the frame header lands at the end of the
2239 * HTX block to alias it upon recv. We cannot use the
2240 * head because rcv_buf() will realign the buffer if
2241 * it's empty. Thus we cheat and pretend we already
2242 * have a few bytes there.
2243 */
2244 max = buf_room_for_htx_data(buf) + (fconn->state == FCGI_CS_RECORD_H ? 8 : 0);
2245 buf->head = sizeof(struct htx) - (fconn->state == FCGI_CS_RECORD_H ? 8 : 0);
2246 }
2247 else
2248 max = buf_room_for_htx_data(buf);
2249
2250 ret = max ? conn->xprt->rcv_buf(conn, conn->xprt_ctx, buf, max, 0) : 0;
2251
2252 if (max && !ret && fcgi_recv_allowed(fconn))
2253 conn->xprt->subscribe(conn, conn->xprt_ctx, SUB_RETRY_RECV, &fconn->wait_event);
2254
2255 if (!b_data(buf)) {
2256 fcgi_release_buf(fconn, &fconn->dbuf);
2257 return (conn->flags & CO_FL_ERROR || conn_xprt_read0_pending(conn));
2258 }
2259
2260 if (ret == max)
2261 fconn->flags |= FCGI_CF_DEM_DFULL;
2262
2263 return !!ret || (conn->flags & CO_FL_ERROR) || conn_xprt_read0_pending(conn);
2264}
2265
2266
2267/* Try to send data if possible.
2268 * The function returns 1 if data have been sent, otherwise zero.
2269 */
2270static int fcgi_send(struct fcgi_conn *fconn)
2271{
2272 struct connection *conn = fconn->conn;
2273 int done;
2274 int sent = 0;
2275
2276 if (conn->flags & CO_FL_ERROR)
2277 return 1;
2278
2279
2280 if (conn->flags & (CO_FL_HANDSHAKE|CO_FL_WAIT_L4_CONN|CO_FL_WAIT_L6_CONN)) {
2281 /* a handshake was requested */
2282 goto schedule;
2283 }
2284
2285 /* This loop is quite simple : it tries to fill as much as it can from
2286 * pending streams into the existing buffer until it's reportedly full
2287 * or the end of send requests is reached. Then it tries to send this
2288 * buffer's contents out, marks it not full if at least one byte could
2289 * be sent, and tries again.
2290 *
2291 * The snd_buf() function normally takes a "flags" argument which may
2292 * be made of a combination of CO_SFL_MSG_MORE to indicate that more
2293 * data immediately comes and CO_SFL_STREAMER to indicate that the
2294 * connection is streaming lots of data (used to increase TLS record
2295 * size at the expense of latency). The former can be sent any time
2296 * there's a buffer full flag, as it indicates at least one stream
2297 * attempted to send and failed so there are pending data. An
2298 * alternative would be to set it as long as there's an active stream
2299 * but that would be problematic for ACKs until we have an absolute
2300 * guarantee that all waiters have at least one byte to send. The
2301 * latter should possibly not be set for now.
2302 */
2303
2304 done = 0;
2305 while (!done) {
2306 unsigned int flags = 0;
2307 unsigned int released = 0;
2308 struct buffer *buf;
2309
2310 /* fill as much as we can into the current buffer */
2311 while (((fconn->flags & (FCGI_CF_MUX_MFULL|FCGI_CF_MUX_MALLOC)) == 0) && !done)
2312 done = fcgi_process_mux(fconn);
2313
2314 if (fconn->flags & FCGI_CF_MUX_MALLOC)
2315 done = 1; // we won't go further without extra buffers
2316
2317 if (conn->flags & CO_FL_ERROR)
2318 break;
2319
2320 if (fconn->flags & (FCGI_CF_MUX_MFULL | FCGI_CF_DEM_MROOM))
2321 flags |= CO_SFL_MSG_MORE;
2322
2323 for (buf = br_head(fconn->mbuf); b_size(buf); buf = br_del_head(fconn->mbuf)) {
2324 if (b_data(buf)) {
2325 int ret;
2326
2327 ret = conn->xprt->snd_buf(conn, conn->xprt_ctx, buf, b_data(buf), flags);
2328 if (!ret) {
2329 done = 1;
2330 break;
2331 }
2332 sent = 1;
2333 b_del(buf, ret);
2334 if (b_data(buf)) {
2335 done = 1;
2336 break;
2337 }
2338 }
2339 b_free(buf);
2340 released++;
2341 }
2342
2343 if (released)
2344 offer_buffers(NULL, tasks_run_queue);
2345
2346 /* wrote at least one byte, the buffer is not full anymore */
2347 fconn->flags &= ~(FCGI_CF_MUX_MFULL | FCGI_CF_DEM_MROOM);
2348 }
2349
2350 if (conn->flags & CO_FL_SOCK_WR_SH) {
2351 /* output closed, nothing to send, clear the buffer to release it */
2352 b_reset(br_tail(fconn->mbuf));
2353 }
2354 /* We're not full anymore, so we can wake any task that are waiting
2355 * for us.
2356 */
2357 if (!(fconn->flags & (FCGI_CF_MUX_MFULL | FCGI_CF_DEM_MROOM))) {
2358 struct fcgi_strm *fstrm;
2359
2360 list_for_each_entry(fstrm, &fconn->send_list, send_list) {
2361 if (fconn->state == FCGI_CS_CLOSED || fconn->flags & FCGI_CF_MUX_BLOCK_ANY)
2362 break;
2363
2364 if (LIST_ADDED(&fstrm->sending_list))
2365 continue;
2366
2367 /* For some reason, the upper layer failed to subsribe again,
2368 * so remove it from the send_list
2369 */
2370 if (!fstrm->send_wait) {
2371 LIST_DEL_INIT(&fstrm->send_list);
2372 continue;
2373 }
2374 fstrm->flags &= ~FCGI_SF_BLK_ANY;
2375 fstrm->send_wait->events &= ~SUB_RETRY_SEND;
2376 tasklet_wakeup(fstrm->send_wait->tasklet);
2377 LIST_ADDQ(&fconn->sending_list, &fstrm->sending_list);
2378 }
2379 }
2380 /* We're done, no more to send */
2381 if (!br_data(fconn->mbuf))
2382 return sent;
2383schedule:
2384 if (!(conn->flags & CO_FL_ERROR) && !(fconn->wait_event.events & SUB_RETRY_SEND))
2385 conn->xprt->subscribe(conn, conn->xprt_ctx, SUB_RETRY_SEND, &fconn->wait_event);
2386
2387 return sent;
2388}
2389
2390/* this is the tasklet referenced in fconn->wait_event.tasklet */
2391static struct task *fcgi_io_cb(struct task *t, void *ctx, unsigned short status)
2392{
2393 struct fcgi_conn *fconn = ctx;
2394 int ret = 0;
2395
2396 if (!(fconn->wait_event.events & SUB_RETRY_SEND))
2397 ret = fcgi_send(fconn);
2398 if (!(fconn->wait_event.events & SUB_RETRY_RECV))
2399 ret |= fcgi_recv(fconn);
2400 if (ret || b_data(&fconn->dbuf))
2401 fcgi_process(fconn);
2402 return NULL;
2403}
2404
2405/* callback called on any event by the connection handler.
2406 * It applies changes and returns zero, or < 0 if it wants immediate
2407 * destruction of the connection (which normally doesn not happen in FCGI).
2408 */
2409static int fcgi_process(struct fcgi_conn *fconn)
2410{
2411 struct connection *conn = fconn->conn;
2412
2413 if (b_data(&fconn->dbuf) && !(fconn->flags & FCGI_CF_DEM_BLOCK_ANY)) {
2414 fcgi_process_demux(fconn);
2415
2416 if (fconn->state == FCGI_CS_CLOSED || conn->flags & CO_FL_ERROR)
2417 b_reset(&fconn->dbuf);
2418
2419 if (buf_room_for_htx_data(&fconn->dbuf))
2420 fconn->flags &= ~FCGI_CF_DEM_DFULL;
2421 }
2422 fcgi_send(fconn);
2423
2424 if (unlikely(fconn->proxy->state == PR_STSTOPPED)) {
2425 /* frontend is stopping, reload likely in progress, let's try
2426 * to announce a graceful shutdown if not yet done. We don't
2427 * care if it fails, it will be tried again later.
2428 */
2429 if (!(fconn->flags & (FCGI_CF_ABRTS_SENT|FCGI_CF_ABRTS_FAILED))) {
2430 if (fconn->stream_cnt - fconn->nb_reserved > 0)
2431 fcgi_conn_send_aborts(fconn);
2432 }
2433 }
2434
2435 /*
2436 * If we received early data, and the handshake is done, wake
2437 * any stream that was waiting for it.
2438 */
2439 if (!(fconn->flags & FCGI_CF_WAIT_FOR_HS) &&
2440 (conn->flags & (CO_FL_EARLY_SSL_HS | CO_FL_HANDSHAKE | CO_FL_EARLY_DATA)) == CO_FL_EARLY_DATA) {
2441 struct eb32_node *node;
2442 struct fcgi_strm *fstrm;
2443
2444 fconn->flags |= FCGI_CF_WAIT_FOR_HS;
2445 node = eb32_lookup_ge(&fconn->streams_by_id, 1);
2446
2447 while (node) {
2448 fstrm = container_of(node, struct fcgi_strm, by_id);
2449 if (fstrm->cs && fstrm->cs->flags & CS_FL_WAIT_FOR_HS)
2450 fcgi_strm_notify_recv(fstrm);
2451 node = eb32_next(node);
2452 }
2453 }
2454
2455 if ((conn->flags & CO_FL_ERROR) || conn_xprt_read0_pending(conn) ||
2456 fconn->state == FCGI_CS_CLOSED || (fconn->flags & FCGI_CF_ABRTS_FAILED) ||
2457 eb_is_empty(&fconn->streams_by_id)) {
2458 fcgi_wake_some_streams(fconn, 0);
2459
2460 if (eb_is_empty(&fconn->streams_by_id)) {
2461 /* no more stream, kill the connection now */
2462 fcgi_release(fconn);
2463 return -1;
2464 }
2465 }
2466
2467 if (!b_data(&fconn->dbuf))
2468 fcgi_release_buf(fconn, &fconn->dbuf);
2469
2470 if ((conn->flags & CO_FL_SOCK_WR_SH) ||
2471 fconn->state == FCGI_CS_CLOSED || (fconn->flags & FCGI_CF_ABRTS_FAILED) ||
2472 (!br_data(fconn->mbuf) && ((fconn->flags & FCGI_CF_MUX_BLOCK_ANY) || LIST_ISEMPTY(&fconn->send_list))))
2473 fcgi_release_mbuf(fconn);
2474
2475 if (fconn->task) {
2476 fconn->task->expire = tick_add(now_ms, (fconn->state == FCGI_CS_CLOSED ? fconn->shut_timeout : fconn->timeout));
2477 task_queue(fconn->task);
2478 }
2479
2480 fcgi_send(fconn);
2481 return 0;
2482}
2483
2484
2485/* wake-up function called by the connection layer (mux_ops.wake) */
2486static int fcgi_wake(struct connection *conn)
2487{
2488 struct fcgi_conn *fconn = conn->ctx;
2489
2490 return (fcgi_process(fconn));
2491}
2492
2493/* Connection timeout management. The principle is that if there's no receipt
2494 * nor sending for a certain amount of time, the connection is closed. If the
2495 * MUX buffer still has lying data or is not allocatable, the connection is
2496 * immediately killed. If it's allocatable and empty, we attempt to send a
2497 * GOAWAY frame.
2498 */
2499static struct task *fcgi_timeout_task(struct task *t, void *context, unsigned short state)
2500{
2501 struct fcgi_conn *fconn = context;
2502 int expired = tick_is_expired(t->expire, now_ms);
2503
2504 if (!expired && fconn)
2505 return t;
2506
2507 task_destroy(t);
2508
2509 if (!fconn) {
2510 /* resources were already deleted */
2511 return NULL;
2512 }
2513
2514 fconn->task = NULL;
2515 fconn->state = FCGI_CS_CLOSED;
2516 fcgi_wake_some_streams(fconn, 0);
2517
2518 if (br_data(fconn->mbuf)) {
2519 /* don't even try to send aborts, the buffer is stuck */
2520 fconn->flags |= FCGI_CF_ABRTS_FAILED;
2521 goto end;
2522 }
2523
2524 /* try to send but no need to insist */
2525 if (!fcgi_conn_send_aborts(fconn))
2526 fconn->flags |= FCGI_CF_ABRTS_FAILED;
2527
2528 if (br_data(fconn->mbuf) && !(fconn->flags & FCGI_CF_ABRTS_FAILED) &&
2529 conn_xprt_ready(fconn->conn)) {
2530 unsigned int released = 0;
2531 struct buffer *buf;
2532
2533 for (buf = br_head(fconn->mbuf); b_size(buf); buf = br_del_head(fconn->mbuf)) {
2534 if (b_data(buf)) {
2535 int ret = fconn->conn->xprt->snd_buf(fconn->conn, fconn->conn->xprt_ctx,
2536 buf, b_data(buf), 0);
2537 if (!ret)
2538 break;
2539 b_del(buf, ret);
2540 if (b_data(buf))
2541 break;
2542 b_free(buf);
2543 released++;
2544 }
2545 }
2546
2547 if (released)
2548 offer_buffers(NULL, tasks_run_queue);
2549 }
2550
2551 end:
2552 /* either we can release everything now or it will be done later once
2553 * the last stream closes.
2554 */
2555 if (eb_is_empty(&fconn->streams_by_id))
2556 fcgi_release(fconn);
2557
2558 return NULL;
2559}
2560
2561
2562/*******************************************/
2563/* functions below are used by the streams */
2564/*******************************************/
2565
2566/* Append the description of what is present in error snapshot <es> into <out>.
2567 * The description must be small enough to always fit in a buffer. The output
2568 * buffer may be the trash so the trash must not be used inside this function.
2569 */
2570static void fcgi_show_error_snapshot(struct buffer *out, const struct error_snapshot *es)
2571{
2572 chunk_appendf(out,
2573 " FCGI connection flags 0x%08x, FCGI stream flags 0x%08x\n"
2574 " H1 msg state %s(%d), H1 msg flags 0x%08x\n"
2575 " H1 chunk len %lld bytes, H1 body len %lld bytes :\n",
2576 es->ctx.h1.c_flags, es->ctx.h1.s_flags,
2577 h1m_state_str(es->ctx.h1.state), es->ctx.h1.state,
2578 es->ctx.h1.m_flags, es->ctx.h1.m_clen, es->ctx.h1.m_blen);
2579}
2580/*
2581 * Capture a bad response and archive it in the proxy's structure. By default
2582 * it tries to report the error position as h1m->err_pos. However if this one is
2583 * not set, it will then report h1m->next, which is the last known parsing
2584 * point. The function is able to deal with wrapping buffers. It always displays
2585 * buffers as a contiguous area starting at buf->p. The direction is determined
2586 * thanks to the h1m's flags.
2587 */
2588static void fcgi_strm_capture_bad_message(struct fcgi_conn *fconn, struct fcgi_strm *fstrm,
2589 struct h1m *h1m, struct buffer *buf)
2590{
2591 struct session *sess = fstrm->sess;
2592 struct proxy *proxy = fconn->proxy;
2593 struct proxy *other_end = sess->fe;
2594 union error_snapshot_ctx ctx;
2595
2596 /* http-specific part now */
2597 ctx.h1.state = h1m->state;
2598 ctx.h1.c_flags = fconn->flags;
2599 ctx.h1.s_flags = fstrm->flags;
2600 ctx.h1.m_flags = h1m->flags;
2601 ctx.h1.m_clen = h1m->curr_len;
2602 ctx.h1.m_blen = h1m->body_len;
2603
2604 proxy_capture_error(proxy, 1, other_end, fconn->conn->target, sess, buf, 0, 0,
2605 (h1m->err_pos >= 0) ? h1m->err_pos : h1m->next,
2606 &ctx, fcgi_show_error_snapshot);
2607}
2608
2609static size_t fcgi_strm_parse_headers(struct fcgi_strm *fstrm, struct h1m *h1m, struct htx *htx,
2610 struct buffer *buf, size_t *ofs, size_t max)
2611{
2612 int ret;
2613
2614 ret = h1_parse_msg_hdrs(h1m, NULL, htx, buf, *ofs, max);
2615 if (!ret) {
2616 if (htx->flags & HTX_FL_PARSING_ERROR) {
2617 fcgi_strm_error(fstrm);
2618 fcgi_strm_capture_bad_message(fstrm->fconn, fstrm, h1m, buf);
2619 }
2620 goto end;
2621 }
2622
2623 *ofs += ret;
2624 end:
2625 return ret;
2626
2627}
2628
2629static size_t fcgi_strm_parse_data(struct fcgi_strm *fstrm, struct h1m *h1m, struct htx *htx,
2630 struct buffer *buf, size_t *ofs, size_t max, struct buffer *htxbuf)
2631{
2632 int ret;
2633
2634 ret = h1_parse_msg_data(h1m, htx, buf, *ofs, max, htxbuf);
2635 if (ret <= 0) {
2636 if (htx->flags & HTX_FL_PARSING_ERROR) {
2637 fcgi_strm_error(fstrm);
2638 fcgi_strm_capture_bad_message(fstrm->fconn, fstrm, h1m, buf);
2639 }
2640 goto end;
2641 }
2642 *ofs += ret;
2643 end:
2644 return ret;
2645}
2646
2647static size_t fcgi_strm_parse_trailers(struct fcgi_strm *fstrm, struct h1m *h1m, struct htx *htx,
2648 struct buffer *buf, size_t *ofs, size_t max)
2649{
2650 int ret;
2651
2652 ret = h1_parse_msg_tlrs(h1m, htx, buf, *ofs, max);
2653 if (ret <= 0) {
2654 if (htx->flags & HTX_FL_PARSING_ERROR) {
2655 fcgi_strm_error(fstrm);
2656 fcgi_strm_capture_bad_message(fstrm->fconn, fstrm, h1m, buf);
2657 }
2658 goto end;
2659 }
2660 *ofs += ret;
2661 fstrm->flags |= FCGI_SF_HAVE_I_TLR;
2662 end:
2663 return ret;
2664}
2665
2666static size_t fcgi_strm_add_eom(struct fcgi_strm *fstrm, struct h1m *h1m, struct htx *htx,
2667 size_t max)
2668{
2669 if (max < sizeof(struct htx_blk) + 1 || !htx_add_endof(htx, HTX_BLK_EOM))
2670 return 0;
2671
2672 h1m->state = H1_MSG_DONE;
2673 return (sizeof(struct htx_blk) + 1);
2674}
2675
2676static size_t fcgi_strm_parse_response(struct fcgi_strm *fstrm, struct buffer *buf, size_t count)
2677{
2678 struct htx *htx;
2679 struct h1m *h1m = &fstrm->h1m;
2680 size_t ret, data, total = 0;
2681
2682 htx = htx_from_buf(buf);
2683 data = htx->data;
2684 if (fstrm->state == FCGI_SS_ERROR)
2685 goto end;
2686
2687 do {
2688 size_t used = htx_used_space(htx);
2689
2690 if (h1m->state <= H1_MSG_LAST_LF) {
2691 ret = fcgi_strm_parse_headers(fstrm, h1m, htx, &fstrm->rxbuf, &total, count);
2692 if (!ret)
2693 break;
2694 if ((h1m->flags & (H1_MF_VER_11|H1_MF_XFER_LEN)) == H1_MF_VER_11) {
2695 struct htx_blk *blk = htx_get_head_blk(htx);
2696 struct htx_sl *sl;
2697
2698 if (!blk)
2699 break;
2700 sl = htx_get_blk_ptr(htx, blk);
2701 sl->flags |= HTX_SL_F_XFER_LEN;
2702 htx->extra = 0;
2703 }
2704 }
2705 else if (h1m->state < H1_MSG_TRAILERS) {
2706 ret = fcgi_strm_parse_data(fstrm, h1m, htx, &fstrm->rxbuf, &total, count, buf);
2707 htx = htx_from_buf(buf);
2708 if (!ret)
2709 break;
2710 }
2711 else if (h1m->state == H1_MSG_TRAILERS) {
2712 if (!(fstrm->flags & FCGI_SF_HAVE_I_TLR)) {
2713 ret = fcgi_strm_parse_trailers(fstrm, h1m, htx, &fstrm->rxbuf, &total, count);
2714 if (!ret)
2715 break;
2716 }
2717 else if (!fcgi_strm_add_eom(fstrm, h1m, htx, count))
2718 break;
2719 }
2720 else if (h1m->state == H1_MSG_DONE) {
2721 if (b_data(&fstrm->rxbuf) > total) {
2722 htx->flags |= HTX_FL_PARSING_ERROR;
2723 fcgi_strm_error(fstrm);
2724 }
2725 break;
2726 }
2727 else if (h1m->state == H1_MSG_TUNNEL) {
2728 ret = fcgi_strm_parse_data(fstrm, h1m, htx, &fstrm->rxbuf, &total, count, buf);
2729 htx = htx_from_buf(buf);
2730 if (fstrm->state != FCGI_SS_ERROR &&
2731 (fstrm->flags & FCGI_SF_ES_RCVD) && b_data(&fstrm->rxbuf) == total) {
2732 if ((h1m->flags & (H1_MF_VER_11|H1_MF_XFER_LEN)) == H1_MF_VER_11) {
2733 if (!fcgi_strm_add_eom(fstrm, h1m, htx, count))
2734 break;
2735 }
2736 else {
2737 h1m->state = H1_MSG_DONE;
2738 break;
2739 }
2740 }
2741 if (!ret)
2742 break;
2743 }
2744 else {
2745 htx->flags |= HTX_FL_PROCESSING_ERROR;
2746 fcgi_strm_error(fstrm);
2747 break;
2748 }
2749
2750 count -= htx_used_space(htx) - used;
2751 } while (fstrm->state != FCGI_SS_ERROR/* /\*fstrm->state == FCGI_SS_OPEN && *\/count */);
2752
2753 if (fstrm->state == FCGI_SS_ERROR) {
2754 b_reset(&fstrm->rxbuf);
2755 htx_to_buf(htx, buf);
2756 return 0;
2757 }
2758
2759 b_del(&fstrm->rxbuf, total);
2760
2761 end:
2762 htx_to_buf(htx, buf);
2763 ret = htx->data - data;
2764 return ret;
2765}
2766
2767/*
2768 * Attach a new stream to a connection
2769 * (Used for outgoing connections)
2770 */
2771static struct conn_stream *fcgi_attach(struct connection *conn, struct session *sess)
2772{
2773 struct conn_stream *cs;
2774 struct fcgi_strm *fstrm;
2775 struct fcgi_conn *fconn = conn->ctx;
2776
2777 cs = cs_new(conn);
2778 if (!cs)
2779 return NULL;
2780 fstrm = fcgi_conn_stream_new(fconn, cs, sess);
2781 if (!fstrm) {
2782 cs_free(cs);
2783 return NULL;
2784 }
2785 return cs;
2786}
2787
2788/* Retrieves the first valid conn_stream from this connection, or returns NULL.
2789 * We have to scan because we may have some orphan streams. It might be
2790 * beneficial to scan backwards from the end to reduce the likeliness to find
2791 * orphans.
2792 */
2793static const struct conn_stream *fcgi_get_first_cs(const struct connection *conn)
2794{
2795 struct fcgi_conn *fconn = conn->ctx;
2796 struct fcgi_strm *fstrm;
2797 struct eb32_node *node;
2798
2799 node = eb32_first(&fconn->streams_by_id);
2800 while (node) {
2801 fstrm = container_of(node, struct fcgi_strm, by_id);
2802 if (fstrm->cs)
2803 return fstrm->cs;
2804 node = eb32_next(node);
2805 }
2806 return NULL;
2807}
2808
2809/*
2810 * Destroy the mux and the associated connection, if it is no longer used
2811 */
2812static void fcgi_destroy(void *ctx)
2813{
2814 struct fcgi_conn *fconn = ctx;
2815
2816 if (eb_is_empty(&fconn->streams_by_id) || !fconn->conn || fconn->conn->ctx != fconn)
2817 fcgi_release(fconn);
2818}
2819
2820/*
2821 * Detach the stream from the connection and possibly release the connection.
2822 */
2823static void fcgi_detach(struct conn_stream *cs)
2824{
2825 struct fcgi_strm *fstrm = cs->ctx;
2826 struct fcgi_conn *fconn;
2827 struct session *sess;
2828
2829 cs->ctx = NULL;
2830 if (!fstrm)
2831 return;
2832
2833 /* The stream is about to die, so no need to attempt to run its task */
2834 if (LIST_ADDED(&fstrm->sending_list) &&
2835 fstrm->send_wait != &fstrm->wait_event) {
2836 tasklet_remove_from_tasklet_list(fstrm->send_wait->tasklet);
2837 LIST_DEL_INIT(&fstrm->sending_list);
2838 /*
2839 * At this point, the stream_interface is supposed to have called
2840 * fcgi_unsubscribe(), so the only way there's still a
2841 * subscription that came from the stream_interface (as we
2842 * can subscribe ourself, in fcgi_do_shutw() and fcgi_do_shutr(),
2843 * without the stream_interface involved) is that we subscribed
2844 * for sending, we woke the tasklet up and removed the
2845 * SUB_RETRY_SEND flag, so the stream_interface would not
2846 * know it has to unsubscribe for send, but the tasklet hasn't
2847 * run yet. Make sure to handle that by explicitely setting
2848 * send_wait to NULL, as nothing else will do it for us.
2849 */
2850 fstrm->send_wait = NULL;
2851 }
2852
2853 sess = fstrm->sess;
2854 fconn = fstrm->fconn;
2855 fstrm->cs = NULL;
2856 fconn->nb_cs--;
2857
2858 if (fstrm->proto_status == FCGI_PS_CANT_MPX_CONN) {
2859 fconn->flags &= ~FCGI_CF_MPXS_CONNS;
2860 fconn->streams_limit = 1;
2861 }
2862 else if (fstrm->proto_status == FCGI_PS_OVERLOADED ||
2863 fstrm->proto_status == FCGI_PS_UNKNOWN_ROLE) {
2864 fconn->flags &= ~FCGI_CF_KEEP_CONN;
2865 fconn->state = FCGI_CS_CLOSED;
2866 }
2867
2868 /* this stream may be blocked waiting for some data to leave, so orphan
2869 * it in this case.
2870 */
2871 if (!(cs->conn->flags & CO_FL_ERROR) &&
2872 (fconn->state != FCGI_CS_CLOSED) &&
2873 (fstrm->flags & (FCGI_SF_BLK_MBUSY|FCGI_SF_BLK_MROOM)) && (fstrm->send_wait || fstrm->recv_wait))
2874 return;
2875
2876 if ((fconn->flags & FCGI_CF_DEM_BLOCK_ANY && fstrm->id == fconn->dsi)) {
2877 /* unblock the connection if it was blocked on this stream. */
2878 fconn->flags &= ~FCGI_CF_DEM_BLOCK_ANY;
2879 fcgi_conn_restart_reading(fconn, 1);
2880 }
2881
2882 fcgi_strm_destroy(fstrm);
2883
2884 if (!(fconn->conn->flags & (CO_FL_ERROR|CO_FL_SOCK_RD_SH|CO_FL_SOCK_WR_SH)) &&
2885 !(fconn->flags & FCGI_CF_KEEP_CONN)) {
2886 if (!fconn->conn->owner) {
2887 fconn->conn->owner = sess;
2888 if (!session_add_conn(sess, fconn->conn, fconn->conn->target)) {
2889 fconn->conn->owner = NULL;
2890 if (eb_is_empty(&fconn->streams_by_id)) {
2891 if (!srv_add_to_idle_list(objt_server(fconn->conn->target), fconn->conn))
2892 /* The server doesn't want it, let's kill the connection right away */
2893 fconn->conn->mux->destroy(fconn->conn);
2894 return;
2895 }
2896 }
2897 }
2898 if (eb_is_empty(&fconn->streams_by_id)) {
2899 if (session_check_idle_conn(fconn->conn->owner, fconn->conn) != 0)
2900 /* At this point either the connection is destroyed,
2901 or it's been added to the server idle list, just stop */
2902 return;
2903 }
2904 /* Never ever allow to reuse a connection from a non-reuse backend */
2905 if ((fconn->proxy->options & PR_O_REUSE_MASK) == PR_O_REUSE_NEVR)
2906 fconn->conn->flags |= CO_FL_PRIVATE;
2907 if (!LIST_ADDED(&fconn->conn->list) && fconn->nb_streams < fconn->streams_limit) {
2908 struct server *srv = objt_server(fconn->conn->target);
2909
2910 if (srv) {
2911 if (fconn->conn->flags & CO_FL_PRIVATE)
2912 LIST_ADD(&srv->priv_conns[tid], &fconn->conn->list);
2913 else
2914 LIST_ADD(&srv->idle_conns[tid], &fconn->conn->list);
2915 }
2916 }
2917 }
2918
2919 /* We don't want to close right now unless we're removing the last
2920 * stream, and either the connection is in error, or it reached the ID
2921 * already specified in a GOAWAY frame received or sent (as seen by
2922 * last_sid >= 0).
2923 */
2924 if (fcgi_conn_is_dead(fconn)) {
2925 /* no more stream will come, kill it now */
2926 fcgi_release(fconn);
2927 }
2928 else if (fconn->task) {
2929 fconn->task->expire = tick_add(now_ms, (fconn->state == FCGI_CS_CLOSED ? fconn->shut_timeout : fconn->timeout));
2930 task_queue(fconn->task);
2931 }
2932}
2933
2934
2935/* Performs a synchronous or asynchronous shutr(). */
2936static void fcgi_do_shutr(struct fcgi_strm *fstrm)
2937{
2938 struct fcgi_conn *fconn = fstrm->fconn;
2939 struct wait_event *sw = &fstrm->wait_event;
2940
2941 if (fstrm->state == FCGI_SS_CLOSED)
2942 goto done;
2943
2944 /* a connstream may require us to immediately kill the whole connection
2945 * for example because of a "tcp-request content reject" rule that is
2946 * normally used to limit abuse.
2947 */
2948 if ((fstrm->flags & FCGI_SF_KILL_CONN) &&
2949 !(fconn->flags & (FCGI_CF_ABRTS_SENT|FCGI_CF_ABRTS_FAILED)))
2950 fconn->state = FCGI_CS_CLOSED;
2951 else if (fstrm->flags & FCGI_SF_BEGIN_SENT) {
2952 if (!(fstrm->flags & (FCGI_SF_ES_SENT|FCGI_SF_ABRT_SENT)) &&
2953 !fcgi_strm_send_abort(fconn, fstrm))
2954 goto add_to_list;
2955 }
2956
2957 fcgi_strm_close(fstrm);
2958
2959 if (!(fconn->wait_event.events & SUB_RETRY_SEND))
2960 tasklet_wakeup(fconn->wait_event.tasklet);
2961 done:
2962 fstrm->flags &= ~FCGI_SF_WANT_SHUTR;
2963 return;
2964
2965 add_to_list:
2966 if (!LIST_ADDED(&fstrm->send_list)) {
2967 sw->events |= SUB_RETRY_SEND;
2968 if (fstrm->flags & (FCGI_SF_BLK_MBUSY|FCGI_SF_BLK_MROOM)) {
2969 fstrm->send_wait = sw;
2970 LIST_ADDQ(&fconn->send_list, &fstrm->send_list);
2971 }
2972 }
2973 /* Let the handler know we want shutr */
2974 fstrm->flags |= FCGI_SF_WANT_SHUTR;
2975 return;
2976}
2977
2978/* Performs a synchronous or asynchronous shutw(). */
2979static void fcgi_do_shutw(struct fcgi_strm *fstrm)
2980{
2981 struct fcgi_conn *fconn = fstrm->fconn;
2982 struct wait_event *sw = &fstrm->wait_event;
2983
2984 if (fstrm->state != FCGI_SS_HLOC || fstrm->state == FCGI_SS_CLOSED)
2985 goto done;
2986
2987 if (fstrm->state != FCGI_SS_ERROR && (fstrm->flags & FCGI_SF_BEGIN_SENT)) {
2988 if (!(fstrm->flags & (FCGI_SF_ES_SENT|FCGI_SF_ABRT_SENT)) &&
2989 !fcgi_strm_send_abort(fconn, fstrm))
2990 goto add_to_list;
2991
2992 if (fstrm->state == FCGI_SS_HREM)
2993 fcgi_strm_close(fstrm);
2994 else
2995 fstrm->state = FCGI_SS_HLOC;
2996 } else {
2997 /* a connstream may require us to immediately kill the whole connection
2998 * for example because of a "tcp-request content reject" rule that is
2999 * normally used to limit abuse.
3000 */
3001 if ((fstrm->flags & FCGI_SF_KILL_CONN) &&
3002 !(fconn->flags & (FCGI_CF_ABRTS_SENT|FCGI_CF_ABRTS_FAILED)))
3003 fconn->state = FCGI_CS_CLOSED;
3004
3005 fcgi_strm_close(fstrm);
3006 }
3007
3008 if (!(fconn->wait_event.events & SUB_RETRY_SEND))
3009 tasklet_wakeup(fconn->wait_event.tasklet);
3010 done:
3011 fstrm->flags &= ~FCGI_SF_WANT_SHUTW;
3012 return;
3013
3014 add_to_list:
3015 if (!LIST_ADDED(&fstrm->send_list)) {
3016 sw->events |= SUB_RETRY_SEND;
3017 if (fstrm->flags & (FCGI_SF_BLK_MBUSY|FCGI_SF_BLK_MROOM)) {
3018 fstrm->send_wait = sw;
3019 LIST_ADDQ(&fconn->send_list, &fstrm->send_list);
3020 }
3021 }
3022 /* let the handler know we want to shutw */
3023 fstrm->flags |= FCGI_SF_WANT_SHUTW;
3024 return;
3025}
3026
3027/* This is the tasklet referenced in fstrm->wait_event.tasklet, it is used for
3028 * deferred shutdowns when the fcgi_detach() was done but the mux buffer was full
3029 * and prevented the last frame from being emitted.
3030 */
3031static struct task *fcgi_deferred_shut(struct task *t, void *ctx, unsigned short state)
3032{
3033 struct fcgi_strm *fstrm = ctx;
3034 struct fcgi_conn *fconn = fstrm->fconn;
3035
3036 LIST_DEL_INIT(&fstrm->sending_list);
3037 if (fstrm->flags & FCGI_SF_WANT_SHUTW)
3038 fcgi_do_shutw(fstrm);
3039
3040 if (fstrm->flags & FCGI_SF_WANT_SHUTR)
3041 fcgi_do_shutr(fstrm);
3042
3043 if (!(fstrm->flags & (FCGI_SF_WANT_SHUTR|FCGI_SF_WANT_SHUTW))) {
3044 /* We're done trying to send, remove ourself from the send_list */
3045 LIST_DEL_INIT(&fstrm->send_list);
3046
3047 if (!fstrm->cs) {
3048 fcgi_strm_destroy(fstrm);
3049 if (fcgi_conn_is_dead(fconn))
3050 fcgi_release(fconn);
3051 }
3052 }
3053
3054 return NULL;
3055}
3056
3057/* shutr() called by the conn_stream (mux_ops.shutr) */
3058static void fcgi_shutr(struct conn_stream *cs, enum cs_shr_mode mode)
3059{
3060 struct fcgi_strm *fstrm = cs->ctx;
3061
3062 if (cs->flags & CS_FL_KILL_CONN)
3063 fstrm->flags |= FCGI_SF_KILL_CONN;
3064
3065 if (!mode)
3066 return;
3067
3068 fcgi_do_shutr(fstrm);
3069}
3070
3071/* shutw() called by the conn_stream (mux_ops.shutw) */
3072static void fcgi_shutw(struct conn_stream *cs, enum cs_shw_mode mode)
3073{
3074 struct fcgi_strm *fstrm = cs->ctx;
3075
3076 if (cs->flags & CS_FL_KILL_CONN)
3077 fstrm->flags |= FCGI_SF_KILL_CONN;
3078
3079 fcgi_do_shutw(fstrm);
3080}
3081
3082/* Called from the upper layer, to subscribe to events, such as being able to send.
3083 * The <param> argument here is supposed to be a pointer to a wait_event struct
3084 * which will be passed to fstrm->recv_wait or fstrm->send_wait depending on the
3085 * event_type. The event_type must only be a combination of SUB_RETRY_RECV and
3086 * SUB_RETRY_SEND, other values will lead to -1 being returned. It always
3087 * returns 0 except for the error above.
3088 */
3089static int fcgi_subscribe(struct conn_stream *cs, int event_type, void *param)
3090{
3091 struct wait_event *sw;
3092 struct fcgi_strm *fstrm = cs->ctx;
3093 struct fcgi_conn *fconn = fstrm->fconn;
3094
3095 if (event_type & SUB_RETRY_RECV) {
3096 sw = param;
3097 BUG_ON(fstrm->recv_wait != NULL || (sw->events & SUB_RETRY_RECV));
3098 sw->events |= SUB_RETRY_RECV;
3099 fstrm->recv_wait = sw;
3100 event_type &= ~SUB_RETRY_RECV;
3101 }
3102 if (event_type & SUB_RETRY_SEND) {
3103 sw = param;
3104 BUG_ON(fstrm->send_wait != NULL || (sw->events & SUB_RETRY_SEND));
3105 sw->events |= SUB_RETRY_SEND;
3106 fstrm->send_wait = sw;
3107 if (!LIST_ADDED(&fstrm->send_list))
3108 LIST_ADDQ(&fconn->send_list, &fstrm->send_list);
3109 event_type &= ~SUB_RETRY_SEND;
3110 }
3111 if (event_type != 0)
3112 return -1;
3113 return 0;
3114}
3115
3116/* Called from the upper layer, to unsubscribe some events (undo fcgi_subscribe).
3117 * The <param> argument here is supposed to be a pointer to the same wait_event
3118 * struct that was passed to fcgi_subscribe() otherwise nothing will be changed.
3119 * It always returns zero.
3120 */
3121static int fcgi_unsubscribe(struct conn_stream *cs, int event_type, void *param)
3122{
3123 struct wait_event *sw;
3124 struct fcgi_strm *fstrm = cs->ctx;
3125
3126 if (event_type & SUB_RETRY_RECV) {
3127 sw = param;
3128 BUG_ON(fstrm->recv_wait != sw);
3129 sw->events &= ~SUB_RETRY_RECV;
3130 fstrm->recv_wait = NULL;
3131 }
3132 if (event_type & SUB_RETRY_SEND) {
3133 sw = param;
3134 BUG_ON(fstrm->send_wait != sw);
3135 LIST_DEL(&fstrm->send_list);
3136 LIST_INIT(&fstrm->send_list);
3137 sw->events &= ~SUB_RETRY_SEND;
3138 /* We were about to send, make sure it does not happen */
3139 if (LIST_ADDED(&fstrm->sending_list) && fstrm->send_wait != &fstrm->wait_event) {
3140 tasklet_remove_from_tasklet_list(fstrm->send_wait->tasklet);
3141 LIST_DEL_INIT(&fstrm->sending_list);
3142 }
3143 fstrm->send_wait = NULL;
3144 }
3145 return 0;
3146}
3147
3148/* Called from the upper layer, to receive data */
3149static size_t fcgi_rcv_buf(struct conn_stream *cs, struct buffer *buf, size_t count, int flags)
3150{
3151 struct fcgi_strm *fstrm = cs->ctx;
3152 struct fcgi_conn *fconn = fstrm->fconn;
3153 size_t ret = 0;
3154
3155 if (!(fconn->flags & FCGI_CF_DEM_SALLOC))
3156 ret = fcgi_strm_parse_response(fstrm, buf, count);
3157
3158 if (b_data(&fstrm->rxbuf))
3159 cs->flags |= (CS_FL_RCV_MORE | CS_FL_WANT_ROOM);
3160 else {
3161 cs->flags &= ~(CS_FL_RCV_MORE | CS_FL_WANT_ROOM);
3162 if (fstrm->state == FCGI_SS_ERROR || fstrm->h1m.state == H1_MSG_DONE) {
3163 cs->flags |= CS_FL_EOI;
3164 if (!(fstrm->h1m.flags & (H1_MF_VER_11|H1_MF_XFER_LEN)))
3165 cs->flags |= CS_FL_EOS;
3166 }
3167 if (conn_xprt_read0_pending(fconn->conn))
3168 cs->flags |= CS_FL_EOS;
3169 if (cs->flags & CS_FL_ERR_PENDING)
3170 cs->flags |= CS_FL_ERROR;
3171 fcgi_release_buf(fconn, &fstrm->rxbuf);
3172 }
3173
3174 if (ret && fconn->dsi == fstrm->id) {
3175 /* demux is blocking on this stream's buffer */
3176 fconn->flags &= ~FCGI_CF_DEM_SFULL;
3177 fcgi_conn_restart_reading(fconn, 1);
3178 }
3179
3180 return ret;
3181}
3182
3183
3184/* stops all senders of this connection for example when the mux buffer is full.
3185 * They are moved from the sending_list to send_list.
3186 */
3187static void fcgi_stop_senders(struct fcgi_conn *fconn)
3188{
3189 struct fcgi_strm *fstrm, *fstrm_back;
3190
3191 list_for_each_entry_safe(fstrm, fstrm_back, &fconn->sending_list, sending_list) {
3192 LIST_DEL_INIT(&fstrm->sending_list);
3193 tasklet_remove_from_tasklet_list(fstrm->send_wait->tasklet);
3194 fstrm->send_wait->events |= SUB_RETRY_SEND;
3195 }
3196}
3197
3198
3199/* Called from the upper layer, to send data from buffer <buf> for no more than
3200 * <count> bytes. Returns the number of bytes effectively sent. Some status
3201 * flags may be updated on the conn_stream.
3202 */
3203static size_t fcgi_snd_buf(struct conn_stream *cs, struct buffer *buf, size_t count, int flags)
3204{
3205 struct fcgi_strm *fstrm = cs->ctx;
3206 struct fcgi_conn *fconn = fstrm->fconn;
3207 size_t total = 0;
3208 size_t ret;
3209 struct htx *htx = NULL;
3210 struct htx_sl *sl;
3211 struct htx_blk *blk;
3212 uint32_t bsize;
3213
3214 /* If we were not just woken because we wanted to send but couldn't,
3215 * and there's somebody else that is waiting to send, do nothing,
3216 * we will subscribe later and be put at the end of the list
3217 */
3218 if (!LIST_ADDED(&fstrm->sending_list) && !LIST_ISEMPTY(&fconn->send_list))
3219 return 0;
3220 LIST_DEL_INIT(&fstrm->sending_list);
3221
3222 /* We couldn't set it to NULL before, because we needed it in case
3223 * we had to cancel the tasklet
3224 */
3225 fstrm->send_wait = NULL;
3226
3227 if (fconn->state < FCGI_CS_RECORD_H)
3228 return 0;
3229
3230 htx = htxbuf(buf);
3231 if (fstrm->id == 0) {
3232 int32_t id = fcgi_conn_get_next_sid(fconn);
3233
3234 if (id < 0) {
3235 fcgi_strm_close(fstrm);
3236 cs->flags |= CS_FL_ERROR;
3237 return 0;
3238 }
3239
3240 eb32_delete(&fstrm->by_id);
3241 fstrm->by_id.key = fstrm->id = id;
3242 fconn->max_id = id;
3243 fconn->nb_reserved--;
3244 eb32_insert(&fconn->streams_by_id, &fstrm->by_id);
3245
3246
3247 /* Check if length of the body is known or if the message is
3248 * full. Otherwise, the request is invalid.
3249 */
3250 sl = http_get_stline(htx);
3251 if (!sl || (!(sl->flags & HTX_SL_F_CLEN) && (htx_get_tail_type(htx) != HTX_BLK_EOM))) {
3252 htx->flags |= HTX_FL_PARSING_ERROR;
3253 fcgi_strm_error(fstrm);
3254 goto done;
3255 }
3256 }
3257
3258 if (!(fstrm->flags & FCGI_SF_BEGIN_SENT)) {
3259 if (!fcgi_strm_send_begin_request(fconn, fstrm))
3260 goto done;
3261 }
3262
3263 if (!(fstrm->flags & FCGI_SF_OUTGOING_DATA) && count)
3264 fstrm->flags |= FCGI_SF_OUTGOING_DATA;
3265
3266 while (fstrm->state < FCGI_SS_HLOC && !(fconn->flags & FCGI_SF_BLK_ANY) &&
3267 count && !htx_is_empty(htx)) {
3268 blk = htx_get_head_blk(htx);
William Lallemand13ed9fa2019-09-25 21:21:57 +02003269 ALREADY_CHECKED(blk);
Christopher Faulet99eff652019-08-11 23:11:30 +02003270 bsize = htx_get_blksz(blk);
3271
3272 switch (htx_get_blk_type(blk)) {
3273 case HTX_BLK_REQ_SL:
3274 case HTX_BLK_HDR:
3275 ret = fcgi_strm_send_params(fconn, fstrm, htx);
3276 if (!ret) {
3277 goto done;
3278 }
3279 total += ret;
3280 count -= ret;
3281 break;
3282
3283 case HTX_BLK_EOH:
3284 ret = fcgi_strm_send_empty_params(fconn, fstrm);
3285 if (!ret)
3286 goto done;
3287 goto remove_blk;
3288
3289 case HTX_BLK_DATA:
3290 ret = fcgi_strm_send_stdin(fconn, fstrm, htx, count, buf);
3291 if (ret > 0) {
3292 htx = htx_from_buf(buf);
3293 total += ret;
3294 count -= ret;
3295 if (ret < bsize)
3296 goto done;
3297 }
3298 break;
3299
3300 case HTX_BLK_EOM:
3301 ret = fcgi_strm_send_empty_stdin(fconn, fstrm);
3302 if (!ret)
3303 goto done;
3304 goto remove_blk;
3305
3306 default:
3307 remove_blk:
3308 htx_remove_blk(htx, blk);
3309 total += bsize;
3310 count -= bsize;
3311 break;
3312 }
3313 }
3314
3315 done:
3316 if (fstrm->state >= FCGI_SS_HLOC) {
3317 /* trim any possibly pending data after we close (extra CR-LF,
3318 * unprocessed trailers, abnormal extra data, ...)
3319 */
3320 total += count;
3321 count = 0;
3322 }
3323
3324 if (fstrm->state == FCGI_SS_ERROR) {
3325 cs_set_error(cs);
3326 if (!(fstrm->flags & FCGI_SF_BEGIN_SENT) || fcgi_strm_send_abort(fconn, fstrm))
3327 fcgi_strm_close(fstrm);
3328 }
3329
3330 if (htx)
3331 htx_to_buf(htx, buf);
3332
3333 /* The mux is full, cancel the pending tasks */
3334 if ((fconn->flags & FCGI_CF_MUX_BLOCK_ANY) || (fstrm->flags & FCGI_SF_BLK_MBUSY))
3335 fcgi_stop_senders(fconn);
3336
3337 if (total > 0) {
3338 if (!(fconn->wait_event.events & SUB_RETRY_SEND))
3339 tasklet_wakeup(fconn->wait_event.tasklet);
3340
3341 /* Ok we managed to send something, leave the send_list */
3342 LIST_DEL_INIT(&fstrm->send_list);
3343 }
3344 return total;
3345}
3346
3347/* for debugging with CLI's "show fd" command */
3348static void fcgi_show_fd(struct buffer *msg, struct connection *conn)
3349{
3350 struct fcgi_conn *fconn = conn->ctx;
3351 struct fcgi_strm *fstrm = NULL;
3352 struct eb32_node *node;
3353 int send_cnt = 0;
3354 int tree_cnt = 0;
3355 int orph_cnt = 0;
3356 struct buffer *hmbuf, *tmbuf;
3357
3358 if (!fconn)
3359 return;
3360
3361 list_for_each_entry(fstrm, &fconn->send_list, send_list)
3362 send_cnt++;
3363
3364 fstrm = NULL;
3365 node = eb32_first(&fconn->streams_by_id);
3366 while (node) {
3367 fstrm = container_of(node, struct fcgi_strm, by_id);
3368 tree_cnt++;
3369 if (!fstrm->cs)
3370 orph_cnt++;
3371 node = eb32_next(node);
3372 }
3373
3374 hmbuf = br_head(fconn->mbuf);
3375 tmbuf = br_tail(fconn->mbuf);
3376 chunk_appendf(msg, " fconn.st0=%d .maxid=%d .flg=0x%04x .nbst=%u"
3377 " .nbcs=%u .send_cnt=%d .tree_cnt=%d .orph_cnt=%d .sub=%d "
3378 ".dsi=%d .dbuf=%u@%p+%u/%u .mbuf=[%u..%u|%u],h=[%u@%p+%u/%u],t=[%u@%p+%u/%u]",
3379 fconn->state, fconn->max_id, fconn->flags,
3380 fconn->nb_streams, fconn->nb_cs, send_cnt, tree_cnt, orph_cnt,
3381 fconn->wait_event.events, fconn->dsi,
3382 (unsigned int)b_data(&fconn->dbuf), b_orig(&fconn->dbuf),
3383 (unsigned int)b_head_ofs(&fconn->dbuf), (unsigned int)b_size(&fconn->dbuf),
3384 br_head_idx(fconn->mbuf), br_tail_idx(fconn->mbuf), br_size(fconn->mbuf),
3385 (unsigned int)b_data(hmbuf), b_orig(hmbuf),
3386 (unsigned int)b_head_ofs(hmbuf), (unsigned int)b_size(hmbuf),
3387 (unsigned int)b_data(tmbuf), b_orig(tmbuf),
3388 (unsigned int)b_head_ofs(tmbuf), (unsigned int)b_size(tmbuf));
3389
3390 if (fstrm) {
3391 chunk_appendf(msg, " last_fstrm=%p .id=%d .flg=0x%04x .rxbuf=%u@%p+%u/%u .cs=%p",
3392 fstrm, fstrm->id, fstrm->flags,
3393 (unsigned int)b_data(&fstrm->rxbuf), b_orig(&fstrm->rxbuf),
3394 (unsigned int)b_head_ofs(&fstrm->rxbuf), (unsigned int)b_size(&fstrm->rxbuf),
3395 fstrm->cs);
3396 if (fstrm->cs)
3397 chunk_appendf(msg, " .cs.flg=0x%08x .cs.data=%p",
3398 fstrm->cs->flags, fstrm->cs->data);
3399 }
3400}
3401
3402/****************************************/
3403/* MUX initialization and instanciation */
3404/****************************************/
3405
3406/* The mux operations */
3407static const struct mux_ops mux_fcgi_ops = {
3408 .init = fcgi_init,
3409 .wake = fcgi_wake,
3410 .attach = fcgi_attach,
3411 .get_first_cs = fcgi_get_first_cs,
3412 .detach = fcgi_detach,
3413 .destroy = fcgi_destroy,
3414 .avail_streams = fcgi_avail_streams,
3415 .used_streams = fcgi_used_streams,
3416 .rcv_buf = fcgi_rcv_buf,
3417 .snd_buf = fcgi_snd_buf,
3418 .subscribe = fcgi_subscribe,
3419 .unsubscribe = fcgi_unsubscribe,
3420 .shutr = fcgi_shutr,
3421 .shutw = fcgi_shutw,
3422 .show_fd = fcgi_show_fd,
3423 .flags = MX_FL_HTX,
3424 .name = "FCGI",
3425};
3426
3427
3428/* this mux registers FCGI proto */
3429static struct mux_proto_list mux_proto_fcgi =
3430{ .token = IST("fcgi"), .mode = PROTO_MODE_HTTP, .side = PROTO_SIDE_BE, .mux = &mux_fcgi_ops };
3431
3432INITCALL1(STG_REGISTER, register_mux_proto, &mux_proto_fcgi);
3433
3434/*
3435 * Local variables:
3436 * c-indent-level: 8
3437 * c-basic-offset: 8
3438 * End:
3439 */