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