reverted removed #endif
[mod-proxy-fdpass.git] / mod_proxy_fdpass2.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 #include <time.h>
23 #include <stdlib.h>
24
25 #ifndef CMSG_DATA
26 #error This module only works on unix platforms with the correct OS support
27 #endif
28
29 #include "apr_version.h"
30 #if APR_MAJOR_VERSION < 2
31 /* for apr_wait_for_io_or_timeout */
32 #include "apr_support.h"
33 #endif
34
35 #include "mod_proxy_fdpass2.h"
36
37 module AP_MODULE_DECLARE_DATA proxy_fdpass2_module;
38
39 #define ALTOUT_USOCK_N 10
40 #define ALTOUT_DEBUG 1
41 #define ALTOUT_DBG_FILE "/home/log/fdpass2.log"
42
43 static int proxy_fdpass2_canon(request_rec *r, char *url)
44 {
45     const char *path;
46     char sfx[16];
47
48 #if ALTOUT_DEBUG > 1
49     {
50         int mop_fd;
51         char mop_bf[512];
52
53         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
54         sprintf(mop_bf, "proxy_http_canon: start [%p]\n", r->headers_in);
55         write(mop_fd, mop_bf, strlen(mop_bf));
56         close(mop_fd);
57     }
58 #endif
59
60     if (strncasecmp(url, "fd://", 5) == 0) {
61         url += 5;
62     }
63     else {
64         return DECLINED;
65     }
66
67     path = ap_server_root_relative(r->pool, url);
68
69     sprintf(sfx, "%d.sock", rand() % ALTOUT_USOCK_N);
70     r->filename = apr_pstrcat(r->pool, "proxy:fd://", path, sfx, NULL);
71
72     /* ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
73        "proxy: FD: set r->filename to %s", r->filename); */
74     return OK;
75 }
76
77 /* TODO: In APR 2.x: Extend apr_sockaddr_t to possibly be a path !!! */
78 static apr_status_t socket_connect_un(request_rec *r, apr_socket_t *sock,
79                                       struct sockaddr_un *sa)
80 {
81     apr_status_t rv;
82     apr_os_sock_t rawsock;
83     apr_interval_time_t t;
84
85     rv = apr_os_sock_get(&rawsock, sock);
86     if (rv != APR_SUCCESS) {
87         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
88                       "proxy: FD: apr_os_sock_get failed");
89         return rv;
90     }
91
92     rv = apr_socket_timeout_get(sock, &t);
93     if (rv != APR_SUCCESS) {
94         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
95                       "proxy: FD: apr_socket_timeout_get failed");
96         return rv;
97     }
98
99     do {
100         /* ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
101            "proxy: FD: pre_connect"); */
102         rv = connect(rawsock, (struct sockaddr*)sa,
103                      sizeof(*sa) /* + strlen(sa->sun_path)*/ );
104         /* ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
105            "proxy: FD: post_connect %d", rv); */
106     } while (rv == -1 && errno == EINTR);
107
108     if ((rv == -1) && (errno == EINPROGRESS || errno == EALREADY)
109         && (t > 0)) {
110 #if APR_MAJOR_VERSION < 2
111         rv = apr_wait_for_io_or_timeout(NULL, sock, 0);
112 #else
113         rv = apr_socket_wait(sock, APR_WAIT_WRITE);
114 #endif
115
116         if (rv != APR_SUCCESS) {
117             ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL,
118                          "proxy: FD: apr_socket_wait failed");
119             return rv;
120         }
121     }
122
123     if (rv == -1 && errno != EISCONN) {
124         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
125                       "proxy: FD: socket_connect_un preexit %d", errno);
126         return errno;
127     }
128
129     return APR_SUCCESS;
130 }
131
132 static apr_status_t get_socket_from_path(request_rec *r, apr_pool_t *p,
133                                          const char* path,
134                                          apr_socket_t **out_sock)
135 {
136     struct sockaddr_un sa;
137     apr_socket_t *s;
138     apr_status_t rv;
139     *out_sock = NULL;
140
141     /*
142     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
143                   "proxy: FD: Failed to connect to '%s' %d xxx",
144                       url, rv);
145     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
146                  "proxy: FD: get_socket_from_path::START");
147     */
148
149     rv = apr_socket_create(&s, AF_UNIX, SOCK_STREAM, 0, p);
150
151     if (rv != APR_SUCCESS) {
152         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
153                       "proxy: FD: get_socket_from_path::create %d", rv);
154         return rv;
155     }
156
157     sa.sun_family = AF_UNIX;
158     apr_cpystrn(sa.sun_path, path, sizeof(sa.sun_path));
159
160     rv = socket_connect_un(r, s, &sa);
161     if (rv != APR_SUCCESS) {
162         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
163                       "proxy: FD: get_socket_from_path::connect_un %d", rv);
164         return rv;
165     }
166
167     *out_sock = s;
168
169     return APR_SUCCESS;
170 }
171
172 #define ANCIL_FD_BUFFER(n) \
173     struct { \
174         struct cmsghdr h; \
175         int fd[n]; \
176     }
177
178 static apr_status_t send_socket(apr_pool_t *p,
179                                 apr_socket_t *s,
180                                 apr_socket_t *outbound,
181                                 apr_socket_t *ctrlsock)
182 {
183     apr_status_t rv;
184     apr_os_sock_t rawsock;
185     apr_os_sock_t srawsock;
186     apr_os_sock_t sctrlsock;
187     struct msghdr msg;
188     struct cmsghdr *cmsg;
189     struct iovec iov;
190     char b = '\0', *buf;
191     ANCIL_FD_BUFFER(2) ancil_buf;
192
193 #if ALTOUT_DEBUG > 1
194     {
195         int mop_fd;
196         char mop_bf[512];
197
198         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
199         sprintf(mop_bf, "send_socket: start\n");
200         write(mop_fd, mop_bf, strlen(mop_bf));
201         close(mop_fd);
202     }
203 #endif
204
205     rv = apr_os_sock_get(&rawsock, outbound);
206     if (rv != APR_SUCCESS) {
207         return rv;
208     }
209
210     rv = apr_os_sock_get(&srawsock, s);
211     if (rv != APR_SUCCESS) {
212         return rv;
213     }
214
215     rv = apr_os_sock_get(&sctrlsock, ctrlsock);
216     if (rv != APR_SUCCESS) {
217         return rv;
218     }
219
220 #if ALTOUT_DEBUG > 1
221     {
222         int mop_fd;
223         char mop_bf[512];
224
225         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
226         write(mop_fd, "XX", 2);
227         write(mop_fd, &srawsock, sizeof(apr_os_sock_t));
228         write(mop_fd, "XX", 2);
229         close(mop_fd);
230     }
231 #endif
232
233     memset(&msg, 0, sizeof(msg));
234
235     msg.msg_iov = &iov;
236     msg.msg_iovlen = 1;
237
238     iov.iov_base = &b;
239     iov.iov_len = 1;
240
241     msg.msg_control = &ancil_buf;
242     msg.msg_controllen = sizeof(struct cmsghdr) + sizeof(rawsock) * 2;
243
244     // cmsg = apr_palloc(p, sizeof(*cmsg) + sizeof(rawsock));
245     cmsg = CMSG_FIRSTHDR(&msg);
246     cmsg->cmsg_len = sizeof(*cmsg) + sizeof(rawsock) * 2;
247     cmsg->cmsg_level = SOL_SOCKET;
248     cmsg->cmsg_type = SCM_RIGHTS;
249
250     ((int *)CMSG_DATA(cmsg))[0] = rawsock;
251     ((int *)CMSG_DATA(cmsg))[1] = sctrlsock;
252
253     rv = sendmsg(srawsock, &msg, 0);
254
255 #if ALTOUT_DEBUG > 1
256     {
257         int mop_fd;
258         char mop_bf[512];
259
260         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
261         sprintf(mop_bf, "SENT BYTES: %d\n", rv);
262         write(mop_fd, mop_bf, strlen(mop_bf));
263         close(mop_fd);
264     }
265
266     if (rv == -1) {
267         return errno;
268     }
269
270     return APR_SUCCESS;
271 }
272
273 static int headers_builder(void *rec, const char *key, const char *value)
274 {
275     char *s;
276
277     s = (char *)rec;
278
279 #if ALTOUT_DEBUG > 1
280     {
281         int mop_fd;
282         char mop_bf[512];
283
284         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
285         sprintf(mop_bf, "HEADERS_BUILDER: [%s:%s]\n", key, value);
286         write(mop_fd, mop_bf, strlen(mop_bf));
287         close(mop_fd);
288     }
289 #endif
290
291     // TODO: verify length
292     // sprintf(s, "%s%s:%s\n", s, key, value);
293     strcat(s, key);
294     strcat(s, ":");
295     strcat(s, value);
296     strcat(s, "\n");
297 }
298
299 #define CTRL_BUFF_MAX_SZ (8*1024)
300
301 #define DEFAULT_ENCTYPE "application/x-www-form-urlencoded"
302
303 int util_read(request_rec *r, const char **rbuf)
304 {
305     int rc;
306
307     if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)) != OK) {
308         return rc;
309     }
310
311     if (ap_should_client_block(r)) {
312         char argsbuffer[HUGE_STRING_LEN];
313         int rsize, len_read, rpos=0;
314         long length = r->remaining;
315         *rbuf = (char *)apr_pcalloc(r->pool, length +1);
316         if ((len_read = ap_get_client_block(r, argsbuffer,
317                                             sizeof(argsbuffer))) > 0) {
318             if ((rpos + len_read) > length) {
319                 rsize = length - rpos;
320             } else {
321                 rsize = len_read;
322             }
323
324             memcpy((char *)*rbuf + rpos, argsbuffer, rsize);
325             rpos += rsize;
326         }
327
328     }
329
330     return rc;
331 }
332
333 int read_post(request_rec *r, const char **data)
334 {
335     const char *type;
336     char *p, s_type[256];
337     int rc = OK;
338
339     s_type[255] = '\0';
340 #if ALTOUT_DEBUG > 1
341     {
342         int mop_fd;
343         char mop_bf[512];
344
345         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
346         sprintf(mop_bf, "read_post: start: numb: %d %d head_in: [%s]\n", r->method_number, M_POST, apr_table_get(r->headers_in, "Content-Type"));
347         write(mop_fd, mop_bf, strlen(mop_bf));
348         close(mop_fd);
349     }
350 #endif
351
352
353     if (r->method_number != M_POST) {
354         return rc;
355     }
356
357     type = apr_table_get(r->headers_in, "Content-Type");
358     strncpy(s_type, type, 255);
359     if (p = strchr(s_type, ';')) {
360         *p = '\0';
361     }
362
363     if (strcasecmp(s_type, DEFAULT_ENCTYPE) != 0) {
364         return DECLINED;
365     }
366
367     if ((rc = util_read(r, data)) != OK) {
368         return rc;
369     }
370
371 #if ALTOUT_DEBUG > 1
372     {
373         int mop_fd;
374         char mop_bf[512];
375
376         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
377         sprintf(mop_bf, "read_post: finish\n");
378         write(mop_fd, mop_bf, strlen(mop_bf));
379         close(mop_fd);
380     }
381 #endif
382
383     return OK;
384 }
385
386
387 // TODO: sanitize calloc
388 static int proxy_fdpass2_handler(request_rec *r, proxy_worker *worker,
389                               proxy_server_conf *conf,
390                               char *url, const char *proxyname,
391                               apr_port_t proxyport)
392 {
393     apr_status_t rv;
394     apr_socket_t *sock;
395     apr_socket_t *clientsock;
396     char *buf;
397     char *headers_out = NULL;
398     int ctrlrawsock[2];
399     apr_socket_t *ctrlsock = NULL, *clientctrlsock = NULL;
400     apr_size_t wrlen;
401     const char *post_data = NULL;
402
403     ap_filter_t *f;
404     ap_filter_rec_t *fg;
405
406     if (strncasecmp(url, "fd://", 5) == 0) {
407         url += 5;
408     }
409     else {
410         return DECLINED;
411     }
412
413     rv = get_socket_from_path(r, r->pool, url, &sock);
414
415 #if ALTOUT_DEBUG > 0
416     time_t t_cur;
417     int t_rnd;
418     t_cur = time();
419     t_rnd = rand();
420 #endif
421
422 #if ALTOUT_DEBUG > 0
423     {
424         int mop_fd;
425         char mop_bf[512];
426
427         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
428         sprintf(mop_bf, "%lld: (%d) proxy_fdpass2_handler: start\n", t_cur, t_rnd);
429         write(mop_fd, mop_bf, strlen(mop_bf));
430         close(mop_fd);
431     }
432 #endif
433
434     if (rv != APR_SUCCESS) {
435         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
436                       "proxy: FD: Failed to connect to '%s' %d xxx",
437                       url, rv);
438         return HTTP_INTERNAL_SERVER_ERROR;
439     }
440
441     fg = ap_get_output_filter_handle("HTTP_HEADER");
442
443     /*
444     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
445                   "proxy: FD: filter fg: %lx  func %lx", fg, ap_http_header_filter);
446     */
447
448     for (f = r->output_filters ; f != NULL ; f = f->next) {
449         /* ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
450            "proxy: FD: filter loop: %lx", f->frec);
451         */
452         if (f->frec == fg) {
453             /*
454             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
455                           "proxy: FD: filter found, remove it");
456             */
457             ap_remove_output_filter(f);
458             break;
459         }
460     }
461
462     if ((headers_out = calloc(CTRL_BUFF_MAX_SZ, 1)) != NULL) {
463         sprintf(headers_out, "The-Request:%s\n", r->the_request);
464         apr_table_do(headers_builder, headers_out, r->headers_in, NULL);
465     }
466     read_post(r, &post_data);
467
468 #if ALTOUT_DEBUG > 1
469     {
470         int mop_fd;
471         char mop_bf[512];
472
473         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
474         sprintf(mop_bf, "proxy_fdpass2_handler: headers\n");
475         write(mop_fd, mop_bf, strlen(mop_bf));
476         write(mop_fd, headers_out, strlen(headers_out));
477         close(mop_fd);
478     }
479 #endif
480
481     /* create a couple of sockets and pass one to the client for headers and so on */
482     if (socketpair(AF_UNIX, SOCK_STREAM, 0, ctrlrawsock)) {
483         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
484                       "proxy: FD: Failed create socketpair");
485         return HTTP_INTERNAL_SERVER_ERROR;
486     }
487     rv = apr_os_sock_put(&ctrlsock, &(ctrlrawsock[0]), r->connection->pool);
488     if (rv != APR_SUCCESS) {
489         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
490                       "proxy: FD: apr_os_sock_put failed");
491         return HTTP_INTERNAL_SERVER_ERROR;
492     }
493     rv = apr_os_sock_put(&clientctrlsock, &(ctrlrawsock[1]), r->connection->pool);
494     if (rv != APR_SUCCESS) {
495         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
496                       "proxy: FD: apr_os_sock_put failed");
497         return HTTP_INTERNAL_SERVER_ERROR;
498     }
499
500     {
501         int status;
502         /* const char *flush_method = worker->flusher ? worker->flusher : "flush"; */
503         const char *flush_method = "flush";
504
505         proxy_fdpass2_flush *flush = ap_lookup_provider(PROXY_FDPASS_FLUSHER,
506                                                        flush_method, "0");
507
508         if (!flush) {
509             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
510                           "proxy: FD: Unable to find configured flush "
511                           "provider '%s'", flush_method);
512             return HTTP_INTERNAL_SERVER_ERROR;
513         }
514
515         status = flush->flusher(r);
516         if (status) {
517             return status;
518         }
519     }
520
521     /*
522     if ((buf = apr_table_get(r->headers_in, "Host"))) {
523         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
524                       "proxy: FD: Host is: [%s]", buf);
525     }
526     */
527
528     /* XXXXX: THIS IS AN EVIL HACK */
529     /* There should really be a (documented) public API for this ! */
530     clientsock = ap_get_module_config(r->connection->conn_config, &core_module);
531
532     rv = send_socket(r->pool, sock, clientsock, clientctrlsock);
533     if (rv != APR_SUCCESS) {
534         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
535                       "proxy: FD: send_socket failed:");
536         return HTTP_INTERNAL_SERVER_ERROR;
537     }
538     strcat(headers_out, "\n");
539     wrlen = strlen(headers_out);
540     rv = apr_socket_send(ctrlsock, headers_out, &wrlen);
541
542 #if ALTOUT_DEBUG > 1
543     {
544         int mop_fd;
545         char mop_bf[512];
546
547         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
548         write(mop_fd, "HEADERS_OUT\n", 12);
549         write(mop_fd, headers_out, wrlen);
550         close(mop_fd);
551     }
552 #endif
553
554     if (rv != APR_SUCCESS) {
555         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
556                       "proxy: FD: send headers failed");
557         return HTTP_INTERNAL_SERVER_ERROR;
558     }
559     if (post_data) {
560         wrlen = strlen(post_data);
561         rv = apr_socket_send(ctrlsock, post_data, &wrlen);
562         if (rv != APR_SUCCESS) {
563             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
564                           "proxy: FD: send post failed");
565             return HTTP_INTERNAL_SERVER_ERROR;
566         }
567     }
568     apr_socket_shutdown(ctrlsock, APR_SHUTDOWN_READWRITE);
569     if (headers_out)
570         free(headers_out);
571
572     {
573         apr_socket_t *dummy;
574         /* Create a dummy unconnected socket, and set it as the one we were
575          * connected to, so that when the core closes it, it doesn't close
576          * the tcp connection to the client.
577          */
578         rv = apr_socket_create(&dummy, APR_INET, SOCK_STREAM, APR_PROTO_TCP,
579                                r->connection->pool);
580         if (rv != APR_SUCCESS) {
581             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
582                           "proxy: FD: failed to create dummy socket");
583             return HTTP_INTERNAL_SERVER_ERROR;
584         }
585         ap_set_module_config(r->connection->conn_config, &core_module, dummy);
586     }
587
588 #if ALTOUT_DEBUG > 0
589     {
590         int mop_fd;
591         char mop_bf[512];
592
593         mop_fd = open(ALTOUT_DBG_FILE, O_WRONLY | O_APPEND | O_CREAT, 0644);
594         sprintf(mop_bf, "%lld: (%d) proxy_fdpass2_handler: end\n", t_cur, t_rnd);
595         write(mop_fd, mop_bf, strlen(mop_bf));
596         close(mop_fd);
597     }
598 #endif
599
600     return OK;
601 }
602
603 static int standard_flush(request_rec *r)
604 {
605     int status;
606     apr_bucket_brigade *bb;
607     apr_bucket *e;
608     apr_pool_t *p = r->pool;
609
610     r->connection->keepalive = AP_CONN_CLOSE;
611     /* MOP NOTE: set here the content type */
612     // ap_set_content_type(r, apr_pstrdup(p, NO_CONTENT_TYPE));
613     bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
614     e = apr_bucket_flush_create(r->connection->bucket_alloc);
615
616     APR_BRIGADE_INSERT_TAIL(bb, e);
617
618     status = ap_pass_brigade(r->output_filters, bb);
619
620     if (status != OK) {
621         ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
622                       "proxy: FD: ap_pass_brigade failed:");
623         return status;
624     }
625
626     return OK;
627 }
628
629 static const proxy_fdpass2_flush builtin_flush =
630 {
631     "flush",
632     &standard_flush,
633     NULL
634 };
635
636 static void ap_proxy_fdpass2_register_hooks(apr_pool_t *p)
637 {
638     ap_register_provider(p, PROXY_FDPASS_FLUSHER, "flush", "0", &builtin_flush);
639     proxy_hook_scheme_handler(proxy_fdpass2_handler, NULL, NULL, APR_HOOK_FIRST);
640     proxy_hook_canon_handler(proxy_fdpass2_canon, NULL, NULL, APR_HOOK_FIRST);
641 }
642
643 module AP_MODULE_DECLARE_DATA proxy_fdpass2_module = {
644     STANDARD20_MODULE_STUFF,
645     NULL,              /* create per-directory config structure */
646     NULL,              /* merge per-directory config structures */
647     NULL,              /* create per-server config structure */
648     NULL,              /* merge per-server config structures */
649     NULL,              /* command apr_table_t */
650     ap_proxy_fdpass2_register_hooks                /* register hooks */
651 };