This patch contains the differences between the upstream tarball and
the sources actually used for building the package.

Option single-debian-patch is used as the changes are tracked in git.
--- mongrel2-1.10.0.orig/Makefile
+++ mongrel2-1.10.0/Makefile
@@ -1,12 +1,12 @@
-CFLAGS=-g -O2 -Wall -Wextra -Isrc -Isrc/mbedtls/include -pthread -rdynamic -DNDEBUG $(OPTFLAGS) -D_FILE_OFFSET_BITS=64
-LIBS=-lzmq -ldl -lsqlite3 $(OPTLIBS)
+CFLAGS+=-g -O2 -Wall -Wextra -idirafter "src" -pthread -rdynamic -DNDEBUG $(OPTFLAGS) -D_FILE_OFFSET_BITS=64
+LIBS=-lzmq -ldl -lsqlite3 -lmbedtls -lmbedx509 -lmbedcrypto $(OPTLIBS)
 PREFIX?=/usr/local
 
 get_objs = $(addsuffix .o,$(basename $(wildcard $(1))))
 
 ASM=$(wildcard src/**/*.S src/*.S)
 RAGEL_TARGETS=src/state.c src/http11/http11_parser.c
-SOURCES=$(wildcard src/mbedtls/library/*.c src/**/*.c src/*.c) $(RAGEL_TARGETS)
+SOURCES=$(wildcard src/**/*.c src/*.c) $(RAGEL_TARGETS)
 OBJECTS=$(patsubst %.c,%.o,${SOURCES}) $(patsubst %.S,%.o,${ASM})
 OBJECTS_EXTERNAL+=$(call get_objs,src/mbedtls/library/*.c)
 OBJECTS_NOEXT=$(filter-out ${OBJECTS_EXTERNAL},${OBJECTS})
@@ -22,20 +22,20 @@ MAKEOPTS=OPTFLAGS="${NOEXTCFLAGS} ${OPTF
 #   upon every make invocation, and must be done before the SOURCES variable, above
 #   is lazily evaluated, or none of the src/mbedtls source files will be found
 
-ifdef $($(shell									\
-	if git submodule status | grep '^-'; then				\
-	    echo "mbedtls; init and update git submodule" 1>&2;		\
-	    git submodule init && git submodule update;				\
-	fi ))
-endif
+#ifdef $($(shell									\
+#	if git submodule status | grep '^-'; then				\
+#	    echo "mbedtls; init and update git submodule" 1>&2;		\
+#	    git submodule init && git submodule update;				\
+#	fi ))
+#endif
 
 all: builddirs bin/mongrel2 tests m2sh procer
 
-dev: CFLAGS=-g -Wall -Isrc -Wall -Wextra $(OPTFLAGS) -D_FILE_OFFSET_BITS=64
+dev: CFLAGS=-g -Wall -idirafter "src" -Wall -Wextra $(OPTFLAGS) -D_FILE_OFFSET_BITS=64
 dev: all
 
 ${OBJECTS_NOEXT}: CFLAGS += ${NOEXTCFLAGS}
-${OBJECTS}: src/mbedtls/include/polarssl/config.h
+${OBJECTS}: /usr/include/mbedtls/config.h
 
 # 
 # CFLAGS_DEFS: The $(CC) flags required to obtain C pre-processor #defines, per:
@@ -55,27 +55,27 @@ CFLAGS_DEFS=-dM -E -x c 	# clang, gcc, H
 
 # Configure mbedtls
 # 
-# - check for required src/mbedtls/include/polarssl/config.h definitions
-#   and patch using version-appropriate src/polarssl_config.patch.#.#.# file:
+# - check for required src/mbedtls/include/mbedtls/config.h definitions
+#   and patch using version-appropriate src/mbedtls_config.patch.#.#.# file:
 #   - If desired mbedtls version is not yet supported, git checkout the
-#     new src/mbedtls/ version X.Y.Z, edit its include/polarssl/config.h as
-#     required, and generate a new src/polarssl_config.patch.X.Y.Z using:
+#     new src/mbedtls/ version X.Y.Z, edit its include/mbedtls/config.h as
+#     required, and generate a new src/mbedtls_config.patch.X.Y.Z using:
 # 
-#         git diff -- include/polarssl/config.h > ../polarssl_config.patch.X.Y.Z
-FORCE:
-src/mbedtls/include/polarssl/config.h: src/mbedtls/include/polarssl/version.h FORCE
-	@POLARSSL_VERSION=$$( $(CC) $(CFLAGS_DEFS) $<				\
-	    | sed -n -e 's/^.*POLARSSL_VERSION_STRING[\t ]*"\([^"]*\)".*/\1/p' ); \
-	if $(CC) $(CFLAGS_DEFS) $@ | grep -q POLARSSL_HAVEGE_C; then		\
-	    echo "mbedtls $${POLARSSL_VERSION}; already configured";		\
-	else									\
-	    echo "mbedtls $${POLARSSL_VERSION}; defining POLARSSL_HAVEGE_C...";\
-	    POLARSSL_PATCH=src/polarssl_config.patch.$${POLARSSL_VERSION};	\
-	    if ! patch -d src/mbedtls -p 1 < $${POLARSSL_PATCH}; then		\
-		echo "*** Failed to apply $${POLARSSL_PATCH}";			\
-		exit 1;								\
-	    fi;									\
-	fi
+#         git diff -- include/mbedtls/config.h > ../mbedtls_config.patch.X.Y.Z
+#FORCE:
+#src/mbedtls/include/mbedtls/config.h: src/mbedtls/include/mbedtls/version.h FORCE
+#	@MBEDTLS_VERSION=$$( $(CC) $(CFLAGS_DEFS) $<				\
+#	    | sed -n -e 's/^.*MBEDTLS_VERSION_STRING[\t ]*"\([^"]*\)".*/\1/p' ); \
+#	if $(CC) $(CFLAGS_DEFS) $@ | grep -q MBEDTLS_HAVEGE_C; then		\
+#	    echo "mbedtls $${MBEDTLS_VERSION}; already configured";		\
+#	else									\
+#	    echo "mbedtls $${MBEDTLS_VERSION}; defining MBEDTLS_HAVEGE_C...";\
+#	    MBEDTLS_PATCH=src/mbedtls_config.patch.$${MBEDTLS_VERSION};	\
+#	    if ! patch -d src/mbedtls -p 1 < $${MBEDTLS_PATCH}; then		\
+#		echo "*** Failed to apply $${MBEDTLS_PATCH}";			\
+#		exit 1;								\
+#	    fi;									\
+#	fi
 
 .PHONY: builddirs
 builddirs:
@@ -83,7 +83,7 @@ builddirs:
 	@mkdir -p bin
 
 bin/mongrel2: build/libm2.a src/mongrel2.o
-	$(CC) $(CFLAGS) src/mongrel2.o -o $@ $< $(LIBS)
+	$(CC) $(CFLAGS) $(LDFLAGS) src/mongrel2.o -o $@ $< $(LIBS)
 
 build/libm2.a: CFLAGS += -fPIC
 build/libm2.a: ${LIB_OBJ}
@@ -96,10 +96,11 @@ clean:
 	rm -f tests/test.pid 
 	rm -f tests/tests.log 
 	rm -f tests/empty.sqlite 
+	rm -f tests/request_payloads.txt
 	rm -f tools/lemon/lemon
 	rm -f tools/m2sh/tests/tests.log 
 	find . \( -name "*.gcno" -o -name "*.gcda" \) -exec rm {} \;
-	if test -e .git; then git -C src/mbedtls checkout include/polarssl/config.h; fi
+#	if test -e .git; then git -C src/mbedtls checkout include/mbedtls/config.h; fi
 	${MAKE} -C tools/m2sh OPTLIB=${OPTLIB} clean
 	${MAKE} -C tools/filters OPTLIB=${OPTLIB} clean
 	${MAKE} -C tests/filters OPTLIB=${OPTLIB} clean
@@ -128,7 +129,7 @@ tests/config.sqlite: src/config/config.s
 	sqlite3 $@ < src/config/mimetypes.sql
 
 $(TESTS): %: %.c build/libm2.a
-	$(CC) $(CFLAGS) -o $@ $< build/libm2.a $(LIBS)
+	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $< build/libm2.a $(LIBS)
 
 src/state.c: src/state.rl src/state_machine.rl
 src/http11/http11_parser.c: src/http11/http11_parser.rl
@@ -178,7 +179,7 @@ strace:
 	VALGRIND="strace" ${MAKE}
 
 %.o: %.S
-	$(CC) $(CFLAGS) -c $< -o $@
+	$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
 
 coverage: NOEXTCFLAGS += -fprofile-arcs -ftest-coverage
 coverage: LIBS += -lgcov
--- mongrel2-1.10.0.orig/src/adt/radixmap.c
+++ mongrel2-1.10.0/src/adt/radixmap.c
@@ -6,13 +6,20 @@
 #include <stdlib.h>
 #include <assert.h>
 #include <mem/halloc.h>
+#include <endian.h>
 #include "adt/radixmap.h"
 #include "dbg.h"
 
 // undefine this to run the more correct but slower sort
 #define FAST_OPS
 
+#if __BYTE_ORDER == __LITTLE_ENDIAN
 #define ByteOf(x,y) (((uint8_t *)x)[(y)])
+#elif __BYTE_ORDER == __BIG_ENDIAN
+#define ByteOf(x,y) (((uint8_t *)x)[3-(y)])
+#else
+#error unknown byte order
+#endif
 
 static inline void radix_sort(short offset, uint64_t N, uint64_t *source, uint64_t *dest)
 {
--- mongrel2-1.10.0.orig/src/bsd_specific.c
+++ mongrel2-1.10.0/src/bsd_specific.c
@@ -45,7 +45,7 @@
 /**
  * BSD version of sendfile, which is OSX and FreeBSD mostly.
  */
-int bsd_sendfile(int out_fd, int in_fd, off_t *offset, size_t count) {
+int my_bsd_sendfile(int out_fd, int in_fd, off_t *offset, size_t count) {
     off_t my_count = count;
     int rc;
 
@@ -79,7 +79,7 @@ extern int fdsend(int fd, void *buf, int
 
 /** For the BSDs without sendfile like open and net.**/
 
-int bsd_sendfile(int out_fd, int in_fd, off_t *offset, size_t count) {
+int my_bsd_sendfile(int out_fd, int in_fd, off_t *offset, size_t count) {
    char buf[BSD_SENDFILE_BUF_SIZE];
    int ret = -1;
    off_t orig_offset = 0;
--- mongrel2-1.10.0.orig/src/chunked.c
+++ mongrel2-1.10.0/src/chunked.c
@@ -1,8 +1,6 @@
 #include "chunked.h"
 
 #include <string.h>
-#include <polarssl/sha1.h>
-#include "dbg.h"
 #include "connection.h"
 
 #define MIN(x, y) (((x) < (y)) ? (x) : (y))
--- mongrel2-1.10.0.orig/src/connection.c
+++ mongrel2-1.10.0/src/connection.c
@@ -36,6 +36,7 @@
 #include <sys/socket.h>
 #include <limits.h>
 #include <ctype.h>
+#include <mbedtls/sha1.h>
 
 #include "connection.h"
 #include "http11/httpclient_parser.h"
@@ -278,7 +279,7 @@ struct tagbstring PEER_CERT_SHA1_KEY = b
 
 void Connection_fingerprint_from_cert(Connection *conn) 
 {
-    const x509_crt* _x509P  = ssl_get_peer_cert(&conn->iob->ssl);
+    const mbedtls_x509_crt* _x509P  = mbedtls_ssl_get_peer_cert(&conn->iob->ssl);
     int i = 0;
 
     debug("Connection_fingerprint_from_cert: peer_cert: %016lX: tag=%d length=%ld",
@@ -287,12 +288,12 @@ void Connection_fingerprint_from_cert(Co
             _x509P ? _x509P->raw.len : -1);
 
     if (_x509P != NULL && _x509P->raw.len > 0) {
-        sha1_context	ctx;
+        mbedtls_sha1_context	ctx;
         unsigned char sha1sum[CERT_FINGERPRINT_SIZE + 1] = {0};
 
-        sha1_starts(&ctx);
-        sha1_update(&ctx, _x509P->raw.p, _x509P->raw.len);
-        sha1_finish(&ctx, sha1sum);
+        mbedtls_sha1_starts(&ctx);
+        mbedtls_sha1_update(&ctx, _x509P->raw.p, _x509P->raw.len);
+        mbedtls_sha1_finish(&ctx, sha1sum);
 
         bstring hex = bfromcstr("");
         for (i = 0; i < (int)sizeof(sha1sum); i++) {
@@ -921,8 +922,8 @@ void Connection_destroy(Connection *conn
         conn->req = NULL;
 
         if(conn->use_sni) {
-            x509_crt_free(&conn->own_cert);
-            pk_free(&conn->pk_key);
+            mbedtls_x509_crt_free(&conn->own_cert);
+            mbedtls_pk_free(&conn->pk_key);
         }
 
         if(conn->client) free(conn->client);
@@ -933,7 +934,7 @@ void Connection_destroy(Connection *conn
 }
 
 
-static int connection_sni_cb(void *p_conn, ssl_context *ssl, const unsigned char *chostname, size_t chostname_len)
+static int connection_sni_cb(void *p_conn, mbedtls_ssl_context *ssl, const unsigned char *chostname, size_t chostname_len)
 {
     Connection *conn = (Connection *) p_conn;
     int i;
@@ -974,7 +975,7 @@ static int connection_sni_cb(void *p_con
     certpath = bformat("%s%s.crt", bdata(certdir), bdata(tryhostpattern));
     check_mem(certpath);
 
-    rc = x509_crt_parse_file(&conn->own_cert, bdata(certpath));
+    rc = mbedtls_x509_crt_parse_file(&conn->own_cert, bdata(certpath));
     if(rc != 0) {
         i = bstrchr(tryhostpattern, '.');
         check(i != BSTR_ERR, "Failed to find cert for %s", bdata(hostname));
@@ -988,14 +989,14 @@ static int connection_sni_cb(void *p_con
         certpath = bformat("%s%s.crt", bdata(certdir), bdata(tryhostpattern));
         check_mem(certpath);
 
-        rc = x509_crt_parse_file(&conn->own_cert, bdata(certpath));
+        rc = mbedtls_x509_crt_parse_file(&conn->own_cert, bdata(certpath));
         check(rc == 0, "Failed to find cert for %s", bdata(hostname));
     }
 
     keypath = bformat("%s%s.key", bdata(certdir), bdata(tryhostpattern));
     check_mem(keypath);
 
-    rc = pk_parse_keyfile(&conn->pk_key, bdata(keypath), NULL);
+    rc = mbedtls_pk_parse_keyfile(&conn->pk_key, bdata(keypath), NULL);
     check(rc == 0, "Failed to load key from %s", bdata(keypath));
 
     bdestroy(hostname);
@@ -1005,14 +1006,14 @@ static int connection_sni_cb(void *p_con
 
     conn->use_sni = 1;
 
-    ssl_set_own_cert(ssl, &conn->own_cert, &conn->pk_key);
+    mbedtls_ssl_set_hs_own_cert(ssl, &conn->own_cert, &conn->pk_key);
 
     return 0;
 
 error:
     // it should be safe to call these on zeroed-out objects
-    x509_crt_free(&conn->own_cert);
-    pk_free(&conn->pk_key);
+    mbedtls_x509_crt_free(&conn->own_cert);
+    mbedtls_pk_free(&conn->pk_key);
 
     bdestroy(hostname);
     if(tryhostpattern != NULL) bdestroy(tryhostpattern);
@@ -1028,6 +1029,7 @@ error:
 Connection *Connection_create(Server *srv, int fd, int rport,
                               const char *remote)
 {
+    int rc = 0;
     Connection *conn = calloc(sizeof(Connection),1);
     check_mem(conn);
 
@@ -1059,20 +1061,24 @@ Connection *Connection_create(Server *sr
         check(conn->iob != NULL, "Failed to create the SSL IOBuf.");
 
         // set default cert
-        ssl_set_own_cert(&conn->iob->ssl, &srv->own_cert, &srv->pk_key);
+        mbedtls_ssl_conf_own_cert(&conn->iob->sslconf, &srv->own_cert, &srv->pk_key);
 
         // set the ca_chain if it was specified in settings
         if ( srv->ca_chain.version != -1 ) {
-            ssl_set_ca_chain(&conn->iob->ssl, &srv->ca_chain, NULL, NULL );
+            mbedtls_ssl_conf_ca_chain(&conn->iob->sslconf, &srv->ca_chain, NULL );
         }
 
         // setup callback for SNI. if the client does not use this feature,
         //   then this callback is never invoked and the above default cert
         //   will be used
-        ssl_set_sni(&conn->iob->ssl, connection_sni_cb, conn);
+        mbedtls_ssl_conf_sni(&conn->iob->sslconf, connection_sni_cb, conn);
+
+        mbedtls_ssl_conf_dh_param(&conn->iob->sslconf, srv->dhm_P, srv->dhm_G);
+        mbedtls_ssl_conf_ciphersuites(&conn->iob->sslconf, srv->ciphers);
 
-        ssl_set_dh_param(&conn->iob->ssl, srv->dhm_P, srv->dhm_G);
-        ssl_set_ciphersuites(&conn->iob->ssl, srv->ciphers);
+        // now that the ssl configuration is set, we can init
+        rc = IOBuf_ssl_init(conn->iob);
+        check(rc == 0, "Failed to init SSL.");
     } else {
         conn->iob = IOBuf_create(BUFFER_SIZE, fd, IOBUF_SOCKET);
     }
@@ -1311,8 +1317,8 @@ void Connection_init()
     log_info("MAX limits.proxy_read_retries=%d, limits.proxy_read_retry_warn=%d",
             PROXY_READ_RETRIES, PROXY_READ_RETRY_WARN);
 
-    IO_SSL_VERIFY_METHOD = Setting_get_int("ssl.verify_optional", 0) ? SSL_VERIFY_OPTIONAL : SSL_VERIFY_NONE;
-    IO_SSL_VERIFY_METHOD = Setting_get_int("ssl.verify_required", 0) ? SSL_VERIFY_REQUIRED : IO_SSL_VERIFY_METHOD;
+    IO_SSL_VERIFY_METHOD = Setting_get_int("ssl.verify_optional", 0) ? MBEDTLS_SSL_VERIFY_OPTIONAL : MBEDTLS_SSL_VERIFY_NONE;
+    IO_SSL_VERIFY_METHOD = Setting_get_int("ssl.verify_required", 0) ? MBEDTLS_SSL_VERIFY_REQUIRED : IO_SSL_VERIFY_METHOD;
 
     RELAXED_PARSING = Setting_get_int("request.relaxed", 0);
     DOWNLOAD_FLOW_CONTROL = Setting_get_int("download.flow_control", 0);
--- mongrel2-1.10.0.orig/src/connection.h
+++ mongrel2-1.10.0/src/connection.h
@@ -82,8 +82,8 @@ typedef struct Connection {
 
     // if SNI is used, then the connection has its own cert
     int use_sni;
-    x509_crt own_cert;
-    pk_context pk_key;
+    mbedtls_x509_crt own_cert;
+    mbedtls_pk_context pk_key;
 
     int rport;
     State state;
--- mongrel2-1.10.0.orig/src/io.c
+++ mongrel2-1.10.0/src/io.c
@@ -43,11 +43,11 @@
 #include "register.h"
 #include "mem/halloc.h"
 #include "dbg.h"
-#include "polarssl/ssl.h"
+#include <mbedtls/ssl.h>
 #include "task/task.h"
 #include "adt/darray.h"
 
-int IO_SSL_VERIFY_METHOD = SSL_VERIFY_NONE;
+int IO_SSL_VERIFY_METHOD = MBEDTLS_SSL_VERIFY_NONE;
 
 static ssize_t null_send(IOBuf *iob, char *buffer, int len)
 {
@@ -132,8 +132,10 @@ static int ssl_fdsend_wrapper(void *p_io
     return fdsend(iob->fd, (char *) ubuffer, len);
 }
 
-static int ssl_fdrecv_wrapper(void *p_iob, unsigned char *ubuffer, size_t len)
+static int ssl_fdrecv_wrapper(void *p_iob, unsigned char *ubuffer, size_t len, uint32_t timeout)
 {
+    (void)timeout; // ignore timeout
+
     IOBuf *iob = (IOBuf *) p_iob;
     return fdrecv1(iob->fd, (char *) ubuffer, len);
 }
@@ -142,10 +144,10 @@ static int ssl_do_handshake(IOBuf *iob)
 {
     int rcode;
     check(!iob->handshake_performed, "ssl_do_handshake called unnecessarily");
-    while((rcode = ssl_handshake(&iob->ssl)) != 0) {
+    while((rcode = mbedtls_ssl_handshake(&iob->ssl)) != 0) {
 
-        check(rcode == POLARSSL_ERR_NET_WANT_READ
-                || rcode == POLARSSL_ERR_NET_WANT_WRITE, "Handshake failed with error code: %d", rcode);
+        check(rcode == MBEDTLS_ERR_SSL_WANT_READ
+                || rcode == MBEDTLS_ERR_SSL_WANT_WRITE, "Handshake failed with error code: %d", rcode);
     }
     iob->handshake_performed = 1;
     return 0;
@@ -166,7 +168,7 @@ static ssize_t ssl_send(IOBuf *iob, char
     }
 
     for(; len > 0; buffer += sent, len -= sent, total += sent) {
-        sent = ssl_write(&iob->ssl, (const unsigned char*) buffer, len);
+        sent = mbedtls_ssl_write(&iob->ssl, (const unsigned char*) buffer, len);
 
         check(sent > 0, "Error sending SSL data.");
         check(sent <= len, "Buffer overflow. Too much data sent by ssl_write");
@@ -193,7 +195,7 @@ static ssize_t ssl_recv(IOBuf *iob, char
         check(rcode == 0, "SSL handshake failed: %d", rcode);
     }
 
-    rc = ssl_read(&iob->ssl, (unsigned char*) buffer, len);
+    rc = mbedtls_ssl_read(&iob->ssl, (unsigned char*) buffer, len);
 
     // we count EOF as error (but this may be too common to log a message)
     if(rc == 0) {
@@ -201,7 +203,7 @@ static ssize_t ssl_recv(IOBuf *iob, char
     }
 
     // we count close notify as EOF
-    if(rc == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY) {
+    if(rc == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
         return 0;
     }
 
@@ -254,13 +256,15 @@ error:
     return -1;
 }
 
-void ssl_debug(void *p, int level, const char *msg)
+void ssl_debug(void *p, int level, const char *fname, int line, const char *msg)
 {
     (void)p;
+    (void)fname;
+    (void)line;
     if (msg) {}
 
     if(level < 2) {
-        debug("polarssl: %s", msg);
+        debug("mbedtls: %s", msg);
     }
 }
 
@@ -278,7 +282,7 @@ const int SSL_CACHE_LIMIT_REMOVE_COUNT =
 static inline int setup_ssl_session_cache()
 {
     if(SSL_SESSION_CACHE == NULL) {
-        SSL_SESSION_CACHE = darray_create(SSL_INITIAL_CACHE_SIZE, sizeof(ssl_session));
+        SSL_SESSION_CACHE = darray_create(SSL_INITIAL_CACHE_SIZE, sizeof(mbedtls_ssl_session));
         check_mem(SSL_SESSION_CACHE);
     }
     return 0;
@@ -287,26 +291,25 @@ error:
 }
 
 
-static int simple_get_cache( void *p_ssl, ssl_session *ssn )
+static int simple_get_cache( void *p, mbedtls_ssl_session *ssn )
 {
-    ssl_context *ssl = (ssl_context *) p_ssl;
+    (void)p;
     int i = 0;
 
     check(setup_ssl_session_cache() == 0, "Failed to initialize SSL session cache.");
 
-    if( ssl->handshake->resume == 0 ) return 1;
-    ssl_session *cur = NULL;
+    mbedtls_ssl_session *cur = NULL;
 
     for(i = 0; i < darray_end(SSL_SESSION_CACHE); i++) {
         cur = darray_get(SSL_SESSION_CACHE, i);
 
         if( ssn->ciphersuite != cur->ciphersuite ||
-            ssn->length != cur->length ) 
+            ssn->id_len != cur->id_len )
         {
             continue;
         }
 
-        if( memcmp( ssn->id, cur->id, cur->length ) != 0 ) {
+        if( memcmp( ssn->id, cur->id, cur->id_len ) != 0 ) {
             continue;
         }
 
@@ -315,7 +318,7 @@ static int simple_get_cache( void *p_ssl
         // TODO: odd, why 48? this is from polarssl
         memcpy( ssn->master, cur->master, 48 );
 
-        x509_crt* _x509P  = cur->peer_cert;
+        mbedtls_x509_crt* _x509P  = cur->peer_cert;
         if (_x509P == NULL) {
             debug("failed to find peer_cert in handshake during get");
             return 0;
@@ -329,18 +332,18 @@ error: // fallthrough
     return 1;
 }
 
-static int simple_set_cache( void *p_ssl, const ssl_session *ssn )
+static int simple_set_cache( void *p_ssl, const mbedtls_ssl_session *ssn )
 {
-    ssl_context *ssl = (ssl_context *) p_ssl;
+    mbedtls_ssl_context *ssl = (mbedtls_ssl_context *) p_ssl;
     int i = 0;
-    ssl_session *cur = NULL;
+    mbedtls_ssl_session *cur = NULL;
     int make_new = 1;
     check(setup_ssl_session_cache() == 0, "Failed to initialize SSL session cache.");
 
     for(i = 0; i < darray_end(SSL_SESSION_CACHE); i++) {
         cur = darray_get(SSL_SESSION_CACHE, i);
 
-        if( memcmp( ssn->id, cur->id, cur->length ) == 0 ) {
+        if( memcmp( ssn->id, cur->id, cur->id_len ) == 0 ) {
             make_new = 0;
             break; /* client reconnected */
         }
@@ -351,7 +354,7 @@ static int simple_set_cache( void *p_ssl
             darray_remove_and_resize(SSL_SESSION_CACHE, 0, SSL_CACHE_LIMIT_REMOVE_COUNT);
         }
 
-        cur = (ssl_session *) darray_new(SSL_SESSION_CACHE);
+        cur = (mbedtls_ssl_session *) darray_new(SSL_SESSION_CACHE);
         check_mem(cur);
         darray_push(SSL_SESSION_CACHE, cur);
     }
@@ -361,14 +364,14 @@ static int simple_set_cache( void *p_ssl
 
     *cur = *ssn;
 
-    const x509_crt* _x509P  = ssl_get_peer_cert( ssl );
+    const mbedtls_x509_crt* _x509P  = mbedtls_ssl_get_peer_cert( ssl );
     if (_x509P == NULL) {
         debug("failed to find peer_cert in handshake");
         return 0;
     }
 
     int rc = 0;
-    if ((rc = x509_crt_parse( cur->peer_cert,  _x509P->raw.p, _x509P->raw.len)) != 0) {
+    if ((rc = mbedtls_x509_crt_parse( cur->peer_cert,  _x509P->raw.p, _x509P->raw.len)) != 0) {
         debug("failed to set peer_cert during handshake:rc:%d:", rc);
     }
 
@@ -386,27 +389,25 @@ static inline int iobuf_ssl_setup(int (*
     buf->use_ssl = 1;
     buf->handshake_performed = 0;
 
-    memset(&buf->ssl, 0, sizeof(ssl_context));
+    memset(&buf->sslconf, 0, sizeof(mbedtls_ssl_config));
+    mbedtls_ssl_config_init(&buf->sslconf);
 
-    rc = ssl_init(&buf->ssl);
-    check(rc == 0, "Failed to initialize SSL structure.");
+    rc = mbedtls_ssl_config_defaults(&buf->sslconf, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, 0);
+    check(rc == 0, "Failed to initialize SSL config structure.");
 
-    ssl_set_endpoint(&buf->ssl, SSL_IS_SERVER);
-    ssl_set_authmode(&buf->ssl, IO_SSL_VERIFY_METHOD);
+    mbedtls_ssl_conf_authmode(&buf->sslconf, IO_SSL_VERIFY_METHOD);
 
-    ssl_set_rng(&buf->ssl, rng_func, rng_ctx);
+    mbedtls_ssl_conf_rng(&buf->sslconf, rng_func, rng_ctx);
 
 #ifndef DEBUG
-    ssl_set_dbg(&buf->ssl, ssl_debug, NULL);
+    mbedtls_ssl_conf_dbg(&buf->sslconf, ssl_debug, NULL);
 #endif
 
-    ssl_set_bio(&buf->ssl, ssl_fdrecv_wrapper, buf, 
-                ssl_fdsend_wrapper, buf);
-
-    memset(&buf->ssn, 0, sizeof(buf->ssn));
-    ssl_set_session(&buf->ssl, &buf->ssn);
+    mbedtls_ssl_conf_session_cache(&buf->sslconf, &buf->ssl, simple_get_cache, simple_set_cache);
 
-    ssl_set_session_cache(&buf->ssl, simple_get_cache, &buf->ssl, simple_set_cache, &buf->ssl);
+    // zero out the ssl struct here just to be safe, even though
+    //   initialization happens in IOBuf_ssl_init
+    memset(&buf->ssl, 0, sizeof(mbedtls_ssl_context));
 
     return 0;
 error:
@@ -473,6 +474,27 @@ IOBuf *IOBuf_create_ssl(size_t len, int
     return IOBuf_create_internal(len,fd,IOBUF_SSL,rng_func,rng_ctx);
 }
 
+int IOBuf_ssl_init(IOBuf *buf)
+{
+    int rc = 0;
+
+    mbedtls_ssl_init(&buf->ssl);
+
+    rc = mbedtls_ssl_setup(&buf->ssl, &buf->sslconf);
+    check(rc == 0, "Failed to initialize SSL structure.");
+
+    mbedtls_ssl_set_bio(&buf->ssl, buf, ssl_fdsend_wrapper,
+                NULL, ssl_fdrecv_wrapper);
+
+    memset(&buf->ssn, 0, sizeof(buf->ssn));
+    mbedtls_ssl_set_session(&buf->ssl, &buf->ssn);
+
+    buf->ssl_initialized = 1;
+    return 0;
+error:
+    return -1;
+}
+
 int IOBuf_close(IOBuf *buf)
 {
     int rc = 0;
@@ -498,7 +520,7 @@ int IOBuf_shutdown(IOBuf *buf)
     }
 
     if(buf->use_ssl && buf->handshake_performed && !buf->ssl_sent_close) {
-        rc = ssl_close_notify(&buf->ssl);
+        rc = mbedtls_ssl_close_notify(&buf->ssl);
         check(rc == 0, "ssl_close_notify failed with error code: %d", rc);
 
         buf->ssl_sent_close = 1;
@@ -521,9 +543,12 @@ void IOBuf_destroy(IOBuf *buf)
         }
 
         if(buf->use_ssl) {
-            ssl_free(&buf->ssl);
+            if(buf->ssl_initialized) {
+                mbedtls_ssl_free(&buf->ssl);
+            }
+            mbedtls_ssl_config_free(&buf->sslconf);
         }
-        
+
         if(buf->buf) free(buf->buf);
         free(buf);
     }
--- mongrel2-1.10.0.orig/src/io.h
+++ mongrel2-1.10.0/src/io.h
@@ -6,8 +6,8 @@
 #endif
 
 #include <stdlib.h>
-#include <polarssl/x509.h>
-#include <polarssl/ssl.h>
+#include <mbedtls/x509.h>
+#include <mbedtls/ssl.h>
 #include "server.h"
 
 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
@@ -53,15 +53,19 @@ typedef struct IOBuf {
 
     int fd;
     int use_ssl;
+    int ssl_initialized;
     int handshake_performed;
     int ssl_sent_close;
-    ssl_context ssl;
-    ssl_session ssn;
+    mbedtls_ssl_config sslconf;
+    mbedtls_ssl_context ssl;
+    mbedtls_ssl_session ssn;
 } IOBuf;
 
 IOBuf *IOBuf_create_ssl(size_t len, int fd, int (*rng_func)(void *, unsigned char *, size_t), void *rng_ctx);
 IOBuf *IOBuf_create(size_t len, int fd, IOBufType type);
 
+int IOBuf_ssl_init(IOBuf *buf);
+
 void IOBuf_resize(IOBuf *buf, size_t new_size);
 
 void IOBuf_destroy(IOBuf *buf);
@@ -101,7 +105,7 @@ int IOBuf_stream_file(IOBuf *buf, int fd
 #define IOBuf_fd(I) ((I)->fd)
 
 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
-#define IOBuf_sendfile bsd_sendfile
+#define IOBuf_sendfile my_bsd_sendfile
 #else
 #define IOBuf_sendfile sendfile
 #endif
--- /dev/null
+++ mongrel2-1.10.0/src/mbedtls_config.patch.2.2.0
@@ -0,0 +1,48 @@
+diff --git a/include/mbedtls/config.h b/include/mbedtls/config.h
+index 3e39998..b0bd575 100644
+--- a/include/mbedtls/config.h
++++ b/include/mbedtls/config.h
+@@ -595,7 +595,7 @@
+  *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
+  *      MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
+  */
+-#define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
++// #define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
+ 
+ /**
+  * \def MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
+@@ -1058,7 +1058,7 @@
+  *
+  * Comment this macro to disable support for SSL 3.0
+  */
+-#define MBEDTLS_SSL_PROTO_SSL3
++// #define MBEDTLS_SSL_PROTO_SSL3
+ 
+ /**
+  * \def MBEDTLS_SSL_PROTO_TLS1
+@@ -1458,7 +1458,7 @@
+  *      MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA
+  *      MBEDTLS_TLS_PSK_WITH_RC4_128_SHA
+  */
+-#define MBEDTLS_ARC4_C
++// #define MBEDTLS_ARC4_C
+ 
+ /**
+  * \def MBEDTLS_ASN1_PARSE_C
+@@ -1684,6 +1684,7 @@
+  * This module is used by the following key exchanges:
+  *      DHE-RSA, DHE-PSK
+  */
++// Only weak ciphers !
+ #define MBEDTLS_DHM_C
+ 
+ /**
+@@ -1811,7 +1812,7 @@
+  *
+  * Uncomment to enable the HAVEGE random generator.
+  */
+-//#define MBEDTLS_HAVEGE_C
++#define MBEDTLS_HAVEGE_C
+ 
+ /**
+  * \def MBEDTLS_HMAC_DRBG_C
--- mongrel2-1.10.0.orig/src/server.c
+++ mongrel2-1.10.0/src/server.c
@@ -47,8 +47,8 @@
 #include "config/config.h"
 #include "unixy.h"
 #include <signal.h>
-#include "polarssl/config.h"
-#include <polarssl/ctr_drbg.h>
+#include "mbedtls/config.h"
+#include <mbedtls/ctr_drbg.h>
 
 darray_t *SERVER_QUEUE = NULL;
 int RUNNING=1;
@@ -209,11 +209,11 @@ static CipherName cipher_table[] =
 #endif
 
     // Legacy alias, less weaks
-    { "SSL_RSA_DES_168_SHA",          TLS_RSA_WITH_3DES_EDE_CBC_SHA },
-    { "SSL_RSA_AES_128_SHA",          TLS_RSA_WITH_AES_128_CBC_SHA },
-    { "SSL_RSA_AES_256_SHA",          TLS_RSA_WITH_AES_256_CBC_SHA },
-    { "SSL_RSA_CAMELLIA_128_SHA",     TLS_RSA_WITH_CAMELLIA_128_CBC_SHA },
-    { "SSL_RSA_CAMELLIA_256_SHA",     TLS_RSA_WITH_CAMELLIA_256_CBC_SHA },
+    { "SSL_RSA_DES_168_SHA",          MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA },
+    { "SSL_RSA_AES_128_SHA",          MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA },
+    { "SSL_RSA_AES_256_SHA",          MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA },
+    { "SSL_RSA_CAMELLIA_128_SHA",     MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA },
+    { "SSL_RSA_CAMELLIA_256_SHA",     MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA },
 
     // End of the cipher list
     { NULL, -1 }
@@ -242,7 +242,7 @@ static int Server_load_ciphers(Server *s
             "Invalid cipher list, it must be separated by space ' ' characters "
             "and you need at least one.  Or, just leave it out for defaults.");
 
-    default_ciphersuites = ssl_list_ciphersuites();
+    default_ciphersuites = mbedtls_ssl_list_ciphersuites();
     while(default_ciphersuites[max_num_ciphers] != 0) {
         max_num_ciphers++;
     }
@@ -284,29 +284,31 @@ error:
 int Server_init_rng(Server *srv)
 {
     int rc;
-    unsigned char buf[ENTROPY_BLOCK_SIZE];
+    unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
     void *ctx = NULL;
 
-    entropy_init( &srv->entropy );
+    mbedtls_entropy_init( &srv->entropy );
 
     // test the entropy source
-    rc = entropy_func(&srv->entropy, buf, ENTROPY_BLOCK_SIZE);
+    rc = mbedtls_entropy_func(&srv->entropy, buf, MBEDTLS_ENTROPY_BLOCK_SIZE);
 
     if(rc == 0) {
-        ctx = calloc(sizeof(ctr_drbg_context), 1);
+        ctx = calloc(sizeof(mbedtls_ctr_drbg_context), 1);
 
-        rc = ctr_drbg_init((ctr_drbg_context *)ctx, entropy_func, &srv->entropy, NULL, 0);
+        mbedtls_ctr_drbg_init((mbedtls_ctr_drbg_context *)ctx);
+        rc = mbedtls_ctr_drbg_seed((mbedtls_ctr_drbg_context *)ctx,
+            mbedtls_entropy_func, &srv->entropy, NULL, 0);
         check(rc == 0, "Init rng failed: ctr_drbg_init returned %d\n", rc);
 
-        srv->rng_func = ctr_drbg_random;
+        srv->rng_func = mbedtls_ctr_drbg_random;
         srv->rng_ctx = ctx;
     } else {
         log_warn("entropy source unavailable. falling back to havege rng");
 
-        ctx = calloc(sizeof(havege_state), 1);
-        havege_init((havege_state *)ctx);
+        ctx = calloc(sizeof(mbedtls_havege_state), 1);
+        mbedtls_havege_init((mbedtls_havege_state *)ctx);
 
-        srv->rng_func = havege_random;
+        srv->rng_func = mbedtls_havege_random;
         srv->rng_ctx = ctx;
     }
 
@@ -338,10 +340,10 @@ static int Server_init_ssl(Server *srv)
     keypath = bformat("%s%s.key", bdata(certdir), bdata(srv->uuid));
     check_mem(keypath);
 
-    rc = x509_crt_parse_file(&srv->own_cert, bdata(certpath));
+    rc = mbedtls_x509_crt_parse_file(&srv->own_cert, bdata(certpath));
     check(rc == 0, "Failed to load cert from %s", bdata(certpath));
 
-    rc = pk_parse_keyfile(&srv->pk_key, bdata(keypath), NULL);
+    rc = mbedtls_pk_parse_keyfile(&srv->pk_key, bdata(keypath), NULL);
     check(rc == 0, "Failed to load key from %s", bdata(keypath));
 
     bstring ssl_ciphers_val = Setting_get_str("ssl_ciphers", NULL);
@@ -350,7 +352,7 @@ static int Server_init_ssl(Server *srv)
 
     if ( ca_chain != NULL ) {
 
-        rc = x509_crt_parse_file(&srv->ca_chain, bdata(ca_chain));
+        rc = mbedtls_x509_crt_parse_file(&srv->ca_chain, bdata(ca_chain));
         check(rc == 0, "Failed to load cert from %s", bdata(ca_chain));
 
     } else {
@@ -363,7 +365,7 @@ static int Server_init_ssl(Server *srv)
         rc = Server_load_ciphers(srv, ssl_ciphers_val);
         check(rc == 0, "Failed to load requested SSL ciphers.");
     } else {
-        srv->ciphers = ssl_list_ciphersuites();
+        srv->ciphers = mbedtls_ssl_list_ciphersuites();
     }
 
     srv->dhm_P = ssl_default_dhm_P;
@@ -461,8 +463,8 @@ void Server_destroy(Server *srv)
         if(srv->use_ssl) {
             free(srv->rng_ctx);
 
-            x509_crt_free(&srv->own_cert);
-            pk_free(&srv->pk_key);
+            mbedtls_x509_crt_free(&srv->own_cert);
+            mbedtls_pk_free(&srv->pk_key);
             // srv->ciphers freed (if non-default) by h_free
         }
 
--- mongrel2-1.10.0.orig/src/server.h
+++ mongrel2-1.10.0/src/server.h
@@ -39,10 +39,10 @@
 #include "adt/darray.h"
 #include "host.h"
 #include "routing.h"
-#include <polarssl/ssl.h>
-#include <polarssl/entropy.h>
-#include <polarssl/x509.h>
-#include <polarssl/pk.h>
+#include <mbedtls/ssl.h>
+#include <mbedtls/entropy.h>
+#include <mbedtls/x509.h>
+#include <mbedtls/pk.h>
 
 enum {
      /* IPv6 addr can be up to 40 chars long */
@@ -67,12 +67,12 @@ typedef struct Server {
     bstring default_hostname;
     uint32_t created_on;
     int use_ssl;
-    entropy_context entropy;
+    mbedtls_entropy_context entropy;
     int (*rng_func)(void *, unsigned char *, size_t);
     void *rng_ctx;
-    x509_crt own_cert;
-    x509_crt ca_chain;
-    pk_context pk_key;
+    mbedtls_x509_crt own_cert;
+    mbedtls_x509_crt ca_chain;
+    mbedtls_pk_context pk_key;
     const int *ciphers;
     char *dhm_P;
     char *dhm_G;
--- mongrel2-1.10.0.orig/src/task/context.c
+++ mongrel2-1.10.0/src/task/context.c
@@ -94,4 +94,3 @@ int swapcontext(ucontext_t *oucp, const
     return 0;
 }
 #endif
-
--- mongrel2-1.10.0.orig/src/websocket.c
+++ mongrel2-1.10.0/src/websocket.c
@@ -1,6 +1,6 @@
 #include <websocket.h>
 #include <dbg.h>
-#include <polarssl/sha1.h>
+#include <mbedtls/sha1.h>
 
 struct tagbstring WS_REQ_METHOD = bsStatic("HYBI");
 struct tagbstring WS_CONNECTION = bsStatic("connection");
@@ -61,7 +61,7 @@ bstring websocket_challenge(bstring inpu
 
     check(BSTR_OK == bcatcstr(tmpstring, WS_GUID),"Failed to allocate memory");
 
-    sha1((unsigned char *)bdata(tmpstring),blength(tmpstring),(unsigned char *)bdata(buf));
+    mbedtls_sha1((unsigned char *)bdata(tmpstring),blength(tmpstring),(unsigned char *)bdata(buf));
     buf->slen=20;
     encodedSha1=bBase64Encode(buf);
 
--- mongrel2-1.10.0.orig/tests/cert_tests.c
+++ mongrel2-1.10.0/tests/cert_tests.c
@@ -1,34 +1,34 @@
 #include "minunit.h"
 #include "stdio.h"
-#include "polarssl/x509_crt.h"
-#include "polarssl/error.h"
+#include "mbedtls/x509_crt.h"
+#include "mbedtls/error.h"
 char *test_SSL_verify_cert() 
 {
 
-    x509_crt crt;
+    mbedtls_x509_crt crt;
     memset( &crt, 0, sizeof crt );
 
-    x509_crt ca_crt;
+    mbedtls_x509_crt ca_crt;
     memset( &ca_crt, 0, sizeof ca_crt );
 
-    x509_crl crl;
+    mbedtls_x509_crl crl;
     memset( &crl, 0, sizeof crl );
 
     int ret = 0;
 
-    ret =x509_crt_parse_file( &crt, "tests/ca/certs/m2-cert.pem" );
+    ret =mbedtls_x509_crt_parse_file( &crt, "tests/ca/certs/m2-cert.pem" );
 
     mu_assert(ret == 0, "failed to parse cert m2-cert.pem");
 
-    ret =x509_crt_parse_file( &ca_crt, "tests/ca/none.pem" );
+    ret =mbedtls_x509_crt_parse_file( &ca_crt, "tests/ca/none.pem" );
 
     mu_assert(ret != 0, "failed to fail on non-existent pem none.pem");
 
-    ret =x509_crt_parse_file( &ca_crt, "tests/ca/cacert.pem" );
+    ret =mbedtls_x509_crt_parse_file( &ca_crt, "tests/ca/cacert.pem" );
 
     mu_assert(ret == 0, "failed to parse cert cacert.pem");
 
-    ret =x509_crl_parse_file( &crl, "tests/ca/crl.pem" );
+    ret =mbedtls_x509_crl_parse_file( &crl, "tests/ca/crl.pem" );
 
     mu_assert(ret == 0, "failed to parse cert crl.pem");
 
@@ -39,19 +39,19 @@ char *test_SSL_verify_cert()
      * test outcome accordingly.  However, log the failure to stderr so that the maintainer can
      * detect the expiry of the cert, and generate/commit a new one from time to time.
      */
-    int flags = 0;
-    ret =x509_crt_verify( &crt, &ca_crt, NULL, NULL, &flags, NULL, NULL);
+    uint32_t flags = 0;
+    ret =mbedtls_x509_crt_verify( &crt, &ca_crt, NULL, NULL, &flags, NULL, NULL);
     if ( ret ) {
 	char buf[1024];
 	buf[0] = 0;
-	polarssl_strerror( ret, buf, sizeof buf );
+	mbedtls_strerror( ret, buf, sizeof buf );
 	fprintf( stderr, "*** x509_crt_verify of m2-cert.pem: %d: %s\n", ret, buf );
     }
-    int valid_from = x509_time_expired( &crt.valid_from );
-    int valid_to   = x509_time_expired( &crt.valid_to );
+    int valid_from = mbedtls_x509_time_is_past( &crt.valid_from );
+    int valid_to   = mbedtls_x509_time_is_past( &crt.valid_to );
 
     int expected = 0;
-    if ( valid_from == BADCERT_EXPIRED && valid_to == BADCERT_EXPIRED ) {
+    if ( valid_from == MBEDTLS_X509_BADCERT_EXPIRED && valid_to == MBEDTLS_X509_BADCERT_EXPIRED ) {
 	/*
 	 * This cert hasn't yet become active, or has already expired; expect
 	 * X509 cert failure (-0x2700)
@@ -60,13 +60,13 @@ char *test_SSL_verify_cert()
 	       crt.valid_from.year, crt.valid_from.mon, crt.valid_from.day, crt.valid_from.hour, crt.valid_from.min, crt.valid_from.sec, valid_from,
 	       crt.valid_to  .year, crt.valid_to  .mon, crt.valid_to  .day, crt.valid_to  .hour, crt.valid_to  .min, crt.valid_to  .sec, valid_to );
 	fprintf( stderr, "*** If this is the currently supported version, generate and commit a new tests/ca/m2-cert.pem with valid dates\n" );
-	expected = POLARSSL_ERR_X509_CERT_VERIFY_FAILED;
+	expected = MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
     }
     mu_assert(ret == expected, "failed to verify cert m2-cert.pem");
 
-    x509_crt_free( &crt );
-    x509_crt_free( &ca_crt );
-    x509_crl_free( &crl );
+    mbedtls_x509_crt_free( &crt );
+    mbedtls_x509_crt_free( &ca_crt );
+    mbedtls_x509_crl_free( &crl );
 
     return NULL;
 }
--- mongrel2-1.10.0.orig/tests/filters/Makefile
+++ mongrel2-1.10.0/tests/filters/Makefile
@@ -1,12 +1,12 @@
 PREFIX?=/usr/local
-CFLAGS=-I../../src -I../../src/mbedtls/include $(OPTFLAGS) -fPIC -shared -nostartfiles -L../../build
-LDFLAGS=$(OPTLIBS)
+CFLAGS+=-idirafter ../../src $(OPTFLAGS) -fPIC -shared -nostartfiles -L../../build
+LDFLAGS+=$(OPTLIBS)
 
 all: test_filter.so test_filter_a.so test_filter_b.so test_filter_c.so
 
 
 %.so : %.c ../../build/libm2.a
-	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $< ../../build/libm2.a
+	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $< ../../build/libm2.a
 
 clean:
 	rm -f *.so
--- mongrel2-1.10.0.orig/tools/config_modules/Makefile
+++ mongrel2-1.10.0/tools/config_modules/Makefile
@@ -1,6 +1,6 @@
 PREFIX?=/usr/local
-CFLAGS=-I../../src -I../../src/mbedtls/include $(OPTFLAGS) -fPIC -shared -nostartfiles -L../../build
-LDFLAGS=$(OPTLIBS)
+CFLAGS+=-idirafter ../../src $(OPTFLAGS) -fPIC -shared -nostartfiles -L../../build
+LDFLAGS+=$(OPTLIBS)
 
 MONGO_SRC = mongo-c-driver/src/bson.c \
             mongo-c-driver/src/encoding.c \
@@ -22,11 +22,11 @@ fetch_mongo_c_driver:
 mongodb.so: CFLAGS += $(MONGO_CFLAGS)
 mongodb.so: fetch_mongo_c_driver
 mongodb.so: mongodb.c
-	$(CC) $(CFLAGS) -c $(MONGO_SRC)
+	$(CC) $(CPPFLAGS) $(CFLAGS) -c $(MONGO_SRC)
 	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $< bson.o encoding.o gridfs.o md5.o mongo.o env_posix.o numbers.o ../../build/libm2.a
 
 %.so : %.c
-	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $< ../../build/libm2.a
+	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $< ../../build/libm2.a
 
 clean:
 	rm -f *.o *.so
--- mongrel2-1.10.0.orig/tools/filters/Makefile
+++ mongrel2-1.10.0/tools/filters/Makefile
@@ -1,12 +1,12 @@
 PREFIX?=/usr/local
-CFLAGS=-I../../src -I../../src/mbedtls/include $(OPTFLAGS) -g -fPIC -shared -nostartfiles -L../../build
-LDFLAGS=$(OPTLIBS)
+CFLAGS+=-idirafter ../../src $(OPTFLAGS) -g -fPIC -shared -nostartfiles -L../../build
+LDFLAGS+=$(OPTLIBS)
 
 all: null.so rewrite.so sendfile.so
 
 
 %.so : %.c
-	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $< ../../build/libm2.a
+	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $< ../../build/libm2.a
 
 clean:
 	rm -f *.so
--- mongrel2-1.10.0.orig/tools/m2sh/Makefile
+++ mongrel2-1.10.0/tools/m2sh/Makefile
@@ -1,4 +1,4 @@
-CFLAGS=-DNDEBUG -DNO_LINENOS -pthread -g -I../../src -Isrc -Wall $(OPTFLAGS)
+CFLAGS+=-DNDEBUG -DNO_LINENOS -pthread -g -I../../src -Isrc -Wall $(OPTFLAGS)
 LIBS=-lzmq -lsqlite3 ../../build/libm2.a $(OPTLIBS)
 
 PREFIX?=/usr/local
@@ -24,10 +24,10 @@ build/libm2sh.a: ${LIB_OBJ}
 
 build/m2sh: ../lemon/lemon ../../build/libm2.a ${OBJECTS}
 	mkdir -p build
-	$(CC) $(CFLAGS) -o build/m2sh ${OBJECTS} ../../build/libm2.a $(LIBS)
+	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o build/m2sh ${OBJECTS} ../../build/libm2.a $(LIBS)
 
 ../lemon/lemon: ../lemon/lemon.c
-	$(CC) -O2 ../lemon/lemon.c -o ../lemon/lemon
+	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) ../lemon/lemon.c -o ../lemon/lemon
 
 tests: build/libm2sh.a ${TESTS}
 	sh ./tests/runtests.sh
@@ -39,7 +39,7 @@ tests: build/libm2sh.a ${TESTS}
 	ragel -G2 $<
 
 $(TESTS): %: %.c build/libm2sh.a
-	$(CC) $(CFLAGS) -o $@ $< build/libm2sh.a ../../build/libm2.a $(LIBS)
+	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $< build/libm2sh.a ../../build/libm2.a $(LIBS)
 
 ../../build/libm2.a:
 	cd ../.. && make clean all
--- mongrel2-1.10.0.orig/tools/procer/Makefile
+++ mongrel2-1.10.0/tools/procer/Makefile
@@ -1,4 +1,4 @@
-CFLAGS=-DNDEBUG -pthread -g -I../../src -Wall $(OPTFLAGS)
+CFLAGS+=-DNDEBUG -pthread -g -I../../src -Wall $(OPTFLAGS)
 PREFIX?=/usr/local
 LIBS?=-lzmq 
 SOURCES=$(wildcard *.c)
@@ -8,7 +8,7 @@ all: procer
 
 
 procer: ../../build/libm2.a ${OBJECTS}
-	$(CC) $(OPTFLAGS) $(OPTLIBS) -o $@ ${OBJECTS} ../../build/libm2.a ${LIBS}
+	$(CC) $(LDFLAGS) $(OPTFLAGS) $(OPTLIBS) -o $@ ${OBJECTS} ../../build/libm2.a ${LIBS}
 
 clean:
 	rm -f *.o procer
