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