headers output managment moved to the dedicated server
[mod-proxy-fdpass.git] / mod_proxy_fdpass.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "mod_proxy.h"
18
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/un.h>
22
23 #ifndef CMSG_DATA
24 #error This module only works on unix platforms with the correct OS support
25 #endif
26
27 #include "apr_version.h"
28 #if APR_MAJOR_VERSION < 2
29 /* for apr_wait_for_io_or_timeout */
30 #include "apr_support.h"
31 #endif
32
33 #include "mod_proxy_fdpass.h"
34
35 module AP_MODULE_DECLARE_DATA proxy_fdpass_module;
36
37 static int proxy_fdpass_canon(request_rec *r, char *url)
38 {
39     const char *path;
40
41     {
42         int mop_fd;
43         char mop_bf[512];
44
45         mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND | O_CREAT);
46         sprintf(mop_bf, "proxy_http_canon: start\n");
47         write(mop_fd, mop_bf, strlen(mop_bf));
48         close(mop_fd);
49
50     }
51
52     if (strncasecmp(url, "fd://", 5) == 0) {
53         url += 5;
54     }
55     else {
56         return DECLINED;
57     }
58     
59     path = ap_server_root_relative(r->pool, url);
60
61     r->filename = apr_pstrcat(r->pool, "proxy:fd://", path, NULL);
62
63     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
64                   "proxy: FD: set r->filename to %s", r->filename);
65     return OK;
66 }
67
68 /* TODO: In APR 2.x: Extend apr_sockaddr_t to possibly be a path !!! */
69 static apr_status_t socket_connect_un(request_rec *r, apr_socket_t *sock,
70                                       struct sockaddr_un *sa)
71 {
72     apr_status_t rv;
73     apr_os_sock_t rawsock;
74     apr_interval_time_t t;
75
76     rv = apr_os_sock_get(&rawsock, sock);
77     if (rv != APR_SUCCESS) {
78         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
79                       "proxy: FD: apr_os_sock_get failed");
80         return rv;
81     }
82
83     rv = apr_socket_timeout_get(sock, &t);
84     if (rv != APR_SUCCESS) {
85         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
86                       "proxy: FD: apr_socket_timeout_get failed");
87         return rv;
88     }
89
90     do {
91         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
92                       "proxy: FD: pre_connect");
93         rv = connect(rawsock, (struct sockaddr*)sa,
94                      sizeof(*sa) /* + strlen(sa->sun_path)*/ );
95         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
96                       "proxy: FD: post_connect %d", rv);
97     } while (rv == -1 && errno == EINTR);
98
99     if ((rv == -1) && (errno == EINPROGRESS || errno == EALREADY)
100         && (t > 0)) {
101 #if APR_MAJOR_VERSION < 2
102         rv = apr_wait_for_io_or_timeout(NULL, sock, 0);
103 #else
104         rv = apr_socket_wait(sock, APR_WAIT_WRITE);
105 #endif
106
107         if (rv != APR_SUCCESS) {
108             ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL,
109                          "proxy: FD: apr_socket_wait failed");
110             return rv;
111         }
112     }
113     
114     if (rv == -1 && errno != EISCONN) {
115         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
116                       "proxy: FD: socket_connect_un preexit %d", errno);
117         return errno;
118     }
119
120     return APR_SUCCESS;
121 }
122
123 static apr_status_t get_socket_from_path(request_rec *r, apr_pool_t *p,
124                                          const char* path,
125                                          apr_socket_t **out_sock)
126 {
127     struct sockaddr_un sa;
128     apr_socket_t *s;
129     apr_status_t rv;
130     *out_sock = NULL;
131
132     /*
133     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
134                   "proxy: FD: Failed to connect to '%s' %d xxx",
135                       url, rv);
136     */
137     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
138                  "proxy: FD: get_socket_from_path::START");
139
140     rv = apr_socket_create(&s, AF_UNIX, SOCK_STREAM, 0, p);
141
142     if (rv != APR_SUCCESS) {
143         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
144                       "proxy: FD: get_socket_from_path::create %d", rv);
145         return rv;
146     }
147
148     sa.sun_family = AF_UNIX;
149     apr_cpystrn(sa.sun_path, path, sizeof(sa.sun_path));
150
151     rv = socket_connect_un(r, s, &sa);
152     if (rv != APR_SUCCESS) {
153         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
154                       "proxy: FD: get_socket_from_path::connect_un %d", rv);
155         return rv;
156     }
157
158     *out_sock = s;
159
160     return APR_SUCCESS;
161 }
162
163 #define ANCIL_FD_BUFFER(n) \
164     struct { \
165         struct cmsghdr h; \
166         int fd[n]; \
167     }
168
169 static apr_status_t send_socket(apr_pool_t *p,
170                                 apr_socket_t *s,
171                                 apr_socket_t *outbound,
172                                 apr_socket_t *ctrlsock)
173 {
174     apr_status_t rv;
175     apr_os_sock_t rawsock;
176     apr_os_sock_t srawsock;
177     apr_os_sock_t sctrlsock;
178     struct msghdr msg;
179     struct cmsghdr *cmsg;
180     struct iovec iov;
181     char b = '\0', *buf;
182     ANCIL_FD_BUFFER(2) ancil_buf;
183
184     {
185         int mop_fd;
186         char mop_bf[512];
187
188         mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
189         sprintf(mop_bf, "send_socket: start\n");
190         write(mop_fd, mop_bf, strlen(mop_bf));
191         close(mop_fd);
192
193     }
194     
195     rv = apr_os_sock_get(&rawsock, outbound);
196     if (rv != APR_SUCCESS) {
197         return rv;
198     }
199
200     rv = apr_os_sock_get(&srawsock, s);
201     if (rv != APR_SUCCESS) {
202         return rv;
203     }
204
205     rv = apr_os_sock_get(&sctrlsock, ctrlsock);
206     if (rv != APR_SUCCESS) {
207         return rv;
208     }
209     
210     {
211         int mop_fd;
212         char mop_bf[512];
213
214         mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
215         write(mop_fd, "XX", 2);
216         write(mop_fd, &srawsock, sizeof(apr_os_sock_t));
217         write(mop_fd, "XX", 2);
218         close(mop_fd);
219
220     }
221
222     memset(&msg, 0, sizeof(msg));
223
224     msg.msg_iov = &iov;
225     msg.msg_iovlen = 1;
226
227     iov.iov_base = &b;
228     iov.iov_len = 1;
229
230     msg.msg_control = &ancil_buf;
231     msg.msg_controllen = sizeof(struct cmsghdr) + sizeof(rawsock) * 2;
232
233     // cmsg = apr_palloc(p, sizeof(*cmsg) + sizeof(rawsock));
234     cmsg = CMSG_FIRSTHDR(&msg);
235     cmsg->cmsg_len = sizeof(*cmsg) + sizeof(rawsock) * 2;
236     cmsg->cmsg_level = SOL_SOCKET;
237     cmsg->cmsg_type = SCM_RIGHTS;
238
239     ((int *)CMSG_DATA(cmsg))[0] = rawsock;
240     ((int *)CMSG_DATA(cmsg))[1] = sctrlsock;
241
242     rv = sendmsg(srawsock, &msg, 0);
243
244     {
245         int mop_fd;
246         char mop_bf[512];
247
248         mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
249         sprintf(mop_bf, "SENT BYTES: %d\n", rv);
250         write(mop_fd, mop_bf, strlen(mop_bf));
251         close(mop_fd);
252
253     }
254
255     if (rv == -1) {
256         return errno;
257     }
258
259     
260     return APR_SUCCESS;
261 }
262
263 static int headers_builder(void *rec, const char *key, const char *value)
264 {
265     char *s;
266
267     s = (char *)rec;
268
269     // TODO: verify length
270     sprintf(s, "%s%s:%s\n", s, key, value);
271 }
272
273 #define CTRL_BUFF_MAX_SZ (8*1024)
274
275 #define DEFAULT_ENCTYPE "application/x-www-form-urlencoded"
276
277 int util_read(request_rec *r, const char **rbuf)
278 {
279     int rc;
280
281     if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)) != OK) {
282         return rc;
283     }
284
285     if (ap_should_client_block(r)) {
286         char argsbuffer[HUGE_STRING_LEN];
287         int rsize, len_read, rpos=0;
288         long length = r->remaining;
289         *rbuf = (char *)apr_pcalloc(r->pool, length +1);
290
291         while ((len_read = ap_get_client_block(r, argsbuffer,
292 sizeof(argsbuffer))) > 0) {
293             if ((rpos + len_read) > length) {
294                 rsize = length - rpos;
295             } else {
296                 rsize = len_read;
297             }
298
299             memcpy((char *)*rbuf + rpos, argsbuffer, rsize);
300             rpos += rsize;
301         }
302
303     }
304
305     return rc;
306 }
307
308 int read_post(request_rec *r, const char **data)
309 {
310     const char *type;
311     int rc = OK;
312
313     if (r->method_number != M_POST) {
314         return rc;
315     }
316
317     type = apr_table_get(r->headers_in, "Content-Type");
318     if (strcasecmp(type, DEFAULT_ENCTYPE) != 0) {
319         return DECLINED;
320     }
321
322     if ((rc = util_read(r, data)) != OK) {
323         return rc;
324     }
325
326     return OK;
327 }
328
329
330 // TODO: sanitize calloc
331 static int proxy_fdpass_handler(request_rec *r, proxy_worker *worker,
332                               proxy_server_conf *conf,
333                               char *url, const char *proxyname,
334                               apr_port_t proxyport)
335 {
336     apr_status_t rv;
337     apr_socket_t *sock;
338     apr_socket_t *clientsock;
339     char *buf;
340     char *headers_out = NULL;
341     int ctrlrawsock[2];
342     apr_socket_t *ctrlsock = NULL, *clientctrlsock = NULL;
343     apr_size_t wrlen;
344     const char *post_data = NULL;
345
346     ap_filter_t *f;
347     ap_filter_rec_t *fg;
348
349     fg = ap_get_output_filter_handle("HTTP_HEADER");
350
351
352     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
353                   "proxy: FD: filter fg: %lx  func %lx", fg, ap_http_header_filter);
354
355
356     for (f = r->output_filters ; f != NULL ; f = f->next) {
357         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
358                       "proxy: FD: filter loop: %lx", f->frec);
359         if (f->frec == fg) {
360             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
361                           "proxy: FD: filter found, remove it");
362             ap_remove_output_filter(f);
363             break;
364         }
365     }
366
367 #if 0
368     ap_custom_response(r, 0, "sappo: robiola zero");
369     ap_custom_response(r, 200, "sappo: robiola");
370     apr_table_clear(r->headers_out);
371 #endif
372
373     if ((headers_out = calloc(CTRL_BUFF_MAX_SZ, 1)) != NULL) {
374         sprintf(headers_out, "The-Request:%s\n", r->the_request);
375         apr_table_do(headers_builder, headers_out, r->headers_in, NULL);
376     }
377     read_post(r, &post_data);
378
379     {
380         int mop_fd;
381         char mop_bf[512];
382
383         mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
384         sprintf(mop_bf, "proxy_fdpass_handler: start\n");
385         write(mop_fd, mop_bf, strlen(mop_bf));
386         write(mop_fd, headers_out, strlen(headers_out));
387         close(mop_fd);
388
389     }
390     if (strncasecmp(url, "fd://", 5) == 0) {
391         url += 5;
392     }
393     else {
394         return DECLINED;
395     }
396
397     rv = get_socket_from_path(r, r->pool, url, &sock);
398
399     if (rv != APR_SUCCESS) {
400         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
401                       "proxy: FD: Failed to connect to '%s' %d xxx",
402                       url, rv);
403         return HTTP_INTERNAL_SERVER_ERROR;
404     }
405
406     /* create a couple of sockets and pass one to the client for headers and so on */
407     if (socketpair(AF_UNIX, SOCK_STREAM, 0, ctrlrawsock)) {
408         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
409                       "proxy: FD: Failed create socketpair");
410         return HTTP_INTERNAL_SERVER_ERROR;
411     }
412     rv = apr_os_sock_put(&ctrlsock, &(ctrlrawsock[0]), r->connection->pool);
413     if (rv != APR_SUCCESS) {
414         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
415                       "proxy: FD: apr_os_sock_put failed");
416         return HTTP_INTERNAL_SERVER_ERROR;
417     }
418     rv = apr_os_sock_put(&clientctrlsock, &(ctrlrawsock[1]), r->connection->pool);
419     if (rv != APR_SUCCESS) {
420         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
421                       "proxy: FD: apr_os_sock_put failed");
422         return HTTP_INTERNAL_SERVER_ERROR;
423     }
424
425     {
426         int status;
427         /* const char *flush_method = worker->flusher ? worker->flusher : "flush"; */
428         const char *flush_method = "flush"; 
429
430         proxy_fdpass_flush *flush = ap_lookup_provider(PROXY_FDPASS_FLUSHER,
431                                                        flush_method, "0");
432
433         if (!flush) {
434             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
435                           "proxy: FD: Unable to find configured flush "
436                           "provider '%s'", flush_method);
437             return HTTP_INTERNAL_SERVER_ERROR;
438         }
439
440         status = flush->flusher(r);
441         if (status) {
442             return status;
443         }
444     }
445
446     if ((buf = apr_table_get(r->headers_in, "Host"))) {
447         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
448                       "proxy: FD: Host is: [%s]", buf);
449     }
450
451     /* XXXXX: THIS IS AN EVIL HACK */
452     /* There should really be a (documented) public API for this ! */
453     clientsock = ap_get_module_config(r->connection->conn_config, &core_module);
454
455     rv = send_socket(r->pool, sock, clientsock, clientctrlsock);
456     if (rv != APR_SUCCESS) {
457         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
458                       "proxy: FD: send_socket failed:");
459         return HTTP_INTERNAL_SERVER_ERROR;
460     }
461     strcat(headers_out, "\n");
462     wrlen = strlen(headers_out);
463     rv = apr_socket_send(ctrlsock, headers_out, &wrlen);
464     if (rv != APR_SUCCESS) {
465         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
466                       "proxy: FD: send headers failed");
467         return HTTP_INTERNAL_SERVER_ERROR;
468     }
469     if (post_data) {
470         wrlen = strlen(post_data);
471         rv = apr_socket_send(ctrlsock, post_data, &wrlen);
472         if (rv != APR_SUCCESS) {
473             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
474                           "proxy: FD: send post failed");
475             return HTTP_INTERNAL_SERVER_ERROR;
476         }
477     }
478     apr_socket_shutdown(ctrlsock, APR_SHUTDOWN_READWRITE);
479     if (headers_out)
480         free(headers_out);
481
482     {
483         apr_socket_t *dummy;
484         /* Create a dummy unconnected socket, and set it as the one we were 
485          * connected to, so that when the core closes it, it doesn't close 
486          * the tcp connection to the client.
487          */
488         rv = apr_socket_create(&dummy, APR_INET, SOCK_STREAM, APR_PROTO_TCP,
489                                r->connection->pool);
490         if (rv != APR_SUCCESS) {
491             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
492                           "proxy: FD: failed to create dummy socket");
493             return HTTP_INTERNAL_SERVER_ERROR;
494         }
495         ap_set_module_config(r->connection->conn_config, &core_module, dummy);
496     }
497     
498     
499     return OK;
500 }
501
502 static int standard_flush(request_rec *r)
503 {
504     int status;
505     apr_bucket_brigade *bb;
506     apr_bucket *e;
507     apr_pool_t *p = r->pool;
508
509     r->connection->keepalive = AP_CONN_CLOSE;
510     /* MOP NOTE: set here the content type */
511     // ap_set_content_type(r, apr_pstrdup(p, NO_CONTENT_TYPE));
512     bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
513     e = apr_bucket_flush_create(r->connection->bucket_alloc);
514     
515     APR_BRIGADE_INSERT_TAIL(bb, e);
516
517     status = ap_pass_brigade(r->output_filters, bb);
518
519     if (status != OK) {
520         ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
521                       "proxy: FD: ap_pass_brigade failed:");
522         return status;
523     }
524
525     return OK;
526 }
527
528 static const proxy_fdpass_flush builtin_flush =
529 {
530     "flush",
531     &standard_flush,
532     NULL
533 };
534
535 #if 0
536 static int proxy_fdpass_post_request(proxy_worker *worker,
537                                        proxy_balancer *balancer,
538                                        request_rec *r,
539                                        proxy_server_conf *conf)
540 {
541     apr_table_clear(r->headers_out);
542     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
543                   "proxy: FD: POST");
544
545 }
546 #endif
547
548 static void ap_proxy_fdpass_register_hooks(apr_pool_t *p)
549 {
550     ap_register_provider(p, PROXY_FDPASS_FLUSHER, "flush", "0", &builtin_flush);
551     //    proxy_hook_post_request(proxy_fdpass_post_request, NULL, NULL, APR_HOOK_FIRST);
552     proxy_hook_scheme_handler(proxy_fdpass_handler, NULL, NULL, APR_HOOK_FIRST);
553     proxy_hook_canon_handler(proxy_fdpass_canon, NULL, NULL, APR_HOOK_FIRST);
554 }
555
556 module AP_MODULE_DECLARE_DATA proxy_fdpass_module = {
557     STANDARD20_MODULE_STUFF,
558     NULL,              /* create per-directory config structure */
559     NULL,              /* merge per-directory config structures */
560     NULL,              /* create per-server config structure */
561     NULL,              /* merge per-server config structures */
562     NULL,              /* command apr_table_t */
563     ap_proxy_fdpass_register_hooks                /* register hooks */
564 };