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