blob: f6529558f4614097daf2ad35b8aa33828747f247 [file] [log] [blame]
willy tarreau0f7af912005-12-17 12:21:26 +01001/*
willy tarreau5cbea6f2005-12-17 12:48:26 +01002 * HA-Proxy : High Availability-enabled HTTP/TCP proxy
willy tarreau0174f312005-12-18 01:02:42 +01003 * 2000-2005 - Willy Tarreau - willy AT meta-x DOT org.
willy tarreau0f7af912005-12-17 12:21:26 +01004 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version
8 * 2 of the License, or (at your option) any later version.
9 *
willy tarreau906b2682005-12-17 13:49:52 +010010 * Please refer to RFC2068 or RFC2616 for informations about HTTP protocol, and
willy tarreau982249e2005-12-18 00:57:06 +010011 * RFC2965 for informations about cookies usage. More generally, the IETF HTTP
12 * Working Group's web site should be consulted for protocol related changes :
13 *
14 * http://ftp.ics.uci.edu/pub/ietf/http/
willy tarreau906b2682005-12-17 13:49:52 +010015 *
16 * Pending bugs (may be not fixed because never reproduced) :
willy tarreaua1598082005-12-17 13:08:06 +010017 * - solaris only : sometimes, an HTTP proxy with only a dispatch address causes
18 * the proxy to terminate (no core) if the client breaks the connection during
willy tarreauc29948c2005-12-17 13:10:27 +010019 * the response. Seen on 1.1.8pre4, but never reproduced. May not be related to
willy tarreau8337c6b2005-12-17 13:41:01 +010020 * the snprintf() bug since requests were simple (GET / HTTP/1.0), but may be
21 * related to missing setsid() (fixed in 1.1.15)
willy tarreauef900ab2005-12-17 12:52:52 +010022 * - a proxy with an invalid config will prevent the startup even if disabled.
23 *
willy tarreau036e1ce2005-12-17 13:46:33 +010024 * ChangeLog has moved to the CHANGELOG file.
willy tarreau0f7af912005-12-17 12:21:26 +010025 *
willy tarreau5cbea6f2005-12-17 12:48:26 +010026 * TODO:
27 * - handle properly intermediate incomplete server headers. Done ?
willy tarreau5cbea6f2005-12-17 12:48:26 +010028 * - handle hot-reconfiguration
willy tarreau906b2682005-12-17 13:49:52 +010029 * - fix client/server state transition when server is in connect or headers state
30 * and client suddenly disconnects. The server *should* switch to SHUT_WR, but
31 * still handle HTTP headers.
willy tarreau4302f492005-12-18 01:00:37 +010032 * - remove MAX_NEWHDR
willy tarreauc1f47532005-12-18 01:08:26 +010033 * - cut this huge file into several ones
willy tarreau0f7af912005-12-17 12:21:26 +010034 *
35 */
36
37#include <stdio.h>
38#include <stdlib.h>
39#include <unistd.h>
40#include <string.h>
41#include <ctype.h>
42#include <sys/time.h>
43#include <sys/types.h>
44#include <sys/socket.h>
45#include <netinet/tcp.h>
46#include <netinet/in.h>
47#include <arpa/inet.h>
48#include <netdb.h>
49#include <fcntl.h>
50#include <errno.h>
51#include <signal.h>
52#include <stdarg.h>
53#include <sys/resource.h>
54#include <time.h>
willy tarreau0f7af912005-12-17 12:21:26 +010055#include <syslog.h>
willy tarreau77bc8542005-12-18 01:31:43 +010056
57#ifdef USE_PCRE
58#include <pcre.h>
59#include <pcreposix.h>
60#else
61#include <regex.h>
62#endif
63
willy tarreaua1598082005-12-17 13:08:06 +010064#if defined(TPROXY) && defined(NETFILTER)
willy tarreau5cbea6f2005-12-17 12:48:26 +010065#include <linux/netfilter_ipv4.h>
66#endif
willy tarreau0f7af912005-12-17 12:21:26 +010067
willy tarreau12350152005-12-18 01:03:27 +010068#if defined(__dietlibc__)
69#include <strings.h>
70#endif
71
willy tarreau1c2ad212005-12-18 01:11:29 +010072#if defined(ENABLE_POLL)
73#include <sys/poll.h>
74#endif
75
76#if defined(ENABLE_EPOLL)
77#if !defined(USE_MY_EPOLL)
willy tarreauad90a0c2005-12-18 01:09:15 +010078#include <sys/epoll.h>
willy tarreau1c2ad212005-12-18 01:11:29 +010079#else
80#include "include/epoll.h"
81#endif
82#endif
willy tarreauad90a0c2005-12-18 01:09:15 +010083
willy tarreau598da412005-12-18 01:07:29 +010084#include "include/appsession.h"
willy tarreau12350152005-12-18 01:03:27 +010085
willy tarreaua56eca72005-12-18 01:34:42 +010086#define HAPROXY_VERSION "1.2.7"
87#define HAPROXY_DATE "2005/11/13"
willy tarreau0f7af912005-12-17 12:21:26 +010088
89/* this is for libc5 for example */
90#ifndef TCP_NODELAY
91#define TCP_NODELAY 1
92#endif
93
94#ifndef SHUT_RD
95#define SHUT_RD 0
96#endif
97
98#ifndef SHUT_WR
99#define SHUT_WR 1
100#endif
101
willy tarreau0174f312005-12-18 01:02:42 +0100102/*
103 * BUFSIZE defines the size of a read and write buffer. It is the maximum
104 * amount of bytes which can be stored by the proxy for each session. However,
105 * when reading HTTP headers, the proxy needs some spare space to add or rewrite
106 * headers if needed. The size of this spare is defined with MAXREWRITE. So it
107 * is not possible to process headers longer than BUFSIZE-MAXREWRITE bytes. By
108 * default, BUFSIZE=16384 bytes and MAXREWRITE=BUFSIZE/2, so the maximum length
109 * of headers accepted is 8192 bytes, which is in line with Apache's limits.
110 */
111#ifndef BUFSIZE
112#define BUFSIZE 16384
113#endif
willy tarreau0f7af912005-12-17 12:21:26 +0100114
115// reserved buffer space for header rewriting
willy tarreau0174f312005-12-18 01:02:42 +0100116#ifndef MAXREWRITE
117#define MAXREWRITE (BUFSIZE / 2)
118#endif
119
willy tarreau9fe663a2005-12-17 13:02:59 +0100120#define REQURI_LEN 1024
willy tarreau8337c6b2005-12-17 13:41:01 +0100121#define CAPTURE_LEN 64
willy tarreau0f7af912005-12-17 12:21:26 +0100122
willy tarreau5cbea6f2005-12-17 12:48:26 +0100123// max # args on a configuration line
willy tarreaue39cd132005-12-17 13:00:18 +0100124#define MAX_LINE_ARGS 40
willy tarreau5cbea6f2005-12-17 12:48:26 +0100125
willy tarreaue39cd132005-12-17 13:00:18 +0100126// max # of added headers per request
127#define MAX_NEWHDR 10
willy tarreau0f7af912005-12-17 12:21:26 +0100128
129// max # of matches per regexp
130#define MAX_MATCH 10
131
willy tarreau0174f312005-12-18 01:02:42 +0100132// cookie delimitor in "prefix" mode. This character is inserted between the
133// persistence cookie and the original value. The '~' is allowed by RFC2965,
134// and should not be too common in server names.
135#ifndef COOKIE_DELIM
136#define COOKIE_DELIM '~'
137#endif
138
willy tarreau0f7af912005-12-17 12:21:26 +0100139#define CONN_RETRIES 3
140
willy tarreau5cbea6f2005-12-17 12:48:26 +0100141#define CHK_CONNTIME 2000
willy tarreaue47c8d72005-12-17 12:55:52 +0100142#define DEF_CHKINTR 2000
143#define DEF_FALLTIME 3
144#define DEF_RISETIME 2
willy tarreau2f6ba652005-12-17 13:57:42 +0100145#define DEF_CHECK_REQ "OPTIONS / HTTP/1.0\r\n\r\n"
willy tarreau5cbea6f2005-12-17 12:48:26 +0100146
willy tarreau9fe663a2005-12-17 13:02:59 +0100147/* default connections limit */
148#define DEFAULT_MAXCONN 2000
149
willy tarreau0f7af912005-12-17 12:21:26 +0100150/* how many bits are needed to code the size of an int (eg: 32bits -> 5) */
151#define INTBITS 5
152
153/* show stats this every millisecond, 0 to disable */
154#ifndef STATTIME
155#define STATTIME 2000
156#endif
157
willy tarreau5cbea6f2005-12-17 12:48:26 +0100158/* this reduces the number of calls to select() by choosing appropriate
159 * sheduler precision in milliseconds. It should be near the minimum
160 * time that is needed by select() to collect all events. All timeouts
161 * are rounded up by adding this value prior to pass it to select().
162 */
163#define SCHEDULER_RESOLUTION 9
164
willy tarreaub952e1d2005-12-18 01:31:20 +0100165#define TIME_ETERNITY -1
166/* returns the lowest delay amongst <old> and <new>, and respects TIME_ETERNITY */
willy tarreau0f7af912005-12-17 12:21:26 +0100167#define MINTIME(old, new) (((new)<0)?(old):(((old)<0||(new)<(old))?(new):(old)))
168#define SETNOW(a) (*a=now)
169
willy tarreau9da061b2005-12-17 12:29:56 +0100170/****** string-specific macros and functions ******/
171/* if a > max, then bound <a> to <max>. The macro returns the new <a> */
172#define UBOUND(a, max) ({ typeof(a) b = (max); if ((a) > b) (a) = b; (a); })
173
174/* if a < min, then bound <a> to <min>. The macro returns the new <a> */
175#define LBOUND(a, min) ({ typeof(a) b = (min); if ((a) < b) (a) = b; (a); })
176
willy tarreau0174f312005-12-18 01:02:42 +0100177/* returns 1 only if only zero or one bit is set in X, which means that X is a
178 * power of 2, and 0 otherwise */
179#define POWEROF2(x) (((x) & ((x)-1)) == 0)
willy tarreau9da061b2005-12-17 12:29:56 +0100180/*
181 * copies at most <size-1> chars from <src> to <dst>. Last char is always
182 * set to 0, unless <size> is 0. The number of chars copied is returned
183 * (excluding the terminating zero).
184 * This code has been optimized for size and speed : on x86, it's 45 bytes
185 * long, uses only registers, and consumes only 4 cycles per char.
186 */
willy tarreau750a4722005-12-17 13:21:24 +0100187int strlcpy2(char *dst, const char *src, int size) {
willy tarreau9da061b2005-12-17 12:29:56 +0100188 char *orig = dst;
189 if (size) {
190 while (--size && (*dst = *src)) {
191 src++; dst++;
192 }
193 *dst = 0;
194 }
195 return dst - orig;
196}
willy tarreau9da061b2005-12-17 12:29:56 +0100197
willy tarreau4302f492005-12-18 01:00:37 +0100198/*
199 * Returns a pointer to an area of <__len> bytes taken from the pool <pool> or
200 * dynamically allocated. In the first case, <__pool> is updated to point to
201 * the next element in the list.
202 */
203#define pool_alloc_from(__pool, __len) ({ \
204 void *__p; \
205 if ((__p = (__pool)) == NULL) \
206 __p = malloc(((__len) >= sizeof (void *)) ? (__len) : sizeof(void *)); \
207 else { \
208 __pool = *(void **)(__pool); \
209 } \
210 __p; \
211})
212
213/*
214 * Puts a memory area back to the corresponding pool.
215 * Items are chained directly through a pointer that
216 * is written in the beginning of the memory area, so
217 * there's no need for any carrier cell. This implies
218 * that each memory area is at least as big as one
219 * pointer.
220 */
221#define pool_free_to(__pool, __ptr) ({ \
222 *(void **)(__ptr) = (void *)(__pool); \
223 __pool = (void *)(__ptr); \
224})
225
226
willy tarreau0f7af912005-12-17 12:21:26 +0100227#define MEM_OPTIM
228#ifdef MEM_OPTIM
229/*
230 * Returns a pointer to type <type> taken from the
231 * pool <pool_type> or dynamically allocated. In the
232 * first case, <pool_type> is updated to point to the
233 * next element in the list.
234 */
235#define pool_alloc(type) ({ \
willy tarreau4302f492005-12-18 01:00:37 +0100236 void *__p; \
237 if ((__p = pool_##type) == NULL) \
238 __p = malloc(sizeof_##type); \
willy tarreau0f7af912005-12-17 12:21:26 +0100239 else { \
240 pool_##type = *(void **)pool_##type; \
241 } \
willy tarreau4302f492005-12-18 01:00:37 +0100242 __p; \
willy tarreau0f7af912005-12-17 12:21:26 +0100243})
244
245/*
246 * Puts a memory area back to the corresponding pool.
247 * Items are chained directly through a pointer that
248 * is written in the beginning of the memory area, so
willy tarreau9da061b2005-12-17 12:29:56 +0100249 * there's no need for any carrier cell. This implies
willy tarreau0f7af912005-12-17 12:21:26 +0100250 * that each memory area is at least as big as one
251 * pointer.
252 */
253#define pool_free(type, ptr) ({ \
254 *(void **)ptr = (void *)pool_##type; \
255 pool_##type = (void *)ptr; \
256})
257
258#else
259#define pool_alloc(type) (calloc(1,sizeof_##type));
260#define pool_free(type, ptr) (free(ptr));
261#endif /* MEM_OPTIM */
262
willy tarreau5cbea6f2005-12-17 12:48:26 +0100263#define sizeof_task sizeof(struct task)
264#define sizeof_session sizeof(struct session)
willy tarreau0f7af912005-12-17 12:21:26 +0100265#define sizeof_buffer sizeof(struct buffer)
266#define sizeof_fdtab sizeof(struct fdtab)
willy tarreau9fe663a2005-12-17 13:02:59 +0100267#define sizeof_requri REQURI_LEN
willy tarreau8337c6b2005-12-17 13:41:01 +0100268#define sizeof_capture CAPTURE_LEN
willy tarreau64a3cc32005-12-18 01:13:11 +0100269#define sizeof_curappsession CAPTURE_LEN /* current_session pool */
willy tarreau12350152005-12-18 01:03:27 +0100270#define sizeof_appsess sizeof(struct appsessions)
willy tarreau0f7af912005-12-17 12:21:26 +0100271
willy tarreau5cbea6f2005-12-17 12:48:26 +0100272/* different possible states for the sockets */
willy tarreau0f7af912005-12-17 12:21:26 +0100273#define FD_STCLOSE 0
274#define FD_STLISTEN 1
275#define FD_STCONN 2
276#define FD_STREADY 3
277#define FD_STERROR 4
278
willy tarreau5cbea6f2005-12-17 12:48:26 +0100279/* values for task->state */
willy tarreau0f7af912005-12-17 12:21:26 +0100280#define TASK_IDLE 0
281#define TASK_RUNNING 1
282
willy tarreau5cbea6f2005-12-17 12:48:26 +0100283/* values for proxy->state */
willy tarreau0f7af912005-12-17 12:21:26 +0100284#define PR_STNEW 0
285#define PR_STIDLE 1
286#define PR_STRUN 2
287#define PR_STDISABLED 3
288
willy tarreau5cbea6f2005-12-17 12:48:26 +0100289/* values for proxy->mode */
willy tarreau0f7af912005-12-17 12:21:26 +0100290#define PR_MODE_TCP 0
291#define PR_MODE_HTTP 1
292#define PR_MODE_HEALTH 2
293
willy tarreau1c2ad212005-12-18 01:11:29 +0100294/* possible actions for the *poll() loops */
295#define POLL_LOOP_ACTION_INIT 0
296#define POLL_LOOP_ACTION_RUN 1
297#define POLL_LOOP_ACTION_CLEAN 2
298
willy tarreau64a3cc32005-12-18 01:13:11 +0100299/* poll mechanisms available */
300#define POLL_USE_SELECT (1<<0)
301#define POLL_USE_POLL (1<<1)
302#define POLL_USE_EPOLL (1<<2)
303
willy tarreau5cbea6f2005-12-17 12:48:26 +0100304/* bits for proxy->options */
willy tarreau0174f312005-12-18 01:02:42 +0100305#define PR_O_REDISP 0x00000001 /* allow reconnection to dispatch in case of errors */
306#define PR_O_TRANSP 0x00000002 /* transparent mode : use original DEST as dispatch */
307#define PR_O_COOK_RW 0x00000004 /* rewrite all direct cookies with the right serverid */
308#define PR_O_COOK_IND 0x00000008 /* keep only indirect cookies */
309#define PR_O_COOK_INS 0x00000010 /* insert cookies when not accessing a server directly */
310#define PR_O_COOK_PFX 0x00000020 /* rewrite all cookies by prefixing the right serverid */
311#define PR_O_COOK_ANY (PR_O_COOK_RW | PR_O_COOK_IND | PR_O_COOK_INS | PR_O_COOK_PFX)
312#define PR_O_BALANCE_RR 0x00000040 /* balance in round-robin mode */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100313#define PR_O_BALANCE (PR_O_BALANCE_RR)
willy tarreau0174f312005-12-18 01:02:42 +0100314#define PR_O_KEEPALIVE 0x00000080 /* follow keep-alive sessions */
315#define PR_O_FWDFOR 0x00000100 /* insert x-forwarded-for with client address */
316#define PR_O_BIND_SRC 0x00000200 /* bind to a specific source address when connect()ing */
317#define PR_O_NULLNOLOG 0x00000400 /* a connect without request will not be logged */
318#define PR_O_COOK_NOC 0x00000800 /* add a 'Cache-control' header with the cookie */
319#define PR_O_COOK_POST 0x00001000 /* don't insert cookies for requests other than a POST */
320#define PR_O_HTTP_CHK 0x00002000 /* use HTTP 'OPTIONS' method to check server health */
321#define PR_O_PERSIST 0x00004000 /* server persistence stays effective even when server is down */
322#define PR_O_LOGASAP 0x00008000 /* log as soon as possible, without waiting for the session to complete */
323#define PR_O_HTTP_CLOSE 0x00010000 /* force 'connection: close' in both directions */
324#define PR_O_CHK_CACHE 0x00020000 /* require examination of cacheability of the 'set-cookie' field */
willy tarreaub952e1d2005-12-18 01:31:20 +0100325#define PR_O_TCP_CLI_KA 0x00040000 /* enable TCP keep-alive on client-side sessions */
326#define PR_O_TCP_SRV_KA 0x00080000 /* enable TCP keep-alive on server-side sessions */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100327
willy tarreaue39cd132005-12-17 13:00:18 +0100328/* various session flags */
willy tarreau036e1ce2005-12-17 13:46:33 +0100329#define SN_DIRECT 0x00000001 /* connection made on the server matching the client cookie */
330#define SN_CLDENY 0x00000002 /* a client header matches a deny regex */
331#define SN_CLALLOW 0x00000004 /* a client header matches an allow regex */
332#define SN_SVDENY 0x00000008 /* a server header matches a deny regex */
333#define SN_SVALLOW 0x00000010 /* a server header matches an allow regex */
334#define SN_POST 0x00000020 /* the request was an HTTP POST */
willy tarreaub1285d52005-12-18 01:20:14 +0100335#define SN_MONITOR 0x00000040 /* this session comes from a monitoring system */
willy tarreau036e1ce2005-12-17 13:46:33 +0100336
337#define SN_CK_NONE 0x00000000 /* this session had no cookie */
338#define SN_CK_INVALID 0x00000040 /* this session had a cookie which matches no server */
339#define SN_CK_DOWN 0x00000080 /* this session had cookie matching a down server */
340#define SN_CK_VALID 0x000000C0 /* this session had cookie matching a valid server */
341#define SN_CK_MASK 0x000000C0 /* mask to get this session's cookie flags */
342#define SN_CK_SHIFT 6 /* bit shift */
343
willy tarreaub1285d52005-12-18 01:20:14 +0100344#define SN_ERR_NONE 0x00000000
willy tarreau036e1ce2005-12-17 13:46:33 +0100345#define SN_ERR_CLITO 0x00000100 /* client time-out */
346#define SN_ERR_CLICL 0x00000200 /* client closed (read/write error) */
347#define SN_ERR_SRVTO 0x00000300 /* server time-out, connect time-out */
348#define SN_ERR_SRVCL 0x00000400 /* server closed (connect/read/write error) */
349#define SN_ERR_PRXCOND 0x00000500 /* the proxy decided to close (deny...) */
willy tarreaub1285d52005-12-18 01:20:14 +0100350#define SN_ERR_RESOURCE 0x00000600 /* the proxy encountered a lack of a local resources (fd, mem, ...) */
351#define SN_ERR_INTERNAL 0x00000700 /* the proxy encountered an internal error */
willy tarreau036e1ce2005-12-17 13:46:33 +0100352#define SN_ERR_MASK 0x00000700 /* mask to get only session error flags */
353#define SN_ERR_SHIFT 8 /* bit shift */
354
355#define SN_FINST_R 0x00001000 /* session ended during client request */
356#define SN_FINST_C 0x00002000 /* session ended during server connect */
357#define SN_FINST_H 0x00003000 /* session ended during server headers */
358#define SN_FINST_D 0x00004000 /* session ended during data phase */
359#define SN_FINST_L 0x00005000 /* session ended while pushing last data to client */
360#define SN_FINST_MASK 0x00007000 /* mask to get only final session state flags */
361#define SN_FINST_SHIFT 12 /* bit shift */
362
363#define SN_SCK_NONE 0x00000000 /* no set-cookie seen for the server cookie */
364#define SN_SCK_DELETED 0x00010000 /* existing set-cookie deleted or changed */
365#define SN_SCK_INSERTED 0x00020000 /* new set-cookie inserted or changed existing one */
366#define SN_SCK_SEEN 0x00040000 /* set-cookie seen for the server cookie */
367#define SN_SCK_MASK 0x00070000 /* mask to get the set-cookie field */
willy tarreau97f58572005-12-18 00:53:44 +0100368#define SN_SCK_ANY 0x00080000 /* at least one set-cookie seen (not to be counted) */
willy tarreau036e1ce2005-12-17 13:46:33 +0100369#define SN_SCK_SHIFT 16 /* bit shift */
370
willy tarreau97f58572005-12-18 00:53:44 +0100371#define SN_CACHEABLE 0x00100000 /* at least part of the response is cacheable */
372#define SN_CACHE_COOK 0x00200000 /* a cookie in the response is cacheable */
373#define SN_CACHE_SHIFT 20 /* bit shift */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100374
375/* different possible states for the client side */
willy tarreau0f7af912005-12-17 12:21:26 +0100376#define CL_STHEADERS 0
377#define CL_STDATA 1
378#define CL_STSHUTR 2
379#define CL_STSHUTW 3
380#define CL_STCLOSE 4
381
willy tarreau5cbea6f2005-12-17 12:48:26 +0100382/* different possible states for the server side */
willy tarreau0f7af912005-12-17 12:21:26 +0100383#define SV_STIDLE 0
384#define SV_STCONN 1
385#define SV_STHEADERS 2
386#define SV_STDATA 3
387#define SV_STSHUTR 4
388#define SV_STSHUTW 5
389#define SV_STCLOSE 6
390
391/* result of an I/O event */
392#define RES_SILENT 0 /* didn't happen */
393#define RES_DATA 1 /* data were sent or received */
394#define RES_NULL 2 /* result is 0 (read == 0), or connect without need for writing */
395#define RES_ERROR 3 /* result -1 or error on the socket (eg: connect()) */
396
willy tarreau9fe663a2005-12-17 13:02:59 +0100397/* modes of operation (global.mode) */
willy tarreau0f7af912005-12-17 12:21:26 +0100398#define MODE_DEBUG 1
399#define MODE_STATS 2
400#define MODE_LOG 4
401#define MODE_DAEMON 8
willy tarreau5cbea6f2005-12-17 12:48:26 +0100402#define MODE_QUIET 16
willy tarreaudd07e972005-12-18 00:48:48 +0100403#define MODE_CHECK 32
willy tarreau982249e2005-12-18 00:57:06 +0100404#define MODE_VERBOSE 64
willy tarreaud0fb4652005-12-18 01:32:04 +0100405#define MODE_STARTING 128
willy tarreau5cbea6f2005-12-17 12:48:26 +0100406
407/* server flags */
willy tarreaua41a8b42005-12-17 14:02:24 +0100408#define SRV_RUNNING 1 /* the server is UP */
409#define SRV_BACKUP 2 /* this server is a backup server */
410#define SRV_MAPPORTS 4 /* this server uses mapped ports */
willy tarreau0174f312005-12-18 01:02:42 +0100411#define SRV_BIND_SRC 8 /* this server uses a specific source address */
willy tarreau0f7af912005-12-17 12:21:26 +0100412
willy tarreaue39cd132005-12-17 13:00:18 +0100413/* what to do when a header matches a regex */
414#define ACT_ALLOW 0 /* allow the request */
415#define ACT_REPLACE 1 /* replace the matching header */
416#define ACT_REMOVE 2 /* remove the matching header */
417#define ACT_DENY 3 /* deny the request */
willy tarreau036e1ce2005-12-17 13:46:33 +0100418#define ACT_PASS 4 /* pass this header without allowing or denying the request */
willy tarreaue39cd132005-12-17 13:00:18 +0100419
willy tarreau9fe663a2005-12-17 13:02:59 +0100420/* configuration sections */
421#define CFG_NONE 0
422#define CFG_GLOBAL 1
423#define CFG_LISTEN 2
424
willy tarreaua1598082005-12-17 13:08:06 +0100425/* fields that need to be logged. They appear as flags in session->logs.logwait */
willy tarreau9fe663a2005-12-17 13:02:59 +0100426#define LW_DATE 1 /* date */
427#define LW_CLIP 2 /* CLient IP */
428#define LW_SVIP 4 /* SerVer IP */
429#define LW_SVID 8 /* server ID */
430#define LW_REQ 16 /* http REQuest */
431#define LW_RESP 32 /* http RESPonse */
432#define LW_PXIP 64 /* proxy IP */
433#define LW_PXID 128 /* proxy ID */
willy tarreaua1598082005-12-17 13:08:06 +0100434#define LW_BYTES 256 /* bytes read from server */
willy tarreau4302f492005-12-18 01:00:37 +0100435#define LW_COOKIE 512 /* captured cookie */
436#define LW_REQHDR 1024 /* request header(s) */
437#define LW_RSPHDR 2048 /* response header(s) */
willy tarreau9fe663a2005-12-17 13:02:59 +0100438
willy tarreau0f7af912005-12-17 12:21:26 +0100439/*********************************************************************/
440
441#define LIST_HEAD(a) ((void *)(&(a)))
442
443/*********************************************************************/
444
willy tarreau4302f492005-12-18 01:00:37 +0100445struct cap_hdr {
446 struct cap_hdr *next;
447 char *name; /* header name, case insensitive */
448 int namelen; /* length of the header name, to speed-up lookups */
449 int len; /* capture length, not including terminal zero */
450 int index; /* index in the output array */
451 void *pool; /* pool of pre-allocated memory area of (len+1) bytes */
452};
453
willy tarreau0f7af912005-12-17 12:21:26 +0100454struct hdr_exp {
willy tarreaue39cd132005-12-17 13:00:18 +0100455 struct hdr_exp *next;
456 regex_t *preg; /* expression to look for */
457 int action; /* ACT_ALLOW, ACT_REPLACE, ACT_REMOVE, ACT_DENY */
458 char *replace; /* expression to set instead */
willy tarreau0f7af912005-12-17 12:21:26 +0100459};
460
461struct buffer {
462 unsigned int l; /* data length */
463 char *r, *w, *h, *lr; /* read ptr, write ptr, last header ptr, last read */
willy tarreauef900ab2005-12-17 12:52:52 +0100464 char *rlim; /* read limit, used for header rewriting */
willy tarreaua1598082005-12-17 13:08:06 +0100465 unsigned long long total; /* total data read */
willy tarreau0f7af912005-12-17 12:21:26 +0100466 char data[BUFSIZE];
467};
468
469struct server {
470 struct server *next;
willy tarreau5cbea6f2005-12-17 12:48:26 +0100471 int state; /* server state (SRV_*) */
472 int cklen; /* the len of the cookie, to speed up checks */
473 char *cookie; /* the id set in the cookie */
474 char *id; /* just for identification */
willy tarreau0f7af912005-12-17 12:21:26 +0100475 struct sockaddr_in addr; /* the address to connect to */
willy tarreau0174f312005-12-18 01:02:42 +0100476 struct sockaddr_in source_addr; /* the address to which we want to bind for connect() */
willy tarreaua41a8b42005-12-17 14:02:24 +0100477 short check_port; /* the port to use for the health checks */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100478 int health; /* 0->rise-1 = bad; rise->rise+fall-1 = good */
willy tarreaue47c8d72005-12-17 12:55:52 +0100479 int rise, fall; /* time in iterations */
480 int inter; /* time in milliseconds */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100481 int result; /* 0 = connect OK, -1 = connect KO */
482 int curfd; /* file desc used for current test, or -1 if not in test */
willy tarreau535ae7a2005-12-17 12:58:00 +0100483 struct proxy *proxy; /* the proxy this server belongs to */
willy tarreau0f7af912005-12-17 12:21:26 +0100484};
485
willy tarreau5cbea6f2005-12-17 12:48:26 +0100486/* The base for all tasks */
willy tarreau0f7af912005-12-17 12:21:26 +0100487struct task {
488 struct task *next, *prev; /* chaining ... */
489 struct task *rqnext; /* chaining in run queue ... */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100490 struct task *wq; /* the wait queue this task is in */
willy tarreau0f7af912005-12-17 12:21:26 +0100491 int state; /* task state : IDLE or RUNNING */
492 struct timeval expire; /* next expiration time for this task, use only for fast sorting */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100493 int (*process)(struct task *t); /* the function which processes the task */
494 void *context; /* the task's context */
495};
496
497/* WARNING: if new fields are added, they must be initialized in event_accept() */
498struct session {
499 struct task *task; /* the task associated with this session */
willy tarreau0f7af912005-12-17 12:21:26 +0100500 /* application specific below */
501 struct timeval crexpire; /* expiration date for a client read */
502 struct timeval cwexpire; /* expiration date for a client write */
503 struct timeval srexpire; /* expiration date for a server read */
504 struct timeval swexpire; /* expiration date for a server write */
505 struct timeval cnexpire; /* expiration date for a connect */
506 char res_cr, res_cw, res_sr, res_sw;/* results of some events */
507 struct proxy *proxy; /* the proxy this socket belongs to */
508 int cli_fd; /* the client side fd */
509 int srv_fd; /* the server side fd */
510 int cli_state; /* state of the client side */
511 int srv_state; /* state of the server side */
512 int conn_retries; /* number of connect retries left */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100513 int flags; /* some flags describing the session */
willy tarreau0f7af912005-12-17 12:21:26 +0100514 struct buffer *req; /* request buffer */
515 struct buffer *rep; /* response buffer */
willy tarreau8a86dbf2005-12-18 00:45:59 +0100516 struct sockaddr_storage cli_addr; /* the client address */
willy tarreau0f7af912005-12-17 12:21:26 +0100517 struct sockaddr_in srv_addr; /* the address to connect to */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100518 struct server *srv; /* the server being used */
willy tarreau4302f492005-12-18 01:00:37 +0100519 char **req_cap; /* array of captured request headers (may be NULL) */
520 char **rsp_cap; /* array of captured response headers (may be NULL) */
willy tarreaua1598082005-12-17 13:08:06 +0100521 struct {
522 int logwait; /* log fields waiting to be collected : LW_* */
523 struct timeval tv_accept; /* date of the accept() (beginning of the session) */
524 long t_request; /* delay before the end of the request arrives, -1 if never occurs */
525 long t_connect; /* delay before the connect() to the server succeeds, -1 if never occurs */
526 long t_data; /* delay before the first data byte from the server ... */
527 unsigned long t_close; /* total session duration */
528 char *uri; /* first line if log needed, NULL otherwise */
willy tarreau8337c6b2005-12-17 13:41:01 +0100529 char *cli_cookie; /* cookie presented by the client, in capture mode */
530 char *srv_cookie; /* cookie presented by the server, in capture mode */
willy tarreaua1598082005-12-17 13:08:06 +0100531 int status; /* HTTP status from the server, negative if from proxy */
532 long long bytes; /* number of bytes transferred from the server */
533 } logs;
willy tarreau2f6ba652005-12-17 13:57:42 +0100534 unsigned int uniq_id; /* unique ID used for the traces */
willy tarreau0f7af912005-12-17 12:21:26 +0100535};
536
willy tarreaua41a8b42005-12-17 14:02:24 +0100537struct listener {
willy tarreau8a86dbf2005-12-18 00:45:59 +0100538 int fd; /* the listen socket */
539 struct sockaddr_storage addr; /* the address we listen to */
540 struct listener *next; /* next address or NULL */
willy tarreaua41a8b42005-12-17 14:02:24 +0100541};
542
543
willy tarreau0f7af912005-12-17 12:21:26 +0100544struct proxy {
willy tarreaua41a8b42005-12-17 14:02:24 +0100545 struct listener *listen; /* the listen addresses and sockets */
willy tarreaub1285d52005-12-18 01:20:14 +0100546 struct in_addr mon_net, mon_mask; /* don't forward connections from this net (network order) FIXME: should support IPv6 */
willy tarreau0f7af912005-12-17 12:21:26 +0100547 int state; /* proxy state */
willy tarreau0f7af912005-12-17 12:21:26 +0100548 struct sockaddr_in dispatch_addr; /* the default address to connect to */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100549 struct server *srv, *cursrv; /* known servers, current server */
550 int nbservers; /* # of servers */
willy tarreau0f7af912005-12-17 12:21:26 +0100551 char *cookie_name; /* name of the cookie to look for */
willy tarreau12350152005-12-18 01:03:27 +0100552 int cookie_len; /* strlen(cookie_name), computed only once */
553 char *appsession_name; /* name of the cookie to look for */
554 int appsession_name_len; /* strlen(appsession_name), computed only once */
555 int appsession_len; /* length of the appsession cookie value to be used */
556 int appsession_timeout;
557 CHTbl htbl_proxy; /* Per Proxy hashtable */
willy tarreau8337c6b2005-12-17 13:41:01 +0100558 char *capture_name; /* beginning of the name of the cookie to capture */
559 int capture_namelen; /* length of the cookie name to match */
560 int capture_len; /* length of the string to be captured */
willy tarreau0f7af912005-12-17 12:21:26 +0100561 int clitimeout; /* client I/O timeout (in milliseconds) */
562 int srvtimeout; /* server I/O timeout (in milliseconds) */
563 int contimeout; /* connect timeout (in milliseconds) */
564 char *id; /* proxy id */
565 int nbconn; /* # of active sessions */
566 int maxconn; /* max # of active sessions */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100567 int conn_retries; /* maximum number of connect retries */
willy tarreaub952e1d2005-12-18 01:31:20 +0100568 int options; /* PR_O_REDISP, PR_O_TRANSP, ... */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100569 int mode; /* mode = PR_MODE_TCP, PR_MODE_HTTP or PR_MODE_HEALTH */
willy tarreaua1598082005-12-17 13:08:06 +0100570 struct sockaddr_in source_addr; /* the address to which we want to bind for connect() */
willy tarreau0f7af912005-12-17 12:21:26 +0100571 struct proxy *next;
572 struct sockaddr_in logsrv1, logsrv2; /* 2 syslog servers */
willy tarreau5dffb602005-12-18 01:15:23 +0100573 signed char logfac1, logfac2; /* log facility for both servers. -1 = disabled */
willy tarreau8337c6b2005-12-17 13:41:01 +0100574 int loglev1, loglev2; /* log level for each server, 7 by default */
willy tarreau9fe663a2005-12-17 13:02:59 +0100575 int to_log; /* things to be logged (LW_*) */
willy tarreau0f7af912005-12-17 12:21:26 +0100576 struct timeval stop_time; /* date to stop listening, when stopping != 0 */
willy tarreaue39cd132005-12-17 13:00:18 +0100577 int nb_reqadd, nb_rspadd;
578 struct hdr_exp *req_exp; /* regular expressions for request headers */
579 struct hdr_exp *rsp_exp; /* regular expressions for response headers */
willy tarreau4302f492005-12-18 01:00:37 +0100580 int nb_req_cap, nb_rsp_cap; /* # of headers to be captured */
581 struct cap_hdr *req_cap; /* chained list of request headers to be captured */
582 struct cap_hdr *rsp_cap; /* chained list of response headers to be captured */
583 void *req_cap_pool, *rsp_cap_pool; /* pools of pre-allocated char ** used to build the sessions */
willy tarreaue39cd132005-12-17 13:00:18 +0100584 char *req_add[MAX_NEWHDR], *rsp_add[MAX_NEWHDR]; /* headers to be added */
willy tarreau0f7af912005-12-17 12:21:26 +0100585 int grace; /* grace time after stop request */
willy tarreau2f6ba652005-12-17 13:57:42 +0100586 char *check_req; /* HTTP request to use if PR_O_HTTP_CHK is set, else NULL */
587 int check_len; /* Length of the HTTP request */
willy tarreau8337c6b2005-12-17 13:41:01 +0100588 struct {
589 char *msg400; /* message for error 400 */
590 int len400; /* message length for error 400 */
591 char *msg403; /* message for error 403 */
592 int len403; /* message length for error 403 */
593 char *msg408; /* message for error 408 */
594 int len408; /* message length for error 408 */
595 char *msg500; /* message for error 500 */
596 int len500; /* message length for error 500 */
597 char *msg502; /* message for error 502 */
598 int len502; /* message length for error 502 */
599 char *msg503; /* message for error 503 */
600 int len503; /* message length for error 503 */
601 char *msg504; /* message for error 504 */
602 int len504; /* message length for error 504 */
603 } errmsg;
willy tarreau0f7af912005-12-17 12:21:26 +0100604};
605
606/* info about one given fd */
607struct fdtab {
608 int (*read)(int fd); /* read function */
609 int (*write)(int fd); /* write function */
610 struct task *owner; /* the session (or proxy) associated with this fd */
611 int state; /* the state of this fd */
612};
613
614/*********************************************************************/
615
willy tarreaub952e1d2005-12-18 01:31:20 +0100616int cfg_maxpconn = DEFAULT_MAXCONN; /* # of simultaneous connections per proxy (-N) */
willy tarreau0f7af912005-12-17 12:21:26 +0100617char *cfg_cfgfile = NULL; /* configuration file */
618char *progname = NULL; /* program name */
619int pid; /* current process id */
willy tarreau9fe663a2005-12-17 13:02:59 +0100620
621/* global options */
622static struct {
623 int uid;
624 int gid;
625 int nbproc;
626 int maxconn;
627 int maxsock; /* max # of sockets */
willy tarreaub1285d52005-12-18 01:20:14 +0100628 int rlimit_nofile; /* default ulimit-n value : 0=unset */
willy tarreau9fe663a2005-12-17 13:02:59 +0100629 int mode;
630 char *chroot;
willy tarreaufe2c5c12005-12-17 14:14:34 +0100631 char *pidfile;
willy tarreau9fe663a2005-12-17 13:02:59 +0100632 int logfac1, logfac2;
willy tarreau8337c6b2005-12-17 13:41:01 +0100633 int loglev1, loglev2;
willy tarreau9fe663a2005-12-17 13:02:59 +0100634 struct sockaddr_in logsrv1, logsrv2;
635} global = {
636 logfac1 : -1,
637 logfac2 : -1,
willy tarreau8337c6b2005-12-17 13:41:01 +0100638 loglev1 : 7, /* max syslog level : debug */
639 loglev2 : 7,
willy tarreau9fe663a2005-12-17 13:02:59 +0100640 /* others NULL OK */
641};
642
willy tarreau0f7af912005-12-17 12:21:26 +0100643/*********************************************************************/
644
willy tarreau1c2ad212005-12-18 01:11:29 +0100645fd_set *StaticReadEvent,
willy tarreau0f7af912005-12-17 12:21:26 +0100646 *StaticWriteEvent;
647
willy tarreau64a3cc32005-12-18 01:13:11 +0100648int cfg_polling_mechanism = 0; /* POLL_USE_{SELECT|POLL|EPOLL} */
willy tarreauad90a0c2005-12-18 01:09:15 +0100649
willy tarreau0f7af912005-12-17 12:21:26 +0100650void **pool_session = NULL,
651 **pool_buffer = NULL,
652 **pool_fdtab = NULL,
willy tarreau9fe663a2005-12-17 13:02:59 +0100653 **pool_requri = NULL,
willy tarreau8337c6b2005-12-17 13:41:01 +0100654 **pool_task = NULL,
willy tarreau12350152005-12-18 01:03:27 +0100655 **pool_capture = NULL,
656 **pool_appsess = NULL;
willy tarreau0f7af912005-12-17 12:21:26 +0100657
658struct proxy *proxy = NULL; /* list of all existing proxies */
659struct fdtab *fdtab = NULL; /* array of all the file descriptors */
willy tarreau5cbea6f2005-12-17 12:48:26 +0100660struct task *rq = NULL; /* global run queue */
661struct task wait_queue = { /* global wait queue */
662 prev:LIST_HEAD(wait_queue),
663 next:LIST_HEAD(wait_queue)
664};
willy tarreau0f7af912005-12-17 12:21:26 +0100665
willy tarreau0f7af912005-12-17 12:21:26 +0100666static int totalconn = 0; /* total # of terminated sessions */
667static int actconn = 0; /* # of active sessions */
668static int maxfd = 0; /* # of the highest fd + 1 */
669static int listeners = 0; /* # of listeners */
670static int stopping = 0; /* non zero means stopping in progress */
671static struct timeval now = {0,0}; /* the current date at any moment */
willy tarreaua41a8b42005-12-17 14:02:24 +0100672static struct proxy defproxy; /* fake proxy used to assign default values on all instances */
willy tarreau0f7af912005-12-17 12:21:26 +0100673
willy tarreau08dedbe2005-12-18 01:13:48 +0100674#if defined(ENABLE_EPOLL)
675/* FIXME: this is dirty, but at the moment, there's no other solution to remove
676 * the old FDs from outside the loop. Perhaps we should export a global 'poll'
677 * structure with pointers to functions such as init_fd() and close_fd(), plus
678 * a private structure with several pointers to places such as below.
679 */
680
681static fd_set *PrevReadEvent = NULL, *PrevWriteEvent = NULL;
682#endif
683
willy tarreau0f7af912005-12-17 12:21:26 +0100684static regmatch_t pmatch[MAX_MATCH]; /* rm_so, rm_eo for regular expressions */
willy tarreau750a4722005-12-17 13:21:24 +0100685/* this is used to drain data, and as a temporary buffer for sprintf()... */
willy tarreau0f7af912005-12-17 12:21:26 +0100686static char trash[BUFSIZE];
687
willy tarreaudd07e972005-12-18 00:48:48 +0100688const int zero = 0;
689const int one = 1;
690
willy tarreau0f7af912005-12-17 12:21:26 +0100691/*
willy tarreau036e1ce2005-12-17 13:46:33 +0100692 * Syslog facilities and levels. Conforming to RFC3164.
willy tarreau0f7af912005-12-17 12:21:26 +0100693 */
694
695#define MAX_SYSLOG_LEN 1024
696#define NB_LOG_FACILITIES 24
697const char *log_facilities[NB_LOG_FACILITIES] = {
698 "kern", "user", "mail", "daemon",
699 "auth", "syslog", "lpr", "news",
700 "uucp", "cron", "auth2", "ftp",
701 "ntp", "audit", "alert", "cron2",
702 "local0", "local1", "local2", "local3",
703 "local4", "local5", "local6", "local7"
704};
705
706
707#define NB_LOG_LEVELS 8
708const char *log_levels[NB_LOG_LEVELS] = {
709 "emerg", "alert", "crit", "err",
710 "warning", "notice", "info", "debug"
711};
712
713#define SYSLOG_PORT 514
714
715const char *monthname[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
716 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
willy tarreau036e1ce2005-12-17 13:46:33 +0100717
willy tarreaub1285d52005-12-18 01:20:14 +0100718const char sess_term_cond[8] = "-cCsSPRI"; /* normal, CliTo, CliErr, SrvTo, SrvErr, PxErr, Resource, Internal */
willy tarreau036e1ce2005-12-17 13:46:33 +0100719const char sess_fin_state[8] = "-RCHDL67"; /* cliRequest, srvConnect, srvHeader, Data, Last, unknown */
720const char sess_cookie[4] = "NIDV"; /* No cookie, Invalid cookie, cookie for a Down server, Valid cookie */
721const char sess_set_cookie[8] = "N1I3PD5R"; /* No set-cookie, unknown, Set-Cookie Inserted, unknown,
722 Set-cookie seen and left unchanged (passive), Set-cookie Deleted,
723 unknown, Set-cookie Rewritten */
724
willy tarreau0f7af912005-12-17 12:21:26 +0100725#define MAX_HOSTNAME_LEN 32
726static char hostname[MAX_HOSTNAME_LEN] = "";
727
willy tarreau8337c6b2005-12-17 13:41:01 +0100728const char *HTTP_302 =
729 "HTTP/1.0 302 Found\r\n"
730 "Cache-Control: no-cache\r\n"
731 "Connection: close\r\n"
732 "Location: "; /* not terminated since it will be concatenated with the URL */
733
willy tarreauc1f47532005-12-18 01:08:26 +0100734/* same as 302 except that the browser MUST retry with the GET method */
735const char *HTTP_303 =
736 "HTTP/1.0 303 See Other\r\n"
737 "Cache-Control: no-cache\r\n"
738 "Connection: close\r\n"
739 "Location: "; /* not terminated since it will be concatenated with the URL */
740
willy tarreaua1598082005-12-17 13:08:06 +0100741const char *HTTP_400 =
742 "HTTP/1.0 400 Bad request\r\n"
willy tarreaue39cd132005-12-17 13:00:18 +0100743 "Cache-Control: no-cache\r\n"
744 "Connection: close\r\n"
745 "\r\n"
willy tarreau750a4722005-12-17 13:21:24 +0100746 "<html><body><h1>400 Bad request</h1>\nYour browser sent an invalid request.\n</body></html>\n";
willy tarreaue39cd132005-12-17 13:00:18 +0100747
willy tarreaua1598082005-12-17 13:08:06 +0100748const char *HTTP_403 =
749 "HTTP/1.0 403 Forbidden\r\n"
willy tarreaue39cd132005-12-17 13:00:18 +0100750 "Cache-Control: no-cache\r\n"
751 "Connection: close\r\n"
752 "\r\n"
willy tarreau750a4722005-12-17 13:21:24 +0100753 "<html><body><h1>403 Forbidden</h1>\nRequest forbidden by administrative rules.\n</body></html>\n";
754
willy tarreau8337c6b2005-12-17 13:41:01 +0100755const char *HTTP_408 =
756 "HTTP/1.0 408 Request Time-out\r\n"
757 "Cache-Control: no-cache\r\n"
758 "Connection: close\r\n"
759 "\r\n"
760 "<html><body><h1>408 Request Time-out</h1>\nYour browser didn't send a complete request in time.\n</body></html>\n";
761
willy tarreau750a4722005-12-17 13:21:24 +0100762const char *HTTP_500 =
763 "HTTP/1.0 500 Server Error\r\n"
764 "Cache-Control: no-cache\r\n"
765 "Connection: close\r\n"
766 "\r\n"
767 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
willy tarreaue39cd132005-12-17 13:00:18 +0100768
769const char *HTTP_502 =
willy tarreau8337c6b2005-12-17 13:41:01 +0100770 "HTTP/1.0 502 Bad Gateway\r\n"
willy tarreaue39cd132005-12-17 13:00:18 +0100771 "Cache-Control: no-cache\r\n"
772 "Connection: close\r\n"
773 "\r\n"
willy tarreau8337c6b2005-12-17 13:41:01 +0100774 "<html><body><h1>502 Bad Gateway</h1>\nThe server returned an invalid or incomplete response.\n</body></html>\n";
775
776const char *HTTP_503 =
777 "HTTP/1.0 503 Service Unavailable\r\n"
778 "Cache-Control: no-cache\r\n"
779 "Connection: close\r\n"
780 "\r\n"
781 "<html><body><h1>503 Service Unavailable</h1>\nNo server is available to handle this request.\n</body></html>\n";
782
783const char *HTTP_504 =
784 "HTTP/1.0 504 Gateway Time-out\r\n"
785 "Cache-Control: no-cache\r\n"
786 "Connection: close\r\n"
787 "\r\n"
788 "<html><body><h1>504 Gateway Time-out</h1>\nThe server didn't respond in time.\n</body></html>\n";
willy tarreaue39cd132005-12-17 13:00:18 +0100789
willy tarreau0f7af912005-12-17 12:21:26 +0100790/*********************************************************************/
791/* statistics ******************************************************/
792/*********************************************************************/
793
willy tarreau750a4722005-12-17 13:21:24 +0100794#if STATTIME > 0
willy tarreau0f7af912005-12-17 12:21:26 +0100795static int stats_tsk_lsrch, stats_tsk_rsrch,
796 stats_tsk_good, stats_tsk_right, stats_tsk_left,
797 stats_tsk_new, stats_tsk_nsrch;
willy tarreau750a4722005-12-17 13:21:24 +0100798#endif
willy tarreau0f7af912005-12-17 12:21:26 +0100799
800
801/*********************************************************************/
willy tarreau750a4722005-12-17 13:21:24 +0100802/* debugging *******************************************************/
803/*********************************************************************/
804#ifdef DEBUG_FULL
805static char *cli_stnames[5] = {"HDR", "DAT", "SHR", "SHW", "CLS" };
806static char *srv_stnames[7] = {"IDL", "CON", "HDR", "DAT", "SHR", "SHW", "CLS" };
807#endif
808
809/*********************************************************************/
willy tarreau0f7af912005-12-17 12:21:26 +0100810/* function prototypes *********************************************/
811/*********************************************************************/
812
813int event_accept(int fd);
814int event_cli_read(int fd);
815int event_cli_write(int fd);
816int event_srv_read(int fd);
817int event_srv_write(int fd);
willy tarreau5cbea6f2005-12-17 12:48:26 +0100818int process_session(struct task *t);
willy tarreau0f7af912005-12-17 12:21:26 +0100819
willy tarreau12350152005-12-18 01:03:27 +0100820static int appsession_task_init(void);
821static int appsession_init(void);
822static int appsession_refresh(struct task *t);
823
willy tarreau0f7af912005-12-17 12:21:26 +0100824/*********************************************************************/
825/* general purpose functions ***************************************/
826/*********************************************************************/
827
828void display_version() {
829 printf("HA-Proxy version " HAPROXY_VERSION " " HAPROXY_DATE"\n");
willy tarreau0174f312005-12-18 01:02:42 +0100830 printf("Copyright 2000-2005 Willy Tarreau <w@w.ods.org>\n\n");
willy tarreau0f7af912005-12-17 12:21:26 +0100831}
832
833/*
834 * This function prints the command line usage and exits
835 */
836void usage(char *name) {
837 display_version();
838 fprintf(stderr,
willy tarreau982249e2005-12-18 00:57:06 +0100839 "Usage : %s -f <cfgfile> [ -vdV"
willy tarreau0f7af912005-12-17 12:21:26 +0100840#if STATTIME > 0
841 "sl"
842#endif
willy tarreaufe2c5c12005-12-17 14:14:34 +0100843 "D ] [ -n <maxconn> ] [ -N <maxpconn> ] [ -p <pidfile> ]\n"
willy tarreau0f7af912005-12-17 12:21:26 +0100844 " -v displays version\n"
845 " -d enters debug mode\n"
willy tarreau982249e2005-12-18 00:57:06 +0100846 " -V enters verbose mode (disables quiet mode)\n"
willy tarreau0f7af912005-12-17 12:21:26 +0100847#if STATTIME > 0
848 " -s enables statistics output\n"
849 " -l enables long statistics format\n"
850#endif
willy tarreau5cbea6f2005-12-17 12:48:26 +0100851 " -D goes daemon ; implies -q\n"
852 " -q quiet mode : don't display messages\n"
willy tarreaudd07e972005-12-18 00:48:48 +0100853 " -c check mode : only check config file and exit\n"
willy tarreau0f7af912005-12-17 12:21:26 +0100854 " -n sets the maximum total # of connections (%d)\n"
willy tarreaufe2c5c12005-12-17 14:14:34 +0100855 " -N sets the default, per-proxy maximum # of connections (%d)\n"
willy tarreauad90a0c2005-12-18 01:09:15 +0100856 " -p writes pids of all children to this file\n"
willy tarreau1c2ad212005-12-18 01:11:29 +0100857#if defined(ENABLE_EPOLL)
willy tarreau64a3cc32005-12-18 01:13:11 +0100858 " -de disables epoll() usage even when available\n"
willy tarreau1c2ad212005-12-18 01:11:29 +0100859#endif
860#if defined(ENABLE_POLL)
willy tarreau64a3cc32005-12-18 01:13:11 +0100861 " -dp disables poll() usage even when available\n"
willy tarreau1c2ad212005-12-18 01:11:29 +0100862#endif
willy tarreauad90a0c2005-12-18 01:09:15 +0100863 "\n",
willy tarreau9fe663a2005-12-17 13:02:59 +0100864 name, DEFAULT_MAXCONN, cfg_maxpconn);
willy tarreau0f7af912005-12-17 12:21:26 +0100865 exit(1);
866}
867
868
869/*
willy tarreaud0fb4652005-12-18 01:32:04 +0100870 * Displays the message on stderr with the date and pid. Overrides the quiet
871 * mode during startup.
willy tarreau0f7af912005-12-17 12:21:26 +0100872 */
873void Alert(char *fmt, ...) {
874 va_list argp;
875 struct timeval tv;
876 struct tm *tm;
877
willy tarreaud0fb4652005-12-18 01:32:04 +0100878 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
willy tarreau5cbea6f2005-12-17 12:48:26 +0100879 va_start(argp, fmt);
willy tarreau0f7af912005-12-17 12:21:26 +0100880
willy tarreau5cbea6f2005-12-17 12:48:26 +0100881 gettimeofday(&tv, NULL);
882 tm=localtime(&tv.tv_sec);
883 fprintf(stderr, "[ALERT] %03d/%02d%02d%02d (%d) : ",
willy tarreaua1598082005-12-17 13:08:06 +0100884 tm->tm_yday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)getpid());
willy tarreau5cbea6f2005-12-17 12:48:26 +0100885 vfprintf(stderr, fmt, argp);
886 fflush(stderr);
887 va_end(argp);
888 }
willy tarreau0f7af912005-12-17 12:21:26 +0100889}
890
891
892/*
893 * Displays the message on stderr with the date and pid.
894 */
895void Warning(char *fmt, ...) {
896 va_list argp;
897 struct timeval tv;
898 struct tm *tm;
899
willy tarreau982249e2005-12-18 00:57:06 +0100900 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) {
willy tarreau5cbea6f2005-12-17 12:48:26 +0100901 va_start(argp, fmt);
willy tarreau0f7af912005-12-17 12:21:26 +0100902
willy tarreau5cbea6f2005-12-17 12:48:26 +0100903 gettimeofday(&tv, NULL);
904 tm=localtime(&tv.tv_sec);
905 fprintf(stderr, "[WARNING] %03d/%02d%02d%02d (%d) : ",
willy tarreaua1598082005-12-17 13:08:06 +0100906 tm->tm_yday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)getpid());
willy tarreau5cbea6f2005-12-17 12:48:26 +0100907 vfprintf(stderr, fmt, argp);
908 fflush(stderr);
909 va_end(argp);
910 }
911}
912
913/*
914 * Displays the message on <out> only if quiet mode is not set.
915 */
916void qfprintf(FILE *out, char *fmt, ...) {
917 va_list argp;
918
willy tarreau982249e2005-12-18 00:57:06 +0100919 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) {
willy tarreau5cbea6f2005-12-17 12:48:26 +0100920 va_start(argp, fmt);
921 vfprintf(out, fmt, argp);
922 fflush(out);
923 va_end(argp);
924 }
willy tarreau0f7af912005-12-17 12:21:26 +0100925}
926
927
928/*
929 * converts <str> to a struct sockaddr_in* which is locally allocated.
930 * The format is "addr:port", where "addr" can be empty or "*" to indicate
931 * INADDR_ANY.
932 */
933struct sockaddr_in *str2sa(char *str) {
934 static struct sockaddr_in sa;
935 char *c;
936 int port;
937
willy tarreaua1598082005-12-17 13:08:06 +0100938 memset(&sa, 0, sizeof(sa));
willy tarreau0f7af912005-12-17 12:21:26 +0100939 str=strdup(str);
940
941 if ((c=strrchr(str,':')) != NULL) {
942 *c++=0;
943 port=atol(c);
944 }
945 else
946 port=0;
947
948 if (*str == '*' || *str == '\0') { /* INADDR_ANY */
949 sa.sin_addr.s_addr = INADDR_ANY;
950 }
willy tarreau8a86dbf2005-12-18 00:45:59 +0100951 else if (!inet_pton(AF_INET, str, &sa.sin_addr)) {
willy tarreau0f7af912005-12-17 12:21:26 +0100952 struct hostent *he;
953
954 if ((he = gethostbyname(str)) == NULL) {
willy tarreau036e1ce2005-12-17 13:46:33 +0100955 Alert("Invalid server name: '%s'\n", str);
willy tarreau0f7af912005-12-17 12:21:26 +0100956 }
957 else
958 sa.sin_addr = *(struct in_addr *) *(he->h_addr_list);
959 }
960 sa.sin_port=htons(port);
961 sa.sin_family=AF_INET;
962
963 free(str);
964 return &sa;
965}
966
willy tarreaub1285d52005-12-18 01:20:14 +0100967/*
968 * converts <str> to a two struct in_addr* which are locally allocated.
969 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
970 * is optionnal and either in the dotted or CIDR notation.
971 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
972 */
973int str2net(char *str, struct in_addr *addr, struct in_addr *mask) {
974 char *c;
975 unsigned long len;
976
977 memset(mask, 0, sizeof(*mask));
978 memset(addr, 0, sizeof(*addr));
979 str=strdup(str);
980
981 if ((c = strrchr(str, '/')) != NULL) {
982 *c++ = 0;
983 /* c points to the mask */
984 if (strchr(c, '.') != NULL) { /* dotted notation */
985 if (!inet_pton(AF_INET, c, mask))
986 return 0;
987 }
988 else { /* mask length */
989 char *err;
990 len = strtol(c, &err, 10);
991 if (!*c || (err && *err) || (unsigned)len > 32)
992 return 0;
993 if (len)
994 mask->s_addr = htonl(0xFFFFFFFFUL << (32 - len));
995 else
996 mask->s_addr = 0;
997 }
998 }
999 else {
1000 mask->s_addr = 0xFFFFFFFF;
1001 }
1002 if (!inet_pton(AF_INET, str, addr)) {
1003 struct hostent *he;
1004
1005 if ((he = gethostbyname(str)) == NULL) {
1006 return 0;
1007 }
1008 else
1009 *addr = *(struct in_addr *) *(he->h_addr_list);
1010 }
1011 free(str);
1012 return 1;
1013}
1014
willy tarreau9fe663a2005-12-17 13:02:59 +01001015
1016/*
willy tarreaua41a8b42005-12-17 14:02:24 +01001017 * converts <str> to a list of listeners which are dynamically allocated.
1018 * The format is "{addr|'*'}:port[-end][,{addr|'*'}:port[-end]]*", where :
1019 * - <addr> can be empty or "*" to indicate INADDR_ANY ;
1020 * - <port> is a numerical port from 1 to 65535 ;
1021 * - <end> indicates to use the range from <port> to <end> instead (inclusive).
1022 * This can be repeated as many times as necessary, separated by a coma.
1023 * The <tail> argument is a pointer to a current list which should be appended
1024 * to the tail of the new list. The pointer to the new list is returned.
1025 */
1026struct listener *str2listener(char *str, struct listener *tail) {
1027 struct listener *l;
1028 char *c, *next, *range, *dupstr;
1029 int port, end;
1030
1031 next = dupstr = strdup(str);
willy tarreau4302f492005-12-18 01:00:37 +01001032
willy tarreaua41a8b42005-12-17 14:02:24 +01001033 while (next && *next) {
willy tarreau8a86dbf2005-12-18 00:45:59 +01001034 struct sockaddr_storage ss;
1035
willy tarreaua41a8b42005-12-17 14:02:24 +01001036 str = next;
1037 /* 1) look for the end of the first address */
1038 if ((next = strrchr(str, ',')) != NULL) {
1039 *next++ = 0;
1040 }
1041
willy tarreau8a86dbf2005-12-18 00:45:59 +01001042 /* 2) look for the addr/port delimiter, it's the last colon. */
1043 if ((range = strrchr(str, ':')) == NULL) {
1044 Alert("Missing port number: '%s'\n", str);
willy tarreaud0fb4652005-12-18 01:32:04 +01001045 goto fail;
willy tarreau8a86dbf2005-12-18 00:45:59 +01001046 }
1047
1048 *range++ = 0;
1049
1050 if (strrchr(str, ':') != NULL) {
1051 /* IPv6 address contains ':' */
1052 memset(&ss, 0, sizeof(ss));
1053 ss.ss_family = AF_INET6;
1054
1055 if (!inet_pton(ss.ss_family, str, &((struct sockaddr_in6 *)&ss)->sin6_addr)) {
1056 Alert("Invalid server address: '%s'\n", str);
willy tarreaud0fb4652005-12-18 01:32:04 +01001057 goto fail;
willy tarreau8a86dbf2005-12-18 00:45:59 +01001058 }
willy tarreaua41a8b42005-12-17 14:02:24 +01001059 }
1060 else {
willy tarreau8a86dbf2005-12-18 00:45:59 +01001061 memset(&ss, 0, sizeof(ss));
1062 ss.ss_family = AF_INET;
1063
1064 if (*str == '*' || *str == '\0') { /* INADDR_ANY */
1065 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = INADDR_ANY;
1066 }
1067 else if (!inet_pton(ss.ss_family, str, &((struct sockaddr_in *)&ss)->sin_addr)) {
1068 struct hostent *he;
1069
1070 if ((he = gethostbyname(str)) == NULL) {
1071 Alert("Invalid server name: '%s'\n", str);
willy tarreaud0fb4652005-12-18 01:32:04 +01001072 goto fail;
willy tarreau8a86dbf2005-12-18 00:45:59 +01001073 }
1074 else
1075 ((struct sockaddr_in *)&ss)->sin_addr =
1076 *(struct in_addr *) *(he->h_addr_list);
1077 }
1078 }
willy tarreaua41a8b42005-12-17 14:02:24 +01001079
1080 /* 3) look for the port-end delimiter */
1081 if ((c = strchr(range, '-')) != NULL) {
1082 *c++ = 0;
1083 end = atol(c);
1084 }
1085 else {
1086 end = atol(range);
1087 }
1088
willy tarreaud0fb4652005-12-18 01:32:04 +01001089 port = atol(range);
1090
1091 if (port < 1 || port > 65535) {
1092 Alert("Invalid port '%d' specified for address '%s'.\n", port, str);
1093 goto fail;
1094 }
1095
1096 if (end < 1 || end > 65535) {
1097 Alert("Invalid port '%d' specified for address '%s'.\n", end, str);
1098 goto fail;
1099 }
1100
1101 for (; port <= end; port++) {
willy tarreaua41a8b42005-12-17 14:02:24 +01001102 l = (struct listener *)calloc(1, sizeof(struct listener));
1103 l->next = tail;
1104 tail = l;
1105
willy tarreau8a86dbf2005-12-18 00:45:59 +01001106 l->addr = ss;
1107 if (ss.ss_family == AF_INET6)
1108 ((struct sockaddr_in6 *)(&l->addr))->sin6_port = htons(port);
1109 else
1110 ((struct sockaddr_in *)(&l->addr))->sin_port = htons(port);
1111
willy tarreaua41a8b42005-12-17 14:02:24 +01001112 } /* end for(port) */
1113 } /* end while(next) */
1114 free(dupstr);
1115 return tail;
willy tarreaud0fb4652005-12-18 01:32:04 +01001116 fail:
1117 free(dupstr);
1118 return NULL;
willy tarreaua41a8b42005-12-17 14:02:24 +01001119}
1120
willy tarreau4302f492005-12-18 01:00:37 +01001121
1122#define FD_SETS_ARE_BITFIELDS
1123#ifdef FD_SETS_ARE_BITFIELDS
1124/*
1125 * This map is used with all the FD_* macros to check whether a particular bit
1126 * is set or not. Each bit represents an ACSII code. FD_SET() sets those bytes
1127 * which should be encoded. When FD_ISSET() returns non-zero, it means that the
1128 * byte should be encoded. Be careful to always pass bytes from 0 to 255
1129 * exclusively to the macros.
1130 */
1131fd_set hdr_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))];
1132fd_set url_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))];
1133
1134#else
1135#error "Check if your OS uses bitfields for fd_sets"
1136#endif
1137
1138/* will try to encode the string <string> replacing all characters tagged in
1139 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1140 * prefixed by <escape>, and will store the result between <start> (included
1141 *) and <stop> (excluded), and will always terminate the string with a '\0'
1142 * before <stop>. The position of the '\0' is returned if the conversion
1143 * completes. If bytes are missing between <start> and <stop>, then the
1144 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1145 * cannot even be stored so we return <start> without writing the 0.
1146 * The input string must also be zero-terminated.
1147 */
1148char hextab[16] = "0123456789ABCDEF";
1149char *encode_string(char *start, char *stop,
1150 const char escape, const fd_set *map,
1151 const char *string)
1152{
1153 if (start < stop) {
1154 stop--; /* reserve one byte for the final '\0' */
1155 while (start < stop && *string != 0) {
1156 if (!FD_ISSET((unsigned char)(*string), map))
1157 *start++ = *string;
1158 else {
1159 if (start + 3 >= stop)
1160 break;
1161 *start++ = escape;
1162 *start++ = hextab[(*string >> 4) & 15];
1163 *start++ = hextab[*string & 15];
1164 }
1165 string++;
1166 }
1167 *start = '\0';
1168 }
1169 return start;
1170}
willy tarreaua41a8b42005-12-17 14:02:24 +01001171
1172/*
willy tarreau9fe663a2005-12-17 13:02:59 +01001173 * This function sends a syslog message to both log servers of a proxy,
1174 * or to global log servers if the proxy is NULL.
1175 * It also tries not to waste too much time computing the message header.
1176 * It doesn't care about errors nor does it report them.
willy tarreau9fe663a2005-12-17 13:02:59 +01001177 */
1178void send_log(struct proxy *p, int level, char *message, ...) {
1179 static int logfd = -1; /* syslog UDP socket */
1180 static long tvsec = -1; /* to force the string to be initialized */
1181 struct timeval tv;
1182 va_list argp;
1183 static char logmsg[MAX_SYSLOG_LEN];
1184 static char *dataptr = NULL;
1185 int fac_level;
1186 int hdr_len, data_len;
1187 struct sockaddr_in *sa[2];
willy tarreau8337c6b2005-12-17 13:41:01 +01001188 int facilities[2], loglevel[2];
willy tarreau9fe663a2005-12-17 13:02:59 +01001189 int nbloggers = 0;
1190 char *log_ptr;
1191
1192 if (logfd < 0) {
1193 if ((logfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
1194 return;
1195 }
1196
1197 if (level < 0 || progname == NULL || message == NULL)
1198 return;
1199
1200 gettimeofday(&tv, NULL);
willy tarreauc29948c2005-12-17 13:10:27 +01001201 if (tv.tv_sec != tvsec || dataptr == NULL) {
willy tarreau9fe663a2005-12-17 13:02:59 +01001202 /* this string is rebuild only once a second */
1203 struct tm *tm = localtime(&tv.tv_sec);
1204 tvsec = tv.tv_sec;
1205
willy tarreauc29948c2005-12-17 13:10:27 +01001206 hdr_len = snprintf(logmsg, sizeof(logmsg),
1207 "<<<<>%s %2d %02d:%02d:%02d %s[%d]: ",
1208 monthname[tm->tm_mon],
1209 tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec,
1210 progname, pid);
1211 /* WARNING: depending upon implementations, snprintf may return
1212 * either -1 or the number of bytes that would be needed to store
1213 * the total message. In both cases, we must adjust it.
willy tarreau9fe663a2005-12-17 13:02:59 +01001214 */
willy tarreauc29948c2005-12-17 13:10:27 +01001215 if (hdr_len < 0 || hdr_len > sizeof(logmsg))
1216 hdr_len = sizeof(logmsg);
1217
1218 dataptr = logmsg + hdr_len;
willy tarreau9fe663a2005-12-17 13:02:59 +01001219 }
1220
1221 va_start(argp, message);
1222 data_len = vsnprintf(dataptr, logmsg + sizeof(logmsg) - dataptr, message, argp);
willy tarreauc29948c2005-12-17 13:10:27 +01001223 if (data_len < 0 || data_len > (logmsg + sizeof(logmsg) - dataptr))
1224 data_len = logmsg + sizeof(logmsg) - dataptr;
willy tarreau9fe663a2005-12-17 13:02:59 +01001225 va_end(argp);
willy tarreauc29948c2005-12-17 13:10:27 +01001226 dataptr[data_len - 1] = '\n'; /* force a break on ultra-long lines */
willy tarreau9fe663a2005-12-17 13:02:59 +01001227
1228 if (p == NULL) {
1229 if (global.logfac1 >= 0) {
1230 sa[nbloggers] = &global.logsrv1;
1231 facilities[nbloggers] = global.logfac1;
willy tarreau8337c6b2005-12-17 13:41:01 +01001232 loglevel[nbloggers] = global.loglev1;
willy tarreau9fe663a2005-12-17 13:02:59 +01001233 nbloggers++;
1234 }
1235 if (global.logfac2 >= 0) {
1236 sa[nbloggers] = &global.logsrv2;
1237 facilities[nbloggers] = global.logfac2;
willy tarreau8337c6b2005-12-17 13:41:01 +01001238 loglevel[nbloggers] = global.loglev2;
willy tarreau9fe663a2005-12-17 13:02:59 +01001239 nbloggers++;
1240 }
1241 } else {
1242 if (p->logfac1 >= 0) {
1243 sa[nbloggers] = &p->logsrv1;
1244 facilities[nbloggers] = p->logfac1;
willy tarreau8337c6b2005-12-17 13:41:01 +01001245 loglevel[nbloggers] = p->loglev1;
willy tarreau9fe663a2005-12-17 13:02:59 +01001246 nbloggers++;
1247 }
1248 if (p->logfac2 >= 0) {
1249 sa[nbloggers] = &p->logsrv2;
1250 facilities[nbloggers] = p->logfac2;
willy tarreau8337c6b2005-12-17 13:41:01 +01001251 loglevel[nbloggers] = p->loglev2;
willy tarreau9fe663a2005-12-17 13:02:59 +01001252 nbloggers++;
1253 }
1254 }
1255
1256 while (nbloggers-- > 0) {
willy tarreau8337c6b2005-12-17 13:41:01 +01001257 /* we can filter the level of the messages that are sent to each logger */
1258 if (level > loglevel[nbloggers])
1259 continue;
1260
willy tarreauc29948c2005-12-17 13:10:27 +01001261 /* For each target, we may have a different facility.
1262 * We can also have a different log level for each message.
1263 * This induces variations in the message header length.
1264 * Since we don't want to recompute it each time, nor copy it every
1265 * time, we only change the facility in the pre-computed header,
1266 * and we change the pointer to the header accordingly.
1267 */
willy tarreau9fe663a2005-12-17 13:02:59 +01001268 fac_level = (facilities[nbloggers] << 3) + level;
1269 log_ptr = logmsg + 3; /* last digit of the log level */
1270 do {
1271 *log_ptr = '0' + fac_level % 10;
1272 fac_level /= 10;
1273 log_ptr--;
1274 } while (fac_level && log_ptr > logmsg);
1275 *log_ptr = '<';
willy tarreau9fe663a2005-12-17 13:02:59 +01001276
willy tarreauc29948c2005-12-17 13:10:27 +01001277 /* the total syslog message now starts at logptr, for dataptr+data_len-logptr */
willy tarreau9fe663a2005-12-17 13:02:59 +01001278
1279#ifndef MSG_NOSIGNAL
willy tarreauc29948c2005-12-17 13:10:27 +01001280 sendto(logfd, log_ptr, dataptr + data_len - log_ptr, MSG_DONTWAIT,
willy tarreau9fe663a2005-12-17 13:02:59 +01001281 (struct sockaddr *)sa[nbloggers], sizeof(**sa));
1282#else
willy tarreauc29948c2005-12-17 13:10:27 +01001283 sendto(logfd, log_ptr, dataptr + data_len - log_ptr, MSG_DONTWAIT | MSG_NOSIGNAL,
willy tarreau9fe663a2005-12-17 13:02:59 +01001284 (struct sockaddr *)sa[nbloggers], sizeof(**sa));
1285#endif
1286 }
willy tarreau0f7af912005-12-17 12:21:26 +01001287}
1288
1289
1290/* sets <tv> to the current time */
1291static inline struct timeval *tv_now(struct timeval *tv) {
1292 if (tv)
1293 gettimeofday(tv, NULL);
1294 return tv;
1295}
1296
1297/*
1298 * adds <ms> ms to <from>, set the result to <tv> and returns a pointer <tv>
1299 */
1300static inline struct timeval *tv_delayfrom(struct timeval *tv, struct timeval *from, int ms) {
1301 if (!tv || !from)
1302 return NULL;
1303 tv->tv_usec = from->tv_usec + (ms%1000)*1000;
1304 tv->tv_sec = from->tv_sec + (ms/1000);
1305 while (tv->tv_usec >= 1000000) {
1306 tv->tv_usec -= 1000000;
1307 tv->tv_sec++;
1308 }
1309 return tv;
1310}
1311
1312/*
1313 * compares <tv1> and <tv2> : returns 0 if equal, -1 if tv1 < tv2, 1 if tv1 > tv2
willy tarreaub952e1d2005-12-18 01:31:20 +01001314 * Must not be used when either argument is eternity. Use tv_cmp2() for that.
willy tarreau0f7af912005-12-17 12:21:26 +01001315 */
1316static inline int tv_cmp(struct timeval *tv1, struct timeval *tv2) {
willy tarreau750a4722005-12-17 13:21:24 +01001317 if (tv1->tv_sec < tv2->tv_sec)
willy tarreau0f7af912005-12-17 12:21:26 +01001318 return -1;
willy tarreau750a4722005-12-17 13:21:24 +01001319 else if (tv1->tv_sec > tv2->tv_sec)
willy tarreau0f7af912005-12-17 12:21:26 +01001320 return 1;
1321 else if (tv1->tv_usec < tv2->tv_usec)
1322 return -1;
willy tarreau750a4722005-12-17 13:21:24 +01001323 else if (tv1->tv_usec > tv2->tv_usec)
1324 return 1;
willy tarreau0f7af912005-12-17 12:21:26 +01001325 else
1326 return 0;
1327}
1328
1329/*
1330 * returns the absolute difference, in ms, between tv1 and tv2
willy tarreaub952e1d2005-12-18 01:31:20 +01001331 * Must not be used when either argument is eternity.
willy tarreau0f7af912005-12-17 12:21:26 +01001332 */
1333unsigned long tv_delta(struct timeval *tv1, struct timeval *tv2) {
1334 int cmp;
1335 unsigned long ret;
1336
1337
willy tarreauef900ab2005-12-17 12:52:52 +01001338 cmp = tv_cmp(tv1, tv2);
willy tarreau0f7af912005-12-17 12:21:26 +01001339 if (!cmp)
1340 return 0; /* same dates, null diff */
willy tarreau750a4722005-12-17 13:21:24 +01001341 else if (cmp < 0) {
willy tarreauef900ab2005-12-17 12:52:52 +01001342 struct timeval *tmp = tv1;
1343 tv1 = tv2;
1344 tv2 = tmp;
willy tarreau0f7af912005-12-17 12:21:26 +01001345 }
willy tarreauef900ab2005-12-17 12:52:52 +01001346 ret = (tv1->tv_sec - tv2->tv_sec) * 1000;
willy tarreau0f7af912005-12-17 12:21:26 +01001347 if (tv1->tv_usec > tv2->tv_usec)
willy tarreauef900ab2005-12-17 12:52:52 +01001348 ret += (tv1->tv_usec - tv2->tv_usec) / 1000;
willy tarreau0f7af912005-12-17 12:21:26 +01001349 else
willy tarreauef900ab2005-12-17 12:52:52 +01001350 ret -= (tv2->tv_usec - tv1->tv_usec) / 1000;
willy tarreau0f7af912005-12-17 12:21:26 +01001351 return (unsigned long) ret;
1352}
1353
1354/*
willy tarreau750a4722005-12-17 13:21:24 +01001355 * returns the difference, in ms, between tv1 and tv2
willy tarreaub952e1d2005-12-18 01:31:20 +01001356 * Must not be used when either argument is eternity.
willy tarreau750a4722005-12-17 13:21:24 +01001357 */
1358static inline unsigned long tv_diff(struct timeval *tv1, struct timeval *tv2) {
1359 unsigned long ret;
1360
willy tarreau6e682ce2005-12-17 13:26:49 +01001361 ret = (tv2->tv_sec - tv1->tv_sec) * 1000;
1362 if (tv2->tv_usec > tv1->tv_usec)
1363 ret += (tv2->tv_usec - tv1->tv_usec) / 1000;
willy tarreau750a4722005-12-17 13:21:24 +01001364 else
willy tarreau6e682ce2005-12-17 13:26:49 +01001365 ret -= (tv1->tv_usec - tv2->tv_usec) / 1000;
willy tarreau750a4722005-12-17 13:21:24 +01001366 return (unsigned long) ret;
1367}
1368
1369/*
willy tarreau0f7af912005-12-17 12:21:26 +01001370 * compares <tv1> and <tv2> modulo 1ms: returns 0 if equal, -1 if tv1 < tv2, 1 if tv1 > tv2
willy tarreaub952e1d2005-12-18 01:31:20 +01001371 * Must not be used when either argument is eternity. Use tv_cmp2_ms() for that.
willy tarreau0f7af912005-12-17 12:21:26 +01001372 */
1373static inline int tv_cmp_ms(struct timeval *tv1, struct timeval *tv2) {
willy tarreauefae1842005-12-17 12:51:03 +01001374 if (tv1->tv_sec == tv2->tv_sec) {
willy tarreau750a4722005-12-17 13:21:24 +01001375 if (tv2->tv_usec > tv1->tv_usec + 1000)
willy tarreauefae1842005-12-17 12:51:03 +01001376 return -1;
willy tarreau750a4722005-12-17 13:21:24 +01001377 else if (tv1->tv_usec > tv2->tv_usec + 1000)
1378 return 1;
willy tarreauefae1842005-12-17 12:51:03 +01001379 else
1380 return 0;
1381 }
willy tarreau0f7af912005-12-17 12:21:26 +01001382 else if ((tv2->tv_sec > tv1->tv_sec + 1) ||
willy tarreauef900ab2005-12-17 12:52:52 +01001383 ((tv2->tv_sec == tv1->tv_sec + 1) && (tv2->tv_usec + 1000000 > tv1->tv_usec + 1000)))
willy tarreau0f7af912005-12-17 12:21:26 +01001384 return -1;
willy tarreau750a4722005-12-17 13:21:24 +01001385 else if ((tv1->tv_sec > tv2->tv_sec + 1) ||
1386 ((tv1->tv_sec == tv2->tv_sec + 1) && (tv1->tv_usec + 1000000 > tv2->tv_usec + 1000)))
1387 return 1;
willy tarreau0f7af912005-12-17 12:21:26 +01001388 else
1389 return 0;
1390}
1391
1392/*
1393 * returns the remaining time between tv1=now and event=tv2
1394 * if tv2 is passed, 0 is returned.
willy tarreaub952e1d2005-12-18 01:31:20 +01001395 * Must not be used when either argument is eternity.
willy tarreau0f7af912005-12-17 12:21:26 +01001396 */
1397static inline unsigned long tv_remain(struct timeval *tv1, struct timeval *tv2) {
1398 unsigned long ret;
1399
willy tarreau0f7af912005-12-17 12:21:26 +01001400 if (tv_cmp_ms(tv1, tv2) >= 0)
1401 return 0; /* event elapsed */
1402
willy tarreauef900ab2005-12-17 12:52:52 +01001403 ret = (tv2->tv_sec - tv1->tv_sec) * 1000;
willy tarreau0f7af912005-12-17 12:21:26 +01001404 if (tv2->tv_usec > tv1->tv_usec)
willy tarreauef900ab2005-12-17 12:52:52 +01001405 ret += (tv2->tv_usec - tv1->tv_usec) / 1000;
willy tarreau0f7af912005-12-17 12:21:26 +01001406 else
willy tarreauef900ab2005-12-17 12:52:52 +01001407 ret -= (tv1->tv_usec - tv2->tv_usec) / 1000;
willy tarreau0f7af912005-12-17 12:21:26 +01001408 return (unsigned long) ret;
1409}
1410
1411
1412/*
1413 * zeroes a struct timeval
1414 */
1415
1416static inline struct timeval *tv_eternity(struct timeval *tv) {
1417 tv->tv_sec = tv->tv_usec = 0;
1418 return tv;
1419}
1420
1421/*
1422 * returns 1 if tv is null, else 0
1423 */
1424static inline int tv_iseternity(struct timeval *tv) {
1425 if (tv->tv_sec == 0 && tv->tv_usec == 0)
1426 return 1;
1427 else
1428 return 0;
1429}
1430
1431/*
1432 * compares <tv1> and <tv2> : returns 0 if equal, -1 if tv1 < tv2, 1 if tv1 > tv2,
1433 * considering that 0 is the eternity.
1434 */
1435static inline int tv_cmp2(struct timeval *tv1, struct timeval *tv2) {
1436 if (tv_iseternity(tv1))
1437 if (tv_iseternity(tv2))
1438 return 0; /* same */
1439 else
1440 return 1; /* tv1 later than tv2 */
1441 else if (tv_iseternity(tv2))
1442 return -1; /* tv2 later than tv1 */
1443
1444 if (tv1->tv_sec > tv2->tv_sec)
1445 return 1;
1446 else if (tv1->tv_sec < tv2->tv_sec)
1447 return -1;
1448 else if (tv1->tv_usec > tv2->tv_usec)
1449 return 1;
1450 else if (tv1->tv_usec < tv2->tv_usec)
1451 return -1;
1452 else
1453 return 0;
1454}
1455
1456/*
1457 * compares <tv1> and <tv2> modulo 1 ms: returns 0 if equal, -1 if tv1 < tv2, 1 if tv1 > tv2,
1458 * considering that 0 is the eternity.
1459 */
1460static inline int tv_cmp2_ms(struct timeval *tv1, struct timeval *tv2) {
1461 if (tv_iseternity(tv1))
1462 if (tv_iseternity(tv2))
1463 return 0; /* same */
1464 else
1465 return 1; /* tv1 later than tv2 */
1466 else if (tv_iseternity(tv2))
1467 return -1; /* tv2 later than tv1 */
1468
willy tarreauefae1842005-12-17 12:51:03 +01001469 if (tv1->tv_sec == tv2->tv_sec) {
willy tarreauef900ab2005-12-17 12:52:52 +01001470 if (tv1->tv_usec > tv2->tv_usec + 1000)
willy tarreauefae1842005-12-17 12:51:03 +01001471 return 1;
willy tarreauef900ab2005-12-17 12:52:52 +01001472 else if (tv2->tv_usec > tv1->tv_usec + 1000)
willy tarreauefae1842005-12-17 12:51:03 +01001473 return -1;
1474 else
1475 return 0;
1476 }
1477 else if ((tv1->tv_sec > tv2->tv_sec + 1) ||
willy tarreauef900ab2005-12-17 12:52:52 +01001478 ((tv1->tv_sec == tv2->tv_sec + 1) && (tv1->tv_usec + 1000000 > tv2->tv_usec + 1000)))
willy tarreau0f7af912005-12-17 12:21:26 +01001479 return 1;
1480 else if ((tv2->tv_sec > tv1->tv_sec + 1) ||
willy tarreauef900ab2005-12-17 12:52:52 +01001481 ((tv2->tv_sec == tv1->tv_sec + 1) && (tv2->tv_usec + 1000000 > tv1->tv_usec + 1000)))
willy tarreau0f7af912005-12-17 12:21:26 +01001482 return -1;
1483 else
1484 return 0;
1485}
1486
1487/*
willy tarreaub952e1d2005-12-18 01:31:20 +01001488 * returns the remaining time between tv1=now and event=tv2
1489 * if tv2 is passed, 0 is returned.
1490 * Returns TIME_ETERNITY if tv2 is eternity.
1491 */
1492static inline unsigned long tv_remain2(struct timeval *tv1, struct timeval *tv2) {
1493 unsigned long ret;
1494
1495 if (tv_iseternity(tv2))
1496 return TIME_ETERNITY;
1497
1498 if (tv_cmp_ms(tv1, tv2) >= 0)
1499 return 0; /* event elapsed */
1500
1501 ret = (tv2->tv_sec - tv1->tv_sec) * 1000;
1502 if (tv2->tv_usec > tv1->tv_usec)
1503 ret += (tv2->tv_usec - tv1->tv_usec) / 1000;
1504 else
1505 ret -= (tv1->tv_usec - tv2->tv_usec) / 1000;
1506 return (unsigned long) ret;
1507}
1508
1509/*
willy tarreau0f7af912005-12-17 12:21:26 +01001510 * returns the first event between tv1 and tv2 into tvmin.
1511 * a zero tv is ignored. tvmin is returned.
1512 */
1513static inline struct timeval *tv_min(struct timeval *tvmin,
1514 struct timeval *tv1, struct timeval *tv2) {
1515
1516 if (tv_cmp2(tv1, tv2) <= 0)
1517 *tvmin = *tv1;
1518 else
1519 *tvmin = *tv2;
1520
1521 return tvmin;
1522}
1523
1524
1525
1526/***********************************************************/
1527/* fd management ***************************************/
1528/***********************************************************/
1529
1530
1531
willy tarreau5cbea6f2005-12-17 12:48:26 +01001532/* Deletes an FD from the fdsets, and recomputes the maxfd limit.
1533 * The file descriptor is also closed.
1534 */
willy tarreau0f7af912005-12-17 12:21:26 +01001535static inline void fd_delete(int fd) {
willy tarreau0f7af912005-12-17 12:21:26 +01001536 FD_CLR(fd, StaticReadEvent);
1537 FD_CLR(fd, StaticWriteEvent);
willy tarreau08dedbe2005-12-18 01:13:48 +01001538#if defined(ENABLE_EPOLL)
1539 if (PrevReadEvent) {
1540 FD_CLR(fd, PrevReadEvent);
1541 FD_CLR(fd, PrevWriteEvent);
1542 }
1543#endif
1544
willy tarreau5cbea6f2005-12-17 12:48:26 +01001545 close(fd);
1546 fdtab[fd].state = FD_STCLOSE;
willy tarreau0f7af912005-12-17 12:21:26 +01001547
1548 while ((maxfd-1 >= 0) && (fdtab[maxfd-1].state == FD_STCLOSE))
1549 maxfd--;
1550}
1551
1552/* recomputes the maxfd limit from the fd */
1553static inline void fd_insert(int fd) {
1554 if (fd+1 > maxfd)
1555 maxfd = fd+1;
1556}
1557
1558/*************************************************************/
1559/* task management ***************************************/
1560/*************************************************************/
1561
willy tarreau5cbea6f2005-12-17 12:48:26 +01001562/* puts the task <t> in run queue <q>, and returns <t> */
1563static inline struct task *task_wakeup(struct task **q, struct task *t) {
1564 if (t->state == TASK_RUNNING)
1565 return t;
willy tarreau0f7af912005-12-17 12:21:26 +01001566 else {
willy tarreau5cbea6f2005-12-17 12:48:26 +01001567 t->rqnext = *q;
1568 t->state = TASK_RUNNING;
1569 return *q = t;
willy tarreau0f7af912005-12-17 12:21:26 +01001570 }
1571}
1572
willy tarreau5cbea6f2005-12-17 12:48:26 +01001573/* removes the task <t> from the queue <q>
1574 * <s> MUST be <q>'s first task.
willy tarreau0f7af912005-12-17 12:21:26 +01001575 * set the run queue to point to the next one, and return it
1576 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01001577static inline struct task *task_sleep(struct task **q, struct task *t) {
1578 if (t->state == TASK_RUNNING) {
1579 *q = t->rqnext;
1580 t->state = TASK_IDLE; /* tell that s has left the run queue */
willy tarreau0f7af912005-12-17 12:21:26 +01001581 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01001582 return *q; /* return next running task */
willy tarreau0f7af912005-12-17 12:21:26 +01001583}
1584
1585/*
willy tarreau5cbea6f2005-12-17 12:48:26 +01001586 * removes the task <t> from its wait queue. It must have already been removed
willy tarreau0f7af912005-12-17 12:21:26 +01001587 * from the run queue. A pointer to the task itself is returned.
1588 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01001589static inline struct task *task_delete(struct task *t) {
1590 t->prev->next = t->next;
1591 t->next->prev = t->prev;
1592 return t;
willy tarreau0f7af912005-12-17 12:21:26 +01001593}
1594
1595/*
willy tarreau5cbea6f2005-12-17 12:48:26 +01001596 * frees a task. Its context must have been freed since it will be lost.
willy tarreau0f7af912005-12-17 12:21:26 +01001597 */
1598static inline void task_free(struct task *t) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01001599 pool_free(task, t);
willy tarreau0f7af912005-12-17 12:21:26 +01001600}
1601
willy tarreau5cbea6f2005-12-17 12:48:26 +01001602/* inserts <task> into its assigned wait queue, where it may already be. In this case, it
willy tarreau0f7af912005-12-17 12:21:26 +01001603 * may be only moved or left where it was, depending on its timing requirements.
1604 * <task> is returned.
1605 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01001606struct task *task_queue(struct task *task) {
1607 struct task *list = task->wq;
willy tarreau0f7af912005-12-17 12:21:26 +01001608 struct task *start_from;
1609
1610 /* first, test if the task was already in a list */
1611 if (task->prev == NULL) {
1612 // start_from = list;
1613 start_from = list->prev;
willy tarreau750a4722005-12-17 13:21:24 +01001614#if STATTIME > 0
willy tarreau0f7af912005-12-17 12:21:26 +01001615 stats_tsk_new++;
willy tarreau750a4722005-12-17 13:21:24 +01001616#endif
willy tarreau0f7af912005-12-17 12:21:26 +01001617 /* insert the unlinked <task> into the list, searching back from the last entry */
1618 while (start_from != list && tv_cmp2(&task->expire, &start_from->expire) < 0) {
1619 start_from = start_from->prev;
willy tarreau750a4722005-12-17 13:21:24 +01001620#if STATTIME > 0
willy tarreau0f7af912005-12-17 12:21:26 +01001621 stats_tsk_nsrch++;
willy tarreau750a4722005-12-17 13:21:24 +01001622#endif
willy tarreau0f7af912005-12-17 12:21:26 +01001623 }
1624
1625 // while (start_from->next != list && tv_cmp2(&task->expire, &start_from->next->expire) > 0) {
1626 // start_from = start_from->next;
1627 // stats_tsk_nsrch++;
1628 // }
1629 }
1630 else if (task->prev == list ||
1631 tv_cmp2(&task->expire, &task->prev->expire) >= 0) { /* walk right */
1632 start_from = task->next;
1633 if (start_from == list || tv_cmp2(&task->expire, &start_from->expire) <= 0) {
willy tarreau750a4722005-12-17 13:21:24 +01001634#if STATTIME > 0
willy tarreau0f7af912005-12-17 12:21:26 +01001635 stats_tsk_good++;
willy tarreau750a4722005-12-17 13:21:24 +01001636#endif
willy tarreau0f7af912005-12-17 12:21:26 +01001637 return task; /* it's already in the right place */
1638 }
1639
willy tarreau750a4722005-12-17 13:21:24 +01001640#if STATTIME > 0
willy tarreau0f7af912005-12-17 12:21:26 +01001641 stats_tsk_right++;
willy tarreau750a4722005-12-17 13:21:24 +01001642#endif
1643
1644 /* if the task is not at the right place, there's little chance that
1645 * it has only shifted a bit, and it will nearly always be queued
1646 * at the end of the list because of constant timeouts
1647 * (observed in real case).
1648 */
1649#ifndef WE_REALLY_THINK_THAT_THIS_TASK_MAY_HAVE_SHIFTED
1650 start_from = list->prev; /* assume we'll queue to the end of the list */
1651 while (start_from != list && tv_cmp2(&task->expire, &start_from->expire) < 0) {
1652 start_from = start_from->prev;
1653#if STATTIME > 0
1654 stats_tsk_lsrch++;
1655#endif
1656 }
1657#else /* WE_REALLY_... */
willy tarreau0f7af912005-12-17 12:21:26 +01001658 /* insert the unlinked <task> into the list, searching after position <start_from> */
1659 while (start_from->next != list && tv_cmp2(&task->expire, &start_from->next->expire) > 0) {
1660 start_from = start_from->next;
willy tarreau750a4722005-12-17 13:21:24 +01001661#if STATTIME > 0
willy tarreau0f7af912005-12-17 12:21:26 +01001662 stats_tsk_rsrch++;
willy tarreau750a4722005-12-17 13:21:24 +01001663#endif
willy tarreau0f7af912005-12-17 12:21:26 +01001664 }
willy tarreau750a4722005-12-17 13:21:24 +01001665#endif /* WE_REALLY_... */
1666
willy tarreau0f7af912005-12-17 12:21:26 +01001667 /* we need to unlink it now */
1668 task_delete(task);
1669 }
1670 else { /* walk left. */
willy tarreau750a4722005-12-17 13:21:24 +01001671#if STATTIME > 0
willy tarreau0f7af912005-12-17 12:21:26 +01001672 stats_tsk_left++;
willy tarreau750a4722005-12-17 13:21:24 +01001673#endif
willy tarreau0f7af912005-12-17 12:21:26 +01001674#ifdef LEFT_TO_TOP /* not very good */
1675 start_from = list;
1676 while (start_from->next != list && tv_cmp2(&task->expire, &start_from->next->expire) > 0) {
1677 start_from = start_from->next;
willy tarreau750a4722005-12-17 13:21:24 +01001678#if STATTIME > 0
willy tarreau0f7af912005-12-17 12:21:26 +01001679 stats_tsk_lsrch++;
willy tarreau750a4722005-12-17 13:21:24 +01001680#endif
willy tarreau0f7af912005-12-17 12:21:26 +01001681 }
1682#else
1683 start_from = task->prev->prev; /* valid because of the previous test above */
1684 while (start_from != list && tv_cmp2(&task->expire, &start_from->expire) < 0) {
1685 start_from = start_from->prev;
willy tarreau750a4722005-12-17 13:21:24 +01001686#if STATTIME > 0
willy tarreau0f7af912005-12-17 12:21:26 +01001687 stats_tsk_lsrch++;
willy tarreau750a4722005-12-17 13:21:24 +01001688#endif
willy tarreau0f7af912005-12-17 12:21:26 +01001689 }
1690#endif
1691 /* we need to unlink it now */
1692 task_delete(task);
1693 }
1694 task->prev = start_from;
1695 task->next = start_from->next;
1696 task->next->prev = task;
1697 start_from->next = task;
1698 return task;
1699}
1700
1701
1702/*********************************************************************/
1703/* more specific functions ***************************************/
1704/*********************************************************************/
1705
1706/* some prototypes */
1707static int maintain_proxies(void);
1708
willy tarreaub952e1d2005-12-18 01:31:20 +01001709/* This either returns the sockname or the original destination address. Code
willy tarreau5cbea6f2005-12-17 12:48:26 +01001710 * inspired from Patrick Schaaf's example of nf_getsockname() implementation.
1711 */
willy tarreauc5f73ed2005-12-18 01:26:38 +01001712static int get_original_dst(int fd, struct sockaddr_in *sa, socklen_t *salen) {
willy tarreaua1598082005-12-17 13:08:06 +01001713#if defined(TPROXY) && defined(SO_ORIGINAL_DST)
willy tarreau5cbea6f2005-12-17 12:48:26 +01001714 return getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, (void *)sa, salen);
1715#else
willy tarreaua1598082005-12-17 13:08:06 +01001716#if defined(TPROXY) && defined(USE_GETSOCKNAME)
willy tarreau5cbea6f2005-12-17 12:48:26 +01001717 return getsockname(fd, (struct sockaddr *)sa, salen);
1718#else
1719 return -1;
1720#endif
1721#endif
1722}
1723
1724/*
1725 * frees the context associated to a session. It must have been removed first.
1726 */
1727static inline void session_free(struct session *s) {
1728 if (s->req)
1729 pool_free(buffer, s->req);
1730 if (s->rep)
1731 pool_free(buffer, s->rep);
willy tarreau4302f492005-12-18 01:00:37 +01001732
1733 if (s->rsp_cap != NULL) {
1734 struct cap_hdr *h;
1735 for (h = s->proxy->rsp_cap; h; h = h->next) {
1736 if (s->rsp_cap[h->index] != NULL)
1737 pool_free_to(h->pool, s->rsp_cap[h->index]);
1738 }
1739 pool_free_to(s->proxy->rsp_cap_pool, s->rsp_cap);
1740 }
1741 if (s->req_cap != NULL) {
1742 struct cap_hdr *h;
1743 for (h = s->proxy->req_cap; h; h = h->next) {
1744 if (s->req_cap[h->index] != NULL)
1745 pool_free_to(h->pool, s->req_cap[h->index]);
1746 }
1747 pool_free_to(s->proxy->req_cap_pool, s->req_cap);
1748 }
1749
willy tarreaua1598082005-12-17 13:08:06 +01001750 if (s->logs.uri)
1751 pool_free(requri, s->logs.uri);
willy tarreau8337c6b2005-12-17 13:41:01 +01001752 if (s->logs.cli_cookie)
1753 pool_free(capture, s->logs.cli_cookie);
1754 if (s->logs.srv_cookie)
1755 pool_free(capture, s->logs.srv_cookie);
willy tarreau9fe663a2005-12-17 13:02:59 +01001756
willy tarreau5cbea6f2005-12-17 12:48:26 +01001757 pool_free(session, s);
1758}
1759
willy tarreau0f7af912005-12-17 12:21:26 +01001760
1761/*
willy tarreau8337c6b2005-12-17 13:41:01 +01001762 * This function tries to find a running server for the proxy <px>. A first
1763 * pass looks for active servers, and if none is found, a second pass also
1764 * looks for backup servers.
1765 * If no valid server is found, NULL is returned and px->cursrv is left undefined.
1766 */
1767static inline struct server *find_server(struct proxy *px) {
1768 struct server *srv = px->cursrv;
1769 int ignore_backup = 1;
1770
1771 do {
1772 do {
1773 if (srv == NULL)
1774 srv = px->srv;
1775 if (srv->state & SRV_RUNNING
1776 && !((srv->state & SRV_BACKUP) && ignore_backup))
1777 return srv;
1778 srv = srv->next;
1779 } while (srv != px->cursrv);
1780 } while (ignore_backup--);
1781 return NULL;
1782}
1783
1784/*
willy tarreau5cbea6f2005-12-17 12:48:26 +01001785 * This function initiates a connection to the current server (s->srv) if (s->direct)
willy tarreaub1285d52005-12-18 01:20:14 +01001786 * is set, or to the dispatch server if (s->direct) is 0.
1787 * It can return one of :
1788 * - SN_ERR_NONE if everything's OK
1789 * - SN_ERR_SRVTO if there are no more servers
1790 * - SN_ERR_SRVCL if the connection was refused by the server
1791 * - SN_ERR_PRXCOND if the connection has been limited by the proxy (maxconn)
1792 * - SN_ERR_RESOURCE if a system resource is lacking (eg: fd limits, ports, ...)
1793 * - SN_ERR_INTERNAL for any other purely internal errors
1794 * Additionnally, in the case of SN_ERR_RESOURCE, an emergency log will be emitted.
willy tarreau0f7af912005-12-17 12:21:26 +01001795 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01001796int connect_server(struct session *s) {
willy tarreau0f7af912005-12-17 12:21:26 +01001797 int fd;
1798
willy tarreau12350152005-12-18 01:03:27 +01001799#ifdef DEBUG_FULL
1800 fprintf(stderr,"connect_server : s=%p\n",s);
1801#endif
willy tarreau0f7af912005-12-17 12:21:26 +01001802
willy tarreaue39cd132005-12-17 13:00:18 +01001803 if (s->flags & SN_DIRECT) { /* srv cannot be null */
willy tarreau5cbea6f2005-12-17 12:48:26 +01001804 s->srv_addr = s->srv->addr;
1805 }
1806 else if (s->proxy->options & PR_O_BALANCE) {
1807 if (s->proxy->options & PR_O_BALANCE_RR) {
willy tarreau8337c6b2005-12-17 13:41:01 +01001808 struct server *srv;
willy tarreau5cbea6f2005-12-17 12:48:26 +01001809
willy tarreau8337c6b2005-12-17 13:41:01 +01001810 srv = find_server(s->proxy);
1811
1812 if (srv == NULL) /* no server left */
willy tarreaub1285d52005-12-18 01:20:14 +01001813 return SN_ERR_SRVTO;
willy tarreau5cbea6f2005-12-17 12:48:26 +01001814
willy tarreau8337c6b2005-12-17 13:41:01 +01001815 s->srv_addr = srv->addr;
1816 s->srv = srv;
1817 s->proxy->cursrv = srv->next;
willy tarreau0f7af912005-12-17 12:21:26 +01001818 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01001819 else /* unknown balancing algorithm */
willy tarreaub1285d52005-12-18 01:20:14 +01001820 return SN_ERR_INTERNAL;
willy tarreau0f7af912005-12-17 12:21:26 +01001821 }
willy tarreaua1598082005-12-17 13:08:06 +01001822 else if (*(int *)&s->proxy->dispatch_addr.sin_addr) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01001823 /* connect to the defined dispatch addr */
willy tarreau0f7af912005-12-17 12:21:26 +01001824 s->srv_addr = s->proxy->dispatch_addr;
willy tarreau5cbea6f2005-12-17 12:48:26 +01001825 }
1826 else if (s->proxy->options & PR_O_TRANSP) {
1827 /* in transparent mode, use the original dest addr if no dispatch specified */
willy tarreaub952e1d2005-12-18 01:31:20 +01001828 socklen_t salen = sizeof(s->srv_addr);
1829
willy tarreau5cbea6f2005-12-17 12:48:26 +01001830 if (get_original_dst(s->cli_fd, &s->srv_addr, &salen) == -1) {
1831 qfprintf(stderr, "Cannot get original server address.\n");
willy tarreaub1285d52005-12-18 01:20:14 +01001832 return SN_ERR_INTERNAL;
willy tarreau5cbea6f2005-12-17 12:48:26 +01001833 }
1834 }
willy tarreau0f7af912005-12-17 12:21:26 +01001835
willy tarreaua41a8b42005-12-17 14:02:24 +01001836 /* if this server remaps proxied ports, we'll use
1837 * the port the client connected to with an offset. */
willy tarreaueedaa9f2005-12-17 14:08:03 +01001838 if (s->srv != NULL && s->srv->state & SRV_MAPPORTS) {
willy tarreaua41a8b42005-12-17 14:02:24 +01001839 struct sockaddr_in sockname;
willy tarreaub952e1d2005-12-18 01:31:20 +01001840 socklen_t namelen = sizeof(sockname);
willy tarreaua41a8b42005-12-17 14:02:24 +01001841
willy tarreaub952e1d2005-12-18 01:31:20 +01001842 if (!(s->proxy->options & PR_O_TRANSP) ||
1843 get_original_dst(s->cli_fd, (struct sockaddr_in *)&sockname, &namelen) == -1)
willy tarreaua41a8b42005-12-17 14:02:24 +01001844 getsockname(s->cli_fd, (struct sockaddr *)&sockname, &namelen);
1845 s->srv_addr.sin_port = htons(ntohs(s->srv_addr.sin_port) + ntohs(sockname.sin_port));
1846 }
1847
willy tarreau0f7af912005-12-17 12:21:26 +01001848 if ((fd = s->srv_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01001849 qfprintf(stderr, "Cannot get a server socket.\n");
willy tarreaub1285d52005-12-18 01:20:14 +01001850
1851 if (errno == ENFILE)
1852 send_log(s->proxy, LOG_EMERG,
1853 "Proxy %s reached system FD limit at %d. Please check system tunables.\n",
1854 s->proxy->id, maxfd);
1855 else if (errno == EMFILE)
1856 send_log(s->proxy, LOG_EMERG,
1857 "Proxy %s reached process FD limit at %d. Please check 'ulimit-n' and restart.\n",
1858 s->proxy->id, maxfd);
1859 else if (errno == ENOBUFS || errno == ENOMEM)
1860 send_log(s->proxy, LOG_EMERG,
1861 "Proxy %s reached system memory limit at %d sockets. Please check system tunables.\n",
1862 s->proxy->id, maxfd);
1863 /* this is a resource error */
1864 return SN_ERR_RESOURCE;
willy tarreau0f7af912005-12-17 12:21:26 +01001865 }
1866
willy tarreau9fe663a2005-12-17 13:02:59 +01001867 if (fd >= global.maxsock) {
willy tarreaub1285d52005-12-18 01:20:14 +01001868 /* do not log anything there, it's a normal condition when this option
1869 * is used to serialize connections to a server !
1870 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01001871 Alert("socket(): not enough free sockets. Raise -n argument. Giving up.\n");
1872 close(fd);
willy tarreaub1285d52005-12-18 01:20:14 +01001873 return SN_ERR_PRXCOND; /* it is a configuration limit */
willy tarreau5cbea6f2005-12-17 12:48:26 +01001874 }
1875
willy tarreau0f7af912005-12-17 12:21:26 +01001876 if ((fcntl(fd, F_SETFL, O_NONBLOCK)==-1) ||
1877 (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &one, sizeof(one)) == -1)) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01001878 qfprintf(stderr,"Cannot set client socket to non blocking mode.\n");
willy tarreau0f7af912005-12-17 12:21:26 +01001879 close(fd);
willy tarreaub1285d52005-12-18 01:20:14 +01001880 return SN_ERR_INTERNAL;
willy tarreau0f7af912005-12-17 12:21:26 +01001881 }
1882
willy tarreaub952e1d2005-12-18 01:31:20 +01001883 if (s->proxy->options & PR_O_TCP_SRV_KA)
1884 setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char *) &one, sizeof(one));
1885
willy tarreau0174f312005-12-18 01:02:42 +01001886 /* allow specific binding :
1887 * - server-specific at first
1888 * - proxy-specific next
1889 */
1890 if (s->srv != NULL && s->srv->state & SRV_BIND_SRC) {
1891 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one));
1892 if (bind(fd, (struct sockaddr *)&s->srv->source_addr, sizeof(s->srv->source_addr)) == -1) {
1893 Alert("Cannot bind to source address before connect() for server %s/%s. Aborting.\n",
1894 s->proxy->id, s->srv->id);
1895 close(fd);
willy tarreaub1285d52005-12-18 01:20:14 +01001896 send_log(s->proxy, LOG_EMERG,
1897 "Cannot bind to source address before connect() for server %s/%s.\n",
1898 s->proxy->id, s->srv->id);
1899 return SN_ERR_RESOURCE;
willy tarreau0174f312005-12-18 01:02:42 +01001900 }
1901 }
1902 else if (s->proxy->options & PR_O_BIND_SRC) {
1903 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one));
1904 if (bind(fd, (struct sockaddr *)&s->proxy->source_addr, sizeof(s->proxy->source_addr)) == -1) {
1905 Alert("Cannot bind to source address before connect() for proxy %s. Aborting.\n", s->proxy->id);
1906 close(fd);
willy tarreaub1285d52005-12-18 01:20:14 +01001907 send_log(s->proxy, LOG_EMERG,
1908 "Cannot bind to source address before connect() for server %s/%s.\n",
1909 s->proxy->id, s->srv->id);
1910 return SN_ERR_RESOURCE;
willy tarreau0174f312005-12-18 01:02:42 +01001911 }
willy tarreaua1598082005-12-17 13:08:06 +01001912 }
1913
willy tarreaub1285d52005-12-18 01:20:14 +01001914 if ((connect(fd, (struct sockaddr *)&s->srv_addr, sizeof(s->srv_addr)) == -1) &&
1915 (errno != EINPROGRESS) && (errno != EALREADY) && (errno != EISCONN)) {
1916
1917 if (errno == EAGAIN || errno == EADDRINUSE) {
1918 char *msg;
1919 if (errno == EAGAIN) /* no free ports left, try again later */
1920 msg = "no free ports";
1921 else
1922 msg = "local address already in use";
1923
1924 qfprintf(stderr,"Cannot connect: %s.\n",msg);
willy tarreau0f7af912005-12-17 12:21:26 +01001925 close(fd);
willy tarreaub1285d52005-12-18 01:20:14 +01001926 send_log(s->proxy, LOG_EMERG,
1927 "Connect() failed for server %s/%s: %s.\n",
1928 s->proxy->id, s->srv->id, msg);
1929 return SN_ERR_RESOURCE;
1930 } else if (errno == ETIMEDOUT) {
willy tarreaub952e1d2005-12-18 01:31:20 +01001931 //qfprintf(stderr,"Connect(): ETIMEDOUT");
willy tarreau0f7af912005-12-17 12:21:26 +01001932 close(fd);
willy tarreaub1285d52005-12-18 01:20:14 +01001933 return SN_ERR_SRVTO;
1934 } else {
1935 // (errno == ECONNREFUSED || errno == ENETUNREACH || errno == EACCES || errno == EPERM)
willy tarreaub952e1d2005-12-18 01:31:20 +01001936 //qfprintf(stderr,"Connect(): %d", errno);
willy tarreaub1285d52005-12-18 01:20:14 +01001937 close(fd);
1938 return SN_ERR_SRVCL;
willy tarreau0f7af912005-12-17 12:21:26 +01001939 }
1940 }
1941
willy tarreau5cbea6f2005-12-17 12:48:26 +01001942 fdtab[fd].owner = s->task;
willy tarreau0f7af912005-12-17 12:21:26 +01001943 fdtab[fd].read = &event_srv_read;
1944 fdtab[fd].write = &event_srv_write;
1945 fdtab[fd].state = FD_STCONN; /* connection in progress */
1946
1947 FD_SET(fd, StaticWriteEvent); /* for connect status */
1948
1949 fd_insert(fd);
1950
1951 if (s->proxy->contimeout)
1952 tv_delayfrom(&s->cnexpire, &now, s->proxy->contimeout);
1953 else
1954 tv_eternity(&s->cnexpire);
willy tarreaub1285d52005-12-18 01:20:14 +01001955 return SN_ERR_NONE; /* connection is OK */
willy tarreau0f7af912005-12-17 12:21:26 +01001956}
1957
1958/*
1959 * this function is called on a read event from a client socket.
1960 * It returns 0.
1961 */
1962int event_cli_read(int fd) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01001963 struct task *t = fdtab[fd].owner;
1964 struct session *s = t->context;
willy tarreau0f7af912005-12-17 12:21:26 +01001965 struct buffer *b = s->req;
1966 int ret, max;
willy tarreau0f7af912005-12-17 12:21:26 +01001967
willy tarreau12350152005-12-18 01:03:27 +01001968#ifdef DEBUG_FULL
1969 fprintf(stderr,"event_cli_read : fd=%d, s=%p\n", fd, s);
1970#endif
willy tarreau0f7af912005-12-17 12:21:26 +01001971
willy tarreau0f7af912005-12-17 12:21:26 +01001972 if (fdtab[fd].state != FD_STERROR) {
willy tarreau5dffb602005-12-18 01:15:23 +01001973#ifdef FILL_BUFFERS
1974 while (1)
1975#else
1976 do
1977#endif
1978 {
willy tarreau5cbea6f2005-12-17 12:48:26 +01001979 if (b->l == 0) { /* let's realign the buffer to optimize I/O */
1980 b->r = b->w = b->h = b->lr = b->data;
willy tarreauef900ab2005-12-17 12:52:52 +01001981 max = b->rlim - b->data;
willy tarreau5cbea6f2005-12-17 12:48:26 +01001982 }
1983 else if (b->r > b->w) {
willy tarreauef900ab2005-12-17 12:52:52 +01001984 max = b->rlim - b->r;
willy tarreau5cbea6f2005-12-17 12:48:26 +01001985 }
1986 else {
1987 max = b->w - b->r;
willy tarreauef900ab2005-12-17 12:52:52 +01001988 /* FIXME: theorically, if w>0, we shouldn't have rlim < data+size anymore
1989 * since it means that the rewrite protection has been removed. This
1990 * implies that the if statement can be removed.
1991 */
1992 if (max > b->rlim - b->data)
1993 max = b->rlim - b->data;
willy tarreau5cbea6f2005-12-17 12:48:26 +01001994 }
1995
1996 if (max == 0) { /* not anymore room to store data */
1997 FD_CLR(fd, StaticReadEvent);
willy tarreauef900ab2005-12-17 12:52:52 +01001998 break;
willy tarreau5cbea6f2005-12-17 12:48:26 +01001999 }
2000
willy tarreau3242e862005-12-17 12:27:53 +01002001#ifndef MSG_NOSIGNAL
willy tarreau5cbea6f2005-12-17 12:48:26 +01002002 {
willy tarreaub952e1d2005-12-18 01:31:20 +01002003 int skerr;
2004 socklen_t lskerr = sizeof(skerr);
willy tarreau5cbea6f2005-12-17 12:48:26 +01002005
willy tarreau5cbea6f2005-12-17 12:48:26 +01002006 getsockopt(fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr);
2007 if (skerr)
2008 ret = -1;
2009 else
2010 ret = recv(fd, b->r, max, 0);
2011 }
willy tarreau3242e862005-12-17 12:27:53 +01002012#else
willy tarreau5cbea6f2005-12-17 12:48:26 +01002013 ret = recv(fd, b->r, max, MSG_NOSIGNAL);
willy tarreau3242e862005-12-17 12:27:53 +01002014#endif
willy tarreau5cbea6f2005-12-17 12:48:26 +01002015 if (ret > 0) {
2016 b->r += ret;
2017 b->l += ret;
2018 s->res_cr = RES_DATA;
2019
2020 if (b->r == b->data + BUFSIZE) {
2021 b->r = b->data; /* wrap around the buffer */
2022 }
willy tarreaua1598082005-12-17 13:08:06 +01002023
2024 b->total += ret;
willy tarreau5cbea6f2005-12-17 12:48:26 +01002025 /* we hope to read more data or to get a close on next round */
2026 continue;
willy tarreau0f7af912005-12-17 12:21:26 +01002027 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01002028 else if (ret == 0) {
2029 s->res_cr = RES_NULL;
2030 break;
2031 }
2032 else if (errno == EAGAIN) {/* ignore EAGAIN */
2033 break;
2034 }
2035 else {
2036 s->res_cr = RES_ERROR;
2037 fdtab[fd].state = FD_STERROR;
2038 break;
2039 }
2040 } /* while(1) */
willy tarreau5dffb602005-12-18 01:15:23 +01002041#ifndef FILL_BUFFERS
2042 while (0);
2043#endif
willy tarreau0f7af912005-12-17 12:21:26 +01002044 }
2045 else {
2046 s->res_cr = RES_ERROR;
2047 fdtab[fd].state = FD_STERROR;
2048 }
2049
willy tarreau5cbea6f2005-12-17 12:48:26 +01002050 if (s->res_cr != RES_SILENT) {
willy tarreaub1ff9db2005-12-17 13:51:03 +01002051 if (s->proxy->clitimeout && FD_ISSET(fd, StaticReadEvent))
willy tarreau5cbea6f2005-12-17 12:48:26 +01002052 tv_delayfrom(&s->crexpire, &now, s->proxy->clitimeout);
2053 else
2054 tv_eternity(&s->crexpire);
2055
2056 task_wakeup(&rq, t);
2057 }
willy tarreau0f7af912005-12-17 12:21:26 +01002058
willy tarreau0f7af912005-12-17 12:21:26 +01002059 return 0;
2060}
2061
2062
2063/*
2064 * this function is called on a read event from a server socket.
2065 * It returns 0.
2066 */
2067int event_srv_read(int fd) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01002068 struct task *t = fdtab[fd].owner;
2069 struct session *s = t->context;
willy tarreau0f7af912005-12-17 12:21:26 +01002070 struct buffer *b = s->rep;
2071 int ret, max;
willy tarreau0f7af912005-12-17 12:21:26 +01002072
willy tarreau12350152005-12-18 01:03:27 +01002073#ifdef DEBUG_FULL
2074 fprintf(stderr,"event_srv_read : fd=%d, s=%p\n", fd, s);
2075#endif
willy tarreau0f7af912005-12-17 12:21:26 +01002076
willy tarreau0f7af912005-12-17 12:21:26 +01002077 if (fdtab[fd].state != FD_STERROR) {
willy tarreau5dffb602005-12-18 01:15:23 +01002078#ifdef FILL_BUFFERS
2079 while (1)
2080#else
2081 do
2082#endif
2083 {
willy tarreau5cbea6f2005-12-17 12:48:26 +01002084 if (b->l == 0) { /* let's realign the buffer to optimize I/O */
2085 b->r = b->w = b->h = b->lr = b->data;
willy tarreauef900ab2005-12-17 12:52:52 +01002086 max = b->rlim - b->data;
willy tarreau5cbea6f2005-12-17 12:48:26 +01002087 }
2088 else if (b->r > b->w) {
willy tarreauef900ab2005-12-17 12:52:52 +01002089 max = b->rlim - b->r;
willy tarreau5cbea6f2005-12-17 12:48:26 +01002090 }
2091 else {
2092 max = b->w - b->r;
willy tarreauef900ab2005-12-17 12:52:52 +01002093 /* FIXME: theorically, if w>0, we shouldn't have rlim < data+size anymore
2094 * since it means that the rewrite protection has been removed. This
2095 * implies that the if statement can be removed.
2096 */
2097 if (max > b->rlim - b->data)
2098 max = b->rlim - b->data;
willy tarreau5cbea6f2005-12-17 12:48:26 +01002099 }
2100
2101 if (max == 0) { /* not anymore room to store data */
2102 FD_CLR(fd, StaticReadEvent);
2103 break;
2104 }
2105
willy tarreau3242e862005-12-17 12:27:53 +01002106#ifndef MSG_NOSIGNAL
willy tarreau5cbea6f2005-12-17 12:48:26 +01002107 {
willy tarreaub952e1d2005-12-18 01:31:20 +01002108 int skerr;
2109 socklen_t lskerr = sizeof(skerr);
willy tarreau5cbea6f2005-12-17 12:48:26 +01002110
willy tarreau5cbea6f2005-12-17 12:48:26 +01002111 getsockopt(fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr);
2112 if (skerr)
2113 ret = -1;
2114 else
2115 ret = recv(fd, b->r, max, 0);
2116 }
willy tarreau3242e862005-12-17 12:27:53 +01002117#else
willy tarreau5cbea6f2005-12-17 12:48:26 +01002118 ret = recv(fd, b->r, max, MSG_NOSIGNAL);
willy tarreau3242e862005-12-17 12:27:53 +01002119#endif
willy tarreau5cbea6f2005-12-17 12:48:26 +01002120 if (ret > 0) {
2121 b->r += ret;
2122 b->l += ret;
2123 s->res_sr = RES_DATA;
willy tarreau0f7af912005-12-17 12:21:26 +01002124
willy tarreau5cbea6f2005-12-17 12:48:26 +01002125 if (b->r == b->data + BUFSIZE) {
2126 b->r = b->data; /* wrap around the buffer */
2127 }
willy tarreaua1598082005-12-17 13:08:06 +01002128
2129 b->total += ret;
willy tarreau5cbea6f2005-12-17 12:48:26 +01002130 /* we hope to read more data or to get a close on next round */
2131 continue;
willy tarreau0f7af912005-12-17 12:21:26 +01002132 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01002133 else if (ret == 0) {
2134 s->res_sr = RES_NULL;
2135 break;
2136 }
2137 else if (errno == EAGAIN) {/* ignore EAGAIN */
2138 break;
2139 }
2140 else {
2141 s->res_sr = RES_ERROR;
2142 fdtab[fd].state = FD_STERROR;
2143 break;
2144 }
2145 } /* while(1) */
willy tarreau5dffb602005-12-18 01:15:23 +01002146#ifndef FILL_BUFFERS
2147 while (0);
2148#endif
willy tarreau0f7af912005-12-17 12:21:26 +01002149 }
2150 else {
2151 s->res_sr = RES_ERROR;
2152 fdtab[fd].state = FD_STERROR;
2153 }
2154
willy tarreau5cbea6f2005-12-17 12:48:26 +01002155 if (s->res_sr != RES_SILENT) {
willy tarreaub1ff9db2005-12-17 13:51:03 +01002156 if (s->proxy->srvtimeout && FD_ISSET(fd, StaticReadEvent))
willy tarreau5cbea6f2005-12-17 12:48:26 +01002157 tv_delayfrom(&s->srexpire, &now, s->proxy->srvtimeout);
2158 else
2159 tv_eternity(&s->srexpire);
2160
2161 task_wakeup(&rq, t);
2162 }
willy tarreau0f7af912005-12-17 12:21:26 +01002163
willy tarreau0f7af912005-12-17 12:21:26 +01002164 return 0;
2165}
2166
2167/*
2168 * this function is called on a write event from a client socket.
2169 * It returns 0.
2170 */
2171int event_cli_write(int fd) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01002172 struct task *t = fdtab[fd].owner;
2173 struct session *s = t->context;
willy tarreau0f7af912005-12-17 12:21:26 +01002174 struct buffer *b = s->rep;
2175 int ret, max;
willy tarreau0f7af912005-12-17 12:21:26 +01002176
willy tarreau12350152005-12-18 01:03:27 +01002177#ifdef DEBUG_FULL
2178 fprintf(stderr,"event_cli_write : fd=%d, s=%p\n", fd, s);
2179#endif
willy tarreau0f7af912005-12-17 12:21:26 +01002180
2181 if (b->l == 0) { /* let's realign the buffer to optimize I/O */
willy tarreau9da061b2005-12-17 12:29:56 +01002182 b->r = b->w = b->h = b->lr = b->data;
willy tarreau0f7af912005-12-17 12:21:26 +01002183 // max = BUFSIZE; BUG !!!!
2184 max = 0;
2185 }
2186 else if (b->r > b->w) {
2187 max = b->r - b->w;
2188 }
2189 else
2190 max = b->data + BUFSIZE - b->w;
2191
willy tarreau0f7af912005-12-17 12:21:26 +01002192 if (fdtab[fd].state != FD_STERROR) {
willy tarreauef900ab2005-12-17 12:52:52 +01002193 if (max == 0) {
2194 s->res_cw = RES_NULL;
2195 task_wakeup(&rq, t);
willy tarreaub1ff9db2005-12-17 13:51:03 +01002196 tv_eternity(&s->cwexpire);
2197 FD_CLR(fd, StaticWriteEvent);
willy tarreauef900ab2005-12-17 12:52:52 +01002198 return 0;
willy tarreau0f7af912005-12-17 12:21:26 +01002199 }
2200
willy tarreau3242e862005-12-17 12:27:53 +01002201#ifndef MSG_NOSIGNAL
willy tarreaub952e1d2005-12-18 01:31:20 +01002202 {
2203 int skerr;
2204 socklen_t lskerr = sizeof(skerr);
2205
2206 getsockopt(fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr);
2207 if (skerr)
willy tarreau3242e862005-12-17 12:27:53 +01002208 ret = -1;
willy tarreaub952e1d2005-12-18 01:31:20 +01002209 else
willy tarreau3242e862005-12-17 12:27:53 +01002210 ret = send(fd, b->w, max, MSG_DONTWAIT);
willy tarreaub952e1d2005-12-18 01:31:20 +01002211 }
willy tarreau3242e862005-12-17 12:27:53 +01002212#else
willy tarreau0f7af912005-12-17 12:21:26 +01002213 ret = send(fd, b->w, max, MSG_DONTWAIT | MSG_NOSIGNAL);
willy tarreau3242e862005-12-17 12:27:53 +01002214#endif
willy tarreau0f7af912005-12-17 12:21:26 +01002215
2216 if (ret > 0) {
2217 b->l -= ret;
2218 b->w += ret;
2219
2220 s->res_cw = RES_DATA;
2221
2222 if (b->w == b->data + BUFSIZE) {
2223 b->w = b->data; /* wrap around the buffer */
2224 }
2225 }
2226 else if (ret == 0) {
2227 /* nothing written, just make as if we were never called */
2228// s->res_cw = RES_NULL;
2229 return 0;
2230 }
2231 else if (errno == EAGAIN) /* ignore EAGAIN */
2232 return 0;
2233 else {
2234 s->res_cw = RES_ERROR;
2235 fdtab[fd].state = FD_STERROR;
2236 }
2237 }
2238 else {
2239 s->res_cw = RES_ERROR;
2240 fdtab[fd].state = FD_STERROR;
2241 }
2242
willy tarreaub1ff9db2005-12-17 13:51:03 +01002243 if (s->proxy->clitimeout) {
willy tarreau0f7af912005-12-17 12:21:26 +01002244 tv_delayfrom(&s->cwexpire, &now, s->proxy->clitimeout);
willy tarreaub1ff9db2005-12-17 13:51:03 +01002245 /* FIXME: to avoid the client to read-time-out during writes, we refresh it */
2246 s->crexpire = s->cwexpire;
2247 }
willy tarreau0f7af912005-12-17 12:21:26 +01002248 else
2249 tv_eternity(&s->cwexpire);
2250
willy tarreau5cbea6f2005-12-17 12:48:26 +01002251 task_wakeup(&rq, t);
willy tarreau0f7af912005-12-17 12:21:26 +01002252 return 0;
2253}
2254
2255
2256/*
2257 * this function is called on a write event from a server socket.
2258 * It returns 0.
2259 */
2260int event_srv_write(int fd) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01002261 struct task *t = fdtab[fd].owner;
2262 struct session *s = t->context;
willy tarreau0f7af912005-12-17 12:21:26 +01002263 struct buffer *b = s->req;
2264 int ret, max;
willy tarreau0f7af912005-12-17 12:21:26 +01002265
willy tarreau12350152005-12-18 01:03:27 +01002266#ifdef DEBUG_FULL
2267 fprintf(stderr,"event_srv_write : fd=%d, s=%p\n", fd, s);
2268#endif
willy tarreau0f7af912005-12-17 12:21:26 +01002269
2270 if (b->l == 0) { /* let's realign the buffer to optimize I/O */
willy tarreau9da061b2005-12-17 12:29:56 +01002271 b->r = b->w = b->h = b->lr = b->data;
willy tarreau0f7af912005-12-17 12:21:26 +01002272 // max = BUFSIZE; BUG !!!!
2273 max = 0;
2274 }
2275 else if (b->r > b->w) {
2276 max = b->r - b->w;
2277 }
2278 else
2279 max = b->data + BUFSIZE - b->w;
2280
willy tarreau0f7af912005-12-17 12:21:26 +01002281 if (fdtab[fd].state != FD_STERROR) {
willy tarreauef900ab2005-12-17 12:52:52 +01002282 if (max == 0) {
2283 /* may be we have received a connection acknowledgement in TCP mode without data */
willy tarreau48b06592005-12-18 01:37:12 +01002284 if (s->srv_state == SV_STCONN) {
2285 int skerr;
2286 socklen_t lskerr = sizeof(skerr);
2287 getsockopt(fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr);
2288 if (skerr) {
2289 s->res_sw = RES_ERROR;
2290 fdtab[fd].state = FD_STERROR;
2291 task_wakeup(&rq, t);
2292 tv_eternity(&s->swexpire);
2293 FD_CLR(fd, StaticWriteEvent);
2294 return 0;
2295 }
2296 }
2297
willy tarreau0f7af912005-12-17 12:21:26 +01002298 s->res_sw = RES_NULL;
willy tarreau5cbea6f2005-12-17 12:48:26 +01002299 task_wakeup(&rq, t);
willy tarreauef900ab2005-12-17 12:52:52 +01002300 fdtab[fd].state = FD_STREADY;
willy tarreaub1ff9db2005-12-17 13:51:03 +01002301 tv_eternity(&s->swexpire);
2302 FD_CLR(fd, StaticWriteEvent);
willy tarreau0f7af912005-12-17 12:21:26 +01002303 return 0;
2304 }
2305
willy tarreau3242e862005-12-17 12:27:53 +01002306#ifndef MSG_NOSIGNAL
willy tarreaub952e1d2005-12-18 01:31:20 +01002307 {
2308 int skerr;
2309 socklen_t lskerr = sizeof(skerr);
2310 getsockopt(fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr);
2311 if (skerr)
willy tarreau3242e862005-12-17 12:27:53 +01002312 ret = -1;
willy tarreaub952e1d2005-12-18 01:31:20 +01002313 else
willy tarreau3242e862005-12-17 12:27:53 +01002314 ret = send(fd, b->w, max, MSG_DONTWAIT);
willy tarreaub952e1d2005-12-18 01:31:20 +01002315 }
willy tarreau3242e862005-12-17 12:27:53 +01002316#else
willy tarreau0f7af912005-12-17 12:21:26 +01002317 ret = send(fd, b->w, max, MSG_DONTWAIT | MSG_NOSIGNAL);
willy tarreau3242e862005-12-17 12:27:53 +01002318#endif
willy tarreauef900ab2005-12-17 12:52:52 +01002319 fdtab[fd].state = FD_STREADY;
willy tarreau0f7af912005-12-17 12:21:26 +01002320 if (ret > 0) {
2321 b->l -= ret;
2322 b->w += ret;
2323
2324 s->res_sw = RES_DATA;
2325
2326 if (b->w == b->data + BUFSIZE) {
2327 b->w = b->data; /* wrap around the buffer */
2328 }
2329 }
2330 else if (ret == 0) {
2331 /* nothing written, just make as if we were never called */
2332 // s->res_sw = RES_NULL;
2333 return 0;
2334 }
2335 else if (errno == EAGAIN) /* ignore EAGAIN */
2336 return 0;
2337 else {
2338 s->res_sw = RES_ERROR;
2339 fdtab[fd].state = FD_STERROR;
2340 }
2341 }
2342 else {
2343 s->res_sw = RES_ERROR;
2344 fdtab[fd].state = FD_STERROR;
2345 }
2346
willy tarreaub1ff9db2005-12-17 13:51:03 +01002347 if (s->proxy->srvtimeout) {
willy tarreau0f7af912005-12-17 12:21:26 +01002348 tv_delayfrom(&s->swexpire, &now, s->proxy->srvtimeout);
willy tarreaub1ff9db2005-12-17 13:51:03 +01002349 /* FIXME: to avoid the server to read-time-out during writes, we refresh it */
2350 s->srexpire = s->swexpire;
2351 }
willy tarreau0f7af912005-12-17 12:21:26 +01002352 else
2353 tv_eternity(&s->swexpire);
2354
willy tarreau5cbea6f2005-12-17 12:48:26 +01002355 task_wakeup(&rq, t);
willy tarreau0f7af912005-12-17 12:21:26 +01002356 return 0;
2357}
2358
2359
2360/*
willy tarreaue39cd132005-12-17 13:00:18 +01002361 * returns a message to the client ; the connection is shut down for read,
2362 * and the request is cleared so that no server connection can be initiated.
2363 * The client must be in a valid state for this (HEADER, DATA ...).
2364 * Nothing is performed on the server side.
willy tarreau8337c6b2005-12-17 13:41:01 +01002365 * The reply buffer doesn't need to be empty before this.
willy tarreaue39cd132005-12-17 13:00:18 +01002366 */
2367void client_retnclose(struct session *s, int len, const char *msg) {
2368 FD_CLR(s->cli_fd, StaticReadEvent);
2369 FD_SET(s->cli_fd, StaticWriteEvent);
2370 tv_eternity(&s->crexpire);
willy tarreaub1285d52005-12-18 01:20:14 +01002371 tv_delayfrom(&s->cwexpire, &now, s->proxy->clitimeout);
willy tarreaue39cd132005-12-17 13:00:18 +01002372 shutdown(s->cli_fd, SHUT_RD);
2373 s->cli_state = CL_STSHUTR;
2374 strcpy(s->rep->data, msg);
2375 s->rep->l = len;
willy tarreau8337c6b2005-12-17 13:41:01 +01002376 s->rep->r = s->rep->h = s->rep->lr = s->rep->w = s->rep->data;
willy tarreaue39cd132005-12-17 13:00:18 +01002377 s->rep->r += len;
2378 s->req->l = 0;
2379}
2380
2381
2382/*
2383 * returns a message into the rep buffer, and flushes the req buffer.
willy tarreau8337c6b2005-12-17 13:41:01 +01002384 * The reply buffer doesn't need to be empty before this.
willy tarreaue39cd132005-12-17 13:00:18 +01002385 */
2386void client_return(struct session *s, int len, const char *msg) {
2387 strcpy(s->rep->data, msg);
2388 s->rep->l = len;
willy tarreau8337c6b2005-12-17 13:41:01 +01002389 s->rep->r = s->rep->h = s->rep->lr = s->rep->w = s->rep->data;
willy tarreaue39cd132005-12-17 13:00:18 +01002390 s->rep->r += len;
2391 s->req->l = 0;
2392}
2393
willy tarreau9fe663a2005-12-17 13:02:59 +01002394/*
2395 * send a log for the session when we have enough info about it
2396 */
2397void sess_log(struct session *s) {
willy tarreau8a86dbf2005-12-18 00:45:59 +01002398 char pn[INET6_ADDRSTRLEN + strlen(":65535")];
willy tarreau9fe663a2005-12-17 13:02:59 +01002399 struct proxy *p = s->proxy;
2400 int log;
2401 char *uri;
2402 char *pxid;
2403 char *srv;
willy tarreauc1cae632005-12-17 14:12:23 +01002404 struct tm *tm;
willy tarreau9fe663a2005-12-17 13:02:59 +01002405
2406 /* This is a first attempt at a better logging system.
2407 * For now, we rely on send_log() to provide the date, although it obviously
2408 * is the date of the log and not of the request, and most fields are not
2409 * computed.
2410 */
2411
willy tarreaua1598082005-12-17 13:08:06 +01002412 log = p->to_log & ~s->logs.logwait;
willy tarreau9fe663a2005-12-17 13:02:59 +01002413
willy tarreau8a86dbf2005-12-18 00:45:59 +01002414 if (s->cli_addr.ss_family == AF_INET)
2415 inet_ntop(AF_INET,
2416 (const void *)&((struct sockaddr_in *)&s->cli_addr)->sin_addr,
2417 pn, sizeof(pn));
2418 else
2419 inet_ntop(AF_INET6,
2420 (const void *)&((struct sockaddr_in6 *)(&s->cli_addr))->sin6_addr,
2421 pn, sizeof(pn));
willy tarreau9fe663a2005-12-17 13:02:59 +01002422
willy tarreauc1cae632005-12-17 14:12:23 +01002423 uri = (log & LW_REQ) ? s->logs.uri ? s->logs.uri : "<BADREQ>" : "";
willy tarreau9fe663a2005-12-17 13:02:59 +01002424 pxid = p->id;
willy tarreauc1cae632005-12-17 14:12:23 +01002425 srv = (p->to_log & LW_SVID) ? (s->srv != NULL) ? s->srv->id : "<NOSRV>" : "-";
willy tarreaua1598082005-12-17 13:08:06 +01002426
willy tarreauc1cae632005-12-17 14:12:23 +01002427 tm = localtime(&s->logs.tv_accept.tv_sec);
2428 if (p->to_log & LW_REQ) {
willy tarreau4302f492005-12-18 01:00:37 +01002429 char tmpline[MAX_SYSLOG_LEN], *h;
2430 int hdr;
2431
2432 h = tmpline;
2433 if (p->to_log & LW_REQHDR && (h < tmpline + sizeof(tmpline) - 10)) {
2434 *(h++) = ' ';
2435 *(h++) = '{';
2436 for (hdr = 0; hdr < p->nb_req_cap; hdr++) {
2437 if (hdr)
2438 *(h++) = '|';
2439 if (s->req_cap[hdr] != NULL)
2440 h = encode_string(h, tmpline + sizeof(tmpline) - 7, '#', hdr_encode_map, s->req_cap[hdr]);
2441 }
2442 *(h++) = '}';
2443 }
2444
2445 if (p->to_log & LW_RSPHDR && (h < tmpline + sizeof(tmpline) - 7)) {
2446 *(h++) = ' ';
2447 *(h++) = '{';
2448 for (hdr = 0; hdr < p->nb_rsp_cap; hdr++) {
2449 if (hdr)
2450 *(h++) = '|';
2451 if (s->rsp_cap[hdr] != NULL)
2452 h = encode_string(h, tmpline + sizeof(tmpline) - 4, '#', hdr_encode_map, s->rsp_cap[hdr]);
2453 }
2454 *(h++) = '}';
2455 }
2456
2457 if (h < tmpline + sizeof(tmpline) - 4) {
2458 *(h++) = ' ';
2459 *(h++) = '"';
2460 h = encode_string(h, tmpline + sizeof(tmpline) - 1, '#', url_encode_map, uri);
2461 *(h++) = '"';
2462 }
2463 *h = '\0';
2464
willy tarreau0fe39652005-12-18 01:25:24 +01002465 send_log(p, LOG_INFO, "%s:%d [%02d/%s/%04d:%02d:%02d:%02d] %s %s %d/%d/%d/%s%d %d %s%lld %s %s %c%c%c%c %d/%d%s\n",
willy tarreau8a86dbf2005-12-18 00:45:59 +01002466 pn,
2467 (s->cli_addr.ss_family == AF_INET) ?
2468 ntohs(((struct sockaddr_in *)&s->cli_addr)->sin_port) :
2469 ntohs(((struct sockaddr_in6 *)&s->cli_addr)->sin6_port),
willy tarreaua1598082005-12-17 13:08:06 +01002470 tm->tm_mday, monthname[tm->tm_mon], tm->tm_year+1900,
2471 tm->tm_hour, tm->tm_min, tm->tm_sec,
2472 pxid, srv,
2473 s->logs.t_request,
2474 (s->logs.t_connect >= 0) ? s->logs.t_connect - s->logs.t_request : -1,
2475 (s->logs.t_data >= 0) ? s->logs.t_data - s->logs.t_connect : -1,
willy tarreau25c4ea52005-12-18 00:49:49 +01002476 (p->to_log & LW_BYTES) ? "" : "+", s->logs.t_close,
2477 s->logs.status,
2478 (p->to_log & LW_BYTES) ? "" : "+", s->logs.bytes,
willy tarreau8337c6b2005-12-17 13:41:01 +01002479 s->logs.cli_cookie ? s->logs.cli_cookie : "-",
2480 s->logs.srv_cookie ? s->logs.srv_cookie : "-",
willy tarreau036e1ce2005-12-17 13:46:33 +01002481 sess_term_cond[(s->flags & SN_ERR_MASK) >> SN_ERR_SHIFT],
2482 sess_fin_state[(s->flags & SN_FINST_MASK) >> SN_FINST_SHIFT],
2483 (p->options & PR_O_COOK_ANY) ? sess_cookie[(s->flags & SN_CK_MASK) >> SN_CK_SHIFT] : '-',
2484 (p->options & PR_O_COOK_ANY) ? sess_set_cookie[(s->flags & SN_SCK_MASK) >> SN_SCK_SHIFT] : '-',
willy tarreau0fe39652005-12-18 01:25:24 +01002485 p->nbconn, actconn, tmpline);
willy tarreaua1598082005-12-17 13:08:06 +01002486 }
2487 else {
willy tarreau0fe39652005-12-18 01:25:24 +01002488 send_log(p, LOG_INFO, "%s:%d [%02d/%s/%04d:%02d:%02d:%02d] %s %s %d/%s%d %s%lld %c%c %d/%d\n",
willy tarreau8a86dbf2005-12-18 00:45:59 +01002489 pn,
2490 (s->cli_addr.ss_family == AF_INET) ?
2491 ntohs(((struct sockaddr_in *)&s->cli_addr)->sin_port) :
2492 ntohs(((struct sockaddr_in6 *)&s->cli_addr)->sin6_port),
willy tarreauc1cae632005-12-17 14:12:23 +01002493 tm->tm_mday, monthname[tm->tm_mon], tm->tm_year+1900,
2494 tm->tm_hour, tm->tm_min, tm->tm_sec,
willy tarreaua1598082005-12-17 13:08:06 +01002495 pxid, srv,
willy tarreauc1cae632005-12-17 14:12:23 +01002496 (s->logs.t_connect >= 0) ? s->logs.t_connect : -1,
willy tarreau25c4ea52005-12-18 00:49:49 +01002497 (p->to_log & LW_BYTES) ? "" : "+", s->logs.t_close,
2498 (p->to_log & LW_BYTES) ? "" : "+", s->logs.bytes,
willy tarreau036e1ce2005-12-17 13:46:33 +01002499 sess_term_cond[(s->flags & SN_ERR_MASK) >> SN_ERR_SHIFT],
willy tarreau0fe39652005-12-18 01:25:24 +01002500 sess_fin_state[(s->flags & SN_FINST_MASK) >> SN_FINST_SHIFT],
2501 p->nbconn, actconn);
willy tarreaua1598082005-12-17 13:08:06 +01002502 }
2503
2504 s->logs.logwait = 0;
willy tarreau9fe663a2005-12-17 13:02:59 +01002505}
2506
willy tarreaue39cd132005-12-17 13:00:18 +01002507
2508/*
willy tarreau0f7af912005-12-17 12:21:26 +01002509 * this function is called on a read event from a listen socket, corresponding
willy tarreau5cbea6f2005-12-17 12:48:26 +01002510 * to an accept. It tries to accept as many connections as possible.
2511 * It returns 0.
willy tarreau0f7af912005-12-17 12:21:26 +01002512 */
2513int event_accept(int fd) {
2514 struct proxy *p = (struct proxy *)fdtab[fd].owner;
willy tarreau5cbea6f2005-12-17 12:48:26 +01002515 struct session *s;
2516 struct task *t;
willy tarreau0f7af912005-12-17 12:21:26 +01002517 int cfd;
willy tarreau0f7af912005-12-17 12:21:26 +01002518
willy tarreau5cbea6f2005-12-17 12:48:26 +01002519 while (p->nbconn < p->maxconn) {
willy tarreau8a86dbf2005-12-18 00:45:59 +01002520 struct sockaddr_storage addr;
willy tarreauc5f73ed2005-12-18 01:26:38 +01002521 socklen_t laddr = sizeof(addr);
willy tarreaub952e1d2005-12-18 01:31:20 +01002522
willy tarreaub1285d52005-12-18 01:20:14 +01002523 if ((cfd = accept(fd, (struct sockaddr *)&addr, &laddr)) == -1) {
2524 switch (errno) {
2525 case EAGAIN:
2526 case EINTR:
2527 case ECONNABORTED:
2528 return 0; /* nothing more to accept */
2529 case ENFILE:
2530 send_log(p, LOG_EMERG,
2531 "Proxy %s reached system FD limit at %d. Please check system tunables.\n",
2532 p->id, maxfd);
2533 return 0;
2534 case EMFILE:
2535 send_log(p, LOG_EMERG,
2536 "Proxy %s reached process FD limit at %d. Please check 'ulimit-n' and restart.\n",
2537 p->id, maxfd);
2538 return 0;
2539 case ENOBUFS:
2540 case ENOMEM:
2541 send_log(p, LOG_EMERG,
2542 "Proxy %s reached system memory limit at %d sockets. Please check system tunables.\n",
2543 p->id, maxfd);
2544 return 0;
2545 default:
2546 return 0;
2547 }
2548 }
willy tarreau0f7af912005-12-17 12:21:26 +01002549
willy tarreau5cbea6f2005-12-17 12:48:26 +01002550 if ((s = pool_alloc(session)) == NULL) { /* disable this proxy for a while */
2551 Alert("out of memory in event_accept().\n");
2552 FD_CLR(fd, StaticReadEvent);
2553 p->state = PR_STIDLE;
2554 close(cfd);
2555 return 0;
2556 }
willy tarreau0f7af912005-12-17 12:21:26 +01002557
willy tarreaub1285d52005-12-18 01:20:14 +01002558 /* if this session comes from a known monitoring system, we want to ignore
2559 * it as soon as possible, which means closing it immediately for TCP.
2560 */
2561 s->flags = 0;
2562 if (addr.ss_family == AF_INET &&
2563 p->mon_mask.s_addr &&
2564 (((struct sockaddr_in *)&addr)->sin_addr.s_addr & p->mon_mask.s_addr) == p->mon_net.s_addr) {
2565 if (p->mode == PR_MODE_TCP) {
2566 close(cfd);
2567 pool_free(session, s);
2568 continue;
2569 }
2570 s->flags |= SN_MONITOR;
2571 }
2572
willy tarreau5cbea6f2005-12-17 12:48:26 +01002573 if ((t = pool_alloc(task)) == NULL) { /* disable this proxy for a while */
2574 Alert("out of memory in event_accept().\n");
2575 FD_CLR(fd, StaticReadEvent);
2576 p->state = PR_STIDLE;
2577 close(cfd);
2578 pool_free(session, s);
2579 return 0;
2580 }
willy tarreau0f7af912005-12-17 12:21:26 +01002581
willy tarreau5cbea6f2005-12-17 12:48:26 +01002582 s->cli_addr = addr;
willy tarreau9fe663a2005-12-17 13:02:59 +01002583 if (cfd >= global.maxsock) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01002584 Alert("accept(): not enough free sockets. Raise -n argument. Giving up.\n");
2585 close(cfd);
2586 pool_free(task, t);
2587 pool_free(session, s);
2588 return 0;
2589 }
willy tarreau0f7af912005-12-17 12:21:26 +01002590
willy tarreau5cbea6f2005-12-17 12:48:26 +01002591 if ((fcntl(cfd, F_SETFL, O_NONBLOCK) == -1) ||
2592 (setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY,
2593 (char *) &one, sizeof(one)) == -1)) {
2594 Alert("accept(): cannot set the socket in non blocking mode. Giving up\n");
2595 close(cfd);
2596 pool_free(task, t);
2597 pool_free(session, s);
2598 return 0;
2599 }
willy tarreau0f7af912005-12-17 12:21:26 +01002600
willy tarreaub952e1d2005-12-18 01:31:20 +01002601 if (p->options & PR_O_TCP_CLI_KA)
2602 setsockopt(cfd, SOL_SOCKET, SO_KEEPALIVE, (char *) &one, sizeof(one));
2603
willy tarreau9fe663a2005-12-17 13:02:59 +01002604 t->next = t->prev = t->rqnext = NULL; /* task not in run queue yet */
2605 t->wq = LIST_HEAD(wait_queue); /* but already has a wait queue assigned */
2606 t->state = TASK_IDLE;
2607 t->process = process_session;
2608 t->context = s;
2609
2610 s->task = t;
2611 s->proxy = p;
2612 s->cli_state = (p->mode == PR_MODE_HTTP) ? CL_STHEADERS : CL_STDATA; /* no HTTP headers for non-HTTP proxies */
2613 s->srv_state = SV_STIDLE;
2614 s->req = s->rep = NULL; /* will be allocated later */
willy tarreau97f58572005-12-18 00:53:44 +01002615
willy tarreau9fe663a2005-12-17 13:02:59 +01002616 s->res_cr = s->res_cw = s->res_sr = s->res_sw = RES_SILENT;
2617 s->cli_fd = cfd;
2618 s->srv_fd = -1;
willy tarreaua1598082005-12-17 13:08:06 +01002619 s->srv = NULL;
willy tarreau9fe663a2005-12-17 13:02:59 +01002620 s->conn_retries = p->conn_retries;
willy tarreaua1598082005-12-17 13:08:06 +01002621
willy tarreaub1285d52005-12-18 01:20:14 +01002622 if (s->flags & SN_MONITOR)
2623 s->logs.logwait = 0;
2624 else
2625 s->logs.logwait = p->to_log;
2626
willy tarreaua1598082005-12-17 13:08:06 +01002627 s->logs.tv_accept = now;
2628 s->logs.t_request = -1;
2629 s->logs.t_connect = -1;
2630 s->logs.t_data = -1;
2631 s->logs.t_close = 0;
2632 s->logs.uri = NULL;
willy tarreau8337c6b2005-12-17 13:41:01 +01002633 s->logs.cli_cookie = NULL;
2634 s->logs.srv_cookie = NULL;
willy tarreaua1598082005-12-17 13:08:06 +01002635 s->logs.status = -1;
2636 s->logs.bytes = 0;
willy tarreau9fe663a2005-12-17 13:02:59 +01002637
willy tarreau2f6ba652005-12-17 13:57:42 +01002638 s->uniq_id = totalconn;
2639
willy tarreau4302f492005-12-18 01:00:37 +01002640 if (p->nb_req_cap > 0) {
2641 if ((s->req_cap =
2642 pool_alloc_from(p->req_cap_pool, p->nb_req_cap*sizeof(char *)))
2643 == NULL) { /* no memory */
2644 close(cfd); /* nothing can be done for this fd without memory */
2645 pool_free(task, t);
2646 pool_free(session, s);
2647 return 0;
2648 }
2649 memset(s->req_cap, 0, p->nb_req_cap*sizeof(char *));
2650 }
2651 else
2652 s->req_cap = NULL;
2653
2654 if (p->nb_rsp_cap > 0) {
2655 if ((s->rsp_cap =
2656 pool_alloc_from(p->rsp_cap_pool, p->nb_rsp_cap*sizeof(char *)))
2657 == NULL) { /* no memory */
2658 if (s->req_cap != NULL)
2659 pool_free_to(p->req_cap_pool, s->req_cap);
2660 close(cfd); /* nothing can be done for this fd without memory */
2661 pool_free(task, t);
2662 pool_free(session, s);
2663 return 0;
2664 }
2665 memset(s->rsp_cap, 0, p->nb_rsp_cap*sizeof(char *));
2666 }
2667 else
2668 s->rsp_cap = NULL;
2669
willy tarreau5cbea6f2005-12-17 12:48:26 +01002670 if ((p->mode == PR_MODE_TCP || p->mode == PR_MODE_HTTP)
2671 && (p->logfac1 >= 0 || p->logfac2 >= 0)) {
willy tarreau8a86dbf2005-12-18 00:45:59 +01002672 struct sockaddr_storage sockname;
willy tarreaub952e1d2005-12-18 01:31:20 +01002673 socklen_t namelen = sizeof(sockname);
willy tarreau0f7af912005-12-17 12:21:26 +01002674
willy tarreau8a86dbf2005-12-18 00:45:59 +01002675 if (addr.ss_family != AF_INET ||
willy tarreaub952e1d2005-12-18 01:31:20 +01002676 !(s->proxy->options & PR_O_TRANSP) ||
willy tarreau8a86dbf2005-12-18 00:45:59 +01002677 get_original_dst(cfd, (struct sockaddr_in *)&sockname, &namelen) == -1)
willy tarreau5cbea6f2005-12-17 12:48:26 +01002678 getsockname(cfd, (struct sockaddr *)&sockname, &namelen);
willy tarreau0f7af912005-12-17 12:21:26 +01002679
willy tarreau9fe663a2005-12-17 13:02:59 +01002680 if (p->to_log) {
2681 /* we have the client ip */
willy tarreaua1598082005-12-17 13:08:06 +01002682 if (s->logs.logwait & LW_CLIP)
2683 if (!(s->logs.logwait &= ~LW_CLIP))
willy tarreau9fe663a2005-12-17 13:02:59 +01002684 sess_log(s);
2685 }
willy tarreau8a86dbf2005-12-18 00:45:59 +01002686 else if (s->cli_addr.ss_family == AF_INET) {
2687 char pn[INET_ADDRSTRLEN], sn[INET_ADDRSTRLEN];
2688 if (inet_ntop(AF_INET, (const void *)&((struct sockaddr_in *)&sockname)->sin_addr,
2689 sn, sizeof(sn)) &&
2690 inet_ntop(AF_INET, (const void *)&((struct sockaddr_in *)&s->cli_addr)->sin_addr,
2691 pn, sizeof(pn))) {
2692 send_log(p, LOG_INFO, "Connect from %s:%d to %s:%d (%s/%s)\n",
2693 pn, ntohs(((struct sockaddr_in *)&s->cli_addr)->sin_port),
2694 sn, ntohs(((struct sockaddr_in *)&sockname)->sin_port),
2695 p->id, (p->mode == PR_MODE_HTTP) ? "HTTP" : "TCP");
2696 }
2697 }
2698 else {
2699 char pn[INET6_ADDRSTRLEN], sn[INET6_ADDRSTRLEN];
2700 if (inet_ntop(AF_INET6, (const void *)&((struct sockaddr_in6 *)&sockname)->sin6_addr,
2701 sn, sizeof(sn)) &&
2702 inet_ntop(AF_INET6, (const void *)&((struct sockaddr_in6 *)&s->cli_addr)->sin6_addr,
2703 pn, sizeof(pn))) {
2704 send_log(p, LOG_INFO, "Connect from %s:%d to %s:%d (%s/%s)\n",
2705 pn, ntohs(((struct sockaddr_in6 *)&s->cli_addr)->sin6_port),
2706 sn, ntohs(((struct sockaddr_in6 *)&sockname)->sin6_port),
2707 p->id, (p->mode == PR_MODE_HTTP) ? "HTTP" : "TCP");
2708 }
2709 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01002710 }
willy tarreau0f7af912005-12-17 12:21:26 +01002711
willy tarreau982249e2005-12-18 00:57:06 +01002712 if ((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))) {
willy tarreau2f6ba652005-12-17 13:57:42 +01002713 struct sockaddr_in sockname;
willy tarreaub952e1d2005-12-18 01:31:20 +01002714 socklen_t namelen = sizeof(sockname);
willy tarreauef900ab2005-12-17 12:52:52 +01002715 int len;
willy tarreau8a86dbf2005-12-18 00:45:59 +01002716 if (addr.ss_family != AF_INET ||
willy tarreaub952e1d2005-12-18 01:31:20 +01002717 !(s->proxy->options & PR_O_TRANSP) ||
willy tarreau8a86dbf2005-12-18 00:45:59 +01002718 get_original_dst(cfd, (struct sockaddr_in *)&sockname, &namelen) == -1)
willy tarreau2f6ba652005-12-17 13:57:42 +01002719 getsockname(cfd, (struct sockaddr *)&sockname, &namelen);
willy tarreau2f6ba652005-12-17 13:57:42 +01002720
willy tarreau8a86dbf2005-12-18 00:45:59 +01002721 if (s->cli_addr.ss_family == AF_INET) {
2722 char pn[INET_ADDRSTRLEN];
2723 inet_ntop(AF_INET,
2724 (const void *)&((struct sockaddr_in *)&s->cli_addr)->sin_addr,
2725 pn, sizeof(pn));
2726
2727 len = sprintf(trash, "%08x:%s.accept(%04x)=%04x from [%s:%d]\n",
2728 s->uniq_id, p->id, (unsigned short)fd, (unsigned short)cfd,
2729 pn, ntohs(((struct sockaddr_in *)&s->cli_addr)->sin_port));
2730 }
2731 else {
2732 char pn[INET6_ADDRSTRLEN];
2733 inet_ntop(AF_INET6,
2734 (const void *)&((struct sockaddr_in6 *)(&s->cli_addr))->sin6_addr,
2735 pn, sizeof(pn));
2736
2737 len = sprintf(trash, "%08x:%s.accept(%04x)=%04x from [%s:%d]\n",
2738 s->uniq_id, p->id, (unsigned short)fd, (unsigned short)cfd,
2739 pn, ntohs(((struct sockaddr_in6 *)(&s->cli_addr))->sin6_port));
2740 }
2741
willy tarreauef900ab2005-12-17 12:52:52 +01002742 write(1, trash, len);
2743 }
willy tarreau0f7af912005-12-17 12:21:26 +01002744
willy tarreau5cbea6f2005-12-17 12:48:26 +01002745 if ((s->req = pool_alloc(buffer)) == NULL) { /* no memory */
willy tarreau4302f492005-12-18 01:00:37 +01002746 if (s->rsp_cap != NULL)
2747 pool_free_to(p->rsp_cap_pool, s->rsp_cap);
2748 if (s->req_cap != NULL)
2749 pool_free_to(p->req_cap_pool, s->req_cap);
willy tarreau5cbea6f2005-12-17 12:48:26 +01002750 close(cfd); /* nothing can be done for this fd without memory */
2751 pool_free(task, t);
2752 pool_free(session, s);
2753 return 0;
2754 }
willy tarreau4302f492005-12-18 01:00:37 +01002755
willy tarreau5cbea6f2005-12-17 12:48:26 +01002756 s->req->l = 0;
willy tarreaua1598082005-12-17 13:08:06 +01002757 s->req->total = 0;
willy tarreauef900ab2005-12-17 12:52:52 +01002758 s->req->h = s->req->r = s->req->lr = s->req->w = s->req->data; /* r and w will be reset further */
2759 s->req->rlim = s->req->data + BUFSIZE;
willy tarreaub1ff9db2005-12-17 13:51:03 +01002760 if (s->cli_state == CL_STHEADERS) /* reserve some space for header rewriting */
willy tarreauef900ab2005-12-17 12:52:52 +01002761 s->req->rlim -= MAXREWRITE;
willy tarreau0f7af912005-12-17 12:21:26 +01002762
willy tarreau5cbea6f2005-12-17 12:48:26 +01002763 if ((s->rep = pool_alloc(buffer)) == NULL) { /* no memory */
2764 pool_free(buffer, s->req);
willy tarreau4302f492005-12-18 01:00:37 +01002765 if (s->rsp_cap != NULL)
2766 pool_free_to(p->rsp_cap_pool, s->rsp_cap);
2767 if (s->req_cap != NULL)
2768 pool_free_to(p->req_cap_pool, s->req_cap);
willy tarreau5cbea6f2005-12-17 12:48:26 +01002769 close(cfd); /* nothing can be done for this fd without memory */
2770 pool_free(task, t);
2771 pool_free(session, s);
2772 return 0;
2773 }
2774 s->rep->l = 0;
willy tarreaua1598082005-12-17 13:08:06 +01002775 s->rep->total = 0;
willy tarreauef900ab2005-12-17 12:52:52 +01002776 s->rep->h = s->rep->r = s->rep->lr = s->rep->w = s->rep->rlim = s->rep->data;
willy tarreau0f7af912005-12-17 12:21:26 +01002777
willy tarreau5cbea6f2005-12-17 12:48:26 +01002778 fdtab[cfd].read = &event_cli_read;
2779 fdtab[cfd].write = &event_cli_write;
2780 fdtab[cfd].owner = t;
2781 fdtab[cfd].state = FD_STREADY;
willy tarreau0f7af912005-12-17 12:21:26 +01002782
willy tarreaub1285d52005-12-18 01:20:14 +01002783 if ((p->mode == PR_MODE_HTTP && (s->flags & SN_MONITOR)) ||
2784 (p->mode == PR_MODE_HEALTH && (p->options & PR_O_HTTP_CHK)))
2785 /* Either we got a request from a monitoring system on an HTTP instance,
2786 * or we're in health check mode with the 'httpchk' option enabled. In
2787 * both cases, we return a fake "HTTP/1.0 200 OK" response and we exit.
2788 */
2789 client_retnclose(s, 19, "HTTP/1.0 200 OK\r\n\r\n"); /* forge a 200 response */
2790 else if (p->mode == PR_MODE_HEALTH) { /* health check mode, no client reading */
2791 client_retnclose(s, 3, "OK\n"); /* forge an "OK" response */
willy tarreau5cbea6f2005-12-17 12:48:26 +01002792 }
2793 else {
2794 FD_SET(cfd, StaticReadEvent);
2795 }
2796
willy tarreaub952e1d2005-12-18 01:31:20 +01002797#if defined(DEBUG_FULL) && defined(ENABLE_EPOLL)
2798 if (PrevReadEvent) {
2799 assert(!(FD_ISSET(cfd, PrevReadEvent)));
2800 assert(!(FD_ISSET(cfd, PrevWriteEvent)));
2801 }
2802#endif
willy tarreau5cbea6f2005-12-17 12:48:26 +01002803 fd_insert(cfd);
2804
2805 tv_eternity(&s->cnexpire);
2806 tv_eternity(&s->srexpire);
2807 tv_eternity(&s->swexpire);
willy tarreaub952e1d2005-12-18 01:31:20 +01002808 tv_eternity(&s->crexpire);
willy tarreau5cbea6f2005-12-17 12:48:26 +01002809 tv_eternity(&s->cwexpire);
2810
willy tarreaub1285d52005-12-18 01:20:14 +01002811 if (s->proxy->clitimeout) {
2812 if (FD_ISSET(cfd, StaticReadEvent))
2813 tv_delayfrom(&s->crexpire, &now, s->proxy->clitimeout);
2814 if (FD_ISSET(cfd, StaticWriteEvent))
2815 tv_delayfrom(&s->cwexpire, &now, s->proxy->clitimeout);
2816 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01002817
willy tarreaub1285d52005-12-18 01:20:14 +01002818 tv_min(&t->expire, &s->crexpire, &s->cwexpire);
willy tarreau5cbea6f2005-12-17 12:48:26 +01002819
2820 task_queue(t);
willy tarreauef900ab2005-12-17 12:52:52 +01002821
2822 if (p->mode != PR_MODE_HEALTH)
2823 task_wakeup(&rq, t);
willy tarreau5cbea6f2005-12-17 12:48:26 +01002824
2825 p->nbconn++;
2826 actconn++;
2827 totalconn++;
2828
willy tarreaub952e1d2005-12-18 01:31:20 +01002829 // fprintf(stderr, "accepting from %p => %d conn, %d total, task=%p\n", p, actconn, totalconn, t);
willy tarreau5cbea6f2005-12-17 12:48:26 +01002830 } /* end of while (p->nbconn < p->maxconn) */
2831 return 0;
2832}
willy tarreau0f7af912005-12-17 12:21:26 +01002833
willy tarreau0f7af912005-12-17 12:21:26 +01002834
willy tarreau5cbea6f2005-12-17 12:48:26 +01002835/*
2836 * This function is used only for server health-checks. It handles
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002837 * the connection acknowledgement. If the proxy requires HTTP health-checks,
2838 * it sends the request. In other cases, it returns 1 if the socket is OK,
willy tarreau5cbea6f2005-12-17 12:48:26 +01002839 * or -1 if an error occured.
2840 */
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002841int event_srv_chk_w(int fd) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01002842 struct task *t = fdtab[fd].owner;
2843 struct server *s = t->context;
willy tarreau0f7af912005-12-17 12:21:26 +01002844
willy tarreauc5f73ed2005-12-18 01:26:38 +01002845 int skerr;
willy tarreaub952e1d2005-12-18 01:31:20 +01002846 socklen_t lskerr = sizeof(skerr);
2847
willy tarreau5cbea6f2005-12-17 12:48:26 +01002848 getsockopt(fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr);
willy tarreau197e8ec2005-12-17 14:10:59 +01002849 /* in case of TCP only, this tells us if the connection succeeded */
willy tarreau5cbea6f2005-12-17 12:48:26 +01002850 if (skerr)
2851 s->result = -1;
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002852 else {
2853 if (s->proxy->options & PR_O_HTTP_CHK) {
2854 int ret;
willy tarreau2f6ba652005-12-17 13:57:42 +01002855 /* we want to check if this host replies to "OPTIONS / HTTP/1.0"
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002856 * so we'll send the request, and won't wake the checker up now.
2857 */
2858#ifndef MSG_NOSIGNAL
willy tarreau2f6ba652005-12-17 13:57:42 +01002859 ret = send(fd, s->proxy->check_req, s->proxy->check_len, MSG_DONTWAIT);
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002860#else
willy tarreau2f6ba652005-12-17 13:57:42 +01002861 ret = send(fd, s->proxy->check_req, s->proxy->check_len, MSG_DONTWAIT | MSG_NOSIGNAL);
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002862#endif
willy tarreaufe2c5c12005-12-17 14:14:34 +01002863 if (ret == s->proxy->check_len) {
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002864 FD_SET(fd, StaticReadEvent); /* prepare for reading reply */
2865 FD_CLR(fd, StaticWriteEvent); /* nothing more to write */
2866 return 0;
2867 }
2868 else
2869 s->result = -1;
2870 }
2871 else {
2872 /* good TCP connection is enough */
2873 s->result = 1;
2874 }
2875 }
2876
2877 task_wakeup(&rq, t);
2878 return 0;
2879}
2880
willy tarreau0f7af912005-12-17 12:21:26 +01002881
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002882/*
2883 * This function is used only for server health-checks. It handles
2884 * the server's reply to an HTTP request. It returns 1 if the server replies
2885 * 2xx or 3xx (valid responses), or -1 in other cases.
2886 */
2887int event_srv_chk_r(int fd) {
2888 char reply[64];
2889 int len;
2890 struct task *t = fdtab[fd].owner;
2891 struct server *s = t->context;
2892
willy tarreau197e8ec2005-12-17 14:10:59 +01002893 s->result = len = -1;
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002894#ifndef MSG_NOSIGNAL
willy tarreaub952e1d2005-12-18 01:31:20 +01002895 {
2896 int skerr;
2897 socklen_t lskerr = sizeof(skerr);
2898
2899 getsockopt(fd, SOL_SOCKET, SO_ERROR, &skerr, &lskerr);
2900 if (!skerr)
2901 len = recv(fd, reply, sizeof(reply), 0);
2902 }
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002903#else
willy tarreau197e8ec2005-12-17 14:10:59 +01002904 /* Warning! Linux returns EAGAIN on SO_ERROR if data are still available
2905 * but the connection was closed on the remote end. Fortunately, recv still
2906 * works correctly and we don't need to do the getsockopt() on linux.
2907 */
2908 len = recv(fd, reply, sizeof(reply), MSG_NOSIGNAL);
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002909#endif
willy tarreau197e8ec2005-12-17 14:10:59 +01002910 if ((len >= sizeof("HTTP/1.0 000")) &&
2911 !memcmp(reply, "HTTP/1.", 7) &&
2912 (reply[9] == '2' || reply[9] == '3')) /* 2xx or 3xx */
2913 s->result = 1;
willy tarreaubc4e1fb2005-12-17 13:32:07 +01002914
2915 FD_CLR(fd, StaticReadEvent);
willy tarreau5cbea6f2005-12-17 12:48:26 +01002916 task_wakeup(&rq, t);
willy tarreau0f7af912005-12-17 12:21:26 +01002917 return 0;
2918}
2919
2920
2921/*
2922 * this function writes the string <str> at position <pos> which must be in buffer <b>,
2923 * and moves <end> just after the end of <str>.
2924 * <b>'s parameters (l, r, w, h, lr) are recomputed to be valid after the shift.
2925 * the shift value (positive or negative) is returned.
2926 * If there's no space left, the move is not done.
2927 *
2928 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01002929int buffer_replace(struct buffer *b, char *pos, char *end, char *str) {
willy tarreau0f7af912005-12-17 12:21:26 +01002930 int delta;
2931 int len;
2932
2933 len = strlen(str);
2934 delta = len - (end - pos);
2935
2936 if (delta + b->r >= b->data + BUFSIZE)
2937 return 0; /* no space left */
2938
2939 /* first, protect the end of the buffer */
2940 memmove(end + delta, end, b->data + b->l - end);
2941
2942 /* now, copy str over pos */
2943 memcpy(pos, str,len);
2944
willy tarreau5cbea6f2005-12-17 12:48:26 +01002945 /* we only move data after the displaced zone */
2946 if (b->r > pos) b->r += delta;
2947 if (b->w > pos) b->w += delta;
2948 if (b->h > pos) b->h += delta;
2949 if (b->lr > pos) b->lr += delta;
willy tarreau0f7af912005-12-17 12:21:26 +01002950 b->l += delta;
2951
2952 return delta;
2953}
2954
willy tarreau8337c6b2005-12-17 13:41:01 +01002955/* same except that the string length is given, which allows str to be NULL if
willy tarreau240afa62005-12-17 13:14:35 +01002956 * len is 0.
2957 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01002958int buffer_replace2(struct buffer *b, char *pos, char *end, char *str, int len) {
willy tarreau0f7af912005-12-17 12:21:26 +01002959 int delta;
2960
2961 delta = len - (end - pos);
2962
2963 if (delta + b->r >= b->data + BUFSIZE)
2964 return 0; /* no space left */
2965
2966 /* first, protect the end of the buffer */
2967 memmove(end + delta, end, b->data + b->l - end);
2968
2969 /* now, copy str over pos */
willy tarreau240afa62005-12-17 13:14:35 +01002970 if (len)
2971 memcpy(pos, str, len);
willy tarreau0f7af912005-12-17 12:21:26 +01002972
willy tarreau5cbea6f2005-12-17 12:48:26 +01002973 /* we only move data after the displaced zone */
2974 if (b->r > pos) b->r += delta;
2975 if (b->w > pos) b->w += delta;
2976 if (b->h > pos) b->h += delta;
2977 if (b->lr > pos) b->lr += delta;
willy tarreau0f7af912005-12-17 12:21:26 +01002978 b->l += delta;
2979
2980 return delta;
2981}
2982
2983
2984int exp_replace(char *dst, char *src, char *str, regmatch_t *matches) {
2985 char *old_dst = dst;
2986
2987 while (*str) {
2988 if (*str == '\\') {
2989 str++;
willy tarreauc29948c2005-12-17 13:10:27 +01002990 if (isdigit((int)*str)) {
willy tarreau0f7af912005-12-17 12:21:26 +01002991 int len, num;
2992
2993 num = *str - '0';
2994 str++;
2995
willy tarreau8a86dbf2005-12-18 00:45:59 +01002996 if (matches[num].rm_eo > -1 && matches[num].rm_so > -1) {
willy tarreau0f7af912005-12-17 12:21:26 +01002997 len = matches[num].rm_eo - matches[num].rm_so;
2998 memcpy(dst, src + matches[num].rm_so, len);
2999 dst += len;
3000 }
3001
3002 }
3003 else if (*str == 'x') {
3004 unsigned char hex1, hex2;
3005 str++;
3006
willy tarreauc1f47532005-12-18 01:08:26 +01003007 hex1 = toupper(*str++) - '0';
3008 hex2 = toupper(*str++) - '0';
willy tarreau0f7af912005-12-17 12:21:26 +01003009
3010 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
3011 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
3012 *dst++ = (hex1<<4) + hex2;
3013 }
3014 else
3015 *dst++ = *str++;
3016 }
3017 else
3018 *dst++ = *str++;
3019 }
3020 *dst = 0;
3021 return dst - old_dst;
3022}
3023
willy tarreauc1f47532005-12-18 01:08:26 +01003024static int ishex(char s)
3025{
3026 return (s >= '0' && s <= '9') || (s >= 'A' && s <= 'F') || (s >= 'a' && s <= 'f');
3027}
3028
3029/* returns NULL if the replacement string <str> is valid, or the pointer to the first error */
3030char *check_replace_string(char *str)
3031{
3032 char *err = NULL;
3033 while (*str) {
3034 if (*str == '\\') {
3035 err = str; /* in case of a backslash, we return the pointer to it */
3036 str++;
3037 if (!*str)
3038 return err;
3039 else if (isdigit((int)*str))
3040 err = NULL;
3041 else if (*str == 'x') {
3042 str++;
3043 if (!ishex(*str))
3044 return err;
3045 str++;
3046 if (!ishex(*str))
3047 return err;
3048 err = NULL;
3049 }
3050 else {
3051 Warning("'\\%c' : deprecated use of a backslash before something not '\\','x' or a digit.\n", *str);
3052 err = NULL;
3053 }
3054 }
3055 str++;
3056 }
3057 return err;
3058}
3059
3060
willy tarreau9fe663a2005-12-17 13:02:59 +01003061
willy tarreau0f7af912005-12-17 12:21:26 +01003062/*
3063 * manages the client FSM and its socket. BTW, it also tries to handle the
3064 * cookie. It returns 1 if a state has changed (and a resync may be needed),
3065 * 0 else.
3066 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01003067int process_cli(struct session *t) {
willy tarreau0f7af912005-12-17 12:21:26 +01003068 int s = t->srv_state;
3069 int c = t->cli_state;
3070 struct buffer *req = t->req;
3071 struct buffer *rep = t->rep;
willy tarreau12350152005-12-18 01:03:27 +01003072 int method_checked = 0;
3073 appsess *asession_temp = NULL;
3074 appsess local_asession;
willy tarreau0f7af912005-12-17 12:21:26 +01003075
willy tarreau750a4722005-12-17 13:21:24 +01003076#ifdef DEBUG_FULL
willy tarreaub1285d52005-12-18 01:20:14 +01003077 fprintf(stderr,"process_cli: c=%s s=%s set(r,w)=%d,%d exp(r,w)=%d.%d,%d.%d\n",
3078 cli_stnames[c], srv_stnames[s],
3079 FD_ISSET(t->cli_fd, StaticReadEvent), FD_ISSET(t->cli_fd, StaticWriteEvent),
3080 t->crexpire.tv_sec, t->crexpire.tv_usec,
3081 t->cwexpire.tv_sec, t->cwexpire.tv_usec);
willy tarreau750a4722005-12-17 13:21:24 +01003082#endif
willy tarreau0f7af912005-12-17 12:21:26 +01003083 //fprintf(stderr,"process_cli: c=%d, s=%d, cr=%d, cw=%d, sr=%d, sw=%d\n", c, s,
3084 //FD_ISSET(t->cli_fd, StaticReadEvent), FD_ISSET(t->cli_fd, StaticWriteEvent),
3085 //FD_ISSET(t->srv_fd, StaticReadEvent), FD_ISSET(t->srv_fd, StaticWriteEvent)
3086 //);
3087 if (c == CL_STHEADERS) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01003088 /* now parse the partial (or complete) headers */
3089 while (req->lr < req->r) { /* this loop only sees one header at each iteration */
3090 char *ptr;
3091 int delete_header;
willy tarreau12350152005-12-18 01:03:27 +01003092 char *request_line = NULL;
willy tarreau0f7af912005-12-17 12:21:26 +01003093
willy tarreau5cbea6f2005-12-17 12:48:26 +01003094 ptr = req->lr;
willy tarreau0f7af912005-12-17 12:21:26 +01003095
willy tarreau0f7af912005-12-17 12:21:26 +01003096 /* look for the end of the current header */
3097 while (ptr < req->r && *ptr != '\n' && *ptr != '\r')
3098 ptr++;
3099
willy tarreau5cbea6f2005-12-17 12:48:26 +01003100 if (ptr == req->h) { /* empty line, end of headers */
willy tarreau5cbea6f2005-12-17 12:48:26 +01003101 int line, len;
3102 /* we can only get here after an end of headers */
3103 /* we'll have something else to do here : add new headers ... */
willy tarreau0f7af912005-12-17 12:21:26 +01003104
willy tarreaue39cd132005-12-17 13:00:18 +01003105 if (t->flags & SN_CLDENY) {
3106 /* no need to go further */
willy tarreaua1598082005-12-17 13:08:06 +01003107 t->logs.status = 403;
willy tarreau8337c6b2005-12-17 13:41:01 +01003108 client_retnclose(t, t->proxy->errmsg.len403, t->proxy->errmsg.msg403);
willy tarreau036e1ce2005-12-17 13:46:33 +01003109 if (!(t->flags & SN_ERR_MASK))
3110 t->flags |= SN_ERR_PRXCOND;
3111 if (!(t->flags & SN_FINST_MASK))
3112 t->flags |= SN_FINST_R;
willy tarreaue39cd132005-12-17 13:00:18 +01003113 return 1;
3114 }
3115
willy tarreau5cbea6f2005-12-17 12:48:26 +01003116 for (line = 0; line < t->proxy->nb_reqadd; line++) {
willy tarreau750a4722005-12-17 13:21:24 +01003117 len = sprintf(trash, "%s\r\n", t->proxy->req_add[line]);
3118 buffer_replace2(req, req->h, req->h, trash, len);
willy tarreau5cbea6f2005-12-17 12:48:26 +01003119 }
willy tarreau0f7af912005-12-17 12:21:26 +01003120
willy tarreau9fe663a2005-12-17 13:02:59 +01003121 if (t->proxy->options & PR_O_FWDFOR) {
willy tarreau8a86dbf2005-12-18 00:45:59 +01003122 if (t->cli_addr.ss_family == AF_INET) {
3123 unsigned char *pn;
3124 pn = (unsigned char *)&((struct sockaddr_in *)&t->cli_addr)->sin_addr;
3125 len = sprintf(trash, "X-Forwarded-For: %d.%d.%d.%d\r\n",
3126 pn[0], pn[1], pn[2], pn[3]);
3127 buffer_replace2(req, req->h, req->h, trash, len);
3128 }
3129 else if (t->cli_addr.ss_family == AF_INET6) {
3130 char pn[INET6_ADDRSTRLEN];
3131 inet_ntop(AF_INET6,
3132 (const void *)&((struct sockaddr_in6 *)(&t->cli_addr))->sin6_addr,
3133 pn, sizeof(pn));
3134 len = sprintf(trash, "X-Forwarded-For: %s\r\n", pn);
3135 buffer_replace2(req, req->h, req->h, trash, len);
3136 }
willy tarreau9fe663a2005-12-17 13:02:59 +01003137 }
3138
willy tarreau25c4ea52005-12-18 00:49:49 +01003139 /* add a "connection: close" line if needed */
3140 if (t->proxy->options & PR_O_HTTP_CLOSE)
3141 buffer_replace2(req, req->h, req->h, "Connection: close\r\n", 19);
3142
willy tarreau982249e2005-12-18 00:57:06 +01003143 if (!memcmp(req->data, "POST ", 5)) {
3144 /* this is a POST request, which is not cacheable by default */
3145 t->flags |= SN_POST;
3146 }
willy tarreaucd878942005-12-17 13:27:43 +01003147
willy tarreau5cbea6f2005-12-17 12:48:26 +01003148 t->cli_state = CL_STDATA;
willy tarreauef900ab2005-12-17 12:52:52 +01003149 req->rlim = req->data + BUFSIZE; /* no more rewrite needed */
willy tarreau0f7af912005-12-17 12:21:26 +01003150
willy tarreau750a4722005-12-17 13:21:24 +01003151 t->logs.t_request = tv_diff(&t->logs.tv_accept, &now);
willy tarreau5cbea6f2005-12-17 12:48:26 +01003152 /* FIXME: we'll set the client in a wait state while we try to
3153 * connect to the server. Is this really needed ? wouldn't it be
3154 * better to release the maximum of system buffers instead ? */
willy tarreauef900ab2005-12-17 12:52:52 +01003155 //FD_CLR(t->cli_fd, StaticReadEvent);
3156 //tv_eternity(&t->crexpire);
willy tarreau197e8ec2005-12-17 14:10:59 +01003157
3158 /* FIXME: if we break here (as up to 1.1.23), having the client
3159 * shutdown its connection can lead to an abort further.
3160 * it's better to either return 1 or even jump directly to the
3161 * data state which will save one schedule.
3162 */
3163 //break;
willy tarreauc58fc692005-12-17 14:13:08 +01003164
3165 if (!t->proxy->clitimeout ||
3166 (t->srv_state < SV_STDATA && t->proxy->srvtimeout))
3167 /* If the client has no timeout, or if the server is not ready yet,
3168 * and we know for sure that it can expire, then it's cleaner to
3169 * disable the timeout on the client side so that too low values
3170 * cannot make the sessions abort too early.
willy tarreaub1285d52005-12-18 01:20:14 +01003171 *
3172 * FIXME-20050705: the server needs a way to re-enable this time-out
3173 * when it switches its state, otherwise a client can stay connected
3174 * indefinitely. This now seems to be OK.
willy tarreauc58fc692005-12-17 14:13:08 +01003175 */
3176 tv_eternity(&t->crexpire);
3177
willy tarreau197e8ec2005-12-17 14:10:59 +01003178 goto process_data;
willy tarreau5cbea6f2005-12-17 12:48:26 +01003179 }
willy tarreau0f7af912005-12-17 12:21:26 +01003180
willy tarreau5cbea6f2005-12-17 12:48:26 +01003181 /* to get a complete header line, we need the ending \r\n, \n\r, \r or \n too */
3182 if (ptr > req->r - 2) {
3183 /* this is a partial header, let's wait for more to come */
3184 req->lr = ptr;
3185 break;
3186 }
willy tarreau0f7af912005-12-17 12:21:26 +01003187
willy tarreau5cbea6f2005-12-17 12:48:26 +01003188 /* now we know that *ptr is either \r or \n,
3189 * and that there are at least 1 char after it.
3190 */
3191 if ((ptr[0] == ptr[1]) || (ptr[1] != '\r' && ptr[1] != '\n'))
3192 req->lr = ptr + 1; /* \r\r, \n\n, \r[^\n], \n[^\r] */
3193 else
3194 req->lr = ptr + 2; /* \r\n or \n\r */
willy tarreau0f7af912005-12-17 12:21:26 +01003195
willy tarreau5cbea6f2005-12-17 12:48:26 +01003196 /*
3197 * now we know that we have a full header ; we can do whatever
3198 * we want with these pointers :
3199 * req->h = beginning of header
3200 * ptr = end of header (first \r or \n)
3201 * req->lr = beginning of next line (next rep->h)
3202 * req->r = end of data (not used at this stage)
3203 */
willy tarreau0f7af912005-12-17 12:21:26 +01003204
willy tarreau12350152005-12-18 01:03:27 +01003205 if (!method_checked && (t->proxy->appsession_name != NULL) &&
3206 ((memcmp(req->h, "GET ", 4) == 0) || (memcmp(req->h, "POST ", 4) == 0)) &&
3207 ((request_line = memchr(req->h, ';', req->lr - req->h)) != NULL)) {
3208
3209 /* skip ; */
3210 request_line++;
3211
3212 /* look if we have a jsessionid */
3213
3214 if (strncasecmp(request_line, t->proxy->appsession_name, t->proxy->appsession_name_len) == 0) {
3215
3216 /* skip jsessionid= */
3217 request_line += t->proxy->appsession_name_len + 1;
3218
3219 /* First try if we allready have an appsession */
3220 asession_temp = &local_asession;
3221
3222 if ((asession_temp->sessid = pool_alloc_from(apools.sessid, apools.ses_msize)) == NULL) {
3223 Alert("Not enough memory process_cli():asession_temp->sessid:calloc().\n");
3224 send_log(t->proxy, LOG_ALERT, "Not enough Memory process_cli():asession_temp->sessid:calloc().\n");
3225 return 0;
3226 }
3227
3228 /* Copy the sessionid */
3229 memcpy(asession_temp->sessid, request_line, t->proxy->appsession_len);
3230 asession_temp->sessid[t->proxy->appsession_len] = 0;
3231 asession_temp->serverid = NULL;
3232
3233 /* only do insert, if lookup fails */
3234 if (chtbl_lookup(&(t->proxy->htbl_proxy), (void *)&asession_temp)) {
3235 if ((asession_temp = pool_alloc(appsess)) == NULL) {
3236 Alert("Not enough memory process_cli():asession:calloc().\n");
3237 send_log(t->proxy, LOG_ALERT, "Not enough memory process_cli():asession:calloc().\n");
3238 return 0;
3239 }
3240 asession_temp->sessid = local_asession.sessid;
3241 asession_temp->serverid = local_asession.serverid;
3242 chtbl_insert(&(t->proxy->htbl_proxy), (void *) asession_temp);
willy tarreaub952e1d2005-12-18 01:31:20 +01003243 } /* end if (chtbl_lookup()) */
3244 else {
willy tarreau12350152005-12-18 01:03:27 +01003245 /*free wasted memory;*/
3246 pool_free_to(apools.sessid, local_asession.sessid);
3247 }
3248
3249 tv_delayfrom(&asession_temp->expire, &now, t->proxy->appsession_timeout);
3250 asession_temp->request_count++;
3251
3252#if defined(DEBUG_HASH)
3253 print_table(&(t->proxy->htbl_proxy));
3254#endif
3255
3256 if (asession_temp->serverid == NULL) {
3257 Alert("Found Application Session without matching server.\n");
3258 } else {
3259 struct server *srv = t->proxy->srv;
3260 while (srv) {
3261 if (strcmp(srv->id, asession_temp->serverid) == 0) {
3262 if (srv->state & SRV_RUNNING || t->proxy->options & PR_O_PERSIST) {
3263 /* we found the server and it's usable */
3264 t->flags &= ~SN_CK_MASK;
3265 t->flags |= SN_CK_VALID | SN_DIRECT;
3266 t->srv = srv;
3267 break;
willy tarreaub952e1d2005-12-18 01:31:20 +01003268 } else {
willy tarreau12350152005-12-18 01:03:27 +01003269 t->flags &= ~SN_CK_MASK;
3270 t->flags |= SN_CK_DOWN;
3271 }
willy tarreaub952e1d2005-12-18 01:31:20 +01003272 } /* end if (strcmp()) */
willy tarreau12350152005-12-18 01:03:27 +01003273 srv = srv->next;
3274 }/* end while(srv) */
3275 }/* end else of if (asession_temp->serverid == NULL) */
willy tarreaub952e1d2005-12-18 01:31:20 +01003276 }/* end if (strncasecmp(request_line,t->proxy->appsession_name,apssesion_name_len) == 0) */
willy tarreau12350152005-12-18 01:03:27 +01003277 else {
3278 //fprintf(stderr,">>>>>>>>>>>>>>>>>>>>>>NO SESSION\n");
3279 }
willy tarreau598da412005-12-18 01:07:29 +01003280 method_checked = 1;
willy tarreaub952e1d2005-12-18 01:31:20 +01003281 } /* end if (!method_checked ...) */
willy tarreau12350152005-12-18 01:03:27 +01003282 else{
3283 //printf("No Methode-Header with Session-String\n");
3284 }
3285
willy tarreau8337c6b2005-12-17 13:41:01 +01003286 if (t->logs.logwait & LW_REQ) {
willy tarreau9fe663a2005-12-17 13:02:59 +01003287 /* we have a complete HTTP request that we must log */
3288 int urilen;
3289
willy tarreaua1598082005-12-17 13:08:06 +01003290 if ((t->logs.uri = pool_alloc(requri)) == NULL) {
willy tarreau9fe663a2005-12-17 13:02:59 +01003291 Alert("HTTP logging : out of memory.\n");
willy tarreau750a4722005-12-17 13:21:24 +01003292 t->logs.status = 500;
willy tarreau8337c6b2005-12-17 13:41:01 +01003293 client_retnclose(t, t->proxy->errmsg.len500, t->proxy->errmsg.msg500);
willy tarreau036e1ce2005-12-17 13:46:33 +01003294 if (!(t->flags & SN_ERR_MASK))
3295 t->flags |= SN_ERR_PRXCOND;
3296 if (!(t->flags & SN_FINST_MASK))
3297 t->flags |= SN_FINST_R;
willy tarreau9fe663a2005-12-17 13:02:59 +01003298 return 1;
3299 }
3300
3301 urilen = ptr - req->h;
3302 if (urilen >= REQURI_LEN)
3303 urilen = REQURI_LEN - 1;
willy tarreaua1598082005-12-17 13:08:06 +01003304 memcpy(t->logs.uri, req->h, urilen);
3305 t->logs.uri[urilen] = 0;
willy tarreau9fe663a2005-12-17 13:02:59 +01003306
willy tarreaua1598082005-12-17 13:08:06 +01003307 if (!(t->logs.logwait &= ~LW_REQ))
willy tarreau9fe663a2005-12-17 13:02:59 +01003308 sess_log(t);
3309 }
willy tarreau4302f492005-12-18 01:00:37 +01003310 else if (t->logs.logwait & LW_REQHDR) {
3311 struct cap_hdr *h;
3312 int len;
3313 for (h = t->proxy->req_cap; h; h = h->next) {
3314 if ((h->namelen + 2 <= ptr - req->h) &&
3315 (req->h[h->namelen] == ':') &&
3316 (strncasecmp(req->h, h->name, h->namelen) == 0)) {
3317
3318 if (t->req_cap[h->index] == NULL)
3319 t->req_cap[h->index] = pool_alloc_from(h->pool, h->len + 1);
3320
3321 len = ptr - (req->h + h->namelen + 2);
3322 if (len > h->len)
3323 len = h->len;
3324
3325 memcpy(t->req_cap[h->index], req->h + h->namelen + 2, len);
3326 t->req_cap[h->index][len]=0;
3327 }
3328 }
3329
3330 }
willy tarreau9fe663a2005-12-17 13:02:59 +01003331
willy tarreau5cbea6f2005-12-17 12:48:26 +01003332 delete_header = 0;
willy tarreau0f7af912005-12-17 12:21:26 +01003333
willy tarreau982249e2005-12-18 00:57:06 +01003334 if ((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01003335 int len, max;
willy tarreau2f6ba652005-12-17 13:57:42 +01003336 len = sprintf(trash, "%08x:%s.clihdr[%04x:%04x]: ", t->uniq_id, t->proxy->id, (unsigned short)t->cli_fd, (unsigned short)t->srv_fd);
willy tarreau5cbea6f2005-12-17 12:48:26 +01003337 max = ptr - req->h;
3338 UBOUND(max, sizeof(trash) - len - 1);
willy tarreau750a4722005-12-17 13:21:24 +01003339 len += strlcpy2(trash + len, req->h, max + 1);
willy tarreau5cbea6f2005-12-17 12:48:26 +01003340 trash[len++] = '\n';
3341 write(1, trash, len);
3342 }
willy tarreau0f7af912005-12-17 12:21:26 +01003343
willy tarreau25c4ea52005-12-18 00:49:49 +01003344
3345 /* remove "connection: " if needed */
3346 if (!delete_header && (t->proxy->options & PR_O_HTTP_CLOSE)
3347 && (strncasecmp(req->h, "Connection: ", 12) == 0)) {
3348 delete_header = 1;
3349 }
3350
willy tarreau5cbea6f2005-12-17 12:48:26 +01003351 /* try headers regexps */
willy tarreau25c4ea52005-12-18 00:49:49 +01003352 if (!delete_header && t->proxy->req_exp != NULL
3353 && !(t->flags & SN_CLDENY)) {
willy tarreaue39cd132005-12-17 13:00:18 +01003354 struct hdr_exp *exp;
willy tarreau5cbea6f2005-12-17 12:48:26 +01003355 char term;
3356
3357 term = *ptr;
3358 *ptr = '\0';
willy tarreaue39cd132005-12-17 13:00:18 +01003359 exp = t->proxy->req_exp;
3360 do {
3361 if (regexec(exp->preg, req->h, MAX_MATCH, pmatch, 0) == 0) {
3362 switch (exp->action) {
3363 case ACT_ALLOW:
3364 if (!(t->flags & SN_CLDENY))
3365 t->flags |= SN_CLALLOW;
3366 break;
3367 case ACT_REPLACE:
3368 if (!(t->flags & SN_CLDENY)) {
3369 int len = exp_replace(trash, req->h, exp->replace, pmatch);
3370 ptr += buffer_replace2(req, req->h, ptr, trash, len);
3371 }
3372 break;
3373 case ACT_REMOVE:
3374 if (!(t->flags & SN_CLDENY))
3375 delete_header = 1;
3376 break;
3377 case ACT_DENY:
3378 if (!(t->flags & SN_CLALLOW))
3379 t->flags |= SN_CLDENY;
3380 break;
willy tarreau036e1ce2005-12-17 13:46:33 +01003381 case ACT_PASS: /* we simply don't deny this one */
3382 break;
willy tarreau0f7af912005-12-17 12:21:26 +01003383 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01003384 break;
willy tarreau0f7af912005-12-17 12:21:26 +01003385 }
willy tarreaue39cd132005-12-17 13:00:18 +01003386 } while ((exp = exp->next) != NULL);
willy tarreau5cbea6f2005-12-17 12:48:26 +01003387 *ptr = term; /* restore the string terminator */
willy tarreau0f7af912005-12-17 12:21:26 +01003388 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01003389
willy tarreau240afa62005-12-17 13:14:35 +01003390 /* Now look for cookies. Conforming to RFC2109, we have to support
3391 * attributes whose name begin with a '$', and associate them with
3392 * the right cookie, if we want to delete this cookie.
3393 * So there are 3 cases for each cookie read :
3394 * 1) it's a special attribute, beginning with a '$' : ignore it.
3395 * 2) it's a server id cookie that we *MAY* want to delete : save
3396 * some pointers on it (last semi-colon, beginning of cookie...)
3397 * 3) it's an application cookie : we *MAY* have to delete a previous
3398 * "special" cookie.
3399 * At the end of loop, if a "special" cookie remains, we may have to
3400 * remove it. If no application cookie persists in the header, we
3401 * *MUST* delete it
3402 */
willy tarreau12350152005-12-18 01:03:27 +01003403 if (!delete_header &&
3404 (t->proxy->cookie_name != NULL || t->proxy->capture_name != NULL || t->proxy->appsession_name !=NULL)
willy tarreau240afa62005-12-17 13:14:35 +01003405 && !(t->flags & SN_CLDENY) && (ptr >= req->h + 8)
willy tarreau906b2682005-12-17 13:49:52 +01003406 && (strncasecmp(req->h, "Cookie: ", 8) == 0)) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01003407 char *p1, *p2, *p3, *p4;
willy tarreau240afa62005-12-17 13:14:35 +01003408 char *del_colon, *del_cookie, *colon;
3409 int app_cookies;
3410
willy tarreau5cbea6f2005-12-17 12:48:26 +01003411 p1 = req->h + 8; /* first char after 'Cookie: ' */
willy tarreau240afa62005-12-17 13:14:35 +01003412 colon = p1;
3413 /* del_cookie == NULL => nothing to be deleted */
3414 del_colon = del_cookie = NULL;
3415 app_cookies = 0;
willy tarreau5cbea6f2005-12-17 12:48:26 +01003416
3417 while (p1 < ptr) {
willy tarreau240afa62005-12-17 13:14:35 +01003418 /* skip spaces and colons, but keep an eye on these ones */
3419 while (p1 < ptr) {
3420 if (*p1 == ';' || *p1 == ',')
3421 colon = p1;
3422 else if (!isspace((int)*p1))
3423 break;
willy tarreau5cbea6f2005-12-17 12:48:26 +01003424 p1++;
willy tarreau240afa62005-12-17 13:14:35 +01003425 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01003426
3427 if (p1 == ptr)
3428 break;
willy tarreau5cbea6f2005-12-17 12:48:26 +01003429
3430 /* p1 is at the beginning of the cookie name */
3431 p2 = p1;
willy tarreau240afa62005-12-17 13:14:35 +01003432 while (p2 < ptr && *p2 != '=')
willy tarreau5cbea6f2005-12-17 12:48:26 +01003433 p2++;
3434
3435 if (p2 == ptr)
3436 break;
willy tarreau5cbea6f2005-12-17 12:48:26 +01003437
3438 p3 = p2 + 1; /* skips the '=' sign */
3439 if (p3 == ptr)
3440 break;
3441
willy tarreau240afa62005-12-17 13:14:35 +01003442 p4 = p3;
3443 while (p4 < ptr && !isspace((int)*p4) && *p4 != ';' && *p4 != ',')
willy tarreau5cbea6f2005-12-17 12:48:26 +01003444 p4++;
3445
3446 /* here, we have the cookie name between p1 and p2,
3447 * and its value between p3 and p4.
willy tarreau0174f312005-12-18 01:02:42 +01003448 * we can process it :
3449 *
3450 * Cookie: NAME=VALUE;
3451 * | || || |
3452 * | || || +--> p4
3453 * | || |+-------> p3
3454 * | || +--------> p2
3455 * | |+------------> p1
3456 * | +-------------> colon
3457 * +--------------------> req->h
willy tarreau5cbea6f2005-12-17 12:48:26 +01003458 */
3459
willy tarreau240afa62005-12-17 13:14:35 +01003460 if (*p1 == '$') {
3461 /* skip this one */
3462 }
willy tarreau8337c6b2005-12-17 13:41:01 +01003463 else {
3464 /* first, let's see if we want to capture it */
3465 if (t->proxy->capture_name != NULL &&
3466 t->logs.cli_cookie == NULL &&
3467 (p4 - p1 >= t->proxy->capture_namelen) &&
3468 memcmp(p1, t->proxy->capture_name, t->proxy->capture_namelen) == 0) {
3469 int log_len = p4 - p1;
willy tarreau5cbea6f2005-12-17 12:48:26 +01003470
willy tarreau8337c6b2005-12-17 13:41:01 +01003471 if ((t->logs.cli_cookie = pool_alloc(capture)) == NULL) {
3472 Alert("HTTP logging : out of memory.\n");
willy tarreau12350152005-12-18 01:03:27 +01003473 } else {
3474 if (log_len > t->proxy->capture_len)
3475 log_len = t->proxy->capture_len;
3476 memcpy(t->logs.cli_cookie, p1, log_len);
3477 t->logs.cli_cookie[log_len] = 0;
willy tarreau8337c6b2005-12-17 13:41:01 +01003478 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01003479 }
willy tarreau8337c6b2005-12-17 13:41:01 +01003480
3481 if ((p2 - p1 == t->proxy->cookie_len) && (t->proxy->cookie_name != NULL) &&
3482 (memcmp(p1, t->proxy->cookie_name, p2 - p1) == 0)) {
3483 /* Cool... it's the right one */
3484 struct server *srv = t->proxy->srv;
willy tarreau0174f312005-12-18 01:02:42 +01003485 char *delim;
3486
3487 /* if we're in cookie prefix mode, we'll search the delimitor so that we
3488 * have the server ID betweek p3 and delim, and the original cookie between
3489 * delim+1 and p4. Otherwise, delim==p4 :
3490 *
3491 * Cookie: NAME=SRV~VALUE;
3492 * | || || | |
3493 * | || || | +--> p4
3494 * | || || +--------> delim
3495 * | || |+-----------> p3
3496 * | || +------------> p2
3497 * | |+----------------> p1
3498 * | +-----------------> colon
3499 * +------------------------> req->h
3500 */
willy tarreau8337c6b2005-12-17 13:41:01 +01003501
willy tarreau0174f312005-12-18 01:02:42 +01003502 if (t->proxy->options & PR_O_COOK_PFX) {
3503 for (delim = p3; delim < p4; delim++)
3504 if (*delim == COOKIE_DELIM)
3505 break;
3506 }
3507 else
3508 delim = p4;
3509
3510
3511 /* Here, we'll look for the first running server which supports the cookie.
3512 * This allows to share a same cookie between several servers, for example
3513 * to dedicate backup servers to specific servers only.
3514 */
3515 while (srv) {
3516 if ((srv->cklen == delim - p3) && !memcmp(p3, srv->cookie, delim - p3)) {
3517 if (srv->state & SRV_RUNNING || t->proxy->options & PR_O_PERSIST) {
3518 /* we found the server and it's usable */
3519 t->flags &= ~SN_CK_MASK;
3520 t->flags |= SN_CK_VALID | SN_DIRECT;
3521 t->srv = srv;
3522 break;
willy tarreau12350152005-12-18 01:03:27 +01003523 } else {
willy tarreau0174f312005-12-18 01:02:42 +01003524 /* we found a server, but it's down */
3525 t->flags &= ~SN_CK_MASK;
3526 t->flags |= SN_CK_DOWN;
3527 }
3528 }
willy tarreau8337c6b2005-12-17 13:41:01 +01003529 srv = srv->next;
3530 }
3531
willy tarreau0174f312005-12-18 01:02:42 +01003532 if (!srv && !(t->flags & SN_CK_DOWN)) {
3533 /* no server matched this cookie */
willy tarreau036e1ce2005-12-17 13:46:33 +01003534 t->flags &= ~SN_CK_MASK;
3535 t->flags |= SN_CK_INVALID;
3536 }
willy tarreau036e1ce2005-12-17 13:46:33 +01003537
willy tarreau0174f312005-12-18 01:02:42 +01003538 /* depending on the cookie mode, we may have to either :
3539 * - delete the complete cookie if we're in insert+indirect mode, so that
3540 * the server never sees it ;
3541 * - remove the server id from the cookie value, and tag the cookie as an
3542 * application cookie so that it does not get accidentely removed later,
3543 * if we're in cookie prefix mode
willy tarreau8337c6b2005-12-17 13:41:01 +01003544 */
willy tarreau0174f312005-12-18 01:02:42 +01003545 if ((t->proxy->options & PR_O_COOK_PFX) && (delim != p4)) {
3546 buffer_replace2(req, p3, delim + 1, NULL, 0);
3547 p4 -= (delim + 1 - p3);
3548 ptr -= (delim + 1 - p3);
3549 del_cookie = del_colon = NULL;
3550 app_cookies++; /* protect the header from deletion */
3551 }
3552 else if (del_cookie == NULL &&
willy tarreau8337c6b2005-12-17 13:41:01 +01003553 (t->proxy->options & (PR_O_COOK_INS | PR_O_COOK_IND)) == (PR_O_COOK_INS | PR_O_COOK_IND)) {
willy tarreau240afa62005-12-17 13:14:35 +01003554 del_cookie = p1;
3555 del_colon = colon;
willy tarreau8337c6b2005-12-17 13:41:01 +01003556 }
willy tarreau12350152005-12-18 01:03:27 +01003557 } else {
willy tarreau8337c6b2005-12-17 13:41:01 +01003558 /* now we know that we must keep this cookie since it's
3559 * not ours. But if we wanted to delete our cookie
3560 * earlier, we cannot remove the complete header, but we
3561 * can remove the previous block itself.
3562 */
3563 app_cookies++;
3564
3565 if (del_cookie != NULL) {
3566 buffer_replace2(req, del_cookie, p1, NULL, 0);
3567 p4 -= (p1 - del_cookie);
3568 ptr -= (p1 - del_cookie);
3569 del_cookie = del_colon = NULL;
3570 }
willy tarreau240afa62005-12-17 13:14:35 +01003571 }
willy tarreau12350152005-12-18 01:03:27 +01003572
3573 if ((t->proxy->appsession_name != NULL) &&
3574 (memcmp(p1, t->proxy->appsession_name, p2 - p1) == 0)) {
3575 /* first, let's see if the cookie is our appcookie*/
3576
3577 /* Cool... it's the right one */
3578
3579 asession_temp = &local_asession;
3580
3581 if ((asession_temp->sessid = pool_alloc_from(apools.sessid, apools.ses_msize)) == NULL) {
3582 Alert("Not enough memory process_cli():asession->sessid:malloc().\n");
3583 send_log(t->proxy, LOG_ALERT, "Not enough memory process_cli():asession->sessid:malloc().\n");
3584 return 0;
3585 }
3586
3587 memcpy(asession_temp->sessid, p3, t->proxy->appsession_len);
3588 asession_temp->sessid[t->proxy->appsession_len] = 0;
3589 asession_temp->serverid = NULL;
3590
3591 /* only do insert, if lookup fails */
3592 if (chtbl_lookup(&(t->proxy->htbl_proxy), (void *) &asession_temp) != 0) {
3593 if ((asession_temp = pool_alloc(appsess)) == NULL) {
3594 Alert("Not enough memory process_cli():asession:calloc().\n");
3595 send_log(t->proxy, LOG_ALERT, "Not enough memory process_cli():asession:calloc().\n");
3596 return 0;
3597 }
3598
3599 asession_temp->sessid = local_asession.sessid;
3600 asession_temp->serverid = local_asession.serverid;
3601 chtbl_insert(&(t->proxy->htbl_proxy), (void *) asession_temp);
3602 }
3603 else{
3604 /* free wasted memory */
3605 pool_free_to(apools.sessid, local_asession.sessid);
3606 }
3607
3608 if (asession_temp->serverid == NULL) {
3609 Alert("Found Application Session without matching server.\n");
3610 } else {
3611 struct server *srv = t->proxy->srv;
3612 while (srv) {
willy tarreaub952e1d2005-12-18 01:31:20 +01003613 if (strcmp(srv->id, asession_temp->serverid) == 0) {
willy tarreau12350152005-12-18 01:03:27 +01003614 if (srv->state & SRV_RUNNING || t->proxy->options & PR_O_PERSIST) {
3615 /* we found the server and it's usable */
3616 t->flags &= ~SN_CK_MASK;
3617 t->flags |= SN_CK_VALID | SN_DIRECT;
3618 t->srv = srv;
3619 break;
3620 } else {
3621 t->flags &= ~SN_CK_MASK;
3622 t->flags |= SN_CK_DOWN;
3623 }
3624 }
3625 srv = srv->next;
3626 }/* end while(srv) */
3627 }/* end else if server == NULL */
3628
3629 tv_delayfrom(&asession_temp->expire, &now, t->proxy->appsession_timeout);
willy tarreau12350152005-12-18 01:03:27 +01003630 }/* end if ((t->proxy->appsession_name != NULL) ... */
willy tarreau5cbea6f2005-12-17 12:48:26 +01003631 }
willy tarreau240afa62005-12-17 13:14:35 +01003632
willy tarreau5cbea6f2005-12-17 12:48:26 +01003633 /* we'll have to look for another cookie ... */
3634 p1 = p4;
3635 } /* while (p1 < ptr) */
willy tarreau240afa62005-12-17 13:14:35 +01003636
3637 /* There's no more cookie on this line.
3638 * We may have marked the last one(s) for deletion.
3639 * We must do this now in two ways :
3640 * - if there is no app cookie, we simply delete the header ;
3641 * - if there are app cookies, we must delete the end of the
3642 * string properly, including the colon/semi-colon before
3643 * the cookie name.
3644 */
3645 if (del_cookie != NULL) {
3646 if (app_cookies) {
3647 buffer_replace2(req, del_colon, ptr, NULL, 0);
3648 /* WARNING! <ptr> becomes invalid for now. If some code
3649 * below needs to rely on it before the end of the global
3650 * header loop, we need to correct it with this code :
3651 * ptr = del_colon;
3652 */
3653 }
3654 else
3655 delete_header = 1;
3656 }
3657 } /* end of cookie processing on this header */
willy tarreau5cbea6f2005-12-17 12:48:26 +01003658
3659 /* let's look if we have to delete this header */
willy tarreaue39cd132005-12-17 13:00:18 +01003660 if (delete_header && !(t->flags & SN_CLDENY)) {
willy tarreau240afa62005-12-17 13:14:35 +01003661 buffer_replace2(req, req->h, req->lr, NULL, 0);
willy tarreau0f7af912005-12-17 12:21:26 +01003662 }
willy tarreau240afa62005-12-17 13:14:35 +01003663 /* WARNING: ptr is not valid anymore, since the header may have been deleted or truncated ! */
3664
willy tarreau5cbea6f2005-12-17 12:48:26 +01003665 req->h = req->lr;
3666 } /* while (req->lr < req->r) */
3667
3668 /* end of header processing (even if incomplete) */
3669
willy tarreauef900ab2005-12-17 12:52:52 +01003670 if ((req->l < req->rlim - req->data) && ! FD_ISSET(t->cli_fd, StaticReadEvent)) {
3671 /* fd in StaticReadEvent was disabled, perhaps because of a previous buffer
3672 * full. We cannot loop here since event_cli_read will disable it only if
3673 * req->l == rlim-data
3674 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01003675 FD_SET(t->cli_fd, StaticReadEvent);
3676 if (t->proxy->clitimeout)
3677 tv_delayfrom(&t->crexpire, &now, t->proxy->clitimeout);
3678 else
3679 tv_eternity(&t->crexpire);
3680 }
3681
willy tarreaue39cd132005-12-17 13:00:18 +01003682 /* Since we are in header mode, if there's no space left for headers, we
willy tarreauef900ab2005-12-17 12:52:52 +01003683 * won't be able to free more later, so the session will never terminate.
3684 */
willy tarreaue39cd132005-12-17 13:00:18 +01003685 if (req->l >= req->rlim - req->data) {
willy tarreaua1598082005-12-17 13:08:06 +01003686 t->logs.status = 400;
willy tarreau8337c6b2005-12-17 13:41:01 +01003687 client_retnclose(t, t->proxy->errmsg.len400, t->proxy->errmsg.msg400);
willy tarreau036e1ce2005-12-17 13:46:33 +01003688 if (!(t->flags & SN_ERR_MASK))
3689 t->flags |= SN_ERR_PRXCOND;
3690 if (!(t->flags & SN_FINST_MASK))
3691 t->flags |= SN_FINST_R;
willy tarreaue39cd132005-12-17 13:00:18 +01003692 return 1;
3693 }
willy tarreau8337c6b2005-12-17 13:41:01 +01003694 else if (t->res_cr == RES_ERROR || t->res_cr == RES_NULL) {
willy tarreau036e1ce2005-12-17 13:46:33 +01003695 /* read error, or last read : give up. */
willy tarreau5cbea6f2005-12-17 12:48:26 +01003696 tv_eternity(&t->crexpire);
3697 fd_delete(t->cli_fd);
willy tarreau5cbea6f2005-12-17 12:48:26 +01003698 t->cli_state = CL_STCLOSE;
willy tarreau036e1ce2005-12-17 13:46:33 +01003699 if (!(t->flags & SN_ERR_MASK))
3700 t->flags |= SN_ERR_CLICL;
3701 if (!(t->flags & SN_FINST_MASK))
3702 t->flags |= SN_FINST_R;
willy tarreau5cbea6f2005-12-17 12:48:26 +01003703 return 1;
willy tarreau0f7af912005-12-17 12:21:26 +01003704 }
willy tarreau8337c6b2005-12-17 13:41:01 +01003705 else if (tv_cmp2_ms(&t->crexpire, &now) <= 0) {
3706
3707 /* read timeout : give up with an error message.
3708 */
3709 t->logs.status = 408;
3710 client_retnclose(t, t->proxy->errmsg.len408, t->proxy->errmsg.msg408);
willy tarreau036e1ce2005-12-17 13:46:33 +01003711 if (!(t->flags & SN_ERR_MASK))
3712 t->flags |= SN_ERR_CLITO;
3713 if (!(t->flags & SN_FINST_MASK))
3714 t->flags |= SN_FINST_R;
willy tarreau8337c6b2005-12-17 13:41:01 +01003715 return 1;
3716 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01003717
3718 return t->cli_state != CL_STHEADERS;
willy tarreau0f7af912005-12-17 12:21:26 +01003719 }
3720 else if (c == CL_STDATA) {
willy tarreau197e8ec2005-12-17 14:10:59 +01003721 process_data:
willy tarreauc1cae632005-12-17 14:12:23 +01003722 /* FIXME: this error handling is partly buggy because we always report
3723 * a 'DATA' phase while we don't know if the server was in IDLE, CONN
3724 * or HEADER phase. BTW, it's not logical to expire the client while
3725 * we're waiting for the server to connect.
3726 */
willy tarreau0f7af912005-12-17 12:21:26 +01003727 /* read or write error */
3728 if (t->res_cw == RES_ERROR || t->res_cr == RES_ERROR) {
willy tarreau0f7af912005-12-17 12:21:26 +01003729 tv_eternity(&t->crexpire);
3730 tv_eternity(&t->cwexpire);
willy tarreau5cbea6f2005-12-17 12:48:26 +01003731 fd_delete(t->cli_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01003732 t->cli_state = CL_STCLOSE;
willy tarreau036e1ce2005-12-17 13:46:33 +01003733 if (!(t->flags & SN_ERR_MASK))
3734 t->flags |= SN_ERR_CLICL;
3735 if (!(t->flags & SN_FINST_MASK))
3736 t->flags |= SN_FINST_D;
willy tarreau0f7af912005-12-17 12:21:26 +01003737 return 1;
3738 }
willy tarreau036e1ce2005-12-17 13:46:33 +01003739 /* last read, or end of server write */
3740 else if (t->res_cr == RES_NULL || s == SV_STSHUTW || s == SV_STCLOSE) {
willy tarreau0f7af912005-12-17 12:21:26 +01003741 FD_CLR(t->cli_fd, StaticReadEvent);
willy tarreau0f7af912005-12-17 12:21:26 +01003742 tv_eternity(&t->crexpire);
3743 shutdown(t->cli_fd, SHUT_RD);
3744 t->cli_state = CL_STSHUTR;
3745 return 1;
3746 }
willy tarreau036e1ce2005-12-17 13:46:33 +01003747 /* last server read and buffer empty */
3748 else if ((s == SV_STSHUTR || s == SV_STCLOSE) && (rep->l == 0)) {
willy tarreau0f7af912005-12-17 12:21:26 +01003749 FD_CLR(t->cli_fd, StaticWriteEvent);
3750 tv_eternity(&t->cwexpire);
3751 shutdown(t->cli_fd, SHUT_WR);
willy tarreaub1285d52005-12-18 01:20:14 +01003752 /* We must ensure that the read part is still alive when switching
3753 * to shutw */
3754 FD_SET(t->cli_fd, StaticReadEvent);
3755 if (t->proxy->clitimeout)
3756 tv_delayfrom(&t->crexpire, &now, t->proxy->clitimeout);
willy tarreau0f7af912005-12-17 12:21:26 +01003757 t->cli_state = CL_STSHUTW;
willy tarreaub952e1d2005-12-18 01:31:20 +01003758 //fprintf(stderr,"%p:%s(%d), c=%d, s=%d\n", t, __FUNCTION__, __LINE__, t->cli_state, t->cli_state);
willy tarreau0f7af912005-12-17 12:21:26 +01003759 return 1;
3760 }
willy tarreau036e1ce2005-12-17 13:46:33 +01003761 /* read timeout */
3762 else if (tv_cmp2_ms(&t->crexpire, &now) <= 0) {
3763 FD_CLR(t->cli_fd, StaticReadEvent);
willy tarreau036e1ce2005-12-17 13:46:33 +01003764 tv_eternity(&t->crexpire);
3765 shutdown(t->cli_fd, SHUT_RD);
3766 t->cli_state = CL_STSHUTR;
3767 if (!(t->flags & SN_ERR_MASK))
3768 t->flags |= SN_ERR_CLITO;
3769 if (!(t->flags & SN_FINST_MASK))
3770 t->flags |= SN_FINST_D;
3771 return 1;
3772 }
3773 /* write timeout */
3774 else if (tv_cmp2_ms(&t->cwexpire, &now) <= 0) {
3775 FD_CLR(t->cli_fd, StaticWriteEvent);
3776 tv_eternity(&t->cwexpire);
3777 shutdown(t->cli_fd, SHUT_WR);
willy tarreaub1285d52005-12-18 01:20:14 +01003778 /* We must ensure that the read part is still alive when switching
3779 * to shutw */
3780 FD_SET(t->cli_fd, StaticReadEvent);
3781 if (t->proxy->clitimeout)
3782 tv_delayfrom(&t->crexpire, &now, t->proxy->clitimeout);
3783
willy tarreau036e1ce2005-12-17 13:46:33 +01003784 t->cli_state = CL_STSHUTW;
3785 if (!(t->flags & SN_ERR_MASK))
willy tarreaub1ff9db2005-12-17 13:51:03 +01003786 t->flags |= SN_ERR_CLITO;
willy tarreau036e1ce2005-12-17 13:46:33 +01003787 if (!(t->flags & SN_FINST_MASK))
3788 t->flags |= SN_FINST_D;
3789 return 1;
3790 }
willy tarreau0f7af912005-12-17 12:21:26 +01003791
willy tarreauc58fc692005-12-17 14:13:08 +01003792 if (req->l >= req->rlim - req->data) {
3793 /* no room to read more data */
willy tarreau0f7af912005-12-17 12:21:26 +01003794 if (FD_ISSET(t->cli_fd, StaticReadEvent)) {
willy tarreauef900ab2005-12-17 12:52:52 +01003795 /* stop reading until we get some space */
willy tarreau0f7af912005-12-17 12:21:26 +01003796 FD_CLR(t->cli_fd, StaticReadEvent);
3797 tv_eternity(&t->crexpire);
3798 }
3799 }
3800 else {
willy tarreauef900ab2005-12-17 12:52:52 +01003801 /* there's still some space in the buffer */
willy tarreau0f7af912005-12-17 12:21:26 +01003802 if (! FD_ISSET(t->cli_fd, StaticReadEvent)) {
3803 FD_SET(t->cli_fd, StaticReadEvent);
willy tarreauc58fc692005-12-17 14:13:08 +01003804 if (!t->proxy->clitimeout ||
3805 (t->srv_state < SV_STDATA && t->proxy->srvtimeout))
3806 /* If the client has no timeout, or if the server not ready yet, and we
3807 * know for sure that it can expire, then it's cleaner to disable the
3808 * timeout on the client side so that too low values cannot make the
3809 * sessions abort too early.
3810 */
willy tarreau0f7af912005-12-17 12:21:26 +01003811 tv_eternity(&t->crexpire);
willy tarreauc58fc692005-12-17 14:13:08 +01003812 else
3813 tv_delayfrom(&t->crexpire, &now, t->proxy->clitimeout);
willy tarreau0f7af912005-12-17 12:21:26 +01003814 }
3815 }
3816
3817 if ((rep->l == 0) ||
willy tarreauc1cae632005-12-17 14:12:23 +01003818 ((s < SV_STDATA) /* FIXME: this may be optimized && (rep->w == rep->h)*/)) {
willy tarreau0f7af912005-12-17 12:21:26 +01003819 if (FD_ISSET(t->cli_fd, StaticWriteEvent)) {
3820 FD_CLR(t->cli_fd, StaticWriteEvent); /* stop writing */
3821 tv_eternity(&t->cwexpire);
3822 }
3823 }
3824 else { /* buffer not empty */
3825 if (! FD_ISSET(t->cli_fd, StaticWriteEvent)) {
3826 FD_SET(t->cli_fd, StaticWriteEvent); /* restart writing */
willy tarreaub1ff9db2005-12-17 13:51:03 +01003827 if (t->proxy->clitimeout) {
willy tarreau0f7af912005-12-17 12:21:26 +01003828 tv_delayfrom(&t->cwexpire, &now, t->proxy->clitimeout);
willy tarreaub1ff9db2005-12-17 13:51:03 +01003829 /* FIXME: to avoid the client to read-time-out during writes, we refresh it */
3830 t->crexpire = t->cwexpire;
3831 }
willy tarreau0f7af912005-12-17 12:21:26 +01003832 else
3833 tv_eternity(&t->cwexpire);
3834 }
3835 }
3836 return 0; /* other cases change nothing */
3837 }
3838 else if (c == CL_STSHUTR) {
willy tarreau036e1ce2005-12-17 13:46:33 +01003839 if (t->res_cw == RES_ERROR) {
3840 tv_eternity(&t->cwexpire);
3841 fd_delete(t->cli_fd);
3842 t->cli_state = CL_STCLOSE;
3843 if (!(t->flags & SN_ERR_MASK))
3844 t->flags |= SN_ERR_CLICL;
3845 if (!(t->flags & SN_FINST_MASK))
3846 t->flags |= SN_FINST_D;
3847 return 1;
3848 }
3849 else if ((s == SV_STSHUTR || s == SV_STCLOSE) && (rep->l == 0)) {
willy tarreau0f7af912005-12-17 12:21:26 +01003850 tv_eternity(&t->cwexpire);
3851 fd_delete(t->cli_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01003852 t->cli_state = CL_STCLOSE;
3853 return 1;
3854 }
willy tarreau036e1ce2005-12-17 13:46:33 +01003855 else if (tv_cmp2_ms(&t->cwexpire, &now) <= 0) {
3856 tv_eternity(&t->cwexpire);
3857 fd_delete(t->cli_fd);
3858 t->cli_state = CL_STCLOSE;
3859 if (!(t->flags & SN_ERR_MASK))
3860 t->flags |= SN_ERR_CLITO;
3861 if (!(t->flags & SN_FINST_MASK))
3862 t->flags |= SN_FINST_D;
3863 return 1;
3864 }
willy tarreau0f7af912005-12-17 12:21:26 +01003865 else if ((rep->l == 0) ||
willy tarreau5cbea6f2005-12-17 12:48:26 +01003866 ((s == SV_STHEADERS) /* FIXME: this may be optimized && (rep->w == rep->h)*/)) {
willy tarreau0f7af912005-12-17 12:21:26 +01003867 if (FD_ISSET(t->cli_fd, StaticWriteEvent)) {
3868 FD_CLR(t->cli_fd, StaticWriteEvent); /* stop writing */
3869 tv_eternity(&t->cwexpire);
3870 }
3871 }
3872 else { /* buffer not empty */
3873 if (! FD_ISSET(t->cli_fd, StaticWriteEvent)) {
3874 FD_SET(t->cli_fd, StaticWriteEvent); /* restart writing */
willy tarreaub1ff9db2005-12-17 13:51:03 +01003875 if (t->proxy->clitimeout) {
willy tarreau0f7af912005-12-17 12:21:26 +01003876 tv_delayfrom(&t->cwexpire, &now, t->proxy->clitimeout);
willy tarreaub1ff9db2005-12-17 13:51:03 +01003877 /* FIXME: to avoid the client to read-time-out during writes, we refresh it */
3878 t->crexpire = t->cwexpire;
3879 }
willy tarreau0f7af912005-12-17 12:21:26 +01003880 else
3881 tv_eternity(&t->cwexpire);
3882 }
3883 }
3884 return 0;
3885 }
3886 else if (c == CL_STSHUTW) {
willy tarreau036e1ce2005-12-17 13:46:33 +01003887 if (t->res_cr == RES_ERROR) {
willy tarreau0f7af912005-12-17 12:21:26 +01003888 tv_eternity(&t->crexpire);
3889 fd_delete(t->cli_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01003890 t->cli_state = CL_STCLOSE;
willy tarreau036e1ce2005-12-17 13:46:33 +01003891 if (!(t->flags & SN_ERR_MASK))
3892 t->flags |= SN_ERR_CLICL;
3893 if (!(t->flags & SN_FINST_MASK))
3894 t->flags |= SN_FINST_D;
willy tarreau0f7af912005-12-17 12:21:26 +01003895 return 1;
3896 }
willy tarreau036e1ce2005-12-17 13:46:33 +01003897 else if (t->res_cr == RES_NULL || s == SV_STSHUTW || s == SV_STCLOSE) {
3898 tv_eternity(&t->crexpire);
3899 fd_delete(t->cli_fd);
3900 t->cli_state = CL_STCLOSE;
3901 return 1;
3902 }
3903 else if (tv_cmp2_ms(&t->crexpire, &now) <= 0) {
3904 tv_eternity(&t->crexpire);
3905 fd_delete(t->cli_fd);
3906 t->cli_state = CL_STCLOSE;
3907 if (!(t->flags & SN_ERR_MASK))
3908 t->flags |= SN_ERR_CLITO;
3909 if (!(t->flags & SN_FINST_MASK))
3910 t->flags |= SN_FINST_D;
3911 return 1;
3912 }
willy tarreauef900ab2005-12-17 12:52:52 +01003913 else if (req->l >= req->rlim - req->data) {
3914 /* no room to read more data */
willy tarreaub1285d52005-12-18 01:20:14 +01003915
3916 /* FIXME-20050705: is it possible for a client to maintain a session
3917 * after the timeout by sending more data after it receives a close ?
3918 */
3919
willy tarreau0f7af912005-12-17 12:21:26 +01003920 if (FD_ISSET(t->cli_fd, StaticReadEvent)) {
willy tarreauef900ab2005-12-17 12:52:52 +01003921 /* stop reading until we get some space */
willy tarreau0f7af912005-12-17 12:21:26 +01003922 FD_CLR(t->cli_fd, StaticReadEvent);
3923 tv_eternity(&t->crexpire);
willy tarreaub952e1d2005-12-18 01:31:20 +01003924 //fprintf(stderr,"%p:%s(%d), c=%d, s=%d\n", t, __FUNCTION__, __LINE__, t->cli_state, t->cli_state);
willy tarreau0f7af912005-12-17 12:21:26 +01003925 }
3926 }
3927 else {
willy tarreauef900ab2005-12-17 12:52:52 +01003928 /* there's still some space in the buffer */
willy tarreau0f7af912005-12-17 12:21:26 +01003929 if (! FD_ISSET(t->cli_fd, StaticReadEvent)) {
3930 FD_SET(t->cli_fd, StaticReadEvent);
3931 if (t->proxy->clitimeout)
3932 tv_delayfrom(&t->crexpire, &now, t->proxy->clitimeout);
3933 else
3934 tv_eternity(&t->crexpire);
willy tarreaub952e1d2005-12-18 01:31:20 +01003935 //fprintf(stderr,"%p:%s(%d), c=%d, s=%d\n", t, __FUNCTION__, __LINE__, t->cli_state, t->cli_state);
willy tarreau0f7af912005-12-17 12:21:26 +01003936 }
3937 }
3938 return 0;
3939 }
3940 else { /* CL_STCLOSE: nothing to do */
willy tarreau982249e2005-12-18 00:57:06 +01003941 if ((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))) {
willy tarreau0f7af912005-12-17 12:21:26 +01003942 int len;
willy tarreau2f6ba652005-12-17 13:57:42 +01003943 len = sprintf(trash, "%08x:%s.clicls[%04x:%04x]\n", t->uniq_id, t->proxy->id, (unsigned short)t->cli_fd, (unsigned short)t->srv_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01003944 write(1, trash, len);
3945 }
3946 return 0;
3947 }
3948 return 0;
3949}
3950
3951
3952/*
3953 * manages the server FSM and its socket. It returns 1 if a state has changed
3954 * (and a resync may be needed), 0 else.
3955 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01003956int process_srv(struct session *t) {
willy tarreau0f7af912005-12-17 12:21:26 +01003957 int s = t->srv_state;
3958 int c = t->cli_state;
3959 struct buffer *req = t->req;
3960 struct buffer *rep = t->rep;
willy tarreau12350152005-12-18 01:03:27 +01003961 appsess *asession_temp = NULL;
3962 appsess local_asession;
willy tarreaub1285d52005-12-18 01:20:14 +01003963 int conn_err;
willy tarreau0f7af912005-12-17 12:21:26 +01003964
willy tarreau750a4722005-12-17 13:21:24 +01003965#ifdef DEBUG_FULL
3966 fprintf(stderr,"process_srv: c=%s, s=%s\n", cli_stnames[c], srv_stnames[s]);
3967#endif
willy tarreau5cbea6f2005-12-17 12:48:26 +01003968 //fprintf(stderr,"process_srv: c=%d, s=%d, cr=%d, cw=%d, sr=%d, sw=%d\n", c, s,
3969 //FD_ISSET(t->cli_fd, StaticReadEvent), FD_ISSET(t->cli_fd, StaticWriteEvent),
3970 //FD_ISSET(t->srv_fd, StaticReadEvent), FD_ISSET(t->srv_fd, StaticWriteEvent)
3971 //);
willy tarreau0f7af912005-12-17 12:21:26 +01003972 if (s == SV_STIDLE) {
3973 if (c == CL_STHEADERS)
3974 return 0; /* stay in idle, waiting for data to reach the client side */
3975 else if (c == CL_STCLOSE ||
3976 c == CL_STSHUTW ||
3977 (c == CL_STSHUTR && t->req->l == 0)) { /* give up */
3978 tv_eternity(&t->cnexpire);
3979 t->srv_state = SV_STCLOSE;
willy tarreau036e1ce2005-12-17 13:46:33 +01003980 if (!(t->flags & SN_ERR_MASK))
3981 t->flags |= SN_ERR_CLICL;
3982 if (!(t->flags & SN_FINST_MASK))
3983 t->flags |= SN_FINST_C;
willy tarreau0f7af912005-12-17 12:21:26 +01003984 return 1;
3985 }
3986 else { /* go to SV_STCONN */
willy tarreaub1285d52005-12-18 01:20:14 +01003987 /* initiate a connection to the server */
3988 conn_err = connect_server(t);
3989 if (conn_err == SN_ERR_NONE) {
willy tarreau0f7af912005-12-17 12:21:26 +01003990 //fprintf(stderr,"0: c=%d, s=%d\n", c, s);
3991 t->srv_state = SV_STCONN;
3992 }
3993 else { /* try again */
3994 while (t->conn_retries-- > 0) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01003995 if ((t->proxy->options & PR_O_REDISP) && (t->conn_retries == 0)) {
willy tarreaue39cd132005-12-17 13:00:18 +01003996 t->flags &= ~SN_DIRECT; /* ignore cookie and force to use the dispatcher */
willy tarreau5cbea6f2005-12-17 12:48:26 +01003997 t->srv = NULL; /* it's left to the dispatcher to choose a server */
willy tarreau036e1ce2005-12-17 13:46:33 +01003998 if ((t->flags & SN_CK_MASK) == SN_CK_VALID) {
3999 t->flags &= ~SN_CK_MASK;
4000 t->flags |= SN_CK_DOWN;
4001 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01004002 }
4003
willy tarreaub1285d52005-12-18 01:20:14 +01004004 conn_err = connect_server(t);
4005 if (conn_err == SN_ERR_NONE) {
willy tarreau0f7af912005-12-17 12:21:26 +01004006 t->srv_state = SV_STCONN;
4007 break;
4008 }
4009 }
4010 if (t->conn_retries < 0) {
4011 /* if conn_retries < 0 or other error, let's abort */
4012 tv_eternity(&t->cnexpire);
4013 t->srv_state = SV_STCLOSE;
willy tarreau8337c6b2005-12-17 13:41:01 +01004014 t->logs.status = 503;
willy tarreau750a4722005-12-17 13:21:24 +01004015 if (t->proxy->mode == PR_MODE_HTTP)
willy tarreau8337c6b2005-12-17 13:41:01 +01004016 client_return(t, t->proxy->errmsg.len503, t->proxy->errmsg.msg503);
willy tarreau036e1ce2005-12-17 13:46:33 +01004017 if (!(t->flags & SN_ERR_MASK))
willy tarreaub1285d52005-12-18 01:20:14 +01004018 t->flags |= conn_err; /* report the precise connect() error */
willy tarreau036e1ce2005-12-17 13:46:33 +01004019 if (!(t->flags & SN_FINST_MASK))
4020 t->flags |= SN_FINST_C;
willy tarreau0f7af912005-12-17 12:21:26 +01004021 }
4022 }
4023 return 1;
4024 }
4025 }
4026 else if (s == SV_STCONN) { /* connection in progress */
4027 if (t->res_sw == RES_SILENT && tv_cmp2_ms(&t->cnexpire, &now) > 0) {
4028 //fprintf(stderr,"1: c=%d, s=%d\n", c, s);
4029 return 0; /* nothing changed */
4030 }
4031 else if (t->res_sw == RES_SILENT || t->res_sw == RES_ERROR) {
4032 //fprintf(stderr,"2: c=%d, s=%d\n", c, s);
4033 /* timeout, connect error or first write error */
willy tarreau5cbea6f2005-12-17 12:48:26 +01004034 //FD_CLR(t->srv_fd, StaticWriteEvent);
willy tarreau0f7af912005-12-17 12:21:26 +01004035 fd_delete(t->srv_fd);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004036 //close(t->srv_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01004037 t->conn_retries--;
willy tarreau5cbea6f2005-12-17 12:48:26 +01004038 if (t->conn_retries >= 0) {
4039 if ((t->proxy->options & PR_O_REDISP) && (t->conn_retries == 0)) {
willy tarreaue39cd132005-12-17 13:00:18 +01004040 t->flags &= ~SN_DIRECT; /* ignore cookie and force to use the dispatcher */
willy tarreau5cbea6f2005-12-17 12:48:26 +01004041 t->srv = NULL; /* it's left to the dispatcher to choose a server */
willy tarreau036e1ce2005-12-17 13:46:33 +01004042 if ((t->flags & SN_CK_MASK) == SN_CK_VALID) {
4043 t->flags &= ~SN_CK_MASK;
4044 t->flags |= SN_CK_DOWN;
4045 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01004046 }
willy tarreaub1285d52005-12-18 01:20:14 +01004047 conn_err = connect_server(t);
4048 if (conn_err == SN_ERR_NONE)
willy tarreau5cbea6f2005-12-17 12:48:26 +01004049 return 0; /* no state changed */
willy tarreau0f7af912005-12-17 12:21:26 +01004050 }
willy tarreaub1285d52005-12-18 01:20:14 +01004051 else if (t->res_sw == RES_SILENT)
4052 conn_err = SN_ERR_SRVTO; // it was a connect timeout.
4053 else
4054 conn_err = SN_ERR_SRVCL; // it was a connect error.
4055
willy tarreau0f7af912005-12-17 12:21:26 +01004056 /* if conn_retries < 0 or other error, let's abort */
4057 tv_eternity(&t->cnexpire);
4058 t->srv_state = SV_STCLOSE;
willy tarreau8337c6b2005-12-17 13:41:01 +01004059 t->logs.status = 503;
willy tarreau750a4722005-12-17 13:21:24 +01004060 if (t->proxy->mode == PR_MODE_HTTP)
willy tarreau8337c6b2005-12-17 13:41:01 +01004061 client_return(t, t->proxy->errmsg.len503, t->proxy->errmsg.msg503);
willy tarreau036e1ce2005-12-17 13:46:33 +01004062 if (!(t->flags & SN_ERR_MASK))
willy tarreaub1285d52005-12-18 01:20:14 +01004063 t->flags |= conn_err;
willy tarreau036e1ce2005-12-17 13:46:33 +01004064 if (!(t->flags & SN_FINST_MASK))
4065 t->flags |= SN_FINST_C;
willy tarreau0f7af912005-12-17 12:21:26 +01004066 return 1;
4067 }
4068 else { /* no error or write 0 */
willy tarreau750a4722005-12-17 13:21:24 +01004069 t->logs.t_connect = tv_diff(&t->logs.tv_accept, &now);
willy tarreaua1598082005-12-17 13:08:06 +01004070
willy tarreau0f7af912005-12-17 12:21:26 +01004071 //fprintf(stderr,"3: c=%d, s=%d\n", c, s);
willy tarreaub1ff9db2005-12-17 13:51:03 +01004072 if (req->l == 0) /* nothing to write */ {
willy tarreau0f7af912005-12-17 12:21:26 +01004073 FD_CLR(t->srv_fd, StaticWriteEvent);
willy tarreaub1ff9db2005-12-17 13:51:03 +01004074 tv_eternity(&t->swexpire);
4075 } else /* need the right to write */ {
willy tarreau0f7af912005-12-17 12:21:26 +01004076 FD_SET(t->srv_fd, StaticWriteEvent);
willy tarreaub1ff9db2005-12-17 13:51:03 +01004077 if (t->proxy->srvtimeout) {
4078 tv_delayfrom(&t->swexpire, &now, t->proxy->srvtimeout);
4079 /* FIXME: to avoid the server to read-time-out during writes, we refresh it */
4080 t->srexpire = t->swexpire;
4081 }
4082 else
4083 tv_eternity(&t->swexpire);
4084 }
willy tarreau0f7af912005-12-17 12:21:26 +01004085
4086 if (t->proxy->mode == PR_MODE_TCP) { /* let's allow immediate data connection in this case */
4087 FD_SET(t->srv_fd, StaticReadEvent);
4088 if (t->proxy->srvtimeout)
4089 tv_delayfrom(&t->srexpire, &now, t->proxy->srvtimeout);
4090 else
4091 tv_eternity(&t->srexpire);
4092
4093 t->srv_state = SV_STDATA;
willy tarreauef900ab2005-12-17 12:52:52 +01004094 rep->rlim = rep->data + BUFSIZE; /* no rewrite needed */
willy tarreau25c4ea52005-12-18 00:49:49 +01004095
4096 /* if the user wants to log as soon as possible, without counting
4097 bytes from the server, then this is the right moment. */
willy tarreau4302f492005-12-18 01:00:37 +01004098 if (t->proxy->to_log && !(t->logs.logwait & LW_BYTES)) {
willy tarreau25c4ea52005-12-18 00:49:49 +01004099 t->logs.t_close = t->logs.t_connect; /* to get a valid end date */
4100 sess_log(t);
4101 }
willy tarreau0f7af912005-12-17 12:21:26 +01004102 }
willy tarreauef900ab2005-12-17 12:52:52 +01004103 else {
willy tarreau0f7af912005-12-17 12:21:26 +01004104 t->srv_state = SV_STHEADERS;
willy tarreauef900ab2005-12-17 12:52:52 +01004105 rep->rlim = rep->data + BUFSIZE - MAXREWRITE; /* rewrite needed */
4106 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01004107 tv_eternity(&t->cnexpire);
willy tarreau0f7af912005-12-17 12:21:26 +01004108 return 1;
4109 }
4110 }
4111 else if (s == SV_STHEADERS) { /* receiving server headers */
willy tarreau5cbea6f2005-12-17 12:48:26 +01004112 /* now parse the partial (or complete) headers */
4113 while (rep->lr < rep->r) { /* this loop only sees one header at each iteration */
4114 char *ptr;
4115 int delete_header;
4116
4117 ptr = rep->lr;
4118
4119 /* look for the end of the current header */
4120 while (ptr < rep->r && *ptr != '\n' && *ptr != '\r')
4121 ptr++;
4122
4123 if (ptr == rep->h) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01004124 int line, len;
4125
4126 /* we can only get here after an end of headers */
willy tarreau97f58572005-12-18 00:53:44 +01004127
4128 /* first, we'll block if security checks have caught nasty things */
4129 if (t->flags & SN_CACHEABLE) {
4130 if ((t->flags & SN_CACHE_COOK) &&
4131 (t->flags & SN_SCK_ANY) &&
4132 (t->proxy->options & PR_O_CHK_CACHE)) {
4133
4134 /* we're in presence of a cacheable response containing
4135 * a set-cookie header. We'll block it as requested by
4136 * the 'checkcache' option, and send an alert.
4137 */
4138 tv_eternity(&t->srexpire);
4139 tv_eternity(&t->swexpire);
4140 fd_delete(t->srv_fd);
4141 t->srv_state = SV_STCLOSE;
4142 t->logs.status = 502;
4143 client_return(t, t->proxy->errmsg.len502, t->proxy->errmsg.msg502);
4144 if (!(t->flags & SN_ERR_MASK))
4145 t->flags |= SN_ERR_PRXCOND;
4146 if (!(t->flags & SN_FINST_MASK))
4147 t->flags |= SN_FINST_H;
4148
4149 Alert("Blocking cacheable cookie in response from instance %s, server %s.\n", t->proxy->id, t->srv->id);
4150 send_log(t->proxy, LOG_ALERT, "Blocking cacheable cookie in response from instance %s, server %s.\n", t->proxy->id, t->srv->id);
4151
4152 return 1;
4153 }
4154 }
4155
willy tarreau982249e2005-12-18 00:57:06 +01004156 /* next, we'll block if an 'rspideny' or 'rspdeny' filter matched */
4157 if (t->flags & SN_SVDENY) {
4158 tv_eternity(&t->srexpire);
4159 tv_eternity(&t->swexpire);
4160 fd_delete(t->srv_fd);
4161 t->srv_state = SV_STCLOSE;
4162 t->logs.status = 502;
4163 client_return(t, t->proxy->errmsg.len502, t->proxy->errmsg.msg502);
4164 if (!(t->flags & SN_ERR_MASK))
4165 t->flags |= SN_ERR_PRXCOND;
4166 if (!(t->flags & SN_FINST_MASK))
4167 t->flags |= SN_FINST_H;
4168 return 1;
4169 }
4170
willy tarreau5cbea6f2005-12-17 12:48:26 +01004171 /* we'll have something else to do here : add new headers ... */
4172
willy tarreaucd878942005-12-17 13:27:43 +01004173 if ((t->srv) && !(t->flags & SN_DIRECT) && (t->proxy->options & PR_O_COOK_INS) &&
4174 (!(t->proxy->options & PR_O_COOK_POST) || (t->flags & SN_POST))) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01004175 /* the server is known, it's not the one the client requested, we have to
willy tarreaucd878942005-12-17 13:27:43 +01004176 * insert a set-cookie here, except if we want to insert only on POST
4177 * requests and this one isn't.
willy tarreau5cbea6f2005-12-17 12:48:26 +01004178 */
willy tarreau750a4722005-12-17 13:21:24 +01004179 len = sprintf(trash, "Set-Cookie: %s=%s; path=/\r\n",
willy tarreau8337c6b2005-12-17 13:41:01 +01004180 t->proxy->cookie_name,
4181 t->srv->cookie ? t->srv->cookie : "");
willy tarreau750a4722005-12-17 13:21:24 +01004182
willy tarreau036e1ce2005-12-17 13:46:33 +01004183 t->flags |= SN_SCK_INSERTED;
4184
willy tarreau750a4722005-12-17 13:21:24 +01004185 /* Here, we will tell an eventual cache on the client side that we don't
4186 * want it to cache this reply because HTTP/1.0 caches also cache cookies !
4187 * Some caches understand the correct form: 'no-cache="set-cookie"', but
4188 * others don't (eg: apache <= 1.3.26). So we use 'private' instead.
4189 */
willy tarreau240afa62005-12-17 13:14:35 +01004190 if (t->proxy->options & PR_O_COOK_NOC)
willy tarreau750a4722005-12-17 13:21:24 +01004191 //len += sprintf(newhdr + len, "Cache-control: no-cache=\"set-cookie\"\r\n");
4192 len += sprintf(trash + len, "Cache-control: private\r\n");
willy tarreaucd878942005-12-17 13:27:43 +01004193
willy tarreau750a4722005-12-17 13:21:24 +01004194 buffer_replace2(rep, rep->h, rep->h, trash, len);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004195 }
4196
4197 /* headers to be added */
4198 for (line = 0; line < t->proxy->nb_rspadd; line++) {
willy tarreau750a4722005-12-17 13:21:24 +01004199 len = sprintf(trash, "%s\r\n", t->proxy->rsp_add[line]);
4200 buffer_replace2(rep, rep->h, rep->h, trash, len);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004201 }
4202
willy tarreau25c4ea52005-12-18 00:49:49 +01004203 /* add a "connection: close" line if needed */
4204 if (t->proxy->options & PR_O_HTTP_CLOSE)
4205 buffer_replace2(rep, rep->h, rep->h, "Connection: close\r\n", 19);
4206
willy tarreau5cbea6f2005-12-17 12:48:26 +01004207 t->srv_state = SV_STDATA;
willy tarreauef900ab2005-12-17 12:52:52 +01004208 rep->rlim = rep->data + BUFSIZE; /* no more rewrite needed */
willy tarreau750a4722005-12-17 13:21:24 +01004209 t->logs.t_data = tv_diff(&t->logs.tv_accept, &now);
willy tarreau25c4ea52005-12-18 00:49:49 +01004210
4211 /* if the user wants to log as soon as possible, without counting
4212 bytes from the server, then this is the right moment. */
willy tarreau4302f492005-12-18 01:00:37 +01004213 if (t->proxy->to_log && !(t->logs.logwait & LW_BYTES)) {
willy tarreau25c4ea52005-12-18 00:49:49 +01004214 t->logs.t_close = t->logs.t_data; /* to get a valid end date */
4215 t->logs.bytes = rep->h - rep->data;
4216 sess_log(t);
4217 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01004218 break;
4219 }
4220
4221 /* to get a complete header line, we need the ending \r\n, \n\r, \r or \n too */
4222 if (ptr > rep->r - 2) {
4223 /* this is a partial header, let's wait for more to come */
4224 rep->lr = ptr;
4225 break;
4226 }
4227
4228 // fprintf(stderr,"h=%p, ptr=%p, lr=%p, r=%p, *h=", rep->h, ptr, rep->lr, rep->r);
4229 // write(2, rep->h, ptr - rep->h); fprintf(stderr,"\n");
4230
4231 /* now we know that *ptr is either \r or \n,
4232 * and that there are at least 1 char after it.
4233 */
4234 if ((ptr[0] == ptr[1]) || (ptr[1] != '\r' && ptr[1] != '\n'))
4235 rep->lr = ptr + 1; /* \r\r, \n\n, \r[^\n], \n[^\r] */
4236 else
4237 rep->lr = ptr + 2; /* \r\n or \n\r */
4238
4239 /*
4240 * now we know that we have a full header ; we can do whatever
4241 * we want with these pointers :
4242 * rep->h = beginning of header
4243 * ptr = end of header (first \r or \n)
4244 * rep->lr = beginning of next line (next rep->h)
4245 * rep->r = end of data (not used at this stage)
4246 */
4247
willy tarreaua1598082005-12-17 13:08:06 +01004248
willy tarreau982249e2005-12-18 00:57:06 +01004249 if (t->logs.status == -1) {
willy tarreaua1598082005-12-17 13:08:06 +01004250 t->logs.logwait &= ~LW_RESP;
4251 t->logs.status = atoi(rep->h + 9);
willy tarreau982249e2005-12-18 00:57:06 +01004252 switch (t->logs.status) {
4253 case 200:
4254 case 203:
4255 case 206:
4256 case 300:
4257 case 301:
4258 case 410:
4259 /* RFC2616 @13.4:
4260 * "A response received with a status code of
4261 * 200, 203, 206, 300, 301 or 410 MAY be stored
4262 * by a cache (...) unless a cache-control
4263 * directive prohibits caching."
4264 *
4265 * RFC2616 @9.5: POST method :
4266 * "Responses to this method are not cacheable,
4267 * unless the response includes appropriate
4268 * Cache-Control or Expires header fields."
4269 */
4270 if ((!t->flags & SN_POST) && (t->proxy->options & PR_O_CHK_CACHE))
4271 t->flags |= SN_CACHEABLE | SN_CACHE_COOK;
4272 break;
4273 default:
4274 break;
4275 }
willy tarreau4302f492005-12-18 01:00:37 +01004276 }
4277 else if (t->logs.logwait & LW_RSPHDR) {
4278 struct cap_hdr *h;
4279 int len;
4280 for (h = t->proxy->rsp_cap; h; h = h->next) {
4281 if ((h->namelen + 2 <= ptr - rep->h) &&
4282 (rep->h[h->namelen] == ':') &&
4283 (strncasecmp(rep->h, h->name, h->namelen) == 0)) {
4284
4285 if (t->rsp_cap[h->index] == NULL)
4286 t->rsp_cap[h->index] = pool_alloc_from(h->pool, h->len + 1);
4287
4288 len = ptr - (rep->h + h->namelen + 2);
4289 if (len > h->len)
4290 len = h->len;
4291
4292 memcpy(t->rsp_cap[h->index], rep->h + h->namelen + 2, len);
4293 t->rsp_cap[h->index][len]=0;
4294 }
4295 }
4296
willy tarreaua1598082005-12-17 13:08:06 +01004297 }
4298
willy tarreau5cbea6f2005-12-17 12:48:26 +01004299 delete_header = 0;
4300
willy tarreau982249e2005-12-18 00:57:06 +01004301 if ((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01004302 int len, max;
willy tarreau2f6ba652005-12-17 13:57:42 +01004303 len = sprintf(trash, "%08x:%s.srvhdr[%04x:%04x]: ", t->uniq_id, t->proxy->id, (unsigned short)t->cli_fd, (unsigned short)t->srv_fd);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004304 max = ptr - rep->h;
4305 UBOUND(max, sizeof(trash) - len - 1);
willy tarreau750a4722005-12-17 13:21:24 +01004306 len += strlcpy2(trash + len, rep->h, max + 1);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004307 trash[len++] = '\n';
4308 write(1, trash, len);
4309 }
4310
willy tarreau25c4ea52005-12-18 00:49:49 +01004311 /* remove "connection: " if needed */
4312 if (!delete_header && (t->proxy->options & PR_O_HTTP_CLOSE)
4313 && (strncasecmp(rep->h, "Connection: ", 12) == 0)) {
4314 delete_header = 1;
4315 }
4316
willy tarreau5cbea6f2005-12-17 12:48:26 +01004317 /* try headers regexps */
willy tarreau25c4ea52005-12-18 00:49:49 +01004318 if (!delete_header && t->proxy->rsp_exp != NULL
4319 && !(t->flags & SN_SVDENY)) {
willy tarreaue39cd132005-12-17 13:00:18 +01004320 struct hdr_exp *exp;
willy tarreau5cbea6f2005-12-17 12:48:26 +01004321 char term;
4322
4323 term = *ptr;
4324 *ptr = '\0';
willy tarreaue39cd132005-12-17 13:00:18 +01004325 exp = t->proxy->rsp_exp;
4326 do {
4327 if (regexec(exp->preg, rep->h, MAX_MATCH, pmatch, 0) == 0) {
4328 switch (exp->action) {
4329 case ACT_ALLOW:
4330 if (!(t->flags & SN_SVDENY))
4331 t->flags |= SN_SVALLOW;
4332 break;
4333 case ACT_REPLACE:
4334 if (!(t->flags & SN_SVDENY)) {
4335 int len = exp_replace(trash, rep->h, exp->replace, pmatch);
4336 ptr += buffer_replace2(rep, rep->h, ptr, trash, len);
4337 }
4338 break;
4339 case ACT_REMOVE:
4340 if (!(t->flags & SN_SVDENY))
4341 delete_header = 1;
4342 break;
4343 case ACT_DENY:
4344 if (!(t->flags & SN_SVALLOW))
4345 t->flags |= SN_SVDENY;
4346 break;
willy tarreau036e1ce2005-12-17 13:46:33 +01004347 case ACT_PASS: /* we simply don't deny this one */
4348 break;
willy tarreau5cbea6f2005-12-17 12:48:26 +01004349 }
4350 break;
4351 }
willy tarreaue39cd132005-12-17 13:00:18 +01004352 } while ((exp = exp->next) != NULL);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004353 *ptr = term; /* restore the string terminator */
4354 }
4355
willy tarreau97f58572005-12-18 00:53:44 +01004356 /* check for cache-control: or pragma: headers */
4357 if (!delete_header && (t->flags & SN_CACHEABLE)) {
4358 if (strncasecmp(rep->h, "Pragma: no-cache", 16) == 0)
4359 t->flags &= ~SN_CACHEABLE & ~SN_CACHE_COOK;
4360 else if (strncasecmp(rep->h, "Cache-control: ", 15) == 0) {
4361 if (strncasecmp(rep->h + 15, "no-cache", 8) == 0) {
willy tarreau982249e2005-12-18 00:57:06 +01004362 if (rep->h + 23 == ptr || rep->h[23] == ',')
willy tarreau97f58572005-12-18 00:53:44 +01004363 t->flags &= ~SN_CACHEABLE & ~SN_CACHE_COOK;
4364 else {
4365 if (strncasecmp(rep->h + 23, "=\"set-cookie", 12) == 0
willy tarreau982249e2005-12-18 00:57:06 +01004366 && (rep->h[35] == '"' || rep->h[35] == ','))
willy tarreau97f58572005-12-18 00:53:44 +01004367 t->flags &= ~SN_CACHE_COOK;
4368 }
4369 } else if ((strncasecmp(rep->h + 15, "private", 7) == 0 &&
willy tarreau982249e2005-12-18 00:57:06 +01004370 (rep->h + 22 == ptr || rep->h[22] == ','))
willy tarreau97f58572005-12-18 00:53:44 +01004371 || (strncasecmp(rep->h + 15, "no-store", 8) == 0 &&
willy tarreau982249e2005-12-18 00:57:06 +01004372 (rep->h + 23 == ptr || rep->h[23] == ','))) {
willy tarreau97f58572005-12-18 00:53:44 +01004373 t->flags &= ~SN_CACHEABLE & ~SN_CACHE_COOK;
4374 } else if (strncasecmp(rep->h + 15, "max-age=0", 9) == 0 &&
willy tarreau982249e2005-12-18 00:57:06 +01004375 (rep->h + 24 == ptr || rep->h[24] == ',')) {
willy tarreau97f58572005-12-18 00:53:44 +01004376 t->flags &= ~SN_CACHEABLE & ~SN_CACHE_COOK;
willy tarreau982249e2005-12-18 00:57:06 +01004377 } else if (strncasecmp(rep->h + 15, "s-maxage=0", 10) == 0 &&
4378 (rep->h + 25 == ptr || rep->h[25] == ',')) {
4379 t->flags &= ~SN_CACHEABLE & ~SN_CACHE_COOK;
4380 } else if (strncasecmp(rep->h + 15, "public", 6) == 0 &&
4381 (rep->h + 21 == ptr || rep->h[21] == ',')) {
4382 t->flags |= SN_CACHEABLE | SN_CACHE_COOK;
willy tarreau97f58572005-12-18 00:53:44 +01004383 }
4384 }
4385 }
4386
willy tarreau5cbea6f2005-12-17 12:48:26 +01004387 /* check for server cookies */
willy tarreau8337c6b2005-12-17 13:41:01 +01004388 if (!delete_header /*&& (t->proxy->options & PR_O_COOK_ANY)*/
willy tarreau12350152005-12-18 01:03:27 +01004389 && (t->proxy->cookie_name != NULL || t->proxy->capture_name != NULL || t->proxy->appsession_name !=NULL)
willy tarreau906b2682005-12-17 13:49:52 +01004390 && (strncasecmp(rep->h, "Set-Cookie: ", 12) == 0)) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01004391 char *p1, *p2, *p3, *p4;
4392
willy tarreau97f58572005-12-18 00:53:44 +01004393 t->flags |= SN_SCK_ANY;
4394
willy tarreau5cbea6f2005-12-17 12:48:26 +01004395 p1 = rep->h + 12; /* first char after 'Set-Cookie: ' */
4396
4397 while (p1 < ptr) { /* in fact, we'll break after the first cookie */
willy tarreauc29948c2005-12-17 13:10:27 +01004398 while (p1 < ptr && (isspace((int)*p1)))
willy tarreau5cbea6f2005-12-17 12:48:26 +01004399 p1++;
4400
4401 if (p1 == ptr || *p1 == ';') /* end of cookie */
4402 break;
4403
4404 /* p1 is at the beginning of the cookie name */
4405 p2 = p1;
4406
4407 while (p2 < ptr && *p2 != '=' && *p2 != ';')
4408 p2++;
4409
4410 if (p2 == ptr || *p2 == ';') /* next cookie */
4411 break;
4412
4413 p3 = p2 + 1; /* skips the '=' sign */
4414 if (p3 == ptr)
4415 break;
4416
4417 p4 = p3;
willy tarreauc29948c2005-12-17 13:10:27 +01004418 while (p4 < ptr && !isspace((int)*p4) && *p4 != ';')
willy tarreau5cbea6f2005-12-17 12:48:26 +01004419 p4++;
4420
4421 /* here, we have the cookie name between p1 and p2,
4422 * and its value between p3 and p4.
4423 * we can process it.
4424 */
willy tarreau8337c6b2005-12-17 13:41:01 +01004425
4426 /* first, let's see if we want to capture it */
4427 if (t->proxy->capture_name != NULL &&
4428 t->logs.srv_cookie == NULL &&
4429 (p4 - p1 >= t->proxy->capture_namelen) &&
4430 memcmp(p1, t->proxy->capture_name, t->proxy->capture_namelen) == 0) {
4431 int log_len = p4 - p1;
4432
4433 if ((t->logs.srv_cookie = pool_alloc(capture)) == NULL) {
4434 Alert("HTTP logging : out of memory.\n");
4435 }
4436
4437 if (log_len > t->proxy->capture_len)
4438 log_len = t->proxy->capture_len;
4439 memcpy(t->logs.srv_cookie, p1, log_len);
4440 t->logs.srv_cookie[log_len] = 0;
4441 }
4442
4443 if ((p2 - p1 == t->proxy->cookie_len) && (t->proxy->cookie_name != NULL) &&
4444 (memcmp(p1, t->proxy->cookie_name, p2 - p1) == 0)) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01004445 /* Cool... it's the right one */
willy tarreau036e1ce2005-12-17 13:46:33 +01004446 t->flags |= SN_SCK_SEEN;
willy tarreau5cbea6f2005-12-17 12:48:26 +01004447
4448 /* If the cookie is in insert mode on a known server, we'll delete
4449 * this occurrence because we'll insert another one later.
4450 * We'll delete it too if the "indirect" option is set and we're in
4451 * a direct access. */
4452 if (((t->srv) && (t->proxy->options & PR_O_COOK_INS)) ||
willy tarreaue39cd132005-12-17 13:00:18 +01004453 ((t->flags & SN_DIRECT) && (t->proxy->options & PR_O_COOK_IND))) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01004454 /* this header must be deleted */
4455 delete_header = 1;
willy tarreau036e1ce2005-12-17 13:46:33 +01004456 t->flags |= SN_SCK_DELETED;
willy tarreau5cbea6f2005-12-17 12:48:26 +01004457 }
4458 else if ((t->srv) && (t->proxy->options & PR_O_COOK_RW)) {
4459 /* replace bytes p3->p4 with the cookie name associated
4460 * with this server since we know it.
4461 */
4462 buffer_replace2(rep, p3, p4, t->srv->cookie, t->srv->cklen);
willy tarreau036e1ce2005-12-17 13:46:33 +01004463 t->flags |= SN_SCK_INSERTED | SN_SCK_DELETED;
willy tarreau5cbea6f2005-12-17 12:48:26 +01004464 }
willy tarreau0174f312005-12-18 01:02:42 +01004465 else if ((t->srv) && (t->proxy->options & PR_O_COOK_PFX)) {
4466 /* insert the cookie name associated with this server
4467 * before existing cookie, and insert a delimitor between them..
4468 */
4469 buffer_replace2(rep, p3, p3, t->srv->cookie, t->srv->cklen + 1);
4470 p3[t->srv->cklen] = COOKIE_DELIM;
4471 t->flags |= SN_SCK_INSERTED | SN_SCK_DELETED;
4472 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01004473 break;
4474 }
willy tarreau12350152005-12-18 01:03:27 +01004475
4476 /* first, let's see if the cookie is our appcookie*/
4477 if ((t->proxy->appsession_name != NULL) &&
4478 (memcmp(p1, t->proxy->appsession_name, p2 - p1) == 0)) {
4479
4480 /* Cool... it's the right one */
4481
willy tarreaub952e1d2005-12-18 01:31:20 +01004482 size_t server_id_len = strlen(t->srv->id) + 1;
willy tarreau12350152005-12-18 01:03:27 +01004483 asession_temp = &local_asession;
4484
willy tarreaub952e1d2005-12-18 01:31:20 +01004485 if ((asession_temp->sessid = pool_alloc_from(apools.sessid, apools.ses_msize)) == NULL) {
willy tarreau12350152005-12-18 01:03:27 +01004486 Alert("Not enought Memory process_srv():asession->sessid:malloc().\n");
4487 send_log(t->proxy, LOG_ALERT, "Not enought Memory process_srv():asession->sessid:malloc().\n");
4488 }
4489 memcpy(asession_temp->sessid, p3, t->proxy->appsession_len);
4490 asession_temp->sessid[t->proxy->appsession_len] = 0;
4491 asession_temp->serverid = NULL;
4492
4493 /* only do insert, if lookup fails */
4494 if (chtbl_lookup(&(t->proxy->htbl_proxy), (void *) &asession_temp) != 0) {
4495 if ((asession_temp = pool_alloc(appsess)) == NULL) {
4496 Alert("Not enought Memory process_srv():asession:calloc().\n");
4497 send_log(t->proxy, LOG_ALERT, "Not enought Memory process_srv():asession:calloc().\n");
4498 return 0;
4499 }
4500 asession_temp->sessid = local_asession.sessid;
4501 asession_temp->serverid = local_asession.serverid;
4502 chtbl_insert(&(t->proxy->htbl_proxy), (void *) asession_temp);
willy tarreaub952e1d2005-12-18 01:31:20 +01004503 }/* end if (chtbl_lookup()) */
4504 else {
willy tarreau12350152005-12-18 01:03:27 +01004505 /* free wasted memory */
4506 pool_free_to(apools.sessid, local_asession.sessid);
willy tarreaub952e1d2005-12-18 01:31:20 +01004507 } /* end else from if (chtbl_lookup()) */
willy tarreau12350152005-12-18 01:03:27 +01004508
willy tarreaub952e1d2005-12-18 01:31:20 +01004509 if (asession_temp->serverid == NULL) {
4510 if ((asession_temp->serverid = pool_alloc_from(apools.serverid, apools.ser_msize)) == NULL) {
willy tarreau12350152005-12-18 01:03:27 +01004511 Alert("Not enought Memory process_srv():asession->sessid:malloc().\n");
4512 send_log(t->proxy, LOG_ALERT, "Not enought Memory process_srv():asession->sessid:malloc().\n");
4513 }
4514 asession_temp->serverid[0] = '\0';
4515 }
4516
willy tarreaub952e1d2005-12-18 01:31:20 +01004517 if (asession_temp->serverid[0] == '\0')
4518 memcpy(asession_temp->serverid,t->srv->id,server_id_len);
willy tarreau12350152005-12-18 01:03:27 +01004519
4520 tv_delayfrom(&asession_temp->expire, &now, t->proxy->appsession_timeout);
4521
4522#if defined(DEBUG_HASH)
4523 print_table(&(t->proxy->htbl_proxy));
4524#endif
4525 break;
4526 }/* end if ((t->proxy->appsession_name != NULL) ... */
willy tarreau5cbea6f2005-12-17 12:48:26 +01004527 else {
4528 // fprintf(stderr,"Ignoring unknown cookie : ");
4529 // write(2, p1, p2-p1);
4530 // fprintf(stderr," = ");
4531 // write(2, p3, p4-p3);
4532 // fprintf(stderr,"\n");
4533 }
4534 break; /* we don't want to loop again since there cannot be another cookie on the same line */
4535 } /* we're now at the end of the cookie value */
4536 } /* end of cookie processing */
4537
willy tarreau97f58572005-12-18 00:53:44 +01004538 /* check for any set-cookie in case we check for cacheability */
4539 if (!delete_header && !(t->flags & SN_SCK_ANY) &&
4540 (t->proxy->options & PR_O_CHK_CACHE) &&
4541 (strncasecmp(rep->h, "Set-Cookie: ", 12) == 0)) {
4542 t->flags |= SN_SCK_ANY;
4543 }
4544
willy tarreau5cbea6f2005-12-17 12:48:26 +01004545 /* let's look if we have to delete this header */
willy tarreaue39cd132005-12-17 13:00:18 +01004546 if (delete_header && !(t->flags & SN_SVDENY))
willy tarreau5cbea6f2005-12-17 12:48:26 +01004547 buffer_replace2(rep, rep->h, rep->lr, "", 0);
willy tarreaue39cd132005-12-17 13:00:18 +01004548
willy tarreau5cbea6f2005-12-17 12:48:26 +01004549 rep->h = rep->lr;
4550 } /* while (rep->lr < rep->r) */
4551
4552 /* end of header processing (even if incomplete) */
4553
willy tarreauef900ab2005-12-17 12:52:52 +01004554 if ((rep->l < rep->rlim - rep->data) && ! FD_ISSET(t->srv_fd, StaticReadEvent)) {
4555 /* fd in StaticReadEvent was disabled, perhaps because of a previous buffer
4556 * full. We cannot loop here since event_srv_read will disable it only if
4557 * rep->l == rlim-data
4558 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01004559 FD_SET(t->srv_fd, StaticReadEvent);
4560 if (t->proxy->srvtimeout)
4561 tv_delayfrom(&t->srexpire, &now, t->proxy->srvtimeout);
4562 else
4563 tv_eternity(&t->srexpire);
4564 }
willy tarreau0f7af912005-12-17 12:21:26 +01004565
willy tarreau8337c6b2005-12-17 13:41:01 +01004566 /* read error, write error */
willy tarreau0f7af912005-12-17 12:21:26 +01004567 if (t->res_sw == RES_ERROR || t->res_sr == RES_ERROR) {
willy tarreau0f7af912005-12-17 12:21:26 +01004568 tv_eternity(&t->srexpire);
4569 tv_eternity(&t->swexpire);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004570 fd_delete(t->srv_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01004571 t->srv_state = SV_STCLOSE;
willy tarreaucd878942005-12-17 13:27:43 +01004572 t->logs.status = 502;
willy tarreau8337c6b2005-12-17 13:41:01 +01004573 client_return(t, t->proxy->errmsg.len502, t->proxy->errmsg.msg502);
willy tarreau036e1ce2005-12-17 13:46:33 +01004574 if (!(t->flags & SN_ERR_MASK))
4575 t->flags |= SN_ERR_SRVCL;
4576 if (!(t->flags & SN_FINST_MASK))
4577 t->flags |= SN_FINST_H;
willy tarreau0f7af912005-12-17 12:21:26 +01004578 return 1;
4579 }
willy tarreau8337c6b2005-12-17 13:41:01 +01004580 /* end of client write or end of server read.
willy tarreauef900ab2005-12-17 12:52:52 +01004581 * since we are in header mode, if there's no space left for headers, we
4582 * won't be able to free more later, so the session will never terminate.
4583 */
willy tarreau8337c6b2005-12-17 13:41:01 +01004584 else if (t->res_sr == RES_NULL || c == CL_STSHUTW || c == CL_STCLOSE || rep->l >= rep->rlim - rep->data) {
willy tarreau0f7af912005-12-17 12:21:26 +01004585 FD_CLR(t->srv_fd, StaticReadEvent);
4586 tv_eternity(&t->srexpire);
4587 shutdown(t->srv_fd, SHUT_RD);
4588 t->srv_state = SV_STSHUTR;
willy tarreaub952e1d2005-12-18 01:31:20 +01004589 //fprintf(stderr,"%p:%s(%d), c=%d, s=%d\n", t, __FUNCTION__, __LINE__, t->cli_state, t->cli_state);
willy tarreau0f7af912005-12-17 12:21:26 +01004590 return 1;
willy tarreau8337c6b2005-12-17 13:41:01 +01004591 }
4592 /* read timeout : return a 504 to the client.
4593 */
4594 else if (FD_ISSET(t->srv_fd, StaticReadEvent) && tv_cmp2_ms(&t->srexpire, &now) <= 0) {
4595 tv_eternity(&t->srexpire);
4596 tv_eternity(&t->swexpire);
4597 fd_delete(t->srv_fd);
4598 t->srv_state = SV_STCLOSE;
4599 t->logs.status = 504;
4600 client_return(t, t->proxy->errmsg.len504, t->proxy->errmsg.msg504);
willy tarreau036e1ce2005-12-17 13:46:33 +01004601 if (!(t->flags & SN_ERR_MASK))
4602 t->flags |= SN_ERR_SRVTO;
4603 if (!(t->flags & SN_FINST_MASK))
4604 t->flags |= SN_FINST_H;
willy tarreau8337c6b2005-12-17 13:41:01 +01004605 return 1;
willy tarreau0f7af912005-12-17 12:21:26 +01004606
4607 }
willy tarreau036e1ce2005-12-17 13:46:33 +01004608 /* last client read and buffer empty */
willy tarreau750a4722005-12-17 13:21:24 +01004609 /* FIXME!!! here, we don't want to switch to SHUTW if the
4610 * client shuts read too early, because we may still have
4611 * some work to do on the headers.
willy tarreau036e1ce2005-12-17 13:46:33 +01004612 * The side-effect is that if the client completely closes its
4613 * connection during SV_STHEADER, the connection to the server
4614 * is kept until a response comes back or the timeout is reached.
willy tarreau750a4722005-12-17 13:21:24 +01004615 */
willy tarreau036e1ce2005-12-17 13:46:33 +01004616 else if ((/*c == CL_STSHUTR ||*/ c == CL_STCLOSE) && (req->l == 0)) {
willy tarreau0f7af912005-12-17 12:21:26 +01004617 FD_CLR(t->srv_fd, StaticWriteEvent);
4618 tv_eternity(&t->swexpire);
willy tarreaub1285d52005-12-18 01:20:14 +01004619
4620 /* We must ensure that the read part is still alive when switching
4621 * to shutw */
4622 FD_SET(t->srv_fd, StaticReadEvent);
4623 if (t->proxy->srvtimeout)
4624 tv_delayfrom(&t->srexpire, &now, t->proxy->srvtimeout);
4625
willy tarreau0f7af912005-12-17 12:21:26 +01004626 shutdown(t->srv_fd, SHUT_WR);
4627 t->srv_state = SV_STSHUTW;
4628 return 1;
4629 }
willy tarreau036e1ce2005-12-17 13:46:33 +01004630 /* write timeout */
4631 /* FIXME!!! here, we don't want to switch to SHUTW if the
4632 * client shuts read too early, because we may still have
4633 * some work to do on the headers.
4634 */
4635 else if (FD_ISSET(t->srv_fd, StaticWriteEvent) && tv_cmp2_ms(&t->swexpire, &now) <= 0) {
4636 FD_CLR(t->srv_fd, StaticWriteEvent);
4637 tv_eternity(&t->swexpire);
4638 shutdown(t->srv_fd, SHUT_WR);
willy tarreaub1285d52005-12-18 01:20:14 +01004639 /* We must ensure that the read part is still alive when switching
4640 * to shutw */
4641 FD_SET(t->srv_fd, StaticReadEvent);
4642 if (t->proxy->srvtimeout)
4643 tv_delayfrom(&t->srexpire, &now, t->proxy->srvtimeout);
4644
4645 /* We must ensure that the read part is still alive when switching
4646 * to shutw */
4647 FD_SET(t->srv_fd, StaticReadEvent);
4648 if (t->proxy->srvtimeout)
4649 tv_delayfrom(&t->srexpire, &now, t->proxy->srvtimeout);
4650
willy tarreau036e1ce2005-12-17 13:46:33 +01004651 t->srv_state = SV_STSHUTW;
4652 if (!(t->flags & SN_ERR_MASK))
4653 t->flags |= SN_ERR_SRVTO;
4654 if (!(t->flags & SN_FINST_MASK))
4655 t->flags |= SN_FINST_H;
4656 return 1;
4657 }
willy tarreau0f7af912005-12-17 12:21:26 +01004658
4659 if (req->l == 0) {
4660 if (FD_ISSET(t->srv_fd, StaticWriteEvent)) {
4661 FD_CLR(t->srv_fd, StaticWriteEvent); /* stop writing */
4662 tv_eternity(&t->swexpire);
4663 }
4664 }
4665 else { /* client buffer not empty */
4666 if (! FD_ISSET(t->srv_fd, StaticWriteEvent)) {
4667 FD_SET(t->srv_fd, StaticWriteEvent); /* restart writing */
willy tarreaub1ff9db2005-12-17 13:51:03 +01004668 if (t->proxy->srvtimeout) {
willy tarreau0f7af912005-12-17 12:21:26 +01004669 tv_delayfrom(&t->swexpire, &now, t->proxy->srvtimeout);
willy tarreaub1ff9db2005-12-17 13:51:03 +01004670 /* FIXME: to avoid the server to read-time-out during writes, we refresh it */
4671 t->srexpire = t->swexpire;
4672 }
willy tarreau0f7af912005-12-17 12:21:26 +01004673 else
4674 tv_eternity(&t->swexpire);
4675 }
4676 }
4677
willy tarreau5cbea6f2005-12-17 12:48:26 +01004678 /* be nice with the client side which would like to send a complete header
4679 * FIXME: COMPLETELY BUGGY !!! not all headers may be processed because the client
4680 * would read all remaining data at once ! The client should not write past rep->lr
4681 * when the server is in header state.
4682 */
4683 //return header_processed;
4684 return t->srv_state != SV_STHEADERS;
willy tarreau0f7af912005-12-17 12:21:26 +01004685 }
4686 else if (s == SV_STDATA) {
4687 /* read or write error */
4688 if (t->res_sw == RES_ERROR || t->res_sr == RES_ERROR) {
willy tarreau0f7af912005-12-17 12:21:26 +01004689 tv_eternity(&t->srexpire);
4690 tv_eternity(&t->swexpire);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004691 fd_delete(t->srv_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01004692 t->srv_state = SV_STCLOSE;
willy tarreau036e1ce2005-12-17 13:46:33 +01004693 if (!(t->flags & SN_ERR_MASK))
4694 t->flags |= SN_ERR_SRVCL;
4695 if (!(t->flags & SN_FINST_MASK))
4696 t->flags |= SN_FINST_D;
willy tarreau0f7af912005-12-17 12:21:26 +01004697 return 1;
4698 }
willy tarreau036e1ce2005-12-17 13:46:33 +01004699 /* last read, or end of client write */
4700 else if (t->res_sr == RES_NULL || c == CL_STSHUTW || c == CL_STCLOSE) {
willy tarreau0f7af912005-12-17 12:21:26 +01004701 FD_CLR(t->srv_fd, StaticReadEvent);
4702 tv_eternity(&t->srexpire);
4703 shutdown(t->srv_fd, SHUT_RD);
4704 t->srv_state = SV_STSHUTR;
willy tarreaub952e1d2005-12-18 01:31:20 +01004705 //fprintf(stderr,"%p:%s(%d), c=%d, s=%d\n", t, __FUNCTION__, __LINE__, t->cli_state, t->cli_state);
willy tarreau0f7af912005-12-17 12:21:26 +01004706 return 1;
willy tarreaua41a8b42005-12-17 14:02:24 +01004707 }
4708 /* end of client read and no more data to send */
4709 else if ((c == CL_STSHUTR || c == CL_STCLOSE) && (req->l == 0)) {
4710 FD_CLR(t->srv_fd, StaticWriteEvent);
4711 tv_eternity(&t->swexpire);
4712 shutdown(t->srv_fd, SHUT_WR);
willy tarreaub1285d52005-12-18 01:20:14 +01004713 /* We must ensure that the read part is still alive when switching
4714 * to shutw */
4715 FD_SET(t->srv_fd, StaticReadEvent);
4716 if (t->proxy->srvtimeout)
4717 tv_delayfrom(&t->srexpire, &now, t->proxy->srvtimeout);
4718
willy tarreaua41a8b42005-12-17 14:02:24 +01004719 t->srv_state = SV_STSHUTW;
4720 return 1;
4721 }
willy tarreau036e1ce2005-12-17 13:46:33 +01004722 /* read timeout */
4723 else if (tv_cmp2_ms(&t->srexpire, &now) <= 0) {
4724 FD_CLR(t->srv_fd, StaticReadEvent);
4725 tv_eternity(&t->srexpire);
4726 shutdown(t->srv_fd, SHUT_RD);
4727 t->srv_state = SV_STSHUTR;
4728 if (!(t->flags & SN_ERR_MASK))
4729 t->flags |= SN_ERR_SRVTO;
4730 if (!(t->flags & SN_FINST_MASK))
4731 t->flags |= SN_FINST_D;
4732 return 1;
willy tarreau0f7af912005-12-17 12:21:26 +01004733 }
willy tarreau036e1ce2005-12-17 13:46:33 +01004734 /* write timeout */
4735 else if (tv_cmp2_ms(&t->swexpire, &now) <= 0) {
willy tarreau0f7af912005-12-17 12:21:26 +01004736 FD_CLR(t->srv_fd, StaticWriteEvent);
4737 tv_eternity(&t->swexpire);
4738 shutdown(t->srv_fd, SHUT_WR);
willy tarreaub1285d52005-12-18 01:20:14 +01004739 /* We must ensure that the read part is still alive when switching
4740 * to shutw */
4741 FD_SET(t->srv_fd, StaticReadEvent);
4742 if (t->proxy->srvtimeout)
4743 tv_delayfrom(&t->srexpire, &now, t->proxy->srvtimeout);
willy tarreau0f7af912005-12-17 12:21:26 +01004744 t->srv_state = SV_STSHUTW;
willy tarreau036e1ce2005-12-17 13:46:33 +01004745 if (!(t->flags & SN_ERR_MASK))
4746 t->flags |= SN_ERR_SRVTO;
4747 if (!(t->flags & SN_FINST_MASK))
4748 t->flags |= SN_FINST_D;
willy tarreau0f7af912005-12-17 12:21:26 +01004749 return 1;
4750 }
willy tarreaub1ff9db2005-12-17 13:51:03 +01004751
4752 /* recompute request time-outs */
4753 if (req->l == 0) {
willy tarreau0f7af912005-12-17 12:21:26 +01004754 if (FD_ISSET(t->srv_fd, StaticWriteEvent)) {
4755 FD_CLR(t->srv_fd, StaticWriteEvent); /* stop writing */
4756 tv_eternity(&t->swexpire);
4757 }
4758 }
willy tarreaub1ff9db2005-12-17 13:51:03 +01004759 else { /* buffer not empty, there are still data to be transferred */
willy tarreau0f7af912005-12-17 12:21:26 +01004760 if (! FD_ISSET(t->srv_fd, StaticWriteEvent)) {
4761 FD_SET(t->srv_fd, StaticWriteEvent); /* restart writing */
willy tarreaub1ff9db2005-12-17 13:51:03 +01004762 if (t->proxy->srvtimeout) {
willy tarreau0f7af912005-12-17 12:21:26 +01004763 tv_delayfrom(&t->swexpire, &now, t->proxy->srvtimeout);
willy tarreaub1ff9db2005-12-17 13:51:03 +01004764 /* FIXME: to avoid the server to read-time-out during writes, we refresh it */
4765 t->srexpire = t->swexpire;
4766 }
willy tarreau0f7af912005-12-17 12:21:26 +01004767 else
4768 tv_eternity(&t->swexpire);
4769 }
4770 }
4771
willy tarreaub1ff9db2005-12-17 13:51:03 +01004772 /* recompute response time-outs */
willy tarreau0f7af912005-12-17 12:21:26 +01004773 if (rep->l == BUFSIZE) { /* no room to read more data */
4774 if (FD_ISSET(t->srv_fd, StaticReadEvent)) {
4775 FD_CLR(t->srv_fd, StaticReadEvent);
4776 tv_eternity(&t->srexpire);
4777 }
4778 }
4779 else {
4780 if (! FD_ISSET(t->srv_fd, StaticReadEvent)) {
4781 FD_SET(t->srv_fd, StaticReadEvent);
4782 if (t->proxy->srvtimeout)
4783 tv_delayfrom(&t->srexpire, &now, t->proxy->srvtimeout);
4784 else
4785 tv_eternity(&t->srexpire);
4786 }
4787 }
4788
4789 return 0; /* other cases change nothing */
4790 }
4791 else if (s == SV_STSHUTR) {
willy tarreau036e1ce2005-12-17 13:46:33 +01004792 if (t->res_sw == RES_ERROR) {
4793 //FD_CLR(t->srv_fd, StaticWriteEvent);
4794 tv_eternity(&t->swexpire);
4795 fd_delete(t->srv_fd);
4796 //close(t->srv_fd);
4797 t->srv_state = SV_STCLOSE;
4798 if (!(t->flags & SN_ERR_MASK))
4799 t->flags |= SN_ERR_SRVCL;
4800 if (!(t->flags & SN_FINST_MASK))
4801 t->flags |= SN_FINST_D;
4802 return 1;
4803 }
4804 else if ((c == CL_STSHUTR || c == CL_STCLOSE) && (req->l == 0)) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01004805 //FD_CLR(t->srv_fd, StaticWriteEvent);
willy tarreau0f7af912005-12-17 12:21:26 +01004806 tv_eternity(&t->swexpire);
4807 fd_delete(t->srv_fd);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004808 //close(t->srv_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01004809 t->srv_state = SV_STCLOSE;
4810 return 1;
4811 }
willy tarreau036e1ce2005-12-17 13:46:33 +01004812 else if (tv_cmp2_ms(&t->swexpire, &now) <= 0) {
4813 //FD_CLR(t->srv_fd, StaticWriteEvent);
4814 tv_eternity(&t->swexpire);
4815 fd_delete(t->srv_fd);
4816 //close(t->srv_fd);
4817 t->srv_state = SV_STCLOSE;
4818 if (!(t->flags & SN_ERR_MASK))
4819 t->flags |= SN_ERR_SRVTO;
4820 if (!(t->flags & SN_FINST_MASK))
4821 t->flags |= SN_FINST_D;
4822 return 1;
4823 }
willy tarreau0f7af912005-12-17 12:21:26 +01004824 else if (req->l == 0) {
4825 if (FD_ISSET(t->srv_fd, StaticWriteEvent)) {
4826 FD_CLR(t->srv_fd, StaticWriteEvent); /* stop writing */
4827 tv_eternity(&t->swexpire);
4828 }
4829 }
4830 else { /* buffer not empty */
4831 if (! FD_ISSET(t->srv_fd, StaticWriteEvent)) {
4832 FD_SET(t->srv_fd, StaticWriteEvent); /* restart writing */
willy tarreaub1ff9db2005-12-17 13:51:03 +01004833 if (t->proxy->srvtimeout) {
willy tarreau0f7af912005-12-17 12:21:26 +01004834 tv_delayfrom(&t->swexpire, &now, t->proxy->srvtimeout);
willy tarreaub1ff9db2005-12-17 13:51:03 +01004835 /* FIXME: to avoid the server to read-time-out during writes, we refresh it */
4836 t->srexpire = t->swexpire;
4837 }
willy tarreau0f7af912005-12-17 12:21:26 +01004838 else
4839 tv_eternity(&t->swexpire);
4840 }
4841 }
4842 return 0;
4843 }
4844 else if (s == SV_STSHUTW) {
willy tarreau036e1ce2005-12-17 13:46:33 +01004845 if (t->res_sr == RES_ERROR) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01004846 //FD_CLR(t->srv_fd, StaticReadEvent);
willy tarreau0f7af912005-12-17 12:21:26 +01004847 tv_eternity(&t->srexpire);
4848 fd_delete(t->srv_fd);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004849 //close(t->srv_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01004850 t->srv_state = SV_STCLOSE;
willy tarreau036e1ce2005-12-17 13:46:33 +01004851 if (!(t->flags & SN_ERR_MASK))
4852 t->flags |= SN_ERR_SRVCL;
4853 if (!(t->flags & SN_FINST_MASK))
4854 t->flags |= SN_FINST_D;
willy tarreau0f7af912005-12-17 12:21:26 +01004855 return 1;
4856 }
willy tarreau036e1ce2005-12-17 13:46:33 +01004857 else if (t->res_sr == RES_NULL || c == CL_STSHUTW || c == CL_STCLOSE) {
4858 //FD_CLR(t->srv_fd, StaticReadEvent);
4859 tv_eternity(&t->srexpire);
4860 fd_delete(t->srv_fd);
4861 //close(t->srv_fd);
4862 t->srv_state = SV_STCLOSE;
4863 return 1;
4864 }
4865 else if (tv_cmp2_ms(&t->srexpire, &now) <= 0) {
4866 //FD_CLR(t->srv_fd, StaticReadEvent);
4867 tv_eternity(&t->srexpire);
4868 fd_delete(t->srv_fd);
4869 //close(t->srv_fd);
4870 t->srv_state = SV_STCLOSE;
4871 if (!(t->flags & SN_ERR_MASK))
4872 t->flags |= SN_ERR_SRVTO;
4873 if (!(t->flags & SN_FINST_MASK))
4874 t->flags |= SN_FINST_D;
4875 return 1;
4876 }
willy tarreau0f7af912005-12-17 12:21:26 +01004877 else if (rep->l == BUFSIZE) { /* no room to read more data */
4878 if (FD_ISSET(t->srv_fd, StaticReadEvent)) {
4879 FD_CLR(t->srv_fd, StaticReadEvent);
4880 tv_eternity(&t->srexpire);
4881 }
4882 }
4883 else {
4884 if (! FD_ISSET(t->srv_fd, StaticReadEvent)) {
4885 FD_SET(t->srv_fd, StaticReadEvent);
4886 if (t->proxy->srvtimeout)
4887 tv_delayfrom(&t->srexpire, &now, t->proxy->srvtimeout);
4888 else
4889 tv_eternity(&t->srexpire);
4890 }
4891 }
4892 return 0;
4893 }
4894 else { /* SV_STCLOSE : nothing to do */
willy tarreau982249e2005-12-18 00:57:06 +01004895 if ((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))) {
willy tarreau0f7af912005-12-17 12:21:26 +01004896 int len;
willy tarreau2f6ba652005-12-17 13:57:42 +01004897 len = sprintf(trash, "%08x:%s.srvcls[%04x:%04x]\n", t->uniq_id, t->proxy->id, (unsigned short)t->cli_fd, (unsigned short)t->srv_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01004898 write(1, trash, len);
4899 }
4900 return 0;
4901 }
4902 return 0;
4903}
4904
4905
willy tarreau5cbea6f2005-12-17 12:48:26 +01004906/* Processes the client and server jobs of a session task, then
4907 * puts it back to the wait queue in a clean state, or
4908 * cleans up its resources if it must be deleted. Returns
willy tarreaub952e1d2005-12-18 01:31:20 +01004909 * the time the task accepts to wait, or TIME_ETERNITY for
4910 * infinity.
willy tarreau0f7af912005-12-17 12:21:26 +01004911 */
willy tarreau5cbea6f2005-12-17 12:48:26 +01004912int process_session(struct task *t) {
4913 struct session *s = t->context;
4914 int fsm_resync = 0;
willy tarreau0f7af912005-12-17 12:21:26 +01004915
willy tarreau5cbea6f2005-12-17 12:48:26 +01004916 do {
4917 fsm_resync = 0;
4918 //fprintf(stderr,"before_cli:cli=%d, srv=%d\n", t->cli_state, t->srv_state);
4919 fsm_resync |= process_cli(s);
4920 //fprintf(stderr,"cli/srv:cli=%d, srv=%d\n", t->cli_state, t->srv_state);
4921 fsm_resync |= process_srv(s);
4922 //fprintf(stderr,"after_srv:cli=%d, srv=%d\n", t->cli_state, t->srv_state);
4923 } while (fsm_resync);
4924
4925 if (s->cli_state != CL_STCLOSE || s->srv_state != SV_STCLOSE) {
willy tarreau0f7af912005-12-17 12:21:26 +01004926 struct timeval min1, min2;
willy tarreau5cbea6f2005-12-17 12:48:26 +01004927 s->res_cw = s->res_cr = s->res_sw = s->res_sr = RES_SILENT;
willy tarreau0f7af912005-12-17 12:21:26 +01004928
willy tarreau5cbea6f2005-12-17 12:48:26 +01004929 tv_min(&min1, &s->crexpire, &s->cwexpire);
4930 tv_min(&min2, &s->srexpire, &s->swexpire);
4931 tv_min(&min1, &min1, &s->cnexpire);
willy tarreau0f7af912005-12-17 12:21:26 +01004932 tv_min(&t->expire, &min1, &min2);
4933
4934 /* restore t to its place in the task list */
willy tarreau5cbea6f2005-12-17 12:48:26 +01004935 task_queue(t);
willy tarreau0f7af912005-12-17 12:21:26 +01004936
willy tarreaub952e1d2005-12-18 01:31:20 +01004937 return tv_remain2(&now, &t->expire); /* nothing more to do */
willy tarreau0f7af912005-12-17 12:21:26 +01004938 }
4939
willy tarreau5cbea6f2005-12-17 12:48:26 +01004940 s->proxy->nbconn--;
willy tarreau0f7af912005-12-17 12:21:26 +01004941 actconn--;
4942
willy tarreau982249e2005-12-18 00:57:06 +01004943 if ((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))) {
willy tarreau0f7af912005-12-17 12:21:26 +01004944 int len;
willy tarreau2f6ba652005-12-17 13:57:42 +01004945 len = sprintf(trash, "%08x:%s.closed[%04x:%04x]\n", s->uniq_id, s->proxy->id, (unsigned short)s->cli_fd, (unsigned short)s->srv_fd);
willy tarreau0f7af912005-12-17 12:21:26 +01004946 write(1, trash, len);
4947 }
4948
willy tarreau750a4722005-12-17 13:21:24 +01004949 s->logs.t_close = tv_diff(&s->logs.tv_accept, &now);
willy tarreaua1598082005-12-17 13:08:06 +01004950 if (s->rep != NULL)
4951 s->logs.bytes = s->rep->total;
4952
willy tarreau9fe663a2005-12-17 13:02:59 +01004953 /* let's do a final log if we need it */
willy tarreaua1598082005-12-17 13:08:06 +01004954 if (s->logs.logwait && (!(s->proxy->options & PR_O_NULLNOLOG) || s->req->total))
willy tarreau9fe663a2005-12-17 13:02:59 +01004955 sess_log(s);
4956
willy tarreau0f7af912005-12-17 12:21:26 +01004957 /* the task MUST not be in the run queue anymore */
4958 task_delete(t);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004959 session_free(s);
willy tarreau0f7af912005-12-17 12:21:26 +01004960 task_free(t);
willy tarreaub952e1d2005-12-18 01:31:20 +01004961 return TIME_ETERNITY; /* rest in peace for eternity */
willy tarreau5cbea6f2005-12-17 12:48:26 +01004962}
4963
4964
4965
4966/*
4967 * manages a server health-check. Returns
willy tarreaub952e1d2005-12-18 01:31:20 +01004968 * the time the task accepts to wait, or TIME_ETERNITY for infinity.
willy tarreau5cbea6f2005-12-17 12:48:26 +01004969 */
4970int process_chk(struct task *t) {
4971 struct server *s = t->context;
willy tarreaua41a8b42005-12-17 14:02:24 +01004972 struct sockaddr_in sa;
willy tarreau5cbea6f2005-12-17 12:48:26 +01004973 int fd = s->curfd;
willy tarreau5cbea6f2005-12-17 12:48:26 +01004974
willy tarreauef900ab2005-12-17 12:52:52 +01004975 //fprintf(stderr, "process_chk: task=%p\n", t);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004976
4977 if (fd < 0) { /* no check currently running */
4978 //fprintf(stderr, "process_chk: 2\n");
4979 if (tv_cmp2_ms(&t->expire, &now) > 0) { /* not good time yet */
4980 task_queue(t); /* restore t to its place in the task list */
willy tarreaub952e1d2005-12-18 01:31:20 +01004981 return tv_remain2(&now, &t->expire);
willy tarreau5cbea6f2005-12-17 12:48:26 +01004982 }
4983
4984 /* we'll initiate a new check */
4985 s->result = 0; /* no result yet */
4986 if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) != -1) {
willy tarreau9fe663a2005-12-17 13:02:59 +01004987 if ((fd < global.maxsock) &&
willy tarreau5cbea6f2005-12-17 12:48:26 +01004988 (fcntl(fd, F_SETFL, O_NONBLOCK) != -1) &&
4989 (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &one, sizeof(one)) != -1)) {
4990 //fprintf(stderr, "process_chk: 3\n");
4991
willy tarreaua41a8b42005-12-17 14:02:24 +01004992 /* we'll connect to the check port on the server */
4993 sa = s->addr;
4994 sa.sin_port = htons(s->check_port);
4995
willy tarreau0174f312005-12-18 01:02:42 +01004996 /* allow specific binding :
4997 * - server-specific at first
4998 * - proxy-specific next
4999 */
5000 if (s->state & SRV_BIND_SRC) {
5001 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one));
5002 if (bind(fd, (struct sockaddr *)&s->source_addr, sizeof(s->source_addr)) == -1) {
5003 Alert("Cannot bind to source address before connect() for server %s/%s. Aborting.\n",
5004 s->proxy->id, s->id);
5005 s->result = -1;
5006 }
willy tarreau036e1ce2005-12-17 13:46:33 +01005007 }
willy tarreau0174f312005-12-18 01:02:42 +01005008 else if (s->proxy->options & PR_O_BIND_SRC) {
5009 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one));
5010 if (bind(fd, (struct sockaddr *)&s->proxy->source_addr, sizeof(s->proxy->source_addr)) == -1) {
5011 Alert("Cannot bind to source address before connect() for proxy %s. Aborting.\n",
5012 s->proxy->id);
5013 s->result = -1;
5014 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01005015 }
willy tarreau0174f312005-12-18 01:02:42 +01005016
5017 if (!s->result) {
5018 if ((connect(fd, (struct sockaddr *)&sa, sizeof(sa)) != -1) || (errno == EINPROGRESS)) {
5019 /* OK, connection in progress or established */
5020
5021 //fprintf(stderr, "process_chk: 4\n");
5022
5023 s->curfd = fd; /* that's how we know a test is in progress ;-) */
5024 fdtab[fd].owner = t;
5025 fdtab[fd].read = &event_srv_chk_r;
5026 fdtab[fd].write = &event_srv_chk_w;
5027 fdtab[fd].state = FD_STCONN; /* connection in progress */
5028 FD_SET(fd, StaticWriteEvent); /* for connect status */
5029 fd_insert(fd);
5030 /* FIXME: we allow up to <inter> for a connection to establish, but we should use another parameter */
5031 tv_delayfrom(&t->expire, &now, s->inter);
5032 task_queue(t); /* restore t to its place in the task list */
5033 return tv_remain(&now, &t->expire);
5034 }
5035 else if (errno != EALREADY && errno != EISCONN && errno != EAGAIN) {
5036 s->result = -1; /* a real error */
5037 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01005038 }
5039 }
willy tarreau08dedbe2005-12-18 01:13:48 +01005040 close(fd); /* socket creation error */
willy tarreau5cbea6f2005-12-17 12:48:26 +01005041 }
5042
5043 if (!s->result) { /* nothing done */
5044 //fprintf(stderr, "process_chk: 6\n");
willy tarreaue47c8d72005-12-17 12:55:52 +01005045 tv_delayfrom(&t->expire, &now, s->inter);
willy tarreau5cbea6f2005-12-17 12:48:26 +01005046 task_queue(t); /* restore t to its place in the task list */
5047 return tv_remain(&now, &t->expire);
5048 }
5049
5050 /* here, we have seen a failure */
willy tarreaue47c8d72005-12-17 12:55:52 +01005051 if (s->health > s->rise)
willy tarreau5cbea6f2005-12-17 12:48:26 +01005052 s->health--; /* still good */
5053 else {
willy tarreaudd07e972005-12-18 00:48:48 +01005054 s->state &= ~SRV_RUNNING;
willy tarreau535ae7a2005-12-17 12:58:00 +01005055 if (s->health == s->rise) {
willy tarreaudd07e972005-12-18 00:48:48 +01005056 Warning("Server %s/%s DOWN.\n", s->proxy->id, s->id);
willy tarreau9fe663a2005-12-17 13:02:59 +01005057 send_log(s->proxy, LOG_ALERT, "Server %s/%s is DOWN.\n", s->proxy->id, s->id);
willy tarreauef900ab2005-12-17 12:52:52 +01005058
willy tarreaudd07e972005-12-18 00:48:48 +01005059 if (find_server(s->proxy) == NULL) {
5060 Alert("Proxy %s has no server available !\n", s->proxy->id);
5061 send_log(s->proxy, LOG_EMERG, "Proxy %s has no server available !\n", s->proxy->id);
5062 }
5063 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01005064 s->health = 0; /* failure */
willy tarreau5cbea6f2005-12-17 12:48:26 +01005065 }
5066
5067 //fprintf(stderr, "process_chk: 7\n");
willy tarreaue47c8d72005-12-17 12:55:52 +01005068 /* FIXME: we allow up to <inter> for a connection to establish, but we should use another parameter */
5069 tv_delayfrom(&t->expire, &now, s->inter);
willy tarreau5cbea6f2005-12-17 12:48:26 +01005070 }
5071 else {
5072 //fprintf(stderr, "process_chk: 8\n");
5073 /* there was a test running */
5074 if (s->result > 0) { /* good server detected */
5075 //fprintf(stderr, "process_chk: 9\n");
5076 s->health++; /* was bad, stays for a while */
willy tarreaue47c8d72005-12-17 12:55:52 +01005077 if (s->health >= s->rise) {
willy tarreau535ae7a2005-12-17 12:58:00 +01005078 if (s->health == s->rise) {
willy tarreaudd07e972005-12-18 00:48:48 +01005079 Warning("server %s/%s UP.\n", s->proxy->id, s->id);
willy tarreau9fe663a2005-12-17 13:02:59 +01005080 send_log(s->proxy, LOG_NOTICE, "Server %s/%s is UP.\n", s->proxy->id, s->id);
willy tarreau535ae7a2005-12-17 12:58:00 +01005081 }
willy tarreauef900ab2005-12-17 12:52:52 +01005082
willy tarreaue47c8d72005-12-17 12:55:52 +01005083 s->health = s->rise + s->fall - 1; /* OK now */
willy tarreau5cbea6f2005-12-17 12:48:26 +01005084 s->state |= SRV_RUNNING;
5085 }
willy tarreauef900ab2005-12-17 12:52:52 +01005086 s->curfd = -1; /* no check running anymore */
5087 //FD_CLR(fd, StaticWriteEvent);
willy tarreau5cbea6f2005-12-17 12:48:26 +01005088 fd_delete(fd);
willy tarreaue47c8d72005-12-17 12:55:52 +01005089 tv_delayfrom(&t->expire, &now, s->inter);
willy tarreau5cbea6f2005-12-17 12:48:26 +01005090 }
5091 else if (s->result < 0 || tv_cmp2_ms(&t->expire, &now) <= 0) {
5092 //fprintf(stderr, "process_chk: 10\n");
5093 /* failure or timeout detected */
willy tarreaue47c8d72005-12-17 12:55:52 +01005094 if (s->health > s->rise)
willy tarreau5cbea6f2005-12-17 12:48:26 +01005095 s->health--; /* still good */
5096 else {
willy tarreaudd07e972005-12-18 00:48:48 +01005097 s->state &= ~SRV_RUNNING;
willy tarreau9fe663a2005-12-17 13:02:59 +01005098
willy tarreaudd07e972005-12-18 00:48:48 +01005099 if (s->health == s->rise) {
5100 Warning("Server %s/%s DOWN.\n", s->proxy->id, s->id);
willy tarreau9fe663a2005-12-17 13:02:59 +01005101 send_log(s->proxy, LOG_ALERT, "Server %s/%s is DOWN.\n", s->proxy->id, s->id);
willy tarreaudd07e972005-12-18 00:48:48 +01005102
5103 if (find_server(s->proxy) == NULL) {
5104 Alert("Proxy %s has no server available !\n", s->proxy->id);
5105 send_log(s->proxy, LOG_EMERG, "Proxy %s has no server available !\n", s->proxy->id);
5106 }
willy tarreau535ae7a2005-12-17 12:58:00 +01005107 }
willy tarreauef900ab2005-12-17 12:52:52 +01005108
willy tarreau5cbea6f2005-12-17 12:48:26 +01005109 s->health = 0; /* failure */
willy tarreau5cbea6f2005-12-17 12:48:26 +01005110 }
5111 s->curfd = -1;
willy tarreauef900ab2005-12-17 12:52:52 +01005112 //FD_CLR(fd, StaticWriteEvent);
willy tarreau5cbea6f2005-12-17 12:48:26 +01005113 fd_delete(fd);
willy tarreaue47c8d72005-12-17 12:55:52 +01005114 tv_delayfrom(&t->expire, &now, s->inter);
willy tarreau5cbea6f2005-12-17 12:48:26 +01005115 }
5116 /* if result is 0 and there's no timeout, we have to wait again */
5117 }
5118 //fprintf(stderr, "process_chk: 11\n");
5119 s->result = 0;
5120 task_queue(t); /* restore t to its place in the task list */
willy tarreaub952e1d2005-12-18 01:31:20 +01005121 return tv_remain2(&now, &t->expire);
willy tarreau0f7af912005-12-17 12:21:26 +01005122}
5123
5124
willy tarreau5cbea6f2005-12-17 12:48:26 +01005125
willy tarreau0f7af912005-12-17 12:21:26 +01005126#if STATTIME > 0
5127int stats(void);
5128#endif
5129
5130/*
willy tarreau1c2ad212005-12-18 01:11:29 +01005131 * This does 4 things :
5132 * - wake up all expired tasks
5133 * - call all runnable tasks
5134 * - call maintain_proxies() to enable/disable the listeners
5135 * - return the delay till next event in ms, -1 = wait indefinitely
5136 * Note: this part should be rewritten with the O(ln(n)) scheduler.
5137 *
willy tarreau0f7af912005-12-17 12:21:26 +01005138 */
5139
willy tarreau1c2ad212005-12-18 01:11:29 +01005140int process_runnable_tasks() {
willy tarreau0f7af912005-12-17 12:21:26 +01005141 int next_time;
willy tarreau0f7af912005-12-17 12:21:26 +01005142 int time2;
willy tarreau5cbea6f2005-12-17 12:48:26 +01005143 struct task *t, *tnext;
willy tarreau0f7af912005-12-17 12:21:26 +01005144
willy tarreaub952e1d2005-12-18 01:31:20 +01005145 next_time = TIME_ETERNITY; /* set the timer to wait eternally first */
willy tarreau0f7af912005-12-17 12:21:26 +01005146
willy tarreau1c2ad212005-12-18 01:11:29 +01005147 /* look for expired tasks and add them to the run queue.
5148 */
5149 tnext = ((struct task *)LIST_HEAD(wait_queue))->next;
5150 while ((t = tnext) != LIST_HEAD(wait_queue)) { /* we haven't looped ? */
5151 tnext = t->next;
5152 if (t->state & TASK_RUNNING)
5153 continue;
5154
willy tarreaub952e1d2005-12-18 01:31:20 +01005155 if (tv_iseternity(&t->expire))
5156 continue;
5157
willy tarreau1c2ad212005-12-18 01:11:29 +01005158 /* wakeup expired entries. It doesn't matter if they are
5159 * already running because of a previous event
willy tarreau5cbea6f2005-12-17 12:48:26 +01005160 */
willy tarreaub952e1d2005-12-18 01:31:20 +01005161 if (tv_cmp_ms(&t->expire, &now) <= 0) {
willy tarreau1c2ad212005-12-18 01:11:29 +01005162 task_wakeup(&rq, t);
5163 }
5164 else {
5165 /* first non-runnable task. Use its expiration date as an upper bound */
5166 int temp_time = tv_remain(&now, &t->expire);
5167 if (temp_time)
5168 next_time = temp_time;
5169 break;
willy tarreau5cbea6f2005-12-17 12:48:26 +01005170 }
willy tarreau1c2ad212005-12-18 01:11:29 +01005171 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01005172
willy tarreau1c2ad212005-12-18 01:11:29 +01005173 /* process each task in the run queue now. Each task may be deleted
5174 * since we only use tnext.
5175 */
5176 tnext = rq;
5177 while ((t = tnext) != NULL) {
5178 int temp_time;
5179
5180 tnext = t->rqnext;
5181 task_sleep(&rq, t);
5182 temp_time = t->process(t);
5183 next_time = MINTIME(temp_time, next_time);
5184 }
5185
5186 /* maintain all proxies in a consistent state. This should quickly become a task */
5187 time2 = maintain_proxies();
5188 return MINTIME(time2, next_time);
5189}
5190
5191
5192#if defined(ENABLE_EPOLL)
5193
5194/*
5195 * Main epoll() loop.
5196 */
5197
5198/* does 3 actions :
5199 * 0 (POLL_LOOP_ACTION_INIT) : initializes necessary private structures
5200 * 1 (POLL_LOOP_ACTION_RUN) : runs the loop
5201 * 2 (POLL_LOOP_ACTION_CLEAN) : cleans up
5202 *
5203 * returns 0 if initialization failed, !0 otherwise.
5204 */
5205
5206int epoll_loop(int action) {
5207 int next_time;
5208 int status;
5209 int fd;
5210
5211 int fds, count;
5212 int pr, pw, sr, sw;
5213 unsigned rn, ro, wn, wo; /* read new, read old, write new, write old */
5214 struct epoll_event ev;
5215
5216 /* private data */
willy tarreau1c2ad212005-12-18 01:11:29 +01005217 static struct epoll_event *epoll_events = NULL;
5218 static int epoll_fd;
5219
5220 if (action == POLL_LOOP_ACTION_INIT) {
5221 epoll_fd = epoll_create(global.maxsock + 1);
5222 if (epoll_fd < 0)
5223 return 0;
5224 else {
5225 epoll_events = (struct epoll_event*)
5226 calloc(1, sizeof(struct epoll_event) * global.maxsock);
5227 PrevReadEvent = (fd_set *)
5228 calloc(1, sizeof(fd_set) * (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
5229 PrevWriteEvent = (fd_set *)
5230 calloc(1, sizeof(fd_set) * (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
willy tarreau5cbea6f2005-12-17 12:48:26 +01005231 }
willy tarreau1c2ad212005-12-18 01:11:29 +01005232 return 1;
5233 }
5234 else if (action == POLL_LOOP_ACTION_CLEAN) {
5235 if (PrevWriteEvent) free(PrevWriteEvent);
5236 if (PrevReadEvent) free(PrevReadEvent);
5237 if (epoll_events) free(epoll_events);
5238 close(epoll_fd);
willy tarreau1c2ad212005-12-18 01:11:29 +01005239 epoll_fd = 0;
5240 return 1;
5241 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01005242
willy tarreau1c2ad212005-12-18 01:11:29 +01005243 /* OK, it's POLL_LOOP_ACTION_RUN */
willy tarreau5cbea6f2005-12-17 12:48:26 +01005244
willy tarreau1c2ad212005-12-18 01:11:29 +01005245 tv_now(&now);
5246
5247 while (1) {
5248 next_time = process_runnable_tasks();
willy tarreau5cbea6f2005-12-17 12:48:26 +01005249
5250 /* stop when there's no connection left and we don't allow them anymore */
5251 if (!actconn && listeners == 0)
5252 break;
5253
willy tarreau0f7af912005-12-17 12:21:26 +01005254#if STATTIME > 0
willy tarreau1c2ad212005-12-18 01:11:29 +01005255 {
5256 int time2;
5257 time2 = stats();
5258 next_time = MINTIME(time2, next_time);
5259 }
willy tarreau0f7af912005-12-17 12:21:26 +01005260#endif
5261
willy tarreau1c2ad212005-12-18 01:11:29 +01005262 for (fds = 0; (fds << INTBITS) < maxfd; fds++) {
5263
5264 rn = ((int*)StaticReadEvent)[fds]; ro = ((int*)PrevReadEvent)[fds];
5265 wn = ((int*)StaticWriteEvent)[fds]; wo = ((int*)PrevWriteEvent)[fds];
5266
5267 if ((ro^rn) | (wo^wn)) {
5268 for (count = 0, fd = fds << INTBITS; count < (1<<INTBITS) && fd < maxfd; count++, fd++) {
5269#define FDSETS_ARE_INT_ALIGNED
5270#ifdef FDSETS_ARE_INT_ALIGNED
willy tarreau0f7af912005-12-17 12:21:26 +01005271
willy tarreauad90a0c2005-12-18 01:09:15 +01005272#define WE_REALLY_NOW_THAT_FDSETS_ARE_INTS
5273#ifdef WE_REALLY_NOW_THAT_FDSETS_ARE_INTS
willy tarreau1c2ad212005-12-18 01:11:29 +01005274 pr = (ro >> count) & 1;
5275 pw = (wo >> count) & 1;
5276 sr = (rn >> count) & 1;
5277 sw = (wn >> count) & 1;
willy tarreauad90a0c2005-12-18 01:09:15 +01005278#else
willy tarreau1c2ad212005-12-18 01:11:29 +01005279 pr = FD_ISSET(fd&((1<<INTBITS)-1), (typeof(fd_set*))&ro);
5280 pw = FD_ISSET(fd&((1<<INTBITS)-1), (typeof(fd_set*))&wo);
5281 sr = FD_ISSET(fd&((1<<INTBITS)-1), (typeof(fd_set*))&rn);
5282 sw = FD_ISSET(fd&((1<<INTBITS)-1), (typeof(fd_set*))&wn);
willy tarreauad90a0c2005-12-18 01:09:15 +01005283#endif
5284#else
willy tarreau1c2ad212005-12-18 01:11:29 +01005285 pr = FD_ISSET(fd, PrevReadEvent);
5286 pw = FD_ISSET(fd, PrevWriteEvent);
5287 sr = FD_ISSET(fd, StaticReadEvent);
5288 sw = FD_ISSET(fd, StaticWriteEvent);
willy tarreauad90a0c2005-12-18 01:09:15 +01005289#endif
willy tarreau1c2ad212005-12-18 01:11:29 +01005290 if (!((sr^pr) | (sw^pw)))
5291 continue;
willy tarreauad90a0c2005-12-18 01:09:15 +01005292
willy tarreau1c2ad212005-12-18 01:11:29 +01005293 ev.events = (sr ? EPOLLIN : 0) | (sw ? EPOLLOUT : 0);
5294 ev.data.fd = fd;
willy tarreauad90a0c2005-12-18 01:09:15 +01005295
willy tarreaub952e1d2005-12-18 01:31:20 +01005296#ifdef EPOLL_CTL_MOD_WORKAROUND
5297 /* I encountered a rarely reproducible problem with
5298 * EPOLL_CTL_MOD where a modified FD (systematically
5299 * the one in epoll_events[0], fd#7) would sometimes
5300 * be set EPOLL_OUT while asked for a read ! This is
5301 * with the 2.4 epoll patch. The workaround is to
5302 * delete then recreate in case of modification.
5303 * This is in 2.4 up to epoll-lt-0.21 but not in 2.6
5304 * nor RHEL kernels.
5305 */
5306
5307 if ((pr | pw) && fdtab[fd].state != FD_STCLOSE)
5308 epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &ev);
5309
5310 if ((sr | sw))
5311 epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev);
5312#else
willy tarreau1c2ad212005-12-18 01:11:29 +01005313 if ((pr | pw)) {
5314 /* the file-descriptor already exists... */
5315 if ((sr | sw)) {
5316 /* ...and it will still exist */
5317 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ev) < 0) {
5318 // perror("epoll_ctl(MOD)");
5319 // exit(1);
willy tarreauad90a0c2005-12-18 01:09:15 +01005320 }
5321 } else {
willy tarreau1c2ad212005-12-18 01:11:29 +01005322 /* ...and it will be removed */
5323 if (fdtab[fd].state != FD_STCLOSE &&
5324 epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &ev) < 0) {
5325 // perror("epoll_ctl(DEL)");
5326 // exit(1);
willy tarreauad90a0c2005-12-18 01:09:15 +01005327 }
5328 }
willy tarreau1c2ad212005-12-18 01:11:29 +01005329 } else {
5330 /* the file-descriptor did not exist, let's add it */
5331 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) {
5332 // perror("epoll_ctl(ADD)");
5333 // exit(1);
5334 }
willy tarreauad90a0c2005-12-18 01:09:15 +01005335 }
willy tarreaub952e1d2005-12-18 01:31:20 +01005336#endif // EPOLL_CTL_MOD_WORKAROUND
willy tarreau1c2ad212005-12-18 01:11:29 +01005337 }
5338 ((int*)PrevReadEvent)[fds] = rn;
5339 ((int*)PrevWriteEvent)[fds] = wn;
5340 }
5341 }
5342
5343 /* now let's wait for events */
5344 status = epoll_wait(epoll_fd, epoll_events, maxfd, next_time);
5345 tv_now(&now);
willy tarreauad90a0c2005-12-18 01:09:15 +01005346
willy tarreau1c2ad212005-12-18 01:11:29 +01005347 for (count = 0; count < status; count++) {
5348 fd = epoll_events[count].data.fd;
5349
5350 if (fdtab[fd].state == FD_STCLOSE)
5351 continue;
5352
5353 if (epoll_events[count].events & ( EPOLLIN | EPOLLERR | EPOLLHUP ))
5354 fdtab[fd].read(fd);
5355
5356 if (fdtab[fd].state == FD_STCLOSE)
5357 continue;
5358
5359 if (epoll_events[count].events & ( EPOLLOUT | EPOLLERR | EPOLLHUP ))
5360 fdtab[fd].write(fd);
5361 }
5362 }
5363 return 1;
5364}
5365#endif
willy tarreauad90a0c2005-12-18 01:09:15 +01005366
willy tarreauad90a0c2005-12-18 01:09:15 +01005367
willy tarreau5cbea6f2005-12-17 12:48:26 +01005368
willy tarreau1c2ad212005-12-18 01:11:29 +01005369#if defined(ENABLE_POLL)
willy tarreauad90a0c2005-12-18 01:09:15 +01005370
willy tarreau1c2ad212005-12-18 01:11:29 +01005371/*
5372 * Main poll() loop.
5373 */
willy tarreauad90a0c2005-12-18 01:09:15 +01005374
willy tarreau1c2ad212005-12-18 01:11:29 +01005375/* does 3 actions :
5376 * 0 (POLL_LOOP_ACTION_INIT) : initializes necessary private structures
5377 * 1 (POLL_LOOP_ACTION_RUN) : runs the loop
5378 * 2 (POLL_LOOP_ACTION_CLEAN) : cleans up
5379 *
5380 * returns 0 if initialization failed, !0 otherwise.
5381 */
willy tarreauad90a0c2005-12-18 01:09:15 +01005382
willy tarreau1c2ad212005-12-18 01:11:29 +01005383int poll_loop(int action) {
5384 int next_time;
5385 int status;
5386 int fd, nbfd;
5387
5388 int fds, count;
5389 int sr, sw;
5390 unsigned rn, wn; /* read new, write new */
5391
5392 /* private data */
5393 static struct pollfd *poll_events = NULL;
5394
5395 if (action == POLL_LOOP_ACTION_INIT) {
5396 poll_events = (struct pollfd*)
5397 calloc(1, sizeof(struct pollfd) * global.maxsock);
5398 return 1;
5399 }
5400 else if (action == POLL_LOOP_ACTION_CLEAN) {
5401 if (poll_events)
5402 free(poll_events);
5403 return 1;
5404 }
5405
5406 /* OK, it's POLL_LOOP_ACTION_RUN */
5407
5408 tv_now(&now);
5409
5410 while (1) {
5411 next_time = process_runnable_tasks();
5412
5413 /* stop when there's no connection left and we don't allow them anymore */
5414 if (!actconn && listeners == 0)
5415 break;
5416
5417#if STATTIME > 0
5418 {
5419 int time2;
5420 time2 = stats();
5421 next_time = MINTIME(time2, next_time);
5422 }
5423#endif
5424
5425
5426 nbfd = 0;
5427 for (fds = 0; (fds << INTBITS) < maxfd; fds++) {
5428
5429 rn = ((int*)StaticReadEvent)[fds];
5430 wn = ((int*)StaticWriteEvent)[fds];
5431
5432 if ((rn|wn)) {
5433 for (count = 0, fd = fds << INTBITS; count < (1<<INTBITS) && fd < maxfd; count++, fd++) {
5434#define FDSETS_ARE_INT_ALIGNED
5435#ifdef FDSETS_ARE_INT_ALIGNED
5436
5437#define WE_REALLY_NOW_THAT_FDSETS_ARE_INTS
5438#ifdef WE_REALLY_NOW_THAT_FDSETS_ARE_INTS
5439 sr = (rn >> count) & 1;
5440 sw = (wn >> count) & 1;
5441#else
5442 sr = FD_ISSET(fd&((1<<INTBITS)-1), (typeof(fd_set*))&rn);
5443 sw = FD_ISSET(fd&((1<<INTBITS)-1), (typeof(fd_set*))&wn);
5444#endif
5445#else
5446 sr = FD_ISSET(fd, StaticReadEvent);
5447 sw = FD_ISSET(fd, StaticWriteEvent);
5448#endif
5449 if ((sr|sw)) {
5450 poll_events[nbfd].fd = fd;
5451 poll_events[nbfd].events = (sr ? POLLIN : 0) | (sw ? POLLOUT : 0);
5452 nbfd++;
willy tarreauad90a0c2005-12-18 01:09:15 +01005453 }
willy tarreauad90a0c2005-12-18 01:09:15 +01005454 }
willy tarreau1c2ad212005-12-18 01:11:29 +01005455 }
5456 }
5457
5458 /* now let's wait for events */
5459 status = poll(poll_events, nbfd, next_time);
5460 tv_now(&now);
5461
5462 for (count = 0; status > 0 && count < nbfd; count++) {
5463 fd = poll_events[count].fd;
5464
5465 if (!poll_events[count].revents & ( POLLOUT | POLLIN | POLLERR | POLLHUP ))
5466 continue;
5467
5468 /* ok, we found one active fd */
5469 status--;
5470
5471 if (fdtab[fd].state == FD_STCLOSE)
5472 continue;
5473
5474 if (poll_events[count].revents & ( POLLIN | POLLERR | POLLHUP ))
5475 fdtab[fd].read(fd);
5476
5477 if (fdtab[fd].state == FD_STCLOSE)
5478 continue;
5479
5480 if (poll_events[count].revents & ( POLLOUT | POLLERR | POLLHUP ))
5481 fdtab[fd].write(fd);
5482 }
5483 }
5484 return 1;
5485}
willy tarreauad90a0c2005-12-18 01:09:15 +01005486#endif
willy tarreauad90a0c2005-12-18 01:09:15 +01005487
willy tarreauad90a0c2005-12-18 01:09:15 +01005488
willy tarreauad90a0c2005-12-18 01:09:15 +01005489
willy tarreau1c2ad212005-12-18 01:11:29 +01005490/*
5491 * Main select() loop.
5492 */
willy tarreauad90a0c2005-12-18 01:09:15 +01005493
willy tarreau1c2ad212005-12-18 01:11:29 +01005494/* does 3 actions :
5495 * 0 (POLL_LOOP_ACTION_INIT) : initializes necessary private structures
5496 * 1 (POLL_LOOP_ACTION_RUN) : runs the loop
5497 * 2 (POLL_LOOP_ACTION_CLEAN) : cleans up
5498 *
5499 * returns 0 if initialization failed, !0 otherwise.
5500 */
willy tarreauad90a0c2005-12-18 01:09:15 +01005501
willy tarreauad90a0c2005-12-18 01:09:15 +01005502
willy tarreau1c2ad212005-12-18 01:11:29 +01005503int select_loop(int action) {
5504 int next_time;
5505 int status;
5506 int fd,i;
5507 struct timeval delta;
5508 int readnotnull, writenotnull;
5509 static fd_set *ReadEvent = NULL, *WriteEvent = NULL;
willy tarreauad90a0c2005-12-18 01:09:15 +01005510
willy tarreau1c2ad212005-12-18 01:11:29 +01005511 if (action == POLL_LOOP_ACTION_INIT) {
5512 ReadEvent = (fd_set *)
5513 calloc(1, sizeof(fd_set) * (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
5514 WriteEvent = (fd_set *)
5515 calloc(1, sizeof(fd_set) * (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
5516 return 1;
5517 }
5518 else if (action == POLL_LOOP_ACTION_CLEAN) {
5519 if (WriteEvent) free(WriteEvent);
5520 if (ReadEvent) free(ReadEvent);
5521 return 1;
5522 }
willy tarreauad90a0c2005-12-18 01:09:15 +01005523
willy tarreau1c2ad212005-12-18 01:11:29 +01005524 /* OK, it's POLL_LOOP_ACTION_RUN */
willy tarreauad90a0c2005-12-18 01:09:15 +01005525
willy tarreau1c2ad212005-12-18 01:11:29 +01005526 tv_now(&now);
willy tarreauad90a0c2005-12-18 01:09:15 +01005527
willy tarreau1c2ad212005-12-18 01:11:29 +01005528 while (1) {
5529 next_time = process_runnable_tasks();
willy tarreauad90a0c2005-12-18 01:09:15 +01005530
willy tarreau1c2ad212005-12-18 01:11:29 +01005531 /* stop when there's no connection left and we don't allow them anymore */
5532 if (!actconn && listeners == 0)
5533 break;
5534
5535#if STATTIME > 0
5536 {
5537 int time2;
5538 time2 = stats();
5539 next_time = MINTIME(time2, next_time);
5540 }
5541#endif
5542
willy tarreau1c2ad212005-12-18 01:11:29 +01005543 if (next_time > 0) { /* FIXME */
5544 /* Convert to timeval */
5545 /* to avoid eventual select loops due to timer precision */
5546 next_time += SCHEDULER_RESOLUTION;
5547 delta.tv_sec = next_time / 1000;
5548 delta.tv_usec = (next_time % 1000) * 1000;
5549 }
5550 else if (next_time == 0) { /* allow select to return immediately when needed */
5551 delta.tv_sec = delta.tv_usec = 0;
5552 }
5553
5554
5555 /* let's restore fdset state */
5556
5557 readnotnull = 0; writenotnull = 0;
5558 for (i = 0; i < (maxfd + FD_SETSIZE - 1)/(8*sizeof(int)); i++) {
5559 readnotnull |= (*(((int*)ReadEvent)+i) = *(((int*)StaticReadEvent)+i)) != 0;
5560 writenotnull |= (*(((int*)WriteEvent)+i) = *(((int*)StaticWriteEvent)+i)) != 0;
5561 }
5562
5563 // /* just a verification code, needs to be removed for performance */
5564 // for (i=0; i<maxfd; i++) {
5565 // if (FD_ISSET(i, ReadEvent) != FD_ISSET(i, StaticReadEvent))
5566 // abort();
5567 // if (FD_ISSET(i, WriteEvent) != FD_ISSET(i, StaticWriteEvent))
5568 // abort();
5569 //
5570 // }
5571
5572 status = select(maxfd,
5573 readnotnull ? ReadEvent : NULL,
5574 writenotnull ? WriteEvent : NULL,
5575 NULL,
5576 (next_time >= 0) ? &delta : NULL);
5577
5578 /* this is an experiment on the separation of the select work */
5579 // status = (readnotnull ? select(maxfd, ReadEvent, NULL, NULL, (next_time >= 0) ? &delta : NULL) : 0);
5580 // status |= (writenotnull ? select(maxfd, NULL, WriteEvent, NULL, (next_time >= 0) ? &delta : NULL) : 0);
5581
5582 tv_now(&now);
5583
5584 if (status > 0) { /* must proceed with events */
5585
5586 int fds;
5587 char count;
willy tarreauad90a0c2005-12-18 01:09:15 +01005588
willy tarreau1c2ad212005-12-18 01:11:29 +01005589 for (fds = 0; (fds << INTBITS) < maxfd; fds++)
5590 if ((((int *)(ReadEvent))[fds] | ((int *)(WriteEvent))[fds]) != 0)
5591 for (count = 1<<INTBITS, fd = fds << INTBITS; count && fd < maxfd; count--, fd++) {
5592
5593 /* if we specify read first, the accepts and zero reads will be
5594 * seen first. Moreover, system buffers will be flushed faster.
5595 */
5596 if (fdtab[fd].state == FD_STCLOSE)
5597 continue;
willy tarreau64a3cc32005-12-18 01:13:11 +01005598
willy tarreau1c2ad212005-12-18 01:11:29 +01005599 if (FD_ISSET(fd, ReadEvent))
5600 fdtab[fd].read(fd);
willy tarreau64a3cc32005-12-18 01:13:11 +01005601
willy tarreau1c2ad212005-12-18 01:11:29 +01005602 if (FD_ISSET(fd, WriteEvent))
5603 fdtab[fd].write(fd);
5604 }
5605 }
5606 else {
5607 // fprintf(stderr,"select returned %d, maxfd=%d\n", status, maxfd);
willy tarreau0f7af912005-12-17 12:21:26 +01005608 }
willy tarreau0f7af912005-12-17 12:21:26 +01005609 }
willy tarreau1c2ad212005-12-18 01:11:29 +01005610 return 1;
willy tarreau0f7af912005-12-17 12:21:26 +01005611}
5612
5613
5614#if STATTIME > 0
5615/*
5616 * Display proxy statistics regularly. It is designed to be called from the
5617 * select_loop().
5618 */
5619int stats(void) {
5620 static int lines;
5621 static struct timeval nextevt;
5622 static struct timeval lastevt;
5623 static struct timeval starttime = {0,0};
5624 unsigned long totaltime, deltatime;
5625 int ret;
5626
willy tarreau750a4722005-12-17 13:21:24 +01005627 if (tv_cmp(&now, &nextevt) > 0) {
willy tarreau6e682ce2005-12-17 13:26:49 +01005628 deltatime = (tv_diff(&lastevt, &now)?:1);
5629 totaltime = (tv_diff(&starttime, &now)?:1);
willy tarreau0f7af912005-12-17 12:21:26 +01005630
willy tarreau9fe663a2005-12-17 13:02:59 +01005631 if (global.mode & MODE_STATS) {
5632 if ((lines++ % 16 == 0) && !(global.mode & MODE_LOG))
willy tarreau5cbea6f2005-12-17 12:48:26 +01005633 qfprintf(stderr,
willy tarreau0f7af912005-12-17 12:21:26 +01005634 "\n active total tsknew tskgood tskleft tskrght tsknsch tsklsch tskrsch\n");
5635 if (lines>1) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01005636 qfprintf(stderr,"%07d %07d %07d %07d %07d %07d %07d %07d %07d\n",
willy tarreau0f7af912005-12-17 12:21:26 +01005637 actconn, totalconn,
5638 stats_tsk_new, stats_tsk_good,
5639 stats_tsk_left, stats_tsk_right,
5640 stats_tsk_nsrch, stats_tsk_lsrch, stats_tsk_rsrch);
5641 }
5642 }
5643
5644 tv_delayfrom(&nextevt, &now, STATTIME);
5645
5646 lastevt=now;
5647 }
5648 ret = tv_remain(&now, &nextevt);
5649 return ret;
5650}
5651#endif
5652
5653
5654/*
5655 * this function enables proxies when there are enough free sessions,
5656 * or stops them when the table is full. It is designed to be called from the
willy tarreau5cbea6f2005-12-17 12:48:26 +01005657 * select_loop(). It returns the time left before next expiration event
willy tarreaub952e1d2005-12-18 01:31:20 +01005658 * during stop time, TIME_ETERNITY otherwise.
willy tarreau0f7af912005-12-17 12:21:26 +01005659 */
5660static int maintain_proxies(void) {
5661 struct proxy *p;
willy tarreaua41a8b42005-12-17 14:02:24 +01005662 struct listener *l;
willy tarreau5cbea6f2005-12-17 12:48:26 +01005663 int tleft; /* time left */
willy tarreau0f7af912005-12-17 12:21:26 +01005664
5665 p = proxy;
willy tarreaub952e1d2005-12-18 01:31:20 +01005666 tleft = TIME_ETERNITY; /* infinite time */
willy tarreau0f7af912005-12-17 12:21:26 +01005667
5668 /* if there are enough free sessions, we'll activate proxies */
willy tarreau9fe663a2005-12-17 13:02:59 +01005669 if (actconn < global.maxconn) {
willy tarreau0f7af912005-12-17 12:21:26 +01005670 while (p) {
5671 if (p->nbconn < p->maxconn) {
5672 if (p->state == PR_STIDLE) {
willy tarreaua41a8b42005-12-17 14:02:24 +01005673 for (l = p->listen; l != NULL; l = l->next) {
5674 FD_SET(l->fd, StaticReadEvent);
5675 }
willy tarreau0f7af912005-12-17 12:21:26 +01005676 p->state = PR_STRUN;
5677 }
5678 }
5679 else {
5680 if (p->state == PR_STRUN) {
willy tarreaua41a8b42005-12-17 14:02:24 +01005681 for (l = p->listen; l != NULL; l = l->next) {
5682 FD_CLR(l->fd, StaticReadEvent);
5683 }
willy tarreau0f7af912005-12-17 12:21:26 +01005684 p->state = PR_STIDLE;
5685 }
5686 }
5687 p = p->next;
5688 }
5689 }
5690 else { /* block all proxies */
5691 while (p) {
5692 if (p->state == PR_STRUN) {
willy tarreaua41a8b42005-12-17 14:02:24 +01005693 for (l = p->listen; l != NULL; l = l->next) {
5694 FD_CLR(l->fd, StaticReadEvent);
5695 }
willy tarreau0f7af912005-12-17 12:21:26 +01005696 p->state = PR_STIDLE;
5697 }
5698 p = p->next;
5699 }
5700 }
5701
willy tarreau5cbea6f2005-12-17 12:48:26 +01005702 if (stopping) {
5703 p = proxy;
5704 while (p) {
5705 if (p->state != PR_STDISABLED) {
5706 int t;
willy tarreaub952e1d2005-12-18 01:31:20 +01005707 t = tv_remain2(&now, &p->stop_time);
willy tarreau5cbea6f2005-12-17 12:48:26 +01005708 if (t == 0) {
willy tarreau535ae7a2005-12-17 12:58:00 +01005709 Warning("Proxy %s stopped.\n", p->id);
willy tarreau9fe663a2005-12-17 13:02:59 +01005710 send_log(p, LOG_WARNING, "Proxy %s stopped.\n", p->id);
willy tarreau535ae7a2005-12-17 12:58:00 +01005711
willy tarreaua41a8b42005-12-17 14:02:24 +01005712 for (l = p->listen; l != NULL; l = l->next) {
5713 fd_delete(l->fd);
5714 listeners--;
5715 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01005716 p->state = PR_STDISABLED;
willy tarreau5cbea6f2005-12-17 12:48:26 +01005717 }
5718 else {
5719 tleft = MINTIME(t, tleft);
5720 }
5721 }
5722 p = p->next;
5723 }
5724 }
5725 return tleft;
willy tarreau0f7af912005-12-17 12:21:26 +01005726}
5727
5728/*
5729 * this function disables health-check servers so that the process will quickly be ignored
5730 * by load balancers.
5731 */
5732static void soft_stop(void) {
5733 struct proxy *p;
5734
5735 stopping = 1;
5736 p = proxy;
willy tarreau5cbea6f2005-12-17 12:48:26 +01005737 tv_now(&now); /* else, the old time before select will be used */
willy tarreau0f7af912005-12-17 12:21:26 +01005738 while (p) {
willy tarreau535ae7a2005-12-17 12:58:00 +01005739 if (p->state != PR_STDISABLED) {
5740 Warning("Stopping proxy %s in %d ms.\n", p->id, p->grace);
willy tarreau9fe663a2005-12-17 13:02:59 +01005741 send_log(p, LOG_WARNING, "Stopping proxy %s in %d ms.\n", p->id, p->grace);
willy tarreau0f7af912005-12-17 12:21:26 +01005742 tv_delayfrom(&p->stop_time, &now, p->grace);
willy tarreau535ae7a2005-12-17 12:58:00 +01005743 }
willy tarreau0f7af912005-12-17 12:21:26 +01005744 p = p->next;
5745 }
5746}
5747
5748/*
5749 * upon SIGUSR1, let's have a soft stop.
5750 */
5751void sig_soft_stop(int sig) {
5752 soft_stop();
5753 signal(sig, SIG_IGN);
5754}
5755
5756
willy tarreau8337c6b2005-12-17 13:41:01 +01005757/*
5758 * this function dumps every server's state when the process receives SIGHUP.
5759 */
5760void sig_dump_state(int sig) {
5761 struct proxy *p = proxy;
5762
5763 Warning("SIGHUP received, dumping servers states.\n");
5764 while (p) {
5765 struct server *s = p->srv;
5766
5767 send_log(p, LOG_NOTICE, "SIGUP received, dumping servers states.\n");
5768 while (s) {
5769 if (s->state & SRV_RUNNING) {
5770 Warning("SIGHUP: server %s/%s is UP.\n", p->id, s->id);
5771 send_log(p, LOG_NOTICE, "SIGUP: server %s/%s is UP.\n", p->id, s->id);
5772 }
5773 else {
5774 Warning("SIGHUP: server %s/%s is DOWN.\n", p->id, s->id);
5775 send_log(p, LOG_NOTICE, "SIGHUP: server %s/%s is DOWN.\n", p->id, s->id);
5776 }
5777 s = s->next;
5778 }
willy tarreaudd07e972005-12-18 00:48:48 +01005779
5780 if (find_server(p) == NULL) {
5781 Warning("SIGHUP: proxy %s has no server available !\n", p);
5782 send_log(p, LOG_NOTICE, "SIGHUP: proxy %s has no server available !\n", p);
5783 }
5784
willy tarreau8337c6b2005-12-17 13:41:01 +01005785 p = p->next;
5786 }
5787 signal(sig, sig_dump_state);
5788}
5789
willy tarreau0f7af912005-12-17 12:21:26 +01005790void dump(int sig) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01005791 struct task *t, *tnext;
5792 struct session *s;
willy tarreau0f7af912005-12-17 12:21:26 +01005793
willy tarreau5cbea6f2005-12-17 12:48:26 +01005794 tnext = ((struct task *)LIST_HEAD(wait_queue))->next;
5795 while ((t = tnext) != LIST_HEAD(wait_queue)) { /* we haven't looped ? */
5796 tnext = t->next;
5797 s = t->context;
5798 qfprintf(stderr,"[dump] wq: task %p, still %ld ms, "
5799 "cli=%d, srv=%d, cr=%d, cw=%d, sr=%d, sw=%d, "
5800 "req=%d, rep=%d, clifd=%d\n",
5801 s, tv_remain(&now, &t->expire),
5802 s->cli_state,
5803 s->srv_state,
5804 FD_ISSET(s->cli_fd, StaticReadEvent),
5805 FD_ISSET(s->cli_fd, StaticWriteEvent),
5806 FD_ISSET(s->srv_fd, StaticReadEvent),
5807 FD_ISSET(s->srv_fd, StaticWriteEvent),
5808 s->req->l, s->rep?s->rep->l:0, s->cli_fd
5809 );
willy tarreau0f7af912005-12-17 12:21:26 +01005810 }
willy tarreau12350152005-12-18 01:03:27 +01005811}
5812
willy tarreau64a3cc32005-12-18 01:13:11 +01005813#ifdef DEBUG_MEMORY
willy tarreau12350152005-12-18 01:03:27 +01005814static void fast_stop(void)
5815{
5816 struct proxy *p;
5817 p = proxy;
5818 while (p) {
5819 p->grace = 0;
5820 p = p->next;
5821 }
5822 soft_stop();
willy tarreau0f7af912005-12-17 12:21:26 +01005823}
5824
willy tarreau12350152005-12-18 01:03:27 +01005825void sig_int(int sig) {
5826 /* This would normally be a hard stop,
5827 but we want to be sure about deallocation,
5828 and so on, so we do a soft stop with
5829 0 GRACE time
5830 */
5831 fast_stop();
5832 /* If we are killed twice, we decide to die*/
5833 signal(sig, SIG_DFL);
5834}
5835
5836void sig_term(int sig) {
5837 /* This would normally be a hard stop,
5838 but we want to be sure about deallocation,
5839 and so on, so we do a soft stop with
5840 0 GRACE time
5841 */
5842 fast_stop();
5843 /* If we are killed twice, we decide to die*/
5844 signal(sig, SIG_DFL);
5845}
willy tarreau64a3cc32005-12-18 01:13:11 +01005846#endif
willy tarreau12350152005-12-18 01:03:27 +01005847
willy tarreauc1f47532005-12-18 01:08:26 +01005848/* returns the pointer to an error in the replacement string, or NULL if OK */
5849char *chain_regex(struct hdr_exp **head, regex_t *preg, int action, char *replace) {
willy tarreaue39cd132005-12-17 13:00:18 +01005850 struct hdr_exp *exp;
5851
willy tarreauc1f47532005-12-18 01:08:26 +01005852 if (replace != NULL) {
5853 char *err;
5854 err = check_replace_string(replace);
5855 if (err)
5856 return err;
5857 }
5858
willy tarreaue39cd132005-12-17 13:00:18 +01005859 while (*head != NULL)
5860 head = &(*head)->next;
5861
5862 exp = calloc(1, sizeof(struct hdr_exp));
5863
5864 exp->preg = preg;
5865 exp->replace = replace;
5866 exp->action = action;
5867 *head = exp;
willy tarreauc1f47532005-12-18 01:08:26 +01005868
5869 return NULL;
willy tarreaue39cd132005-12-17 13:00:18 +01005870}
5871
willy tarreau9fe663a2005-12-17 13:02:59 +01005872
willy tarreau0f7af912005-12-17 12:21:26 +01005873/*
willy tarreau9fe663a2005-12-17 13:02:59 +01005874 * parse a line in a <global> section. Returns 0 if OK, -1 if error.
willy tarreau0f7af912005-12-17 12:21:26 +01005875 */
willy tarreau9fe663a2005-12-17 13:02:59 +01005876int cfg_parse_global(char *file, int linenum, char **args) {
willy tarreau0f7af912005-12-17 12:21:26 +01005877
willy tarreau9fe663a2005-12-17 13:02:59 +01005878 if (!strcmp(args[0], "global")) { /* new section */
5879 /* no option, nothing special to do */
5880 return 0;
5881 }
5882 else if (!strcmp(args[0], "daemon")) {
5883 global.mode |= MODE_DAEMON;
5884 }
5885 else if (!strcmp(args[0], "debug")) {
5886 global.mode |= MODE_DEBUG;
5887 }
willy tarreau64a3cc32005-12-18 01:13:11 +01005888 else if (!strcmp(args[0], "noepoll")) {
5889 cfg_polling_mechanism &= ~POLL_USE_EPOLL;
5890 }
5891 else if (!strcmp(args[0], "nopoll")) {
5892 cfg_polling_mechanism &= ~POLL_USE_POLL;
5893 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005894 else if (!strcmp(args[0], "quiet")) {
5895 global.mode |= MODE_QUIET;
5896 }
5897 else if (!strcmp(args[0], "stats")) {
5898 global.mode |= MODE_STATS;
5899 }
5900 else if (!strcmp(args[0], "uid")) {
5901 if (global.uid != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005902 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005903 return 0;
willy tarreau0f7af912005-12-17 12:21:26 +01005904 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005905 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005906 Alert("parsing [%s:%d] : '%s' expects an integer argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005907 return -1;
willy tarreau5cbea6f2005-12-17 12:48:26 +01005908 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005909 global.uid = atol(args[1]);
5910 }
5911 else if (!strcmp(args[0], "gid")) {
5912 if (global.gid != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005913 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005914 return 0;
willy tarreau0f7af912005-12-17 12:21:26 +01005915 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005916 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005917 Alert("parsing [%s:%d] : '%s' expects an integer argument.\n", file, linenum, args[0]);
willy tarreau0f7af912005-12-17 12:21:26 +01005918 return -1;
5919 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005920 global.gid = atol(args[1]);
5921 }
5922 else if (!strcmp(args[0], "nbproc")) {
5923 if (global.nbproc != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005924 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005925 return 0;
willy tarreau0f7af912005-12-17 12:21:26 +01005926 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005927 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005928 Alert("parsing [%s:%d] : '%s' expects an integer argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005929 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01005930 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005931 global.nbproc = atol(args[1]);
5932 }
5933 else if (!strcmp(args[0], "maxconn")) {
5934 if (global.maxconn != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005935 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005936 return 0;
willy tarreau0f7af912005-12-17 12:21:26 +01005937 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005938 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005939 Alert("parsing [%s:%d] : '%s' expects an integer argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005940 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01005941 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005942 global.maxconn = atol(args[1]);
5943 }
willy tarreaub1285d52005-12-18 01:20:14 +01005944 else if (!strcmp(args[0], "ulimit-n")) {
5945 if (global.rlimit_nofile != 0) {
5946 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n", file, linenum, args[0]);
5947 return 0;
5948 }
5949 if (*(args[1]) == 0) {
5950 Alert("parsing [%s:%d] : '%s' expects an integer argument.\n", file, linenum, args[0]);
5951 return -1;
5952 }
5953 global.rlimit_nofile = atol(args[1]);
5954 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005955 else if (!strcmp(args[0], "chroot")) {
5956 if (global.chroot != NULL) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005957 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005958 return 0;
5959 }
5960 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005961 Alert("parsing [%s:%d] : '%s' expects a directory as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005962 return -1;
5963 }
5964 global.chroot = strdup(args[1]);
5965 }
willy tarreaufe2c5c12005-12-17 14:14:34 +01005966 else if (!strcmp(args[0], "pidfile")) {
5967 if (global.pidfile != NULL) {
5968 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n", file, linenum, args[0]);
5969 return 0;
5970 }
5971 if (*(args[1]) == 0) {
5972 Alert("parsing [%s:%d] : '%s' expects a file name as an argument.\n", file, linenum, args[0]);
5973 return -1;
5974 }
5975 global.pidfile = strdup(args[1]);
5976 }
willy tarreau9fe663a2005-12-17 13:02:59 +01005977 else if (!strcmp(args[0], "log")) { /* syslog server address */
5978 struct sockaddr_in *sa;
willy tarreau8337c6b2005-12-17 13:41:01 +01005979 int facility, level;
willy tarreau9fe663a2005-12-17 13:02:59 +01005980
5981 if (*(args[1]) == 0 || *(args[2]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005982 Alert("parsing [%s:%d] : '%s' expects <address> and <facility> as arguments.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005983 return -1;
5984 }
5985
5986 for (facility = 0; facility < NB_LOG_FACILITIES; facility++)
5987 if (!strcmp(log_facilities[facility], args[2]))
5988 break;
5989
5990 if (facility >= NB_LOG_FACILITIES) {
willy tarreau036e1ce2005-12-17 13:46:33 +01005991 Alert("parsing [%s:%d] : unknown log facility '%s'\n", file, linenum, args[2]);
willy tarreau9fe663a2005-12-17 13:02:59 +01005992 exit(1);
5993 }
willy tarreau8337c6b2005-12-17 13:41:01 +01005994
5995 level = 7; /* max syslog level = debug */
5996 if (*(args[3])) {
5997 while (level >= 0 && strcmp(log_levels[level], args[3]))
5998 level--;
5999 if (level < 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006000 Alert("parsing [%s:%d] : unknown optional log level '%s'\n", file, linenum, args[3]);
willy tarreau8337c6b2005-12-17 13:41:01 +01006001 exit(1);
6002 }
6003 }
6004
willy tarreau9fe663a2005-12-17 13:02:59 +01006005 sa = str2sa(args[1]);
6006 if (!sa->sin_port)
6007 sa->sin_port = htons(SYSLOG_PORT);
6008
6009 if (global.logfac1 == -1) {
6010 global.logsrv1 = *sa;
6011 global.logfac1 = facility;
willy tarreau8337c6b2005-12-17 13:41:01 +01006012 global.loglev1 = level;
willy tarreau9fe663a2005-12-17 13:02:59 +01006013 }
6014 else if (global.logfac2 == -1) {
6015 global.logsrv2 = *sa;
6016 global.logfac2 = facility;
willy tarreau8337c6b2005-12-17 13:41:01 +01006017 global.loglev2 = level;
willy tarreau9fe663a2005-12-17 13:02:59 +01006018 }
6019 else {
6020 Alert("parsing [%s:%d] : too many syslog servers\n", file, linenum);
6021 return -1;
6022 }
6023
6024 }
6025 else {
willy tarreau036e1ce2005-12-17 13:46:33 +01006026 Alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], "global");
willy tarreau9fe663a2005-12-17 13:02:59 +01006027 return -1;
6028 }
6029 return 0;
6030}
6031
6032
willy tarreaua41a8b42005-12-17 14:02:24 +01006033void init_default_instance() {
6034 memset(&defproxy, 0, sizeof(defproxy));
6035 defproxy.mode = PR_MODE_TCP;
6036 defproxy.state = PR_STNEW;
6037 defproxy.maxconn = cfg_maxpconn;
6038 defproxy.conn_retries = CONN_RETRIES;
6039 defproxy.logfac1 = defproxy.logfac2 = -1; /* log disabled */
6040}
6041
willy tarreau9fe663a2005-12-17 13:02:59 +01006042/*
6043 * parse a line in a <listen> section. Returns 0 if OK, -1 if error.
6044 */
6045int cfg_parse_listen(char *file, int linenum, char **args) {
6046 static struct proxy *curproxy = NULL;
6047 struct server *newsrv = NULL;
willy tarreauc1f47532005-12-18 01:08:26 +01006048 char *err;
willy tarreau12350152005-12-18 01:03:27 +01006049 int rc;
willy tarreau9fe663a2005-12-17 13:02:59 +01006050
6051 if (!strcmp(args[0], "listen")) { /* new proxy */
willy tarreaua41a8b42005-12-17 14:02:24 +01006052 if (!*args[1]) {
6053 Alert("parsing [%s:%d] : '%s' expects an <id> argument and\n"
6054 " optionnally supports [addr1]:port1[-end1]{,[addr]:port[-end]}...\n",
willy tarreau036e1ce2005-12-17 13:46:33 +01006055 file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006056 return -1;
6057 }
6058
6059 if ((curproxy = (struct proxy *)calloc(1, sizeof(struct proxy))) == NULL) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006060 Alert("parsing [%s:%d] : out of memory.\n", file, linenum);
willy tarreau9fe663a2005-12-17 13:02:59 +01006061 return -1;
6062 }
6063 curproxy->next = proxy;
6064 proxy = curproxy;
6065 curproxy->id = strdup(args[1]);
willy tarreaud0fb4652005-12-18 01:32:04 +01006066
6067 /* parse the listener address if any */
6068 if (*args[2]) {
willy tarreaua41a8b42005-12-17 14:02:24 +01006069 curproxy->listen = str2listener(args[2], curproxy->listen);
willy tarreaud0fb4652005-12-18 01:32:04 +01006070 if (!curproxy->listen)
6071 return -1;
6072 }
willy tarreaua41a8b42005-12-17 14:02:24 +01006073
willy tarreau9fe663a2005-12-17 13:02:59 +01006074 /* set default values */
willy tarreaua41a8b42005-12-17 14:02:24 +01006075 curproxy->state = defproxy.state;
6076 curproxy->maxconn = defproxy.maxconn;
6077 curproxy->conn_retries = defproxy.conn_retries;
6078 curproxy->options = defproxy.options;
willy tarreaueedaa9f2005-12-17 14:08:03 +01006079
6080 if (defproxy.check_req)
6081 curproxy->check_req = strdup(defproxy.check_req);
6082 curproxy->check_len = defproxy.check_len;
6083
6084 if (defproxy.cookie_name)
6085 curproxy->cookie_name = strdup(defproxy.cookie_name);
6086 curproxy->cookie_len = defproxy.cookie_len;
6087
6088 if (defproxy.capture_name)
6089 curproxy->capture_name = strdup(defproxy.capture_name);
6090 curproxy->capture_namelen = defproxy.capture_namelen;
6091 curproxy->capture_len = defproxy.capture_len;
6092
6093 if (defproxy.errmsg.msg400)
6094 curproxy->errmsg.msg400 = strdup(defproxy.errmsg.msg400);
6095 curproxy->errmsg.len400 = defproxy.errmsg.len400;
6096
6097 if (defproxy.errmsg.msg403)
6098 curproxy->errmsg.msg403 = strdup(defproxy.errmsg.msg403);
6099 curproxy->errmsg.len403 = defproxy.errmsg.len403;
6100
6101 if (defproxy.errmsg.msg408)
6102 curproxy->errmsg.msg408 = strdup(defproxy.errmsg.msg408);
6103 curproxy->errmsg.len408 = defproxy.errmsg.len408;
6104
6105 if (defproxy.errmsg.msg500)
6106 curproxy->errmsg.msg500 = strdup(defproxy.errmsg.msg500);
6107 curproxy->errmsg.len500 = defproxy.errmsg.len500;
6108
6109 if (defproxy.errmsg.msg502)
6110 curproxy->errmsg.msg502 = strdup(defproxy.errmsg.msg502);
6111 curproxy->errmsg.len502 = defproxy.errmsg.len502;
6112
6113 if (defproxy.errmsg.msg503)
6114 curproxy->errmsg.msg503 = strdup(defproxy.errmsg.msg503);
6115 curproxy->errmsg.len503 = defproxy.errmsg.len503;
6116
6117 if (defproxy.errmsg.msg504)
6118 curproxy->errmsg.msg504 = strdup(defproxy.errmsg.msg504);
6119 curproxy->errmsg.len504 = defproxy.errmsg.len504;
6120
willy tarreaua41a8b42005-12-17 14:02:24 +01006121 curproxy->clitimeout = defproxy.clitimeout;
6122 curproxy->contimeout = defproxy.contimeout;
6123 curproxy->srvtimeout = defproxy.srvtimeout;
6124 curproxy->mode = defproxy.mode;
6125 curproxy->logfac1 = defproxy.logfac1;
6126 curproxy->logsrv1 = defproxy.logsrv1;
6127 curproxy->loglev1 = defproxy.loglev1;
6128 curproxy->logfac2 = defproxy.logfac2;
6129 curproxy->logsrv2 = defproxy.logsrv2;
6130 curproxy->loglev2 = defproxy.loglev2;
willy tarreau4302f492005-12-18 01:00:37 +01006131 curproxy->to_log = defproxy.to_log & ~LW_COOKIE & ~LW_REQHDR & ~ LW_RSPHDR;
willy tarreaua41a8b42005-12-17 14:02:24 +01006132 curproxy->grace = defproxy.grace;
6133 curproxy->source_addr = defproxy.source_addr;
willy tarreaub1285d52005-12-18 01:20:14 +01006134 curproxy->mon_net = defproxy.mon_net;
6135 curproxy->mon_mask = defproxy.mon_mask;
willy tarreaua41a8b42005-12-17 14:02:24 +01006136 return 0;
6137 }
6138 else if (!strcmp(args[0], "defaults")) { /* use this one to assign default values */
willy tarreaueedaa9f2005-12-17 14:08:03 +01006139 /* some variables may have already been initialized earlier */
6140 if (defproxy.check_req) free(defproxy.check_req);
6141 if (defproxy.cookie_name) free(defproxy.cookie_name);
6142 if (defproxy.capture_name) free(defproxy.capture_name);
6143 if (defproxy.errmsg.msg400) free(defproxy.errmsg.msg400);
6144 if (defproxy.errmsg.msg403) free(defproxy.errmsg.msg403);
6145 if (defproxy.errmsg.msg408) free(defproxy.errmsg.msg408);
6146 if (defproxy.errmsg.msg500) free(defproxy.errmsg.msg500);
6147 if (defproxy.errmsg.msg502) free(defproxy.errmsg.msg502);
6148 if (defproxy.errmsg.msg503) free(defproxy.errmsg.msg503);
6149 if (defproxy.errmsg.msg504) free(defproxy.errmsg.msg504);
6150
6151 init_default_instance();
willy tarreaua41a8b42005-12-17 14:02:24 +01006152 curproxy = &defproxy;
willy tarreau9fe663a2005-12-17 13:02:59 +01006153 return 0;
6154 }
6155 else if (curproxy == NULL) {
willy tarreaua41a8b42005-12-17 14:02:24 +01006156 Alert("parsing [%s:%d] : 'listen' or 'defaults' expected.\n", file, linenum);
willy tarreau9fe663a2005-12-17 13:02:59 +01006157 return -1;
6158 }
6159
willy tarreaua41a8b42005-12-17 14:02:24 +01006160 if (!strcmp(args[0], "bind")) { /* new listen addresses */
6161 if (curproxy == &defproxy) {
6162 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6163 return -1;
6164 }
6165
6166 if (strchr(args[1], ':') == NULL) {
6167 Alert("parsing [%s:%d] : '%s' expects [addr1]:port1[-end1]{,[addr]:port[-end]}... as arguments.\n",
6168 file, linenum, args[0]);
6169 return -1;
6170 }
6171 curproxy->listen = str2listener(args[1], curproxy->listen);
willy tarreaud0fb4652005-12-18 01:32:04 +01006172 if (!curproxy->listen)
6173 return -1;
willy tarreaua41a8b42005-12-17 14:02:24 +01006174 return 0;
6175 }
willy tarreaub1285d52005-12-18 01:20:14 +01006176 else if (!strcmp(args[0], "monitor-net")) { /* set the range of IPs to ignore */
6177 if (!*args[1] || !str2net(args[1], &curproxy->mon_net, &curproxy->mon_mask)) {
6178 Alert("parsing [%s:%d] : '%s' expects address[/mask].\n",
6179 file, linenum, args[0]);
6180 return -1;
6181 }
6182 /* flush useless bits */
6183 curproxy->mon_net.s_addr &= curproxy->mon_mask.s_addr;
6184 return 0;
6185 }
willy tarreaua41a8b42005-12-17 14:02:24 +01006186 else if (!strcmp(args[0], "mode")) { /* sets the proxy mode */
willy tarreau9fe663a2005-12-17 13:02:59 +01006187 if (!strcmp(args[1], "http")) curproxy->mode = PR_MODE_HTTP;
6188 else if (!strcmp(args[1], "tcp")) curproxy->mode = PR_MODE_TCP;
6189 else if (!strcmp(args[1], "health")) curproxy->mode = PR_MODE_HEALTH;
6190 else {
willy tarreau036e1ce2005-12-17 13:46:33 +01006191 Alert("parsing [%s:%d] : unknown proxy mode '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006192 return -1;
6193 }
6194 }
6195 else if (!strcmp(args[0], "disabled")) { /* disables this proxy */
6196 curproxy->state = PR_STDISABLED;
6197 }
willy tarreaua41a8b42005-12-17 14:02:24 +01006198 else if (!strcmp(args[0], "enabled")) { /* enables this proxy (used to revert a disabled default) */
6199 curproxy->state = PR_STNEW;
6200 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006201 else if (!strcmp(args[0], "cookie")) { /* cookie name */
6202 int cur_arg;
willy tarreaueedaa9f2005-12-17 14:08:03 +01006203// if (curproxy == &defproxy) {
6204// Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6205// return -1;
6206// }
willy tarreaua41a8b42005-12-17 14:02:24 +01006207
willy tarreau9fe663a2005-12-17 13:02:59 +01006208 if (curproxy->cookie_name != NULL) {
willy tarreaueedaa9f2005-12-17 14:08:03 +01006209// Alert("parsing [%s:%d] : cookie name already specified. Continuing.\n",
6210// file, linenum);
6211// return 0;
6212 free(curproxy->cookie_name);
willy tarreau9fe663a2005-12-17 13:02:59 +01006213 }
6214
6215 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006216 Alert("parsing [%s:%d] : '%s' expects <cookie_name> as argument.\n",
6217 file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006218 return -1;
6219 }
6220 curproxy->cookie_name = strdup(args[1]);
willy tarreau8337c6b2005-12-17 13:41:01 +01006221 curproxy->cookie_len = strlen(curproxy->cookie_name);
willy tarreau9fe663a2005-12-17 13:02:59 +01006222
6223 cur_arg = 2;
6224 while (*(args[cur_arg])) {
6225 if (!strcmp(args[cur_arg], "rewrite")) {
6226 curproxy->options |= PR_O_COOK_RW;
willy tarreau0f7af912005-12-17 12:21:26 +01006227 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006228 else if (!strcmp(args[cur_arg], "indirect")) {
6229 curproxy->options |= PR_O_COOK_IND;
willy tarreau0f7af912005-12-17 12:21:26 +01006230 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006231 else if (!strcmp(args[cur_arg], "insert")) {
6232 curproxy->options |= PR_O_COOK_INS;
willy tarreau0f7af912005-12-17 12:21:26 +01006233 }
willy tarreau240afa62005-12-17 13:14:35 +01006234 else if (!strcmp(args[cur_arg], "nocache")) {
6235 curproxy->options |= PR_O_COOK_NOC;
6236 }
willy tarreaucd878942005-12-17 13:27:43 +01006237 else if (!strcmp(args[cur_arg], "postonly")) {
6238 curproxy->options |= PR_O_COOK_POST;
6239 }
willy tarreau0174f312005-12-18 01:02:42 +01006240 else if (!strcmp(args[cur_arg], "prefix")) {
6241 curproxy->options |= PR_O_COOK_PFX;
6242 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006243 else {
willy tarreau0174f312005-12-18 01:02:42 +01006244 Alert("parsing [%s:%d] : '%s' supports 'rewrite', 'insert', 'prefix', 'indirect', 'nocache' and 'postonly' options.\n",
willy tarreau036e1ce2005-12-17 13:46:33 +01006245 file, linenum, args[0]);
willy tarreau0f7af912005-12-17 12:21:26 +01006246 return -1;
6247 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006248 cur_arg++;
6249 }
willy tarreau0174f312005-12-18 01:02:42 +01006250 if (!POWEROF2(curproxy->options & (PR_O_COOK_RW|PR_O_COOK_IND))) {
6251 Alert("parsing [%s:%d] : cookie 'rewrite' and 'indirect' modes are incompatible.\n",
6252 file, linenum);
6253 return -1;
6254 }
6255
6256 if (!POWEROF2(curproxy->options & (PR_O_COOK_RW|PR_O_COOK_INS|PR_O_COOK_PFX))) {
6257 Alert("parsing [%s:%d] : cookie 'rewrite', 'insert' and 'prefix' modes are incompatible.\n",
willy tarreau9fe663a2005-12-17 13:02:59 +01006258 file, linenum);
6259 return -1;
6260 }
willy tarreau12350152005-12-18 01:03:27 +01006261 }/* end else if (!strcmp(args[0], "cookie")) */
6262 else if (!strcmp(args[0], "appsession")) { /* cookie name */
6263// if (curproxy == &defproxy) {
6264// Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6265// return -1;
6266// }
6267
6268 if (curproxy->appsession_name != NULL) {
6269// Alert("parsing [%s:%d] : cookie name already specified. Continuing.\n",
6270// file, linenum);
6271// return 0;
6272 free(curproxy->appsession_name);
6273 }
6274
6275 if (*(args[5]) == 0) {
6276 Alert("parsing [%s:%d] : '%s' expects 'appsession' <cookie_name> 'len' <len> 'timeout' <timeout>.\n",
6277 file, linenum, args[0]);
6278 return -1;
6279 }
6280 have_appsession = 1;
6281 curproxy->appsession_name = strdup(args[1]);
6282 curproxy->appsession_name_len = strlen(curproxy->appsession_name);
6283 curproxy->appsession_len = atoi(args[3]);
6284 curproxy->appsession_timeout = atoi(args[5]);
6285 rc = chtbl_init(&(curproxy->htbl_proxy), TBLSIZ, hashpjw, match_str, destroy);
6286 if (rc) {
6287 Alert("Error Init Appsession Hashtable.\n");
6288 return -1;
6289 }
6290 } /* Url App Session */
willy tarreau4302f492005-12-18 01:00:37 +01006291 else if (!strcmp(args[0], "capture")) {
6292 if (!strcmp(args[1], "cookie")) { /* name of a cookie to capture */
6293 // if (curproxy == &defproxy) {
6294 // Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6295 // return -1;
6296 // }
willy tarreaua41a8b42005-12-17 14:02:24 +01006297
willy tarreau4302f492005-12-18 01:00:37 +01006298 if (curproxy->capture_name != NULL) {
6299 // Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n",
6300 // file, linenum, args[0]);
6301 // return 0;
6302 free(curproxy->capture_name);
6303 }
willy tarreau8337c6b2005-12-17 13:41:01 +01006304
willy tarreau4302f492005-12-18 01:00:37 +01006305 if (*(args[4]) == 0) {
6306 Alert("parsing [%s:%d] : '%s' expects 'cookie' <cookie_name> 'len' <len>.\n",
6307 file, linenum, args[0]);
6308 return -1;
6309 }
6310 curproxy->capture_name = strdup(args[2]);
6311 curproxy->capture_namelen = strlen(curproxy->capture_name);
6312 curproxy->capture_len = atol(args[4]);
6313 if (curproxy->capture_len >= CAPTURE_LEN) {
6314 Warning("parsing [%s:%d] : truncating capture length to %d bytes.\n",
6315 file, linenum, CAPTURE_LEN - 1);
6316 curproxy->capture_len = CAPTURE_LEN - 1;
6317 }
6318 curproxy->to_log |= LW_COOKIE;
6319 }
6320 else if (!strcmp(args[1], "request") && !strcmp(args[2], "header")) {
6321 struct cap_hdr *hdr;
6322
6323 if (curproxy == &defproxy) {
6324 Alert("parsing [%s:%d] : '%s %s' not allowed in 'defaults' section.\n", file, linenum, args[0], args[1]);
6325 return -1;
6326 }
6327
6328 if (*(args[3]) == 0 || strcmp(args[4], "len") != 0 || *(args[5]) == 0) {
6329 Alert("parsing [%s:%d] : '%s %s' expects 'header' <header_name> 'len' <len>.\n",
6330 file, linenum, args[0], args[1]);
6331 return -1;
6332 }
6333
6334 hdr = calloc(sizeof(struct cap_hdr), 1);
6335 hdr->next = curproxy->req_cap;
6336 hdr->name = strdup(args[3]);
6337 hdr->namelen = strlen(args[3]);
6338 hdr->len = atol(args[5]);
6339 hdr->index = curproxy->nb_req_cap++;
6340 curproxy->req_cap = hdr;
6341 curproxy->to_log |= LW_REQHDR;
6342 }
6343 else if (!strcmp(args[1], "response") && !strcmp(args[2], "header")) {
6344 struct cap_hdr *hdr;
6345
6346 if (curproxy == &defproxy) {
6347 Alert("parsing [%s:%d] : '%s %s' not allowed in 'defaults' section.\n", file, linenum, args[0], args[1]);
6348 return -1;
6349 }
6350
6351 if (*(args[3]) == 0 || strcmp(args[4], "len") != 0 || *(args[5]) == 0) {
6352 Alert("parsing [%s:%d] : '%s %s' expects 'header' <header_name> 'len' <len>.\n",
6353 file, linenum, args[0], args[1]);
6354 return -1;
6355 }
6356 hdr = calloc(sizeof(struct cap_hdr), 1);
6357 hdr->next = curproxy->rsp_cap;
6358 hdr->name = strdup(args[3]);
6359 hdr->namelen = strlen(args[3]);
6360 hdr->len = atol(args[5]);
6361 hdr->index = curproxy->nb_rsp_cap++;
6362 curproxy->rsp_cap = hdr;
6363 curproxy->to_log |= LW_RSPHDR;
6364 }
6365 else {
6366 Alert("parsing [%s:%d] : '%s' expects 'cookie' or 'request header' or 'response header'.\n",
willy tarreau036e1ce2005-12-17 13:46:33 +01006367 file, linenum, args[0]);
willy tarreau8337c6b2005-12-17 13:41:01 +01006368 return -1;
6369 }
willy tarreau8337c6b2005-12-17 13:41:01 +01006370 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006371 else if (!strcmp(args[0], "contimeout")) { /* connect timeout */
willy tarreaua41a8b42005-12-17 14:02:24 +01006372 if (curproxy->contimeout != defproxy.contimeout) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006373 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006374 return 0;
6375 }
6376 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006377 Alert("parsing [%s:%d] : '%s' expects an integer <time_in_ms> as argument.\n",
6378 file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006379 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01006380 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006381 curproxy->contimeout = atol(args[1]);
6382 }
6383 else if (!strcmp(args[0], "clitimeout")) { /* client timeout */
willy tarreaua41a8b42005-12-17 14:02:24 +01006384 if (curproxy->clitimeout != defproxy.clitimeout) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006385 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n",
6386 file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006387 return 0;
6388 }
6389 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006390 Alert("parsing [%s:%d] : '%s' expects an integer <time_in_ms> as argument.\n",
6391 file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006392 return -1;
6393 }
6394 curproxy->clitimeout = atol(args[1]);
6395 }
6396 else if (!strcmp(args[0], "srvtimeout")) { /* server timeout */
willy tarreaua41a8b42005-12-17 14:02:24 +01006397 if (curproxy->srvtimeout != defproxy.srvtimeout) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006398 Alert("parsing [%s:%d] : '%s' already specified. Continuing.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006399 return 0;
6400 }
6401 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006402 Alert("parsing [%s:%d] : '%s' expects an integer <time_in_ms> as argument.\n",
6403 file, linenum, args[0]);
willy tarreau0f7af912005-12-17 12:21:26 +01006404 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01006405 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006406 curproxy->srvtimeout = atol(args[1]);
6407 }
6408 else if (!strcmp(args[0], "retries")) { /* connection retries */
6409 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006410 Alert("parsing [%s:%d] : '%s' expects an integer argument (dispatch counts for one).\n",
6411 file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006412 return -1;
6413 }
6414 curproxy->conn_retries = atol(args[1]);
6415 }
6416 else if (!strcmp(args[0], "option")) {
6417 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006418 Alert("parsing [%s:%d] : '%s' expects an option name.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006419 return -1;
6420 }
6421 if (!strcmp(args[1], "redispatch"))
willy tarreau5cbea6f2005-12-17 12:48:26 +01006422 /* enable reconnections to dispatch */
6423 curproxy->options |= PR_O_REDISP;
willy tarreaua1598082005-12-17 13:08:06 +01006424#ifdef TPROXY
willy tarreau9fe663a2005-12-17 13:02:59 +01006425 else if (!strcmp(args[1], "transparent"))
willy tarreau5cbea6f2005-12-17 12:48:26 +01006426 /* enable transparent proxy connections */
6427 curproxy->options |= PR_O_TRANSP;
willy tarreau9fe663a2005-12-17 13:02:59 +01006428#endif
6429 else if (!strcmp(args[1], "keepalive"))
6430 /* enable keep-alive */
6431 curproxy->options |= PR_O_KEEPALIVE;
6432 else if (!strcmp(args[1], "forwardfor"))
6433 /* insert x-forwarded-for field */
6434 curproxy->options |= PR_O_FWDFOR;
willy tarreau25c4ea52005-12-18 00:49:49 +01006435 else if (!strcmp(args[1], "logasap"))
6436 /* log as soon as possible, without waiting for the session to complete */
6437 curproxy->options |= PR_O_LOGASAP;
6438 else if (!strcmp(args[1], "httpclose"))
6439 /* force connection: close in both directions in HTTP mode */
6440 curproxy->options |= PR_O_HTTP_CLOSE;
willy tarreau97f58572005-12-18 00:53:44 +01006441 else if (!strcmp(args[1], "checkcache"))
6442 /* require examination of cacheability of the 'set-cookie' field */
6443 curproxy->options |= PR_O_CHK_CACHE;
willy tarreauc1cae632005-12-17 14:12:23 +01006444 else if (!strcmp(args[1], "httplog"))
willy tarreau9fe663a2005-12-17 13:02:59 +01006445 /* generate a complete HTTP log */
willy tarreau25c4ea52005-12-18 00:49:49 +01006446 curproxy->to_log |= LW_DATE | LW_CLIP | LW_SVID | LW_REQ | LW_PXID | LW_RESP | LW_BYTES;
willy tarreauc1cae632005-12-17 14:12:23 +01006447 else if (!strcmp(args[1], "tcplog"))
6448 /* generate a detailed TCP log */
willy tarreau25c4ea52005-12-18 00:49:49 +01006449 curproxy->to_log |= LW_DATE | LW_CLIP | LW_SVID | LW_PXID | LW_BYTES;
willy tarreaua1598082005-12-17 13:08:06 +01006450 else if (!strcmp(args[1], "dontlognull")) {
6451 /* don't log empty requests */
6452 curproxy->options |= PR_O_NULLNOLOG;
willy tarreau5cbea6f2005-12-17 12:48:26 +01006453 }
willy tarreaub952e1d2005-12-18 01:31:20 +01006454 else if (!strcmp(args[1], "tcpka")) {
6455 /* enable TCP keep-alives on client and server sessions */
6456 curproxy->options |= PR_O_TCP_CLI_KA | PR_O_TCP_SRV_KA;
6457 }
6458 else if (!strcmp(args[1], "clitcpka")) {
6459 /* enable TCP keep-alives on client sessions */
6460 curproxy->options |= PR_O_TCP_CLI_KA;
6461 }
6462 else if (!strcmp(args[1], "srvtcpka")) {
6463 /* enable TCP keep-alives on server sessions */
6464 curproxy->options |= PR_O_TCP_SRV_KA;
6465 }
willy tarreaubc4e1fb2005-12-17 13:32:07 +01006466 else if (!strcmp(args[1], "httpchk")) {
6467 /* use HTTP request to check servers' health */
willy tarreaueedaa9f2005-12-17 14:08:03 +01006468 if (curproxy->check_req != NULL) {
6469 free(curproxy->check_req);
6470 }
willy tarreaubc4e1fb2005-12-17 13:32:07 +01006471 curproxy->options |= PR_O_HTTP_CHK;
willy tarreaueedaa9f2005-12-17 14:08:03 +01006472 if (!*args[2]) { /* no argument */
6473 curproxy->check_req = strdup(DEF_CHECK_REQ); /* default request */
6474 curproxy->check_len = strlen(DEF_CHECK_REQ);
6475 } else if (!*args[3]) { /* one argument : URI */
willy tarreau2f6ba652005-12-17 13:57:42 +01006476 int reqlen = strlen(args[2]) + strlen("OPTIONS / HTTP/1.0\r\n\r\n");
6477 curproxy->check_req = (char *)malloc(reqlen);
6478 curproxy->check_len = snprintf(curproxy->check_req, reqlen,
6479 "OPTIONS %s HTTP/1.0\r\n\r\n", args[2]); /* URI to use */
willy tarreaueedaa9f2005-12-17 14:08:03 +01006480 } else { /* more arguments : METHOD URI [HTTP_VER] */
6481 int reqlen = strlen(args[2]) + strlen(args[3]) + 3 + strlen("\r\n\r\n");
6482 if (*args[4])
6483 reqlen += strlen(args[4]);
6484 else
6485 reqlen += strlen("HTTP/1.0");
6486
6487 curproxy->check_req = (char *)malloc(reqlen);
6488 curproxy->check_len = snprintf(curproxy->check_req, reqlen,
6489 "%s %s %s\r\n\r\n", args[2], args[3], *args[4]?args[4]:"HTTP/1.0");
willy tarreau2f6ba652005-12-17 13:57:42 +01006490 }
willy tarreaubc4e1fb2005-12-17 13:32:07 +01006491 }
willy tarreau8337c6b2005-12-17 13:41:01 +01006492 else if (!strcmp(args[1], "persist")) {
6493 /* persist on using the server specified by the cookie, even when it's down */
6494 curproxy->options |= PR_O_PERSIST;
6495 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006496 else {
willy tarreau036e1ce2005-12-17 13:46:33 +01006497 Alert("parsing [%s:%d] : unknown option '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006498 return -1;
6499 }
6500 return 0;
6501 }
6502 else if (!strcmp(args[0], "redispatch") || !strcmp(args[0], "redisp")) {
6503 /* enable reconnections to dispatch */
6504 curproxy->options |= PR_O_REDISP;
6505 }
willy tarreaua1598082005-12-17 13:08:06 +01006506#ifdef TPROXY
willy tarreau9fe663a2005-12-17 13:02:59 +01006507 else if (!strcmp(args[0], "transparent")) {
6508 /* enable transparent proxy connections */
6509 curproxy->options |= PR_O_TRANSP;
6510 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01006511#endif
willy tarreau9fe663a2005-12-17 13:02:59 +01006512 else if (!strcmp(args[0], "maxconn")) { /* maxconn */
6513 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006514 Alert("parsing [%s:%d] : '%s' expects an integer argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006515 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01006516 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006517 curproxy->maxconn = atol(args[1]);
6518 }
6519 else if (!strcmp(args[0], "grace")) { /* grace time (ms) */
6520 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006521 Alert("parsing [%s:%d] : '%s' expects a time in milliseconds.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006522 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01006523 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006524 curproxy->grace = atol(args[1]);
6525 }
6526 else if (!strcmp(args[0], "dispatch")) { /* dispatch address */
willy tarreaua41a8b42005-12-17 14:02:24 +01006527 if (curproxy == &defproxy) {
6528 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6529 return -1;
6530 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006531 if (strchr(args[1], ':') == NULL) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006532 Alert("parsing [%s:%d] : '%s' expects <addr:port> as argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006533 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01006534 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006535 curproxy->dispatch_addr = *str2sa(args[1]);
6536 }
willy tarreau036e1ce2005-12-17 13:46:33 +01006537 else if (!strcmp(args[0], "balance")) { /* set balancing with optional algorithm */
willy tarreau9fe663a2005-12-17 13:02:59 +01006538 if (*(args[1])) {
6539 if (!strcmp(args[1], "roundrobin")) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01006540 curproxy->options |= PR_O_BALANCE_RR;
willy tarreau9fe663a2005-12-17 13:02:59 +01006541 }
6542 else {
willy tarreau036e1ce2005-12-17 13:46:33 +01006543 Alert("parsing [%s:%d] : '%s' only supports 'roundrobin' option.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006544 return -1;
6545 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01006546 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006547 else /* if no option is set, use round-robin by default */
6548 curproxy->options |= PR_O_BALANCE_RR;
6549 }
6550 else if (!strcmp(args[0], "server")) { /* server address */
6551 int cur_arg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006552 char *rport;
6553 char *raddr;
6554 short realport;
6555 int do_check;
6556
6557 if (curproxy == &defproxy) {
6558 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6559 return -1;
6560 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01006561
willy tarreaua41a8b42005-12-17 14:02:24 +01006562 if (!*args[2]) {
6563 Alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
willy tarreau036e1ce2005-12-17 13:46:33 +01006564 file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006565 return -1;
6566 }
6567 if ((newsrv = (struct server *)calloc(1, sizeof(struct server))) == NULL) {
6568 Alert("parsing [%s:%d] : out of memory.\n", file, linenum);
6569 return -1;
6570 }
willy tarreau0174f312005-12-18 01:02:42 +01006571
6572 if (curproxy->srv == NULL)
6573 curproxy->srv = newsrv;
6574 else
6575 curproxy->cursrv->next = newsrv;
6576 curproxy->cursrv = newsrv;
6577
6578 newsrv->next = NULL;
willy tarreau9fe663a2005-12-17 13:02:59 +01006579 newsrv->proxy = curproxy;
willy tarreaua41a8b42005-12-17 14:02:24 +01006580
6581 do_check = 0;
willy tarreau9fe663a2005-12-17 13:02:59 +01006582 newsrv->state = SRV_RUNNING; /* early server setup */
willy tarreaua41a8b42005-12-17 14:02:24 +01006583 newsrv->id = strdup(args[1]);
6584
6585 /* several ways to check the port component :
6586 * - IP => port=+0, relative
6587 * - IP: => port=+0, relative
6588 * - IP:N => port=N, absolute
6589 * - IP:+N => port=+N, relative
6590 * - IP:-N => port=-N, relative
6591 */
6592 raddr = strdup(args[2]);
6593 rport = strchr(raddr, ':');
6594 if (rport) {
6595 *rport++ = 0;
6596 realport = atol(rport);
6597 if (!isdigit((int)*rport))
6598 newsrv->state |= SRV_MAPPORTS;
6599 } else {
6600 realport = 0;
6601 newsrv->state |= SRV_MAPPORTS;
6602 }
6603
6604 newsrv->addr = *str2sa(raddr);
6605 newsrv->addr.sin_port = htons(realport);
6606 free(raddr);
6607
willy tarreau9fe663a2005-12-17 13:02:59 +01006608 newsrv->curfd = -1; /* no health-check in progress */
6609 newsrv->inter = DEF_CHKINTR;
6610 newsrv->rise = DEF_RISETIME;
6611 newsrv->fall = DEF_FALLTIME;
6612 newsrv->health = newsrv->rise; /* up, but will fall down at first failure */
6613 cur_arg = 3;
6614 while (*args[cur_arg]) {
6615 if (!strcmp(args[cur_arg], "cookie")) {
6616 newsrv->cookie = strdup(args[cur_arg + 1]);
6617 newsrv->cklen = strlen(args[cur_arg + 1]);
6618 cur_arg += 2;
willy tarreau0f7af912005-12-17 12:21:26 +01006619 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006620 else if (!strcmp(args[cur_arg], "rise")) {
6621 newsrv->rise = atol(args[cur_arg + 1]);
6622 newsrv->health = newsrv->rise;
6623 cur_arg += 2;
willy tarreau0f7af912005-12-17 12:21:26 +01006624 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006625 else if (!strcmp(args[cur_arg], "fall")) {
6626 newsrv->fall = atol(args[cur_arg + 1]);
6627 cur_arg += 2;
6628 }
6629 else if (!strcmp(args[cur_arg], "inter")) {
6630 newsrv->inter = atol(args[cur_arg + 1]);
6631 cur_arg += 2;
6632 }
willy tarreaua41a8b42005-12-17 14:02:24 +01006633 else if (!strcmp(args[cur_arg], "port")) {
6634 newsrv->check_port = atol(args[cur_arg + 1]);
6635 cur_arg += 2;
6636 }
willy tarreau8337c6b2005-12-17 13:41:01 +01006637 else if (!strcmp(args[cur_arg], "backup")) {
6638 newsrv->state |= SRV_BACKUP;
6639 cur_arg ++;
6640 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006641 else if (!strcmp(args[cur_arg], "check")) {
willy tarreaua41a8b42005-12-17 14:02:24 +01006642 do_check = 1;
willy tarreau9fe663a2005-12-17 13:02:59 +01006643 cur_arg += 1;
willy tarreau5cbea6f2005-12-17 12:48:26 +01006644 }
willy tarreau0174f312005-12-18 01:02:42 +01006645 else if (!strcmp(args[cur_arg], "source")) { /* address to which we bind when connecting */
6646 if (!*args[cur_arg + 1]) {
6647 Alert("parsing [%s:%d] : '%s' expects <addr>[:<port>] as argument.\n",
6648 file, linenum, "source");
6649 return -1;
6650 }
6651 newsrv->state |= SRV_BIND_SRC;
6652 newsrv->source_addr = *str2sa(args[cur_arg + 1]);
6653 cur_arg += 2;
6654 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006655 else {
willy tarreau0174f312005-12-18 01:02:42 +01006656 Alert("parsing [%s:%d] : server %s only supports options 'backup', 'cookie', 'check', 'inter', 'rise', 'fall', 'port' and 'source'.\n",
willy tarreaua41a8b42005-12-17 14:02:24 +01006657 file, linenum, newsrv->id);
6658 return -1;
6659 }
6660 }
6661
6662 if (do_check) {
6663 struct task *t;
6664
6665 if (!newsrv->check_port && !(newsrv->state & SRV_MAPPORTS))
6666 newsrv->check_port = realport; /* by default */
6667 if (!newsrv->check_port) {
6668 Alert("parsing [%s:%d] : server %s has neither service port nor check port. Check has been disabled.\n",
willy tarreau9fe663a2005-12-17 13:02:59 +01006669 file, linenum, newsrv->id);
willy tarreau0f7af912005-12-17 12:21:26 +01006670 return -1;
6671 }
willy tarreaua41a8b42005-12-17 14:02:24 +01006672
6673 if ((t = pool_alloc(task)) == NULL) {
6674 Alert("parsing [%s:%d] : out of memory.\n", file, linenum);
6675 return -1;
6676 }
6677
6678 t->next = t->prev = t->rqnext = NULL; /* task not in run queue yet */
6679 t->wq = LIST_HEAD(wait_queue); /* but already has a wait queue assigned */
6680 t->state = TASK_IDLE;
6681 t->process = process_chk;
6682 t->context = newsrv;
6683
6684 if (curproxy->state != PR_STDISABLED) {
6685 tv_delayfrom(&t->expire, &now, newsrv->inter); /* check this every ms */
6686 task_queue(t);
6687 task_wakeup(&rq, t);
6688 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006689 }
willy tarreaua41a8b42005-12-17 14:02:24 +01006690
willy tarreau9fe663a2005-12-17 13:02:59 +01006691 curproxy->nbservers++;
6692 }
6693 else if (!strcmp(args[0], "log")) { /* syslog server address */
6694 struct sockaddr_in *sa;
6695 int facility;
6696
6697 if (*(args[1]) && *(args[2]) == 0 && !strcmp(args[1], "global")) {
6698 curproxy->logfac1 = global.logfac1;
6699 curproxy->logsrv1 = global.logsrv1;
willy tarreau8337c6b2005-12-17 13:41:01 +01006700 curproxy->loglev1 = global.loglev1;
willy tarreau9fe663a2005-12-17 13:02:59 +01006701 curproxy->logfac2 = global.logfac2;
6702 curproxy->logsrv2 = global.logsrv2;
willy tarreau8337c6b2005-12-17 13:41:01 +01006703 curproxy->loglev2 = global.loglev2;
willy tarreau9fe663a2005-12-17 13:02:59 +01006704 }
6705 else if (*(args[1]) && *(args[2])) {
willy tarreau8337c6b2005-12-17 13:41:01 +01006706 int level;
6707
willy tarreau0f7af912005-12-17 12:21:26 +01006708 for (facility = 0; facility < NB_LOG_FACILITIES; facility++)
6709 if (!strcmp(log_facilities[facility], args[2]))
6710 break;
willy tarreau9fe663a2005-12-17 13:02:59 +01006711
willy tarreau0f7af912005-12-17 12:21:26 +01006712 if (facility >= NB_LOG_FACILITIES) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006713 Alert("parsing [%s:%d] : unknown log facility '%s'\n", file, linenum, args[2]);
willy tarreau0f7af912005-12-17 12:21:26 +01006714 exit(1);
6715 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006716
willy tarreau8337c6b2005-12-17 13:41:01 +01006717 level = 7; /* max syslog level = debug */
6718 if (*(args[3])) {
6719 while (level >= 0 && strcmp(log_levels[level], args[3]))
6720 level--;
6721 if (level < 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006722 Alert("parsing [%s:%d] : unknown optional log level '%s'\n", file, linenum, args[3]);
willy tarreau8337c6b2005-12-17 13:41:01 +01006723 exit(1);
6724 }
6725 }
6726
willy tarreau0f7af912005-12-17 12:21:26 +01006727 sa = str2sa(args[1]);
6728 if (!sa->sin_port)
6729 sa->sin_port = htons(SYSLOG_PORT);
willy tarreau9fe663a2005-12-17 13:02:59 +01006730
willy tarreau0f7af912005-12-17 12:21:26 +01006731 if (curproxy->logfac1 == -1) {
6732 curproxy->logsrv1 = *sa;
6733 curproxy->logfac1 = facility;
willy tarreau8337c6b2005-12-17 13:41:01 +01006734 curproxy->loglev1 = level;
willy tarreau0f7af912005-12-17 12:21:26 +01006735 }
6736 else if (curproxy->logfac2 == -1) {
6737 curproxy->logsrv2 = *sa;
6738 curproxy->logfac2 = facility;
willy tarreau8337c6b2005-12-17 13:41:01 +01006739 curproxy->loglev2 = level;
willy tarreau0f7af912005-12-17 12:21:26 +01006740 }
6741 else {
6742 Alert("parsing [%s:%d] : too many syslog servers\n", file, linenum);
willy tarreau9fe663a2005-12-17 13:02:59 +01006743 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01006744 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006745 }
6746 else {
willy tarreau036e1ce2005-12-17 13:46:33 +01006747 Alert("parsing [%s:%d] : 'log' expects either <address[:port]> and <facility> or 'global' as arguments.\n",
willy tarreau9fe663a2005-12-17 13:02:59 +01006748 file, linenum);
6749 return -1;
6750 }
6751 }
willy tarreaua1598082005-12-17 13:08:06 +01006752 else if (!strcmp(args[0], "source")) { /* address to which we bind when connecting */
willy tarreaua41a8b42005-12-17 14:02:24 +01006753 if (!*args[1]) {
6754 Alert("parsing [%s:%d] : '%s' expects <addr>[:<port>] as argument.\n",
willy tarreau036e1ce2005-12-17 13:46:33 +01006755 file, linenum, "source");
willy tarreaua1598082005-12-17 13:08:06 +01006756 return -1;
6757 }
6758
6759 curproxy->source_addr = *str2sa(args[1]);
6760 curproxy->options |= PR_O_BIND_SRC;
6761 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006762 else if (!strcmp(args[0], "cliexp") || !strcmp(args[0], "reqrep")) { /* replace request header from a regex */
6763 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006764 if (curproxy == &defproxy) {
6765 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6766 return -1;
6767 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006768
6769 if (*(args[1]) == 0 || *(args[2]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006770 Alert("parsing [%s:%d] : '%s' expects <search> and <replace> as arguments.\n",
6771 file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006772 return -1;
6773 }
6774
6775 preg = calloc(1, sizeof(regex_t));
6776 if (regcomp(preg, args[1], REG_EXTENDED) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006777 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006778 return -1;
6779 }
6780
willy tarreauc1f47532005-12-18 01:08:26 +01006781 err = chain_regex(&curproxy->req_exp, preg, ACT_REPLACE, strdup(args[2]));
6782 if (err) {
6783 Alert("parsing [%s:%d] : invalid character or unterminated sequence in replacement string near '%c'.\n",
6784 file, linenum, *err);
6785 return -1;
6786 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006787 }
6788 else if (!strcmp(args[0], "reqdel")) { /* delete request header from a regex */
6789 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006790 if (curproxy == &defproxy) {
6791 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6792 return -1;
6793 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006794
6795 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006796 Alert("parsing [%s:%d] : '%s' expects <regex> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006797 return -1;
6798 }
6799
6800 preg = calloc(1, sizeof(regex_t));
6801 if (regcomp(preg, args[1], REG_EXTENDED) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006802 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006803 return -1;
6804 }
6805
6806 chain_regex(&curproxy->req_exp, preg, ACT_REMOVE, NULL);
6807 }
6808 else if (!strcmp(args[0], "reqdeny")) { /* deny a request if a header matches this regex */
6809 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006810 if (curproxy == &defproxy) {
6811 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6812 return -1;
6813 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006814
6815 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006816 Alert("parsing [%s:%d] : '%s' expects <regex> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006817 return -1;
6818 }
6819
6820 preg = calloc(1, sizeof(regex_t));
6821 if (regcomp(preg, args[1], REG_EXTENDED) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006822 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006823 return -1;
6824 }
6825
6826 chain_regex(&curproxy->req_exp, preg, ACT_DENY, NULL);
6827 }
willy tarreau036e1ce2005-12-17 13:46:33 +01006828 else if (!strcmp(args[0], "reqpass")) { /* pass this header without allowing or denying the request */
6829 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006830 if (curproxy == &defproxy) {
6831 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6832 return -1;
6833 }
willy tarreau036e1ce2005-12-17 13:46:33 +01006834
6835 if (*(args[1]) == 0) {
6836 Alert("parsing [%s:%d] : '%s' expects <regex> as an argument.\n", file, linenum, args[0]);
6837 return -1;
6838 }
6839
6840 preg = calloc(1, sizeof(regex_t));
6841 if (regcomp(preg, args[1], REG_EXTENDED) != 0) {
6842 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
6843 return -1;
6844 }
6845
6846 chain_regex(&curproxy->req_exp, preg, ACT_PASS, NULL);
6847 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006848 else if (!strcmp(args[0], "reqallow")) { /* allow a request if a header matches this regex */
6849 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006850 if (curproxy == &defproxy) {
6851 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6852 return -1;
6853 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006854
6855 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006856 Alert("parsing [%s:%d] : '%s' expects <regex> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006857 return -1;
6858 }
6859
6860 preg = calloc(1, sizeof(regex_t));
6861 if (regcomp(preg, args[1], REG_EXTENDED) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006862 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006863 return -1;
6864 }
6865
6866 chain_regex(&curproxy->req_exp, preg, ACT_ALLOW, NULL);
6867 }
6868 else if (!strcmp(args[0], "reqirep")) { /* replace request header from a regex, ignoring case */
6869 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006870 if (curproxy == &defproxy) {
6871 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6872 return -1;
6873 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006874
6875 if (*(args[1]) == 0 || *(args[2]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006876 Alert("parsing [%s:%d] : '%s' expects <search> and <replace> as arguments.\n",
6877 file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006878 return -1;
6879 }
6880
6881 preg = calloc(1, sizeof(regex_t));
6882 if (regcomp(preg, args[1], REG_EXTENDED | REG_ICASE) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006883 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006884 return -1;
6885 }
6886
willy tarreauc1f47532005-12-18 01:08:26 +01006887 err = chain_regex(&curproxy->req_exp, preg, ACT_REPLACE, strdup(args[2]));
6888 if (err) {
6889 Alert("parsing [%s:%d] : invalid character or unterminated sequence in replacement string near '%c'.\n",
6890 file, linenum, *err);
6891 return -1;
6892 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006893 }
6894 else if (!strcmp(args[0], "reqidel")) { /* delete request header from a regex ignoring case */
6895 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006896 if (curproxy == &defproxy) {
6897 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6898 return -1;
6899 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006900
6901 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006902 Alert("parsing [%s:%d] : '%s' expects <regex> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006903 return -1;
6904 }
6905
6906 preg = calloc(1, sizeof(regex_t));
6907 if (regcomp(preg, args[1], REG_EXTENDED | REG_ICASE) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006908 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006909 return -1;
6910 }
6911
6912 chain_regex(&curproxy->req_exp, preg, ACT_REMOVE, NULL);
6913 }
6914 else if (!strcmp(args[0], "reqideny")) { /* deny a request if a header matches this regex ignoring case */
6915 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006916 if (curproxy == &defproxy) {
6917 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6918 return -1;
6919 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006920
6921 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006922 Alert("parsing [%s:%d] : '%s' expects <regex> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006923 return -1;
6924 }
6925
6926 preg = calloc(1, sizeof(regex_t));
6927 if (regcomp(preg, args[1], REG_EXTENDED | REG_ICASE) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006928 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006929 return -1;
6930 }
6931
6932 chain_regex(&curproxy->req_exp, preg, ACT_DENY, NULL);
6933 }
willy tarreau036e1ce2005-12-17 13:46:33 +01006934 else if (!strcmp(args[0], "reqipass")) { /* pass this header without allowing or denying the request */
6935 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006936 if (curproxy == &defproxy) {
6937 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6938 return -1;
6939 }
willy tarreau036e1ce2005-12-17 13:46:33 +01006940
6941 if (*(args[1]) == 0) {
6942 Alert("parsing [%s:%d] : '%s' expects <regex> as an argument.\n", file, linenum, args[0]);
6943 return -1;
6944 }
6945
6946 preg = calloc(1, sizeof(regex_t));
6947 if (regcomp(preg, args[1], REG_EXTENDED | REG_ICASE) != 0) {
6948 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
6949 return -1;
6950 }
6951
6952 chain_regex(&curproxy->req_exp, preg, ACT_PASS, NULL);
6953 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006954 else if (!strcmp(args[0], "reqiallow")) { /* allow a request if a header matches this regex ignoring case */
6955 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01006956 if (curproxy == &defproxy) {
6957 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6958 return -1;
6959 }
willy tarreau9fe663a2005-12-17 13:02:59 +01006960
6961 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006962 Alert("parsing [%s:%d] : '%s' expects <regex> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006963 return -1;
6964 }
6965
6966 preg = calloc(1, sizeof(regex_t));
6967 if (regcomp(preg, args[1], REG_EXTENDED | REG_ICASE) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006968 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006969 return -1;
6970 }
6971
6972 chain_regex(&curproxy->req_exp, preg, ACT_ALLOW, NULL);
6973 }
6974 else if (!strcmp(args[0], "reqadd")) { /* add request header */
willy tarreaua41a8b42005-12-17 14:02:24 +01006975 if (curproxy == &defproxy) {
6976 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
6977 return -1;
6978 }
6979
willy tarreau9fe663a2005-12-17 13:02:59 +01006980 if (curproxy->nb_reqadd >= MAX_NEWHDR) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006981 Alert("parsing [%s:%d] : too many '%s'. Continuing.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006982 return 0;
6983 }
6984
6985 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01006986 Alert("parsing [%s:%d] : '%s' expects <header> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01006987 return -1;
6988 }
6989
willy tarreau4302f492005-12-18 01:00:37 +01006990 curproxy->req_add[curproxy->nb_reqadd++] = strdup(args[1]);
6991 }
6992 else if (!strcmp(args[0], "srvexp") || !strcmp(args[0], "rsprep")) { /* replace response header from a regex */
6993 regex_t *preg;
6994
6995 if (*(args[1]) == 0 || *(args[2]) == 0) {
6996 Alert("parsing [%s:%d] : '%s' expects <search> and <replace> as arguments.\n",
6997 file, linenum, args[0]);
6998 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01006999 }
willy tarreau4302f492005-12-18 01:00:37 +01007000
7001 preg = calloc(1, sizeof(regex_t));
7002 if (regcomp(preg, args[1], REG_EXTENDED) != 0) {
7003 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
7004 return -1;
willy tarreau9fe663a2005-12-17 13:02:59 +01007005 }
willy tarreau4302f492005-12-18 01:00:37 +01007006
willy tarreauc1f47532005-12-18 01:08:26 +01007007 err = chain_regex(&curproxy->rsp_exp, preg, ACT_REPLACE, strdup(args[2]));
7008 if (err) {
7009 Alert("parsing [%s:%d] : invalid character or unterminated sequence in replacement string near '%c'.\n",
7010 file, linenum, *err);
7011 return -1;
7012 }
willy tarreau4302f492005-12-18 01:00:37 +01007013 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007014 else if (!strcmp(args[0], "rspdel")) { /* delete response header from a regex */
7015 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01007016 if (curproxy == &defproxy) {
7017 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
7018 return -1;
7019 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007020
7021 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01007022 Alert("parsing [%s:%d] : '%s' expects <search> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01007023 return -1;
7024 }
willy tarreaue39cd132005-12-17 13:00:18 +01007025
willy tarreau9fe663a2005-12-17 13:02:59 +01007026 preg = calloc(1, sizeof(regex_t));
7027 if (regcomp(preg, args[1], REG_EXTENDED) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01007028 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01007029 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01007030 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007031
willy tarreauc1f47532005-12-18 01:08:26 +01007032 err = chain_regex(&curproxy->rsp_exp, preg, ACT_REMOVE, strdup(args[2]));
7033 if (err) {
7034 Alert("parsing [%s:%d] : invalid character or unterminated sequence in replacement string near '%c'.\n",
7035 file, linenum, *err);
7036 return -1;
7037 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007038 }
willy tarreau982249e2005-12-18 00:57:06 +01007039 else if (!strcmp(args[0], "rspdeny")) { /* block response header from a regex */
7040 regex_t *preg;
7041 if (curproxy == &defproxy) {
7042 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
7043 return -1;
7044 }
7045
7046 if (*(args[1]) == 0) {
7047 Alert("parsing [%s:%d] : '%s' expects <search> as an argument.\n", file, linenum, args[0]);
7048 return -1;
7049 }
7050
7051 preg = calloc(1, sizeof(regex_t));
7052 if (regcomp(preg, args[1], REG_EXTENDED) != 0) {
7053 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
7054 return -1;
7055 }
7056
willy tarreauc1f47532005-12-18 01:08:26 +01007057 err = chain_regex(&curproxy->rsp_exp, preg, ACT_DENY, strdup(args[2]));
7058 if (err) {
7059 Alert("parsing [%s:%d] : invalid character or unterminated sequence in replacement string near '%c'.\n",
7060 file, linenum, *err);
7061 return -1;
7062 }
willy tarreau982249e2005-12-18 00:57:06 +01007063 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007064 else if (!strcmp(args[0], "rspirep")) { /* replace response header from a regex ignoring case */
willy tarreaua41a8b42005-12-17 14:02:24 +01007065 regex_t *preg;
7066 if (curproxy == &defproxy) {
7067 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
7068 return -1;
7069 }
willy tarreaue39cd132005-12-17 13:00:18 +01007070
willy tarreaua41a8b42005-12-17 14:02:24 +01007071 if (*(args[1]) == 0 || *(args[2]) == 0) {
7072 Alert("parsing [%s:%d] : '%s' expects <search> and <replace> as arguments.\n",
7073 file, linenum, args[0]);
7074 return -1;
7075 }
willy tarreaue39cd132005-12-17 13:00:18 +01007076
willy tarreaua41a8b42005-12-17 14:02:24 +01007077 preg = calloc(1, sizeof(regex_t));
7078 if (regcomp(preg, args[1], REG_EXTENDED | REG_ICASE) != 0) {
7079 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
7080 return -1;
willy tarreau9fe663a2005-12-17 13:02:59 +01007081 }
willy tarreaua41a8b42005-12-17 14:02:24 +01007082
willy tarreauc1f47532005-12-18 01:08:26 +01007083 err = chain_regex(&curproxy->rsp_exp, preg, ACT_REPLACE, strdup(args[2]));
7084 if (err) {
7085 Alert("parsing [%s:%d] : invalid character or unterminated sequence in replacement string near '%c'.\n",
7086 file, linenum, *err);
7087 return -1;
7088 }
willy tarreaua41a8b42005-12-17 14:02:24 +01007089 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007090 else if (!strcmp(args[0], "rspidel")) { /* delete response header from a regex ignoring case */
7091 regex_t *preg;
willy tarreaua41a8b42005-12-17 14:02:24 +01007092 if (curproxy == &defproxy) {
7093 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
7094 return -1;
7095 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007096
7097 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01007098 Alert("parsing [%s:%d] : '%s' expects <search> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01007099 return -1;
7100 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01007101
willy tarreau9fe663a2005-12-17 13:02:59 +01007102 preg = calloc(1, sizeof(regex_t));
7103 if (regcomp(preg, args[1], REG_EXTENDED | REG_ICASE) != 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01007104 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
willy tarreau9fe663a2005-12-17 13:02:59 +01007105 return -1;
willy tarreaue39cd132005-12-17 13:00:18 +01007106 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007107
willy tarreauc1f47532005-12-18 01:08:26 +01007108 err = chain_regex(&curproxy->rsp_exp, preg, ACT_REMOVE, strdup(args[2]));
7109 if (err) {
7110 Alert("parsing [%s:%d] : invalid character or unterminated sequence in replacement string near '%c'.\n",
7111 file, linenum, *err);
7112 return -1;
7113 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007114 }
willy tarreau982249e2005-12-18 00:57:06 +01007115 else if (!strcmp(args[0], "rspideny")) { /* block response header from a regex ignoring case */
7116 regex_t *preg;
7117 if (curproxy == &defproxy) {
7118 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
7119 return -1;
7120 }
7121
7122 if (*(args[1]) == 0) {
7123 Alert("parsing [%s:%d] : '%s' expects <search> as an argument.\n", file, linenum, args[0]);
7124 return -1;
7125 }
7126
7127 preg = calloc(1, sizeof(regex_t));
7128 if (regcomp(preg, args[1], REG_EXTENDED | REG_ICASE) != 0) {
7129 Alert("parsing [%s:%d] : bad regular expression '%s'.\n", file, linenum, args[1]);
7130 return -1;
7131 }
7132
willy tarreauc1f47532005-12-18 01:08:26 +01007133 err = chain_regex(&curproxy->rsp_exp, preg, ACT_DENY, strdup(args[2]));
7134 if (err) {
7135 Alert("parsing [%s:%d] : invalid character or unterminated sequence in replacement string near '%c'.\n",
7136 file, linenum, *err);
7137 return -1;
7138 }
willy tarreau982249e2005-12-18 00:57:06 +01007139 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007140 else if (!strcmp(args[0], "rspadd")) { /* add response header */
willy tarreaua41a8b42005-12-17 14:02:24 +01007141 if (curproxy == &defproxy) {
7142 Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
7143 return -1;
7144 }
7145
willy tarreau9fe663a2005-12-17 13:02:59 +01007146 if (curproxy->nb_rspadd >= MAX_NEWHDR) {
willy tarreau036e1ce2005-12-17 13:46:33 +01007147 Alert("parsing [%s:%d] : too many '%s'. Continuing.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01007148 return 0;
7149 }
7150
7151 if (*(args[1]) == 0) {
willy tarreau036e1ce2005-12-17 13:46:33 +01007152 Alert("parsing [%s:%d] : '%s' expects <header> as an argument.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01007153 return -1;
7154 }
7155
7156 curproxy->rsp_add[curproxy->nb_rspadd++] = strdup(args[1]);
7157 }
willy tarreauc1f47532005-12-18 01:08:26 +01007158 else if (!strcmp(args[0], "errorloc") ||
7159 !strcmp(args[0], "errorloc302") ||
7160 !strcmp(args[0], "errorloc303")) { /* error location */
7161 int errnum, errlen;
willy tarreau8337c6b2005-12-17 13:41:01 +01007162 char *err;
7163
willy tarreaueedaa9f2005-12-17 14:08:03 +01007164 // if (curproxy == &defproxy) {
7165 // Alert("parsing [%s:%d] : '%s' not allowed in 'defaults' section.\n", file, linenum, args[0]);
7166 // return -1;
7167 // }
willy tarreaua41a8b42005-12-17 14:02:24 +01007168
willy tarreau8337c6b2005-12-17 13:41:01 +01007169 if (*(args[2]) == 0) {
7170 Alert("parsing [%s:%d] : <errorloc> expects <error> and <url> as arguments.\n", file, linenum);
7171 return -1;
7172 }
7173
7174 errnum = atol(args[1]);
willy tarreauc1f47532005-12-18 01:08:26 +01007175 if (!strcmp(args[0], "errorloc303")) {
7176 err = malloc(strlen(HTTP_303) + strlen(args[2]) + 5);
7177 errlen = sprintf(err, "%s%s\r\n\r\n", HTTP_303, args[2]);
7178 } else {
7179 err = malloc(strlen(HTTP_302) + strlen(args[2]) + 5);
7180 errlen = sprintf(err, "%s%s\r\n\r\n", HTTP_302, args[2]);
7181 }
willy tarreau8337c6b2005-12-17 13:41:01 +01007182
7183 if (errnum == 400) {
7184 if (curproxy->errmsg.msg400) {
willy tarreaueedaa9f2005-12-17 14:08:03 +01007185 //Warning("parsing [%s:%d] : error %d already defined.\n", file, linenum, errnum);
willy tarreau8337c6b2005-12-17 13:41:01 +01007186 free(curproxy->errmsg.msg400);
7187 }
7188 curproxy->errmsg.msg400 = err;
willy tarreauc1f47532005-12-18 01:08:26 +01007189 curproxy->errmsg.len400 = errlen;
willy tarreau8337c6b2005-12-17 13:41:01 +01007190 }
7191 else if (errnum == 403) {
7192 if (curproxy->errmsg.msg403) {
willy tarreaueedaa9f2005-12-17 14:08:03 +01007193 //Warning("parsing [%s:%d] : error %d already defined.\n", file, linenum, errnum);
willy tarreau8337c6b2005-12-17 13:41:01 +01007194 free(curproxy->errmsg.msg403);
7195 }
7196 curproxy->errmsg.msg403 = err;
willy tarreauc1f47532005-12-18 01:08:26 +01007197 curproxy->errmsg.len403 = errlen;
willy tarreau8337c6b2005-12-17 13:41:01 +01007198 }
7199 else if (errnum == 408) {
7200 if (curproxy->errmsg.msg408) {
willy tarreaueedaa9f2005-12-17 14:08:03 +01007201 //Warning("parsing [%s:%d] : error %d already defined.\n", file, linenum, errnum);
willy tarreau8337c6b2005-12-17 13:41:01 +01007202 free(curproxy->errmsg.msg408);
7203 }
7204 curproxy->errmsg.msg408 = err;
willy tarreauc1f47532005-12-18 01:08:26 +01007205 curproxy->errmsg.len408 = errlen;
willy tarreau8337c6b2005-12-17 13:41:01 +01007206 }
7207 else if (errnum == 500) {
7208 if (curproxy->errmsg.msg500) {
willy tarreaueedaa9f2005-12-17 14:08:03 +01007209 //Warning("parsing [%s:%d] : error %d already defined.\n", file, linenum, errnum);
willy tarreau8337c6b2005-12-17 13:41:01 +01007210 free(curproxy->errmsg.msg500);
7211 }
7212 curproxy->errmsg.msg500 = err;
willy tarreauc1f47532005-12-18 01:08:26 +01007213 curproxy->errmsg.len500 = errlen;
willy tarreau8337c6b2005-12-17 13:41:01 +01007214 }
7215 else if (errnum == 502) {
7216 if (curproxy->errmsg.msg502) {
willy tarreaueedaa9f2005-12-17 14:08:03 +01007217 //Warning("parsing [%s:%d] : error %d already defined.\n", file, linenum, errnum);
willy tarreau8337c6b2005-12-17 13:41:01 +01007218 free(curproxy->errmsg.msg502);
7219 }
7220 curproxy->errmsg.msg502 = err;
willy tarreauc1f47532005-12-18 01:08:26 +01007221 curproxy->errmsg.len502 = errlen;
willy tarreau8337c6b2005-12-17 13:41:01 +01007222 }
7223 else if (errnum == 503) {
7224 if (curproxy->errmsg.msg503) {
willy tarreaueedaa9f2005-12-17 14:08:03 +01007225 //Warning("parsing [%s:%d] : error %d already defined.\n", file, linenum, errnum);
willy tarreau8337c6b2005-12-17 13:41:01 +01007226 free(curproxy->errmsg.msg503);
7227 }
7228 curproxy->errmsg.msg503 = err;
willy tarreauc1f47532005-12-18 01:08:26 +01007229 curproxy->errmsg.len503 = errlen;
willy tarreau8337c6b2005-12-17 13:41:01 +01007230 }
7231 else if (errnum == 504) {
7232 if (curproxy->errmsg.msg504) {
willy tarreaueedaa9f2005-12-17 14:08:03 +01007233 //Warning("parsing [%s:%d] : error %d already defined.\n", file, linenum, errnum);
willy tarreau8337c6b2005-12-17 13:41:01 +01007234 free(curproxy->errmsg.msg504);
7235 }
7236 curproxy->errmsg.msg504 = err;
willy tarreauc1f47532005-12-18 01:08:26 +01007237 curproxy->errmsg.len504 = errlen;
willy tarreau8337c6b2005-12-17 13:41:01 +01007238 }
7239 else {
7240 Warning("parsing [%s:%d] : error %d relocation will be ignored.\n", file, linenum, errnum);
7241 free(err);
7242 }
7243 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007244 else {
willy tarreau036e1ce2005-12-17 13:46:33 +01007245 Alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], "listen");
willy tarreau9fe663a2005-12-17 13:02:59 +01007246 return -1;
7247 }
7248 return 0;
7249}
willy tarreaue39cd132005-12-17 13:00:18 +01007250
willy tarreau5cbea6f2005-12-17 12:48:26 +01007251
willy tarreau9fe663a2005-12-17 13:02:59 +01007252/*
7253 * This function reads and parses the configuration file given in the argument.
7254 * returns 0 if OK, -1 if error.
7255 */
7256int readcfgfile(char *file) {
7257 char thisline[256];
7258 char *line;
7259 FILE *f;
7260 int linenum = 0;
7261 char *end;
7262 char *args[MAX_LINE_ARGS];
7263 int arg;
7264 int cfgerr = 0;
7265 int confsect = CFG_NONE;
willy tarreaue39cd132005-12-17 13:00:18 +01007266
willy tarreau9fe663a2005-12-17 13:02:59 +01007267 struct proxy *curproxy = NULL;
7268 struct server *newsrv = NULL;
willy tarreaue39cd132005-12-17 13:00:18 +01007269
willy tarreau9fe663a2005-12-17 13:02:59 +01007270 if ((f=fopen(file,"r")) == NULL)
7271 return -1;
willy tarreaue39cd132005-12-17 13:00:18 +01007272
willy tarreaueedaa9f2005-12-17 14:08:03 +01007273 init_default_instance();
7274
willy tarreau9fe663a2005-12-17 13:02:59 +01007275 while (fgets(line = thisline, sizeof(thisline), f) != NULL) {
7276 linenum++;
willy tarreau5cbea6f2005-12-17 12:48:26 +01007277
willy tarreau9fe663a2005-12-17 13:02:59 +01007278 end = line + strlen(line);
willy tarreau5cbea6f2005-12-17 12:48:26 +01007279
willy tarreau9fe663a2005-12-17 13:02:59 +01007280 /* skip leading spaces */
willy tarreauc29948c2005-12-17 13:10:27 +01007281 while (isspace((int)*line))
willy tarreau9fe663a2005-12-17 13:02:59 +01007282 line++;
7283
7284 arg = 0;
7285 args[arg] = line;
willy tarreau0f7af912005-12-17 12:21:26 +01007286
willy tarreau9fe663a2005-12-17 13:02:59 +01007287 while (*line && arg < MAX_LINE_ARGS) {
7288 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
7289 * C equivalent value. Other combinations left unchanged (eg: \1).
7290 */
7291 if (*line == '\\') {
7292 int skip = 0;
7293 if (line[1] == ' ' || line[1] == '\\' || line[1] == '#') {
7294 *line = line[1];
7295 skip = 1;
7296 }
7297 else if (line[1] == 'r') {
7298 *line = '\r';
7299 skip = 1;
7300 }
7301 else if (line[1] == 'n') {
7302 *line = '\n';
7303 skip = 1;
7304 }
7305 else if (line[1] == 't') {
7306 *line = '\t';
7307 skip = 1;
7308 }
willy tarreauc1f47532005-12-18 01:08:26 +01007309 else if (line[1] == 'x') {
7310 if ((line + 3 < end ) && ishex(line[2]) && ishex(line[3])) {
7311 unsigned char hex1, hex2;
7312 hex1 = toupper(line[2]) - '0';
7313 hex2 = toupper(line[3]) - '0';
7314 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
7315 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
7316 *line = (hex1<<4) + hex2;
7317 skip = 3;
7318 }
7319 else {
7320 Alert("parsing [%s:%d] : invalid or incomplete '\\x' sequence in '%s'.\n", file, linenum, args[0]);
7321 return -1;
7322 }
7323 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007324 if (skip) {
7325 memmove(line + 1, line + 1 + skip, end - (line + skip + 1));
7326 end -= skip;
7327 }
7328 line++;
willy tarreau0f7af912005-12-17 12:21:26 +01007329 }
willy tarreaua1598082005-12-17 13:08:06 +01007330 else if (*line == '#' || *line == '\n' || *line == '\r') {
7331 /* end of string, end of loop */
7332 *line = 0;
7333 break;
7334 }
willy tarreauc29948c2005-12-17 13:10:27 +01007335 else if (isspace((int)*line)) {
willy tarreau9fe663a2005-12-17 13:02:59 +01007336 /* a non-escaped space is an argument separator */
willy tarreaua1598082005-12-17 13:08:06 +01007337 *line++ = 0;
willy tarreauc29948c2005-12-17 13:10:27 +01007338 while (isspace((int)*line))
willy tarreaua1598082005-12-17 13:08:06 +01007339 line++;
7340 args[++arg] = line;
7341 }
7342 else {
7343 line++;
willy tarreau0f7af912005-12-17 12:21:26 +01007344 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01007345 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01007346
willy tarreau9fe663a2005-12-17 13:02:59 +01007347 /* empty line */
7348 if (!**args)
7349 continue;
willy tarreaue39cd132005-12-17 13:00:18 +01007350
willy tarreau9fe663a2005-12-17 13:02:59 +01007351 /* zero out remaining args */
7352 while (++arg < MAX_LINE_ARGS) {
7353 args[arg] = line;
willy tarreau5cbea6f2005-12-17 12:48:26 +01007354 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01007355
willy tarreaua41a8b42005-12-17 14:02:24 +01007356 if (!strcmp(args[0], "listen") || !strcmp(args[0], "defaults")) /* new proxy */
willy tarreau9fe663a2005-12-17 13:02:59 +01007357 confsect = CFG_LISTEN;
7358 else if (!strcmp(args[0], "global")) /* global config */
7359 confsect = CFG_GLOBAL;
7360 /* else it's a section keyword */
willy tarreau5cbea6f2005-12-17 12:48:26 +01007361
willy tarreau9fe663a2005-12-17 13:02:59 +01007362 switch (confsect) {
7363 case CFG_LISTEN:
7364 if (cfg_parse_listen(file, linenum, args) < 0)
7365 return -1;
7366 break;
7367 case CFG_GLOBAL:
7368 if (cfg_parse_global(file, linenum, args) < 0)
7369 return -1;
7370 break;
7371 default:
willy tarreau036e1ce2005-12-17 13:46:33 +01007372 Alert("parsing [%s:%d] : unknown keyword '%s' out of section.\n", file, linenum, args[0]);
willy tarreau9fe663a2005-12-17 13:02:59 +01007373 return -1;
willy tarreau0f7af912005-12-17 12:21:26 +01007374 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007375
7376
willy tarreau0f7af912005-12-17 12:21:26 +01007377 }
7378 fclose(f);
7379
7380 /*
7381 * Now, check for the integrity of all that we have collected.
7382 */
7383
7384 if ((curproxy = proxy) == NULL) {
7385 Alert("parsing %s : no <listen> line. Nothing to do !\n",
7386 file);
7387 return -1;
7388 }
7389
7390 while (curproxy != NULL) {
willy tarreau0174f312005-12-18 01:02:42 +01007391 curproxy->cursrv = NULL;
willy tarreauef900ab2005-12-17 12:52:52 +01007392 if (curproxy->state == PR_STDISABLED) {
7393 curproxy = curproxy->next;
7394 continue;
7395 }
willy tarreaud0fb4652005-12-18 01:32:04 +01007396
7397 if (curproxy->listen == NULL) {
7398 Alert("parsing %s : listener %s has no listen address. Please either specify a valid address on the <listen> line, or use the <bind> keyword.\n", file, curproxy->id);
7399 cfgerr++;
7400 }
7401 else if ((curproxy->mode != PR_MODE_HEALTH) &&
willy tarreau5cbea6f2005-12-17 12:48:26 +01007402 !(curproxy->options & (PR_O_TRANSP | PR_O_BALANCE)) &&
willy tarreaua1598082005-12-17 13:08:06 +01007403 (*(int *)&curproxy->dispatch_addr.sin_addr == 0)) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01007404 Alert("parsing %s : listener %s has no dispatch address and is not in transparent or balance mode.\n",
7405 file, curproxy->id);
7406 cfgerr++;
7407 }
7408 else if ((curproxy->mode != PR_MODE_HEALTH) && (curproxy->options & PR_O_BALANCE)) {
7409 if (curproxy->options & PR_O_TRANSP) {
7410 Alert("parsing %s : listener %s cannot use both transparent and balance mode.\n",
7411 file, curproxy->id);
7412 cfgerr++;
7413 }
7414 else if (curproxy->srv == NULL) {
7415 Alert("parsing %s : listener %s needs at least 1 server in balance mode.\n",
7416 file, curproxy->id);
7417 cfgerr++;
7418 }
willy tarreaua1598082005-12-17 13:08:06 +01007419 else if (*(int *)&curproxy->dispatch_addr.sin_addr != 0) {
willy tarreau5cbea6f2005-12-17 12:48:26 +01007420 Warning("parsing %s : dispatch address of listener %s will be ignored in balance mode.\n",
7421 file, curproxy->id);
7422 }
7423 }
7424 else if (curproxy->mode == PR_MODE_TCP || curproxy->mode == PR_MODE_HEALTH) { /* TCP PROXY or HEALTH CHECK */
willy tarreau0f7af912005-12-17 12:21:26 +01007425 if (curproxy->cookie_name != NULL) {
7426 Warning("parsing %s : cookie will be ignored for listener %s.\n",
7427 file, curproxy->id);
7428 }
7429 if ((newsrv = curproxy->srv) != NULL) {
7430 Warning("parsing %s : servers will be ignored for listener %s.\n",
7431 file, curproxy->id);
7432 }
willy tarreaue39cd132005-12-17 13:00:18 +01007433 if (curproxy->rsp_exp != NULL) {
willy tarreau0f7af912005-12-17 12:21:26 +01007434 Warning("parsing %s : server regular expressions will be ignored for listener %s.\n",
7435 file, curproxy->id);
7436 }
willy tarreaue39cd132005-12-17 13:00:18 +01007437 if (curproxy->req_exp != NULL) {
willy tarreau0f7af912005-12-17 12:21:26 +01007438 Warning("parsing %s : client regular expressions will be ignored for listener %s.\n",
7439 file, curproxy->id);
7440 }
7441 }
7442 else if (curproxy->mode == PR_MODE_HTTP) { /* HTTP PROXY */
7443 if ((curproxy->cookie_name != NULL) && ((newsrv = curproxy->srv) == NULL)) {
7444 Alert("parsing %s : HTTP proxy %s has a cookie but no server list !\n",
7445 file, curproxy->id);
7446 cfgerr++;
7447 }
7448 else {
7449 while (newsrv != NULL) {
7450 /* nothing to check for now */
7451 newsrv = newsrv->next;
7452 }
7453 }
7454 }
willy tarreau25c4ea52005-12-18 00:49:49 +01007455
7456 if (curproxy->options & PR_O_LOGASAP)
7457 curproxy->to_log &= ~LW_BYTES;
7458
willy tarreau8337c6b2005-12-17 13:41:01 +01007459 if (curproxy->errmsg.msg400 == NULL) {
7460 curproxy->errmsg.msg400 = (char *)HTTP_400;
7461 curproxy->errmsg.len400 = strlen(HTTP_400);
7462 }
7463 if (curproxy->errmsg.msg403 == NULL) {
7464 curproxy->errmsg.msg403 = (char *)HTTP_403;
7465 curproxy->errmsg.len403 = strlen(HTTP_403);
7466 }
7467 if (curproxy->errmsg.msg408 == NULL) {
7468 curproxy->errmsg.msg408 = (char *)HTTP_408;
7469 curproxy->errmsg.len408 = strlen(HTTP_408);
7470 }
7471 if (curproxy->errmsg.msg500 == NULL) {
7472 curproxy->errmsg.msg500 = (char *)HTTP_500;
7473 curproxy->errmsg.len500 = strlen(HTTP_500);
7474 }
7475 if (curproxy->errmsg.msg502 == NULL) {
7476 curproxy->errmsg.msg502 = (char *)HTTP_502;
7477 curproxy->errmsg.len502 = strlen(HTTP_502);
7478 }
7479 if (curproxy->errmsg.msg503 == NULL) {
7480 curproxy->errmsg.msg503 = (char *)HTTP_503;
7481 curproxy->errmsg.len503 = strlen(HTTP_503);
7482 }
7483 if (curproxy->errmsg.msg504 == NULL) {
7484 curproxy->errmsg.msg504 = (char *)HTTP_504;
7485 curproxy->errmsg.len504 = strlen(HTTP_504);
7486 }
willy tarreau0f7af912005-12-17 12:21:26 +01007487 curproxy = curproxy->next;
7488 }
7489 if (cfgerr > 0) {
7490 Alert("Errors found in configuration file, aborting.\n");
7491 return -1;
7492 }
7493 else
7494 return 0;
7495}
7496
7497
7498/*
7499 * This function initializes all the necessary variables. It only returns
7500 * if everything is OK. If something fails, it exits.
7501 */
7502void init(int argc, char **argv) {
7503 int i;
willy tarreau9fe663a2005-12-17 13:02:59 +01007504 int arg_mode = 0; /* MODE_DEBUG, ... */
willy tarreau0f7af912005-12-17 12:21:26 +01007505 char *old_argv = *argv;
7506 char *tmp;
willy tarreaufe2c5c12005-12-17 14:14:34 +01007507 char *cfg_pidfile = NULL;
willy tarreau9fe663a2005-12-17 13:02:59 +01007508 int cfg_maxconn = 0; /* # of simultaneous connections, (-n) */
willy tarreau0f7af912005-12-17 12:21:26 +01007509
7510 if (1<<INTBITS != sizeof(int)*8) {
willy tarreaudd07e972005-12-18 00:48:48 +01007511 fprintf(stderr,
willy tarreau0f7af912005-12-17 12:21:26 +01007512 "Error: wrong architecture. Recompile so that sizeof(int)=%d\n",
willy tarreau982249e2005-12-18 00:57:06 +01007513 (int)(sizeof(int)*8));
willy tarreau0f7af912005-12-17 12:21:26 +01007514 exit(1);
7515 }
7516
willy tarreau4302f492005-12-18 01:00:37 +01007517 /* initialize the log header encoding map : '{|}"#' should be encoded with
7518 * '#' as prefix, as well as non-printable characters ( <32 or >= 127 ).
7519 * URL encoding only requires '"', '#' to be encoded as well as non-
7520 * printable characters above.
7521 */
7522 memset(hdr_encode_map, 0, sizeof(hdr_encode_map));
7523 memset(url_encode_map, 0, sizeof(url_encode_map));
7524 for (i = 0; i < 32; i++) {
7525 FD_SET(i, hdr_encode_map);
7526 FD_SET(i, url_encode_map);
7527 }
7528 for (i = 127; i < 256; i++) {
7529 FD_SET(i, hdr_encode_map);
7530 FD_SET(i, url_encode_map);
7531 }
7532
7533 tmp = "\"#{|}";
7534 while (*tmp) {
7535 FD_SET(*tmp, hdr_encode_map);
7536 tmp++;
7537 }
7538
7539 tmp = "\"#";
7540 while (*tmp) {
7541 FD_SET(*tmp, url_encode_map);
7542 tmp++;
7543 }
7544
willy tarreau64a3cc32005-12-18 01:13:11 +01007545 cfg_polling_mechanism = POLL_USE_SELECT; /* select() is always available */
7546#if defined(ENABLE_POLL)
7547 cfg_polling_mechanism |= POLL_USE_POLL;
7548#endif
7549#if defined(ENABLE_EPOLL)
7550 cfg_polling_mechanism |= POLL_USE_EPOLL;
7551#endif
7552
willy tarreau0f7af912005-12-17 12:21:26 +01007553 pid = getpid();
7554 progname = *argv;
7555 while ((tmp = strchr(progname, '/')) != NULL)
7556 progname = tmp + 1;
7557
7558 argc--; argv++;
7559 while (argc > 0) {
7560 char *flag;
7561
7562 if (**argv == '-') {
7563 flag = *argv+1;
7564
7565 /* 1 arg */
7566 if (*flag == 'v') {
7567 display_version();
7568 exit(0);
7569 }
willy tarreau1c2ad212005-12-18 01:11:29 +01007570#if defined(ENABLE_EPOLL)
willy tarreau64a3cc32005-12-18 01:13:11 +01007571 else if (*flag == 'd' && flag[1] == 'e')
7572 cfg_polling_mechanism &= ~POLL_USE_EPOLL;
willy tarreau1c2ad212005-12-18 01:11:29 +01007573#endif
7574#if defined(ENABLE_POLL)
willy tarreau64a3cc32005-12-18 01:13:11 +01007575 else if (*flag == 'd' && flag[1] == 'p')
7576 cfg_polling_mechanism &= ~POLL_USE_POLL;
willy tarreau1c2ad212005-12-18 01:11:29 +01007577#endif
willy tarreau982249e2005-12-18 00:57:06 +01007578 else if (*flag == 'V')
7579 arg_mode |= MODE_VERBOSE;
willy tarreau0f7af912005-12-17 12:21:26 +01007580 else if (*flag == 'd')
willy tarreau9fe663a2005-12-17 13:02:59 +01007581 arg_mode |= MODE_DEBUG;
willy tarreaudd07e972005-12-18 00:48:48 +01007582 else if (*flag == 'c')
7583 arg_mode |= MODE_CHECK;
willy tarreau0f7af912005-12-17 12:21:26 +01007584 else if (*flag == 'D')
willy tarreau9fe663a2005-12-17 13:02:59 +01007585 arg_mode |= MODE_DAEMON | MODE_QUIET;
willy tarreau5cbea6f2005-12-17 12:48:26 +01007586 else if (*flag == 'q')
willy tarreau9fe663a2005-12-17 13:02:59 +01007587 arg_mode |= MODE_QUIET;
willy tarreau0f7af912005-12-17 12:21:26 +01007588#if STATTIME > 0
7589 else if (*flag == 's')
willy tarreau9fe663a2005-12-17 13:02:59 +01007590 arg_mode |= MODE_STATS;
willy tarreau0f7af912005-12-17 12:21:26 +01007591 else if (*flag == 'l')
willy tarreau9fe663a2005-12-17 13:02:59 +01007592 arg_mode |= MODE_LOG;
willy tarreau0f7af912005-12-17 12:21:26 +01007593#endif
7594 else { /* >=2 args */
7595 argv++; argc--;
7596 if (argc == 0)
7597 usage(old_argv);
7598
7599 switch (*flag) {
7600 case 'n' : cfg_maxconn = atol(*argv); break;
7601 case 'N' : cfg_maxpconn = atol(*argv); break;
7602 case 'f' : cfg_cfgfile = *argv; break;
willy tarreaufe2c5c12005-12-17 14:14:34 +01007603 case 'p' : cfg_pidfile = *argv; break;
willy tarreau0f7af912005-12-17 12:21:26 +01007604 default: usage(old_argv);
7605 }
7606 }
7607 }
7608 else
7609 usage(old_argv);
7610 argv++; argc--;
7611 }
7612
willy tarreaud0fb4652005-12-18 01:32:04 +01007613 global.mode = MODE_STARTING | /* during startup, we want most of the alerts */
7614 (arg_mode & (MODE_DAEMON | MODE_VERBOSE | MODE_QUIET | MODE_CHECK | MODE_DEBUG));
willy tarreaudd07e972005-12-18 00:48:48 +01007615
willy tarreau0f7af912005-12-17 12:21:26 +01007616 if (!cfg_cfgfile)
7617 usage(old_argv);
7618
7619 gethostname(hostname, MAX_HOSTNAME_LEN);
7620
willy tarreau12350152005-12-18 01:03:27 +01007621 have_appsession = 0;
willy tarreau0f7af912005-12-17 12:21:26 +01007622 if (readcfgfile(cfg_cfgfile) < 0) {
7623 Alert("Error reading configuration file : %s\n", cfg_cfgfile);
7624 exit(1);
7625 }
willy tarreau12350152005-12-18 01:03:27 +01007626 if (have_appsession)
7627 appsession_init();
willy tarreau0f7af912005-12-17 12:21:26 +01007628
willy tarreau982249e2005-12-18 00:57:06 +01007629 if (global.mode & MODE_CHECK) {
willy tarreaudd07e972005-12-18 00:48:48 +01007630 qfprintf(stdout, "Configuration file is valid : %s\n", cfg_cfgfile);
7631 exit(0);
7632 }
7633
willy tarreau9fe663a2005-12-17 13:02:59 +01007634 if (cfg_maxconn > 0)
7635 global.maxconn = cfg_maxconn;
7636
willy tarreaufe2c5c12005-12-17 14:14:34 +01007637 if (cfg_pidfile) {
7638 if (global.pidfile)
7639 free(global.pidfile);
7640 global.pidfile = strdup(cfg_pidfile);
7641 }
7642
willy tarreau9fe663a2005-12-17 13:02:59 +01007643 if (global.maxconn == 0)
7644 global.maxconn = DEFAULT_MAXCONN;
7645
7646 global.maxsock = global.maxconn * 2; /* each connection needs two sockets */
7647
7648 if (arg_mode & MODE_DEBUG) {
7649 /* command line debug mode inhibits configuration mode */
7650 global.mode &= ~(MODE_DAEMON | MODE_QUIET);
7651 }
willy tarreau982249e2005-12-18 00:57:06 +01007652 global.mode |= (arg_mode & (MODE_DAEMON | MODE_QUIET | MODE_VERBOSE
7653 | MODE_DEBUG | MODE_STATS | MODE_LOG));
willy tarreau9fe663a2005-12-17 13:02:59 +01007654
7655 if ((global.mode & MODE_DEBUG) && (global.mode & (MODE_DAEMON | MODE_QUIET))) {
7656 Warning("<debug> mode incompatible with <quiet> and <daemon>. Keeping <debug> only.\n");
7657 global.mode &= ~(MODE_DAEMON | MODE_QUIET);
7658 }
7659
7660 if ((global.nbproc > 1) && !(global.mode & MODE_DAEMON)) {
7661 Warning("<nbproc> is only meaningful in daemon mode. Setting limit to 1 process.\n");
7662 global.nbproc = 1;
7663 }
7664
7665 if (global.nbproc < 1)
7666 global.nbproc = 1;
7667
willy tarreau0f7af912005-12-17 12:21:26 +01007668 StaticReadEvent = (fd_set *)calloc(1,
7669 sizeof(fd_set) *
willy tarreau9fe663a2005-12-17 13:02:59 +01007670 (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
willy tarreau0f7af912005-12-17 12:21:26 +01007671 StaticWriteEvent = (fd_set *)calloc(1,
7672 sizeof(fd_set) *
willy tarreau9fe663a2005-12-17 13:02:59 +01007673 (global.maxsock + FD_SETSIZE - 1) / FD_SETSIZE);
willy tarreau0f7af912005-12-17 12:21:26 +01007674
7675 fdtab = (struct fdtab *)calloc(1,
willy tarreau9fe663a2005-12-17 13:02:59 +01007676 sizeof(struct fdtab) * (global.maxsock));
7677 for (i = 0; i < global.maxsock; i++) {
willy tarreau0f7af912005-12-17 12:21:26 +01007678 fdtab[i].state = FD_STCLOSE;
7679 }
7680}
7681
7682/*
7683 * this function starts all the proxies. It returns 0 if OK, -1 if not.
7684 */
7685int start_proxies() {
7686 struct proxy *curproxy;
willy tarreaua41a8b42005-12-17 14:02:24 +01007687 struct listener *listener;
willy tarreau0f7af912005-12-17 12:21:26 +01007688 int fd;
7689
7690 for (curproxy = proxy; curproxy != NULL; curproxy = curproxy->next) {
willy tarreau0f7af912005-12-17 12:21:26 +01007691 if (curproxy->state == PR_STDISABLED)
7692 continue;
7693
willy tarreaua41a8b42005-12-17 14:02:24 +01007694 for (listener = curproxy->listen; listener != NULL; listener = listener->next) {
7695 if ((fd = listener->fd =
willy tarreau8a86dbf2005-12-18 00:45:59 +01007696 socket(listener->addr.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
willy tarreaua41a8b42005-12-17 14:02:24 +01007697 Alert("cannot create listening socket for proxy %s. Aborting.\n",
7698 curproxy->id);
7699 return -1;
7700 }
willy tarreau0f7af912005-12-17 12:21:26 +01007701
willy tarreaua41a8b42005-12-17 14:02:24 +01007702 if (fd >= global.maxsock) {
7703 Alert("socket(): not enough free sockets for proxy %s. Raise -n argument. Aborting.\n",
7704 curproxy->id);
7705 close(fd);
7706 return -1;
7707 }
willy tarreau5cbea6f2005-12-17 12:48:26 +01007708
willy tarreaua41a8b42005-12-17 14:02:24 +01007709 if ((fcntl(fd, F_SETFL, O_NONBLOCK) == -1) ||
7710 (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
7711 (char *) &one, sizeof(one)) == -1)) {
7712 Alert("cannot make socket non-blocking for proxy %s. Aborting.\n",
7713 curproxy->id);
7714 close(fd);
7715 return -1;
7716 }
willy tarreau0f7af912005-12-17 12:21:26 +01007717
willy tarreaua41a8b42005-12-17 14:02:24 +01007718 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof(one)) == -1) {
7719 Alert("cannot do so_reuseaddr for proxy %s. Continuing.\n",
7720 curproxy->id);
7721 }
willy tarreau0f7af912005-12-17 12:21:26 +01007722
willy tarreaua41a8b42005-12-17 14:02:24 +01007723 if (bind(fd,
7724 (struct sockaddr *)&listener->addr,
willy tarreau8a86dbf2005-12-18 00:45:59 +01007725 listener->addr.ss_family == AF_INET6 ?
7726 sizeof(struct sockaddr_in6) :
7727 sizeof(struct sockaddr_in)) == -1) {
willy tarreaua41a8b42005-12-17 14:02:24 +01007728 Alert("cannot bind socket for proxy %s. Aborting.\n",
7729 curproxy->id);
7730 close(fd);
7731 return -1;
7732 }
willy tarreau0f7af912005-12-17 12:21:26 +01007733
willy tarreaua41a8b42005-12-17 14:02:24 +01007734 if (listen(fd, curproxy->maxconn) == -1) {
7735 Alert("cannot listen to socket for proxy %s. Aborting.\n",
7736 curproxy->id);
7737 close(fd);
7738 return -1;
7739 }
willy tarreau0f7af912005-12-17 12:21:26 +01007740
willy tarreaua41a8b42005-12-17 14:02:24 +01007741 /* the function for the accept() event */
7742 fdtab[fd].read = &event_accept;
7743 fdtab[fd].write = NULL; /* never called */
7744 fdtab[fd].owner = (struct task *)curproxy; /* reference the proxy instead of a task */
7745 curproxy->state = PR_STRUN;
7746 fdtab[fd].state = FD_STLISTEN;
7747 FD_SET(fd, StaticReadEvent);
7748 fd_insert(fd);
7749 listeners++;
7750 }
willy tarreaua1598082005-12-17 13:08:06 +01007751 send_log(curproxy, LOG_NOTICE, "Proxy %s started.\n", curproxy->id);
willy tarreau0f7af912005-12-17 12:21:26 +01007752 }
7753 return 0;
7754}
7755
willy tarreaub952e1d2005-12-18 01:31:20 +01007756int match_str(const void *key1, const void *key2) {
willy tarreau12350152005-12-18 01:03:27 +01007757
7758 appsess *temp1,*temp2;
7759 temp1 = (appsess *)key1;
7760 temp2 = (appsess *)key2;
7761
7762 //fprintf(stdout,">>>>>>>>>>>>>>temp1->sessid :%s:\n",temp1->sessid);
7763 //fprintf(stdout,">>>>>>>>>>>>>>temp2->sessid :%s:\n",temp2->sessid);
7764
7765 return (strcmp(temp1->sessid,temp2->sessid) == 0);
7766}/* end match_str */
7767
willy tarreaub952e1d2005-12-18 01:31:20 +01007768void destroy(void *data) {
willy tarreau12350152005-12-18 01:03:27 +01007769 appsess *temp1;
7770
7771 //printf("destroy called\n");
7772 temp1 = (appsess *)data;
7773
7774 if (temp1->sessid)
7775 pool_free_to(apools.sessid, temp1->sessid);
7776
7777 if (temp1->serverid)
7778 pool_free_to(apools.serverid, temp1->serverid);
7779
7780 pool_free(appsess, temp1);
7781} /* end destroy */
7782
7783void appsession_cleanup( void )
7784{
7785 struct proxy *p = proxy;
7786
7787 while(p) {
7788 chtbl_destroy(&(p->htbl_proxy));
7789 p = p->next;
7790 }
7791}/* end appsession_cleanup() */
7792
7793void pool_destroy(void **pool)
7794{
7795 void *temp, *next;
7796 next = pool;
7797 while (next) {
7798 temp = next;
7799 next = *(void **)temp;
7800 free(temp);
7801 }
7802}/* end pool_destroy() */
7803
willy tarreaub952e1d2005-12-18 01:31:20 +01007804void deinit(void) {
willy tarreau12350152005-12-18 01:03:27 +01007805 struct proxy *p = proxy;
7806 struct cap_hdr *h,*h_next;
7807 struct server *s,*s_next;
7808 struct listener *l,*l_next;
7809
7810 while (p) {
7811 if (p->id)
7812 free(p->id);
7813
7814 if (p->check_req)
7815 free(p->check_req);
7816
7817 if (p->cookie_name)
7818 free(p->cookie_name);
7819
7820 if (p->capture_name)
7821 free(p->capture_name);
7822
7823 /* only strup if the user have set in config.
7824 When should we free it?!
willy tarreaub952e1d2005-12-18 01:31:20 +01007825 if (p->errmsg.msg400) free(p->errmsg.msg400);
7826 if (p->errmsg.msg403) free(p->errmsg.msg403);
7827 if (p->errmsg.msg408) free(p->errmsg.msg408);
7828 if (p->errmsg.msg500) free(p->errmsg.msg500);
7829 if (p->errmsg.msg502) free(p->errmsg.msg502);
7830 if (p->errmsg.msg503) free(p->errmsg.msg503);
7831 if (p->errmsg.msg504) free(p->errmsg.msg504);
willy tarreau12350152005-12-18 01:03:27 +01007832 */
7833 if (p->appsession_name)
7834 free(p->appsession_name);
7835
7836 h = p->req_cap;
7837 while (h) {
7838 h_next = h->next;
7839 if (h->name)
7840 free(h->name);
7841 pool_destroy(h->pool);
7842 free(h);
7843 h = h_next;
7844 }/* end while(h) */
7845
7846 h = p->rsp_cap;
7847 while (h) {
7848 h_next = h->next;
7849 if (h->name)
7850 free(h->name);
7851
7852 pool_destroy(h->pool);
7853 free(h);
7854 h = h_next;
7855 }/* end while(h) */
7856
7857 s = p->srv;
7858 while (s) {
7859 s_next = s->next;
willy tarreaub952e1d2005-12-18 01:31:20 +01007860 if (s->id)
willy tarreau12350152005-12-18 01:03:27 +01007861 free(s->id);
7862
willy tarreaub952e1d2005-12-18 01:31:20 +01007863 if (s->cookie)
willy tarreau12350152005-12-18 01:03:27 +01007864 free(s->cookie);
7865
7866 free(s);
7867 s = s_next;
7868 }/* end while(s) */
7869
7870 l = p->listen;
7871 while (l) {
7872 l_next = l->next;
7873 free(l);
7874 l = l_next;
7875 }/* end while(l) */
7876
7877 pool_destroy((void **) p->req_cap_pool);
7878 pool_destroy((void **) p->rsp_cap_pool);
7879 p = p->next;
7880 }/* end while(p) */
7881
7882 if (global.chroot) free(global.chroot);
7883 if (global.pidfile) free(global.pidfile);
7884
willy tarreau12350152005-12-18 01:03:27 +01007885 if (StaticReadEvent) free(StaticReadEvent);
7886 if (StaticWriteEvent) free(StaticWriteEvent);
7887 if (fdtab) free(fdtab);
7888
7889 pool_destroy(pool_session);
7890 pool_destroy(pool_buffer);
7891 pool_destroy(pool_fdtab);
7892 pool_destroy(pool_requri);
7893 pool_destroy(pool_task);
7894 pool_destroy(pool_capture);
7895 pool_destroy(pool_appsess);
7896
7897 if (have_appsession) {
7898 pool_destroy(apools.serverid);
7899 pool_destroy(apools.sessid);
7900 }
7901} /* end deinit() */
willy tarreau0f7af912005-12-17 12:21:26 +01007902
7903int main(int argc, char **argv) {
willy tarreaub1285d52005-12-18 01:20:14 +01007904 struct rlimit limit;
willy tarreaufe2c5c12005-12-17 14:14:34 +01007905 FILE *pidfile = NULL;
willy tarreau0f7af912005-12-17 12:21:26 +01007906 init(argc, argv);
7907
willy tarreau0f7af912005-12-17 12:21:26 +01007908 signal(SIGQUIT, dump);
7909 signal(SIGUSR1, sig_soft_stop);
willy tarreau8337c6b2005-12-17 13:41:01 +01007910 signal(SIGHUP, sig_dump_state);
willy tarreau64a3cc32005-12-18 01:13:11 +01007911#ifdef DEBUG_MEMORY
willy tarreau12350152005-12-18 01:03:27 +01007912 signal(SIGINT, sig_int);
7913 signal(SIGTERM, sig_term);
willy tarreau64a3cc32005-12-18 01:13:11 +01007914#endif
willy tarreau0f7af912005-12-17 12:21:26 +01007915
7916 /* on very high loads, a sigpipe sometimes happen just between the
7917 * getsockopt() which tells "it's OK to write", and the following write :-(
7918 */
willy tarreau3242e862005-12-17 12:27:53 +01007919#ifndef MSG_NOSIGNAL
7920 signal(SIGPIPE, SIG_IGN);
7921#endif
willy tarreau0f7af912005-12-17 12:21:26 +01007922
willy tarreaud0fb4652005-12-18 01:32:04 +01007923 /* start_proxies() sends an alert when it fails. */
willy tarreau0f7af912005-12-17 12:21:26 +01007924 if (start_proxies() < 0)
7925 exit(1);
willy tarreaud0fb4652005-12-18 01:32:04 +01007926
7927 if (listeners == 0) {
7928 Alert("[%s.main()] No enabled listener found (check the <listen> keywords) ! Exiting.\n", argv[0]);
7929 exit(1);
7930 }
7931
7932 /* MODE_QUIET can inhibit alerts and warnings below this line */
7933
7934 global.mode &= ~MODE_STARTING;
7935 if (global.mode & MODE_QUIET) {
7936 /* detach from the tty */
7937 fclose(stdin); fclose(stdout); fclose(stderr);
7938 close(0); close(1); close(2);
7939 }
willy tarreau0f7af912005-12-17 12:21:26 +01007940
willy tarreaufe2c5c12005-12-17 14:14:34 +01007941 /* open log & pid files before the chroot */
7942 if (global.mode & MODE_DAEMON && global.pidfile != NULL) {
7943 int pidfd;
7944 unlink(global.pidfile);
7945 pidfd = open(global.pidfile, O_CREAT | O_WRONLY | O_TRUNC, 0644);
7946 if (pidfd < 0) {
7947 Alert("[%s.main()] Cannot create pidfile %s\n", argv[0], global.pidfile);
7948 exit(1);
7949 }
7950 pidfile = fdopen(pidfd, "w");
7951 }
willy tarreau9fe663a2005-12-17 13:02:59 +01007952
7953 /* chroot if needed */
7954 if (global.chroot != NULL) {
7955 if (chroot(global.chroot) == -1) {
7956 Alert("[%s.main()] Cannot chroot(%s).\n", argv[0], global.chroot);
7957 exit(1);
7958 }
7959 chdir("/");
7960 }
7961
willy tarreaub1285d52005-12-18 01:20:14 +01007962 /* ulimits */
7963 if (global.rlimit_nofile) {
7964 limit.rlim_cur = limit.rlim_max = global.rlimit_nofile;
7965 if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
7966 Warning("[%s.main()] Cannot raise FD limit to %d.\n", argv[0], global.rlimit_nofile);
7967 }
7968 }
7969
willy tarreau9fe663a2005-12-17 13:02:59 +01007970 /* setgid / setuid */
willy tarreau036e1ce2005-12-17 13:46:33 +01007971 if (global.gid && setgid(global.gid) == -1) {
willy tarreau9fe663a2005-12-17 13:02:59 +01007972 Alert("[%s.main()] Cannot set gid %d.\n", argv[0], global.gid);
7973 exit(1);
7974 }
7975
willy tarreau036e1ce2005-12-17 13:46:33 +01007976 if (global.uid && setuid(global.uid) == -1) {
willy tarreau9fe663a2005-12-17 13:02:59 +01007977 Alert("[%s.main()] Cannot set uid %d.\n", argv[0], global.uid);
7978 exit(1);
7979 }
7980
willy tarreaub1285d52005-12-18 01:20:14 +01007981 /* check ulimits */
7982 limit.rlim_cur = limit.rlim_max = 0;
7983 getrlimit(RLIMIT_NOFILE, &limit);
7984 if (limit.rlim_cur < global.maxsock) {
7985 Warning("[%s.main()] FD limit (%d) too low for maxconn=%d/maxsock=%d. Please raise 'ulimit-n' to %d or more to avoid any trouble.\n",
7986 argv[0], limit.rlim_cur, global.maxconn, global.maxsock, global.maxsock);
7987 }
7988
willy tarreau9fe663a2005-12-17 13:02:59 +01007989 if (global.mode & MODE_DAEMON) {
7990 int ret = 0;
7991 int proc;
7992
7993 /* the father launches the required number of processes */
7994 for (proc = 0; proc < global.nbproc; proc++) {
7995 ret = fork();
7996 if (ret < 0) {
7997 Alert("[%s.main()] Cannot fork.\n", argv[0]);
7998 exit(1); /* there has been an error */
7999 }
8000 else if (ret == 0) /* child breaks here */
8001 break;
willy tarreaufe2c5c12005-12-17 14:14:34 +01008002 if (pidfile != NULL) {
8003 fprintf(pidfile, "%d\n", ret);
8004 fflush(pidfile);
8005 }
willy tarreau9fe663a2005-12-17 13:02:59 +01008006 }
willy tarreaufe2c5c12005-12-17 14:14:34 +01008007 /* close the pidfile both in children and father */
8008 if (pidfile != NULL)
8009 fclose(pidfile);
8010 free(global.pidfile);
8011
willy tarreau9fe663a2005-12-17 13:02:59 +01008012 if (proc == global.nbproc)
8013 exit(0); /* parent must leave */
8014
willy tarreau750a4722005-12-17 13:21:24 +01008015 /* if we're NOT in QUIET mode, we should now close the 3 first FDs to ensure
8016 * that we can detach from the TTY. We MUST NOT do it in other cases since
8017 * it would have already be done, and 0-2 would have been affected to listening
8018 * sockets
8019 */
8020 if (!(global.mode & MODE_QUIET)) {
8021 /* detach from the tty */
8022 fclose(stdin); fclose(stdout); fclose(stderr);
8023 close(0); close(1); close(2); /* close all fd's */
8024 global.mode |= MODE_QUIET; /* ensure that we won't say anything from now */
8025 }
willy tarreaua1598082005-12-17 13:08:06 +01008026 pid = getpid(); /* update child's pid */
willy tarreaue867b482005-12-17 13:28:43 +01008027 setsid();
willy tarreau9fe663a2005-12-17 13:02:59 +01008028 }
8029
willy tarreau1c2ad212005-12-18 01:11:29 +01008030#if defined(ENABLE_EPOLL)
willy tarreau64a3cc32005-12-18 01:13:11 +01008031 if (cfg_polling_mechanism & POLL_USE_EPOLL) {
willy tarreau1c2ad212005-12-18 01:11:29 +01008032 if (epoll_loop(POLL_LOOP_ACTION_INIT)) {
8033 epoll_loop(POLL_LOOP_ACTION_RUN);
8034 epoll_loop(POLL_LOOP_ACTION_CLEAN);
willy tarreau64a3cc32005-12-18 01:13:11 +01008035 cfg_polling_mechanism &= POLL_USE_EPOLL;
willy tarreau1c2ad212005-12-18 01:11:29 +01008036 }
8037 else {
willy tarreau64a3cc32005-12-18 01:13:11 +01008038 Warning("epoll() is not available. Using poll()/select() instead.\n");
8039 cfg_polling_mechanism &= ~POLL_USE_EPOLL;
willy tarreau1c2ad212005-12-18 01:11:29 +01008040 }
8041 }
8042#endif
8043
8044#if defined(ENABLE_POLL)
willy tarreau64a3cc32005-12-18 01:13:11 +01008045 if (cfg_polling_mechanism & POLL_USE_POLL) {
willy tarreau1c2ad212005-12-18 01:11:29 +01008046 if (poll_loop(POLL_LOOP_ACTION_INIT)) {
8047 poll_loop(POLL_LOOP_ACTION_RUN);
8048 poll_loop(POLL_LOOP_ACTION_CLEAN);
willy tarreau64a3cc32005-12-18 01:13:11 +01008049 cfg_polling_mechanism &= POLL_USE_POLL;
willy tarreau1c2ad212005-12-18 01:11:29 +01008050 }
8051 else {
8052 Warning("poll() is not available. Using select() instead.\n");
willy tarreau64a3cc32005-12-18 01:13:11 +01008053 cfg_polling_mechanism &= ~POLL_USE_POLL;
willy tarreau1c2ad212005-12-18 01:11:29 +01008054 }
8055 }
8056#endif
willy tarreau64a3cc32005-12-18 01:13:11 +01008057 if (cfg_polling_mechanism & POLL_USE_SELECT) {
willy tarreau1c2ad212005-12-18 01:11:29 +01008058 if (select_loop(POLL_LOOP_ACTION_INIT)) {
8059 select_loop(POLL_LOOP_ACTION_RUN);
8060 select_loop(POLL_LOOP_ACTION_CLEAN);
willy tarreau64a3cc32005-12-18 01:13:11 +01008061 cfg_polling_mechanism &= POLL_USE_SELECT;
willy tarreau1c2ad212005-12-18 01:11:29 +01008062 }
8063 }
8064
willy tarreau0f7af912005-12-17 12:21:26 +01008065
willy tarreau12350152005-12-18 01:03:27 +01008066 /* Free all Hash Keys and all Hash elements */
8067 appsession_cleanup();
8068 /* Do some cleanup */
8069 deinit();
8070
willy tarreau0f7af912005-12-17 12:21:26 +01008071 exit(0);
8072}
willy tarreau12350152005-12-18 01:03:27 +01008073
8074#if defined(DEBUG_HASH)
8075static void print_table(const CHTbl *htbl) {
8076
8077 ListElmt *element;
8078 int i;
8079 appsess *asession;
8080
8081 /*****************************************************************************
8082 * *
8083 * Display the chained hash table. *
8084 * *
8085 *****************************************************************************/
8086
8087 fprintf(stdout, "Table size is %d\n", chtbl_size(htbl));
8088
8089 for (i = 0; i < TBLSIZ; i++) {
8090 fprintf(stdout, "Bucket[%03d]\n", i);
8091
8092 for (element = list_head(&htbl->table[i]); element != NULL; element = list_next(element)) {
8093 //fprintf(stdout, "%c", *(char *)list_data(element));
8094 asession = (appsess *)list_data(element);
8095 fprintf(stdout, "ELEM :%s:", asession->sessid);
8096 fprintf(stdout, " Server :%s: \n", asession->serverid);
8097 //fprintf(stdout, " Server request_count :%li:\n",asession->request_count);
8098 }
8099
8100 fprintf(stdout, "\n");
8101 }
8102 return;
8103} /* end print_table */
8104#endif
8105
8106static int appsession_init(void)
8107{
8108 static int initialized = 0;
8109 int idlen;
8110 struct server *s;
8111 struct proxy *p = proxy;
8112
8113 if (!initialized) {
8114 if (!appsession_task_init()) {
8115 apools.sessid = NULL;
8116 apools.serverid = NULL;
8117 apools.ser_waste = 0;
8118 apools.ser_use = 0;
8119 apools.ser_msize = sizeof(void *);
8120 apools.ses_waste = 0;
8121 apools.ses_use = 0;
8122 apools.ses_msize = sizeof(void *);
8123 while (p) {
8124 s = p->srv;
8125 if (apools.ses_msize < p->appsession_len)
8126 apools.ses_msize = p->appsession_len;
8127 while (s) {
8128 idlen = strlen(s->id);
8129 if (apools.ser_msize < idlen)
8130 apools.ser_msize = idlen;
8131 s = s->next;
8132 }
8133 p = p->next;
8134 }
8135 apools.ser_msize ++; /* we use strings, so reserve space for '\0' */
8136 apools.ses_msize ++;
8137 }
8138 else {
8139 fprintf(stderr, "appsession_task_init failed\n");
8140 return -1;
8141 }
8142 initialized ++;
8143 }
8144 return 0;
8145}
8146
8147static int appsession_task_init(void)
8148{
8149 static int initialized = 0;
8150 struct task *t;
8151 if (!initialized) {
8152 if ((t = pool_alloc(task)) == NULL)
8153 return -1;
8154 t->next = t->prev = t->rqnext = NULL;
8155 t->wq = LIST_HEAD(wait_queue);
8156 t->state = TASK_IDLE;
8157 t->context = NULL;
8158 tv_delayfrom(&t->expire, &now, TBLCHKINT);
8159 task_queue(t);
8160 t->process = appsession_refresh;
8161 initialized ++;
8162 }
8163 return 0;
8164}
8165
8166static int appsession_refresh(struct task *t) {
8167 struct proxy *p = proxy;
8168 CHTbl *htbl;
8169 ListElmt *element, *last;
8170 int i;
8171 appsess *asession;
8172 void *data;
8173
8174 while (p) {
8175 if (p->appsession_name != NULL) {
8176 htbl = &p->htbl_proxy;
8177 /* if we ever give up the use of TBLSIZ, we need to change this */
8178 for (i = 0; i < TBLSIZ; i++) {
8179 last = NULL;
8180 for (element = list_head(&htbl->table[i]); element != NULL; element = list_next(element)) {
8181 asession = (appsess *)list_data(element);
8182 if (tv_cmp2_ms(&asession->expire, &now) <= 0) {
8183 if ((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))) {
8184 int len;
8185 /*
8186 on Linux NULL pointers are catched by sprintf, on solaris -> segfault
8187 */
8188 len = sprintf(trash, "appsession_refresh: cleaning up expired Session '%s' on Server %s\n",
8189 asession->sessid, asession->serverid?asession->serverid:"(null)");
8190 write(1, trash, len);
8191 }
8192 /* delete the expired element from within the hash table */
8193 if ((list_rem_next(&htbl->table[i], last, (void **)&data) == 0)
8194 && (htbl->table[i].destroy != NULL)) {
8195 htbl->table[i].destroy(data);
8196 }
8197 if (last == NULL) {/* patient lost his head, get a new one */
8198 element = list_head(&htbl->table[i]);
8199 if (element == NULL) break; /* no heads left, go to next patient */
8200 }
8201 else
8202 element = last;
8203 }/* end if (tv_cmp2_ms(&asession->expire, &now) <= 0) */
8204 else
8205 last = element;
8206 }/* end for (element = list_head(&htbl->table[i]); element != NULL; element = list_next(element)) */
8207 }
8208 }
8209 p = p->next;
8210 }
8211 tv_delayfrom(&t->expire, &now, TBLCHKINT); /* check expiration every 5 seconds */
8212 return TBLCHKINT;
8213} /* end appsession_refresh */
8214