]> granicus.if.org Git - apache/blob - server/vhost.c
Merge r1741310, r1741461 from trunk:
[apache] / server / vhost.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 /**
18  * @file  vhost.c
19  * @brief functions pertaining to virtual host addresses
20  *        (configuration and run-time)
21  */
22
23 #include "apr.h"
24 #include "apr_strings.h"
25 #include "apr_lib.h"
26
27 #define APR_WANT_STRFUNC
28 #include "apr_want.h"
29
30 #include "ap_config.h"
31 #include "httpd.h"
32 #include "http_config.h"
33 #include "http_log.h"
34 #include "http_vhost.h"
35 #include "http_protocol.h"
36 #include "http_core.h"
37
38 #if APR_HAVE_ARPA_INET_H
39 #include <arpa/inet.h>
40 #endif
41
42 /* we know core's module_index is 0 */
43 #undef APLOG_MODULE_INDEX
44 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
45
46 /*
47  * After all the definitions there's an explanation of how it's all put
48  * together.
49  */
50
51 /* meta-list of name-vhosts.  Each server_rec can be in possibly multiple
52  * lists of name-vhosts.
53  */
54 typedef struct name_chain name_chain;
55 struct name_chain {
56     name_chain *next;
57     server_addr_rec *sar;       /* the record causing it to be in
58                                  * this chain (needed for port comparisons) */
59     server_rec *server;         /* the server to use on a match */
60 };
61
62 /* meta-list of ip addresses.  Each server_rec can be in possibly multiple
63  * hash chains since it can have multiple ips.
64  */
65 typedef struct ipaddr_chain ipaddr_chain;
66 struct ipaddr_chain {
67     ipaddr_chain *next;
68     server_addr_rec *sar;       /* the record causing it to be in
69                                  * this chain (need for both ip addr and port
70                                  * comparisons) */
71     server_rec *server;         /* the server to use if this matches */
72     name_chain *names;          /* if non-NULL then a list of name-vhosts
73                                  * sharing this address */
74     name_chain *initialnames;   /* no runtime use, temporary storage of first
75                                  * NVH'es names */
76 };
77
78 /* This defines the size of the hash table used for hashing ip addresses
79  * of virtual hosts.  It must be a power of two.
80  */
81 #ifndef IPHASH_TABLE_SIZE
82 #define IPHASH_TABLE_SIZE 256
83 #endif
84
85 /* A (n) bucket hash table, each entry has a pointer to a server rec and
86  * a pointer to the other entries in that bucket.  Each individual address,
87  * even for virtualhosts with multiple addresses, has an entry in this hash
88  * table.  There are extra buckets for _default_, and name-vhost entries.
89  *
90  * Note that after config time this is constant, so it is thread-safe.
91  */
92 static ipaddr_chain *iphash_table[IPHASH_TABLE_SIZE];
93
94 /* dump out statistics about the hash function */
95 /* #define IPHASH_STATISTICS */
96
97 /* list of the _default_ servers */
98 static ipaddr_chain *default_list;
99
100 /* whether a config error was seen */
101 static int config_error = 0;
102
103 /* config check function */
104 static int vhost_check_config(apr_pool_t *p, apr_pool_t *plog,
105                               apr_pool_t *ptemp, server_rec *s);
106
107 /*
108  * How it's used:
109  *
110  * The ip address determines which chain in iphash_table is interesting, then
111  * a comparison is done down that chain to find the first ipaddr_chain whose
112  * sar matches the address:port pair.
113  *
114  * If that ipaddr_chain has names == NULL then you're done, it's an ip-vhost.
115  *
116  * Otherwise it's a name-vhost list, and the default is the server in the
117  * ipaddr_chain record.  We tuck away the ipaddr_chain record in the
118  * conn_rec field vhost_lookup_data.  Later on after the headers we get a
119  * second chance, and we use the name_chain to figure out what name-vhost
120  * matches the headers.
121  *
122  * If there was no ip address match in the iphash_table then do a lookup
123  * in the default_list.
124  *
125  * How it's put together ... well you should be able to figure that out
126  * from how it's used.  Or something like that.
127  */
128
129
130 /* called at the beginning of the config */
131 AP_DECLARE(void) ap_init_vhost_config(apr_pool_t *p)
132 {
133     memset(iphash_table, 0, sizeof(iphash_table));
134     default_list = NULL;
135     ap_hook_check_config(vhost_check_config, NULL, NULL, APR_HOOK_MIDDLE);
136 }
137
138
139 /*
140  * Parses a host of the form <address>[:port]
141  * paddr is used to create a list in the order of input
142  * **paddr is the ->next pointer of the last entry (or s->addrs)
143  * *paddr is the variable used to keep track of **paddr between calls
144  * port is the default port to assume
145  */
146 static const char *get_addresses(apr_pool_t *p, const char *w_,
147                                  server_addr_rec ***paddr,
148                                  apr_port_t default_port)
149 {
150     apr_sockaddr_t *my_addr;
151     server_addr_rec *sar;
152     char *w, *host, *scope_id;
153     int wild_port;
154     apr_size_t wlen;
155     apr_port_t port;
156     apr_status_t rv;
157
158     if (*w_ == '\0')
159         return NULL;
160
161     wlen = strlen(w_);                   /* wlen must be > 0 at this point */
162     w = apr_pstrmemdup(p, w_, wlen);
163     /* apr_parse_addr_port() doesn't understand ":*" so handle that first. */
164     wild_port = 0;
165     if (w[wlen - 1] == '*') {
166         if (wlen < 2) {
167             wild_port = 1;
168         }
169         else if (w[wlen - 2] == ':') {
170             w[wlen - 2] = '\0';
171             wild_port = 1;
172         }
173     }
174     rv = apr_parse_addr_port(&host, &scope_id, &port, w, p);
175     /* If the string is "80", apr_parse_addr_port() will be happy and set
176      * host to NULL and port to 80, so watch out for that.
177      */
178     if (rv != APR_SUCCESS) {
179         return "The address or port is invalid";
180     }
181     if (!host) {
182         return "Missing address for VirtualHost";
183     }
184     if (scope_id) {
185         return "Scope ids are not supported";
186     }
187     if (!port && !wild_port) {
188         port = default_port;
189     }
190
191     if (strcmp(host, "*") == 0 || strcasecmp(host, "_default_") == 0) {
192         rv = apr_sockaddr_info_get(&my_addr, NULL, APR_UNSPEC, port, 0, p);
193         if (rv) {
194             return "Could not determine a wildcard address ('0.0.0.0') -- "
195                 "check resolver configuration.";
196         }
197     }
198     else {
199         rv = apr_sockaddr_info_get(&my_addr, host, APR_UNSPEC, port, 0, p);
200         if (rv != APR_SUCCESS) {
201             ap_log_error(APLOG_MARK, APLOG_ERR, rv, NULL, APLOGNO(00547)
202                 "Could not resolve host name %s -- ignoring!", host);
203             return NULL;
204         }
205     }
206
207     /* Remember all addresses for the host */
208
209     do {
210         sar = apr_pcalloc(p, sizeof(server_addr_rec));
211         **paddr = sar;
212         *paddr = &sar->next;
213         sar->host_addr = my_addr;
214         sar->host_port = port;
215         sar->virthost = host;
216         my_addr = my_addr->next;
217     } while (my_addr);
218
219     return NULL;
220 }
221
222
223 /* parse the <VirtualHost> addresses */
224 const char *ap_parse_vhost_addrs(apr_pool_t *p,
225                                  const char *hostname,
226                                  server_rec *s)
227 {
228     server_addr_rec **addrs;
229     const char *err;
230
231     /* start the list of addreses */
232     addrs = &s->addrs;
233     while (hostname[0]) {
234         err = get_addresses(p, ap_getword_conf(p, &hostname), &addrs, s->port);
235         if (err) {
236             *addrs = NULL;
237             return err;
238         }
239     }
240     /* terminate the list */
241     *addrs = NULL;
242     if (s->addrs) {
243         if (s->addrs->host_port) {
244             /* override the default port which is inherited from main_server */
245             s->port = s->addrs->host_port;
246         }
247     }
248     return NULL;
249 }
250
251
252 AP_DECLARE_NONSTD(const char *)ap_set_name_virtual_host(cmd_parms *cmd,
253                                                         void *dummy,
254                                                         const char *arg)
255 {
256     static int warnonce = 0;
257     if (++warnonce == 1) {
258         ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_STARTUP, APR_SUCCESS, NULL, APLOGNO(00548)
259                      "NameVirtualHost has no effect and will be removed in the "
260                      "next release %s:%d",
261                      cmd->directive->filename,
262                      cmd->directive->line_num);
263     }
264
265     return NULL;
266 }
267
268
269 /* hash table statistics, keep this in here for the beta period so
270  * we can find out if the hash function is ok
271  */
272 #ifdef IPHASH_STATISTICS
273 static int iphash_compare(const void *a, const void *b)
274 {
275     return (*(const int *) b - *(const int *) a);
276 }
277
278
279 static void dump_iphash_statistics(server_rec *main_s)
280 {
281     unsigned count[IPHASH_TABLE_SIZE];
282     int i;
283     ipaddr_chain *src;
284     unsigned total;
285     char buf[HUGE_STRING_LEN];
286     char *p;
287
288     total = 0;
289     for (i = 0; i < IPHASH_TABLE_SIZE; ++i) {
290         count[i] = 0;
291         for (src = iphash_table[i]; src; src = src->next) {
292             ++count[i];
293             if (i < IPHASH_TABLE_SIZE) {
294                 /* don't count the slop buckets in the total */
295                 ++total;
296             }
297         }
298     }
299     qsort(count, IPHASH_TABLE_SIZE, sizeof(count[0]), iphash_compare);
300     p = buf + apr_snprintf(buf, sizeof(buf),
301                            APLOGNO(03235) "iphash: total hashed = %u, avg chain = %u, "
302                            "chain lengths (count x len):",
303                            total, total / IPHASH_TABLE_SIZE);
304     total = 1;
305     for (i = 1; i < IPHASH_TABLE_SIZE; ++i) {
306         if (count[i - 1] != count[i]) {
307             p += apr_snprintf(p, sizeof(buf) - (p - buf), " %ux%u",
308                               total, count[i - 1]);
309             total = 1;
310         }
311         else {
312             ++total;
313         }
314     }
315     p += apr_snprintf(p, sizeof(buf) - (p - buf), " %ux%u",
316                       total, count[IPHASH_TABLE_SIZE - 1]);
317     /* Intentional no APLOGNO */
318     /* buf provides APLOGNO */
319     ap_log_error(APLOG_MARK, APLOG_DEBUG, main_s, buf);
320 }
321 #endif
322
323
324 /* This hashing function is designed to get good distribution in the cases
325  * where the server is handling entire "networks" of servers.  i.e. a
326  * whack of /24s.  This is probably the most common configuration for
327  * ISPs with large virtual servers.
328  *
329  * NOTE: This function is symmetric (i.e. collapses all 4 octets
330  * into one), so machine byte order (big/little endianness) does not matter.
331  *
332  * Hash function provided by David Hankins.
333  */
334 static APR_INLINE unsigned hash_inaddr(unsigned key)
335 {
336     key ^= (key >> 16);
337     return ((key >> 8) ^ key) % IPHASH_TABLE_SIZE;
338 }
339
340 static APR_INLINE unsigned hash_addr(struct apr_sockaddr_t *sa)
341 {
342     unsigned key;
343
344     /* The key is the last four bytes of the IP address.
345      * For IPv4, this is the entire address, as always.
346      * For IPv6, this is usually part of the MAC address.
347      */
348     key = *(unsigned *)((char *)sa->ipaddr_ptr + sa->ipaddr_len - 4);
349     return hash_inaddr(key);
350 }
351
352 static ipaddr_chain *new_ipaddr_chain(apr_pool_t *p,
353                                       server_rec *s, server_addr_rec *sar)
354 {
355     ipaddr_chain *new;
356
357     new = apr_palloc(p, sizeof(*new));
358     new->names = NULL;
359     new->initialnames = NULL;
360     new->server = s;
361     new->sar = sar;
362     new->next = NULL;
363     return new;
364 }
365
366
367 static name_chain *new_name_chain(apr_pool_t *p,
368                                   server_rec *s, server_addr_rec *sar)
369 {
370     name_chain *new;
371
372     new = apr_palloc(p, sizeof(*new));
373     new->server = s;
374     new->sar = sar;
375     new->next = NULL;
376     return new;
377 }
378
379
380 static APR_INLINE ipaddr_chain *find_ipaddr(apr_sockaddr_t *sa)
381 {
382     unsigned bucket;
383     ipaddr_chain *trav = NULL;
384     ipaddr_chain *wild_match = NULL;
385
386     /* scan the hash table for an exact match first */
387     bucket = hash_addr(sa);
388     for (trav = iphash_table[bucket]; trav; trav = trav->next) {
389         server_addr_rec *sar = trav->sar;
390         apr_sockaddr_t *cur = sar->host_addr;
391
392         if (cur->port == sa->port) {
393             if (apr_sockaddr_equal(cur, sa)) {
394                 return trav;
395             }
396         }
397         if (wild_match == NULL && (cur->port == 0 || sa->port == 0)) {
398             if (apr_sockaddr_equal(cur, sa)) {
399                 /* don't break, continue looking for an exact match */
400                 wild_match = trav;
401             }
402         }
403     }
404     return wild_match;
405 }
406
407 static ipaddr_chain *find_default_server(apr_port_t port)
408 {
409     server_addr_rec *sar;
410     ipaddr_chain *trav = NULL;
411     ipaddr_chain *wild_match = NULL;
412
413     for (trav = default_list; trav; trav = trav->next) {
414         sar = trav->sar;
415         if (sar->host_port == port) {
416             /* match! */
417             return trav;
418         }
419         if (wild_match == NULL && sar->host_port == 0) {
420             /* don't break, continue looking for an exact match */
421             wild_match = trav;
422         }
423     }
424     return wild_match;
425 }
426
427 #if APR_HAVE_IPV6
428 #define IS_IN6_ANYADDR(ad) ((ad)->family == APR_INET6                   \
429                             && IN6_IS_ADDR_UNSPECIFIED(&(ad)->sa.sin6.sin6_addr))
430 #else
431 #define IS_IN6_ANYADDR(ad) (0)
432 #endif
433
434 static void dump_a_vhost(apr_file_t *f, ipaddr_chain *ic)
435 {
436     name_chain *nc;
437     int len;
438     char buf[MAX_STRING_LEN];
439     apr_sockaddr_t *ha = ic->sar->host_addr;
440
441     if ((ha->family == APR_INET && ha->sa.sin.sin_addr.s_addr == INADDR_ANY)
442         || IS_IN6_ANYADDR(ha)) {
443         len = apr_snprintf(buf, sizeof(buf), "*:%u",
444                            ic->sar->host_port);
445     }
446     else {
447         len = apr_snprintf(buf, sizeof(buf), "%pI", ha);
448     }
449     if (ic->sar->host_port == 0) {
450         buf[len-1] = '*';
451     }
452     if (ic->names == NULL) {
453         apr_file_printf(f, "%-22s %s (%s:%u)\n", buf,
454                         ic->server->server_hostname,
455                         ic->server->defn_name, ic->server->defn_line_number);
456         return;
457     }
458     apr_file_printf(f, "%-22s is a NameVirtualHost\n"
459                     "%8s default server %s (%s:%u)\n",
460                     buf, "", ic->server->server_hostname,
461                     ic->server->defn_name, ic->server->defn_line_number);
462     for (nc = ic->names; nc; nc = nc->next) {
463         if (nc->sar->host_port) {
464             apr_file_printf(f, "%8s port %u ", "", nc->sar->host_port);
465         }
466         else {
467             apr_file_printf(f, "%8s port * ", "");
468         }
469         apr_file_printf(f, "namevhost %s (%s:%u)\n",
470                         nc->server->server_hostname,
471                         nc->server->defn_name, nc->server->defn_line_number);
472         if (nc->server->names) {
473             apr_array_header_t *names = nc->server->names;
474             char **name = (char **)names->elts;
475             int i;
476             for (i = 0; i < names->nelts; ++i) {
477                 if (name[i]) {
478                     apr_file_printf(f, "%16s alias %s\n", "", name[i]);
479                 }
480             }
481         }
482         if (nc->server->wild_names) {
483             apr_array_header_t *names = nc->server->wild_names;
484             char **name = (char **)names->elts;
485             int i;
486             for (i = 0; i < names->nelts; ++i) {
487                 if (name[i]) {
488                     apr_file_printf(f, "%16s wild alias %s\n", "", name[i]);
489                 }
490             }
491         }
492     }
493 }
494
495 static void dump_vhost_config(apr_file_t *f)
496 {
497     ipaddr_chain *ic;
498     int i;
499
500     apr_file_printf(f, "VirtualHost configuration:\n");
501
502     /* non-wildcard servers */
503     for (i = 0; i < IPHASH_TABLE_SIZE; ++i) {
504         for (ic = iphash_table[i]; ic; ic = ic->next) {
505             dump_a_vhost(f, ic);
506         }
507     }
508
509     /* wildcard servers */
510     for (ic = default_list; ic; ic = ic->next) {
511         dump_a_vhost(f, ic);
512     }
513 }
514
515
516 /*
517  * When a second or later virtual host maps to the same IP chain,
518  * add the relevant server names to the chain.  Special care is taken
519  * to avoid adding ic->names until we're sure there are multiple VH'es.
520  */
521 static void add_name_vhost_config(apr_pool_t *p, server_rec *main_s,
522                                  server_rec *s, server_addr_rec *sar,
523                                  ipaddr_chain *ic)
524 {
525
526    name_chain *nc = new_name_chain(p, s, sar);
527    nc->next = ic->names;
528
529    /* iterating backwards, so each one we see becomes the current default server */
530    ic->server = s;
531
532    if (ic->names == NULL) {
533        if (ic->initialnames == NULL) {
534            /* first pass, set these names aside in case we see another VH.
535             * Until then, this looks like an IP-based VH to runtime.
536             */
537            ic->initialnames = nc;
538        }
539        else {
540            /* second pass through this chain -- this really is an NVH, and we
541             * have two sets of names to link in.
542             */
543            nc->next = ic->initialnames;
544            ic->names = nc;
545            ic->initialnames = NULL;
546        }
547    }
548    else {
549        /* 3rd or more -- just keep stacking the names */
550        ic->names = nc;
551    }
552 }
553
554 /* compile the tables and such we need to do the run-time vhost lookups */
555 AP_DECLARE(void) ap_fini_vhost_config(apr_pool_t *p, server_rec *main_s)
556 {
557     server_addr_rec *sar;
558     int has_default_vhost_addr;
559     server_rec *s;
560     int i;
561     ipaddr_chain **iphash_table_tail[IPHASH_TABLE_SIZE];
562
563     /* Main host first */
564     s = main_s;
565
566     if (!s->server_hostname) {
567         s->server_hostname = ap_get_local_host(p);
568     }
569
570     /* initialize the tails */
571     for (i = 0; i < IPHASH_TABLE_SIZE; ++i) {
572         iphash_table_tail[i] = &iphash_table[i];
573     }
574
575     /* The next things to go into the hash table are the virtual hosts
576      * themselves.  They're listed off of main_s->next in the reverse
577      * order they occured in the config file, so we insert them at
578      * the iphash_table_tail but don't advance the tail.
579      */
580
581     for (s = main_s->next; s; s = s->next) {
582         server_addr_rec *sar_prev = NULL;
583         has_default_vhost_addr = 0;
584         for (sar = s->addrs; sar; sar = sar->next) {
585             ipaddr_chain *ic;
586             char inaddr_any[16] = {0}; /* big enough to handle IPv4 or IPv6 */
587             /* XXX: this treats 0.0.0.0 as a "default" server which matches no-exact-match for IPv6 */
588             if (!memcmp(sar->host_addr->ipaddr_ptr, inaddr_any, sar->host_addr->ipaddr_len)) {
589                 ic = find_default_server(sar->host_port);
590
591                 if (ic && sar->host_port == ic->sar->host_port) { /* we're a match for an existing "default server"  */
592                     if (!sar_prev || memcmp(sar_prev->host_addr->ipaddr_ptr, inaddr_any, sar_prev->host_addr->ipaddr_len)
593                                   || sar_prev->host_port != sar->host_port) { 
594                         add_name_vhost_config(p, main_s, s, sar, ic);
595                     }
596                 }
597                 else { 
598                     /* No default server, or we found a default server but
599                     ** exactly one of us is a wildcard port, which means we want
600                     ** two ip-based vhosts not an NVH with two names
601                     */
602                     ic = new_ipaddr_chain(p, s, sar);
603                     ic->next = default_list;
604                     default_list = ic;
605                     add_name_vhost_config(p, main_s, s, sar, ic);
606                 }
607                 has_default_vhost_addr = 1;
608             }
609             else {
610                 /* see if it matches something we've already got */
611                 ic = find_ipaddr(sar->host_addr);
612
613                 if (!ic || sar->host_port != ic->sar->host_port) {
614                     /* No matching server, or we found a matching server but
615                     ** exactly one of us is a wildcard port, which means we want
616                     ** two ip-based vhosts not an NVH with two names
617                     */
618                     unsigned bucket = hash_addr(sar->host_addr);
619                     ic = new_ipaddr_chain(p, s, sar);
620                     ic->next = *iphash_table_tail[bucket];
621                     *iphash_table_tail[bucket] = ic;
622                 }
623                 add_name_vhost_config(p, main_s, s, sar, ic);
624             }
625             sar_prev = sar;
626         }
627
628         /* Ok now we want to set up a server_hostname if the user was
629          * silly enough to forget one.
630          * XXX: This is silly we should just crash and burn.
631          */
632         if (!s->server_hostname) {
633             if (has_default_vhost_addr) {
634                 s->server_hostname = main_s->server_hostname;
635             }
636             else if (!s->addrs) {
637                 /* what else can we do?  at this point this vhost has
638                     no configured name, probably because they used
639                     DNS in the VirtualHost statement.  It's disabled
640                     anyhow by the host matching code.  -djg */
641                 s->server_hostname =
642                     apr_pstrdup(p, "bogus_host_without_forward_dns");
643             }
644             else {
645                 apr_status_t rv;
646                 char *hostname;
647
648                 rv = apr_getnameinfo(&hostname, s->addrs->host_addr, 0);
649                 if (rv == APR_SUCCESS) {
650                     s->server_hostname = apr_pstrdup(p, hostname);
651                 }
652                 else {
653                     /* again, what can we do?  They didn't specify a
654                        ServerName, and their DNS isn't working. -djg */
655                     char *ipaddr_str;
656
657                     apr_sockaddr_ip_get(&ipaddr_str, s->addrs->host_addr);
658                     ap_log_error(APLOG_MARK, APLOG_ERR, rv, main_s, APLOGNO(00549)
659                                  "Failed to resolve server name "
660                                  "for %s (check DNS) -- or specify an explicit "
661                                  "ServerName",
662                                  ipaddr_str);
663                     s->server_hostname =
664                         apr_pstrdup(p, "bogus_host_without_reverse_dns");
665                 }
666             }
667         }
668     }
669
670 #ifdef IPHASH_STATISTICS
671     dump_iphash_statistics(main_s);
672 #endif
673     if (ap_exists_config_define("DUMP_VHOSTS")) {
674         apr_file_t *thefile = NULL;
675         apr_file_open_stdout(&thefile, p);
676         dump_vhost_config(thefile);
677     }
678 }
679
680 static int vhost_check_config(apr_pool_t *p, apr_pool_t *plog,
681                               apr_pool_t *ptemp, server_rec *s)
682 {
683     return config_error ? !OK : OK;
684 }
685
686 /*****************************************************************************
687  * run-time vhost matching functions
688  */
689
690 /* Lowercase and remove any trailing dot and/or :port from the hostname,
691  * and check that it is sane.
692  *
693  * In most configurations the exact syntax of the hostname isn't
694  * important so strict sanity checking isn't necessary. However, in
695  * mass hosting setups (using mod_vhost_alias or mod_rewrite) where
696  * the hostname is interpolated into the filename, we need to be sure
697  * that the interpolation doesn't expose parts of the filesystem.
698  * We don't do strict RFC 952 / RFC 1123 syntax checking in order
699  * to support iDNS and people who erroneously use underscores.
700  * Instead we just check for filesystem metacharacters: directory
701  * separators / and \ and sequences of more than one dot.
702  */
703 static void fix_hostname(request_rec *r)
704 {
705     char *host, *scope_id;
706     char *dst;
707     apr_port_t port;
708     apr_status_t rv;
709     const char *c;
710
711     /* According to RFC 2616, Host header field CAN be blank. */
712     if (!*r->hostname) {
713         return;
714     }
715
716     /* apr_parse_addr_port will interpret a bare integer as a port
717      * which is incorrect in this context.  So treat it separately.
718      */
719     for (c = r->hostname; apr_isdigit(*c); ++c);
720     if (!*c) {  /* pure integer */
721         return;
722     }
723
724     rv = apr_parse_addr_port(&host, &scope_id, &port, r->hostname, r->pool);
725     if (rv != APR_SUCCESS || scope_id) {
726         goto bad;
727     }
728
729     if (port) {
730         /* Don't throw the Host: header's port number away:
731            save it in parsed_uri -- ap_get_server_port() needs it! */
732         /* @@@ XXX there should be a better way to pass the port.
733          *         Like r->hostname, there should be a r->portno
734          */
735         r->parsed_uri.port = port;
736         r->parsed_uri.port_str = apr_itoa(r->pool, (int)port);
737     }
738
739     /* if the hostname is an IPv6 numeric address string, it was validated
740      * already; otherwise, further validation is needed
741      */
742     if (r->hostname[0] != '[') {
743         for (dst = host; *dst; dst++) {
744             if (apr_islower(*dst)) {
745                 /* leave char unchanged */
746             }
747             else if (*dst == '.') {
748                 if (*(dst + 1) == '.') {
749                     goto bad;
750                 }
751             }
752             else if (apr_isupper(*dst)) {
753                 *dst = apr_tolower(*dst);
754             }
755             else if (*dst == '/' || *dst == '\\') {
756                 goto bad;
757             }
758         }
759         /* strip trailing gubbins */
760         if (dst > host && dst[-1] == '.') {
761             dst[-1] = '\0';
762         }
763     }
764     r->hostname = host;
765     return;
766
767 bad:
768     r->status = HTTP_BAD_REQUEST;
769     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00550)
770                   "Client sent malformed Host header: %s",
771                   r->hostname);
772     return;
773 }
774
775
776 /* return 1 if host matches ServerName or ServerAliases */
777 static int matches_aliases(server_rec *s, const char *host)
778 {
779     int i;
780     apr_array_header_t *names;
781
782     /* match ServerName */
783     if (!strcasecmp(host, s->server_hostname)) {
784         return 1;
785     }
786
787     /* search all the aliases from ServerAlias directive */
788     names = s->names;
789     if (names) {
790         char **name = (char **) names->elts;
791         for (i = 0; i < names->nelts; ++i) {
792             if(!name[i]) continue;
793             if (!strcasecmp(host, name[i]))
794                 return 1;
795         }
796     }
797     names = s->wild_names;
798     if (names) {
799         char **name = (char **) names->elts;
800         for (i = 0; i < names->nelts; ++i) {
801             if(!name[i]) continue;
802             if (!ap_strcasecmp_match(host, name[i]))
803                 return 1;
804         }
805     }
806     return 0;
807 }
808
809
810 /* Suppose a request came in on the same socket as this r, and included
811  * a header "Host: host:port", would it map to r->server?  It's more
812  * than just that though.  When we do the normal matches for each request
813  * we don't even bother considering Host: etc on non-namevirtualhosts,
814  * we just call it a match.  But here we require the host:port to match
815  * the ServerName and/or ServerAliases.
816  */
817 AP_DECLARE(int) ap_matches_request_vhost(request_rec *r, const char *host,
818                                          apr_port_t port)
819 {
820     server_rec *s;
821     server_addr_rec *sar;
822
823     s = r->server;
824
825     /* search all the <VirtualHost> values */
826     /* XXX: If this is a NameVirtualHost then we may not be doing the Right Thing
827      * consider:
828      *
829      *     NameVirtualHost 10.1.1.1
830      *     <VirtualHost 10.1.1.1>
831      *     ServerName v1
832      *     </VirtualHost>
833      *     <VirtualHost 10.1.1.1>
834      *     ServerName v2
835      *     </VirtualHost>
836      *
837      * Suppose r->server is v2, and we're asked to match "10.1.1.1".  We'll say
838      * "yup it's v2", when really it isn't... if a request came in for 10.1.1.1
839      * it would really go to v1.
840      */
841     for (sar = s->addrs; sar; sar = sar->next) {
842         if ((sar->host_port == 0 || port == sar->host_port)
843             && !strcasecmp(host, sar->virthost)) {
844             return 1;
845         }
846     }
847
848     /* the Port has to match now, because the rest don't have ports associated
849      * with them. */
850     if (port != s->port) {
851         return 0;
852     }
853
854     return matches_aliases(s, host);
855 }
856
857
858 static void check_hostalias(request_rec *r)
859 {
860     /*
861      * Even if the request has a Host: header containing a port we ignore
862      * that port.  We always use the physical port of the socket.  There
863      * are a few reasons for this:
864      *
865      * - the default of 80 or 443 for SSL is easier to handle this way
866      * - there is less of a possibility of a security problem
867      * - it simplifies the data structure
868      * - the client may have no idea that a proxy somewhere along the way
869      *   translated the request to another ip:port
870      * - except for the addresses from the VirtualHost line, none of the other
871      *   names we'll match have ports associated with them
872      */
873     const char *host = r->hostname;
874     apr_port_t port;
875     server_rec *s;
876     server_rec *virthost_s;
877     server_rec *last_s;
878     name_chain *src;
879
880     virthost_s = NULL;
881     last_s = NULL;
882
883     port = r->connection->local_addr->port;
884
885     /* Recall that the name_chain is a list of server_addr_recs, some of
886      * whose ports may not match.  Also each server may appear more than
887      * once in the chain -- specifically, it will appear once for each
888      * address from its VirtualHost line which matched.  We only want to
889      * do the full ServerName/ServerAlias comparisons once for each
890      * server, fortunately we know that all the VirtualHost addresses for
891      * a single server are adjacent to each other.
892      */
893
894     for (src = r->connection->vhost_lookup_data; src; src = src->next) {
895         server_addr_rec *sar;
896
897         /* We only consider addresses on the name_chain which have a matching
898          * port
899          */
900         sar = src->sar;
901         if (sar->host_port != 0 && port != sar->host_port) {
902             continue;
903         }
904
905         s = src->server;
906
907         /* If we still need to do ServerName and ServerAlias checks for this
908          * server, do them now.
909          */
910         if (s != last_s) {
911             /* does it match any ServerName or ServerAlias directive? */
912             if (matches_aliases(s, host)) {
913                 goto found;
914             }
915         }
916         last_s = s;
917
918         /* Fallback: does it match the virthost from the sar? */
919         if (!strcasecmp(host, sar->virthost)) {
920             /* only the first match is used */
921             if (virthost_s == NULL) {
922                 virthost_s = s;
923             }
924         }
925     }
926
927     /* If ServerName and ServerAlias check failed, we end up here.  If it
928      * matches a VirtualHost, virthost_s is set. Use that as fallback
929      */
930     if (virthost_s) {
931         s = virthost_s;
932         goto found;
933     }
934
935     return;
936
937 found:
938     /* s is the first matching server, we're done */
939     r->server = s;
940 }
941
942
943 static void check_serverpath(request_rec *r)
944 {
945     server_rec *s;
946     server_rec *last_s;
947     name_chain *src;
948     apr_port_t port;
949
950     port = r->connection->local_addr->port;
951
952     /*
953      * This is in conjunction with the ServerPath code in http_core, so we
954      * get the right host attached to a non- Host-sending request.
955      *
956      * See the comment in check_hostalias about how each vhost can be
957      * listed multiple times.
958      */
959
960     last_s = NULL;
961     for (src = r->connection->vhost_lookup_data; src; src = src->next) {
962         /* We only consider addresses on the name_chain which have a matching
963          * port
964          */
965         if (src->sar->host_port != 0 && port != src->sar->host_port) {
966             continue;
967         }
968
969         s = src->server;
970         if (s == last_s) {
971             continue;
972         }
973         last_s = s;
974
975         if (s->path && !strncmp(r->uri, s->path, s->pathlen) &&
976             (s->path[s->pathlen - 1] == '/' ||
977              r->uri[s->pathlen] == '/' ||
978              r->uri[s->pathlen] == '\0')) {
979             r->server = s;
980             return;
981         }
982     }
983 }
984
985
986 AP_DECLARE(void) ap_update_vhost_from_headers(request_rec *r)
987 {
988     /* must set this for HTTP/1.1 support */
989     if (r->hostname || (r->hostname = apr_table_get(r->headers_in, "Host"))) {
990         fix_hostname(r);
991         if (r->status != HTTP_OK)
992             return;
993     }
994     /* check if we tucked away a name_chain */
995     if (r->connection->vhost_lookup_data) {
996         if (r->hostname)
997             check_hostalias(r);
998         else
999             check_serverpath(r);
1000     }
1001 }
1002
1003 /**
1004  * For every virtual host on this connection, call func_cb.
1005  */
1006 AP_DECLARE(int) ap_vhost_iterate_given_conn(conn_rec *conn,
1007                                             ap_vhost_iterate_conn_cb func_cb,
1008                                             void* baton)
1009 {
1010     server_rec *s;
1011     server_rec *last_s;
1012     name_chain *src;
1013     apr_port_t port;
1014     int rv = 0;
1015
1016     if (conn->vhost_lookup_data) {
1017         last_s = NULL;
1018         port = conn->local_addr->port;
1019
1020         for (src = conn->vhost_lookup_data; src; src = src->next) {
1021             server_addr_rec *sar;
1022
1023             /* We only consider addresses on the name_chain which have a
1024              * matching port.
1025              */
1026             sar = src->sar;
1027             if (sar->host_port != 0 && port != sar->host_port) {
1028                 continue;
1029             }
1030
1031             s = src->server;
1032
1033             if (s == last_s) {
1034                 /* we've already done a callback for this vhost. */
1035                 continue;
1036             }
1037
1038             last_s = s;
1039
1040             rv = func_cb(baton, conn, s);
1041
1042             if (rv != 0) {
1043                 break;
1044             }
1045         }
1046     }
1047     else {
1048         rv = func_cb(baton, conn, conn->base_server);
1049     }
1050
1051     return rv;
1052 }
1053
1054 /* Called for a new connection which has a known local_addr.  Note that the
1055  * new connection is assumed to have conn->server == main server.
1056  */
1057 AP_DECLARE(void) ap_update_vhost_given_ip(conn_rec *conn)
1058 {
1059     ipaddr_chain *trav;
1060     apr_port_t port;
1061
1062     /* scan the hash table for an exact match first */
1063     trav = find_ipaddr(conn->local_addr);
1064
1065     if (trav) {
1066         /* save the name_chain for later in case this is a name-vhost */
1067         conn->vhost_lookup_data = trav->names;
1068         conn->base_server = trav->server;
1069         return;
1070     }
1071
1072     /* maybe there's a default server or wildcard name-based vhost
1073      * matching this port
1074      */
1075     port = conn->local_addr->port;
1076
1077     trav = find_default_server(port);
1078     if (trav) {
1079         conn->vhost_lookup_data = trav->names;
1080         conn->base_server = trav->server;
1081         return;
1082     }
1083
1084     /* otherwise we're stuck with just the main server
1085      * and no name-based vhosts
1086      */
1087     conn->vhost_lookup_data = NULL;
1088 }