]> git.ipfire.org Git - thirdparty/squid.git/blob - src/url.cc
Redesign urlParse API part2: fix compile errors after r15191
[thirdparty/squid.git] / src / url.cc
1 /*
2 * Copyright (C) 1996-2017 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 /* DEBUG: section 23 URL Parsing */
10
11 #include "squid.h"
12 #include "globals.h"
13 #include "HttpRequest.h"
14 #include "rfc1738.h"
15 #include "SquidConfig.h"
16 #include "SquidString.h"
17 #include "URL.h"
18
19 static bool urlParseFinish(const HttpRequestMethod& method,
20 const AnyP::ProtocolType protocol,
21 const char *const protoStr,
22 const char *const urlpath,
23 const char *const host,
24 const SBuf &login,
25 const int port,
26 HttpRequest &request);
27 static bool urnParse(const HttpRequestMethod& method, char *urn, HttpRequest &request);
28 static const char valid_hostname_chars_u[] =
29 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30 "abcdefghijklmnopqrstuvwxyz"
31 "0123456789-._"
32 "[:]"
33 ;
34 static const char valid_hostname_chars[] =
35 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
36 "abcdefghijklmnopqrstuvwxyz"
37 "0123456789-."
38 "[:]"
39 ;
40
41 const SBuf &
42 URL::Asterisk()
43 {
44 static SBuf star("*");
45 return star;
46 }
47
48 const SBuf &
49 URL::SlashPath()
50 {
51 static SBuf slash("/");
52 return slash;
53 }
54
55 void
56 URL::host(const char *src)
57 {
58 hostAddr_.setEmpty();
59 hostAddr_ = src;
60 if (hostAddr_.isAnyAddr()) {
61 xstrncpy(host_, src, sizeof(host_));
62 hostIsNumeric_ = false;
63 } else {
64 hostAddr_.toHostStr(host_, sizeof(host_));
65 debugs(23, 3, "given IP: " << hostAddr_);
66 hostIsNumeric_ = 1;
67 }
68 touch();
69 }
70
71 const SBuf &
72 URL::path() const
73 {
74 // RFC 3986 section 3.3 says path can be empty (path-abempty).
75 // RFC 7230 sections 2.7.3, 5.3.1, 5.7.2 - says path cannot be empty, default to "/"
76 // at least when sending and using. We must still accept path-abempty as input.
77 if (path_.isEmpty() && (scheme_ == AnyP::PROTO_HTTP || scheme_ == AnyP::PROTO_HTTPS))
78 return SlashPath();
79
80 return path_;
81 }
82
83 void
84 urlInitialize(void)
85 {
86 debugs(23, 5, "urlInitialize: Initializing...");
87 /* this ensures that the number of protocol strings is the same as
88 * the enum slots allocated because the last enum is always 'MAX'.
89 */
90 assert(strcmp(AnyP::ProtocolType_str[AnyP::PROTO_MAX], "MAX") == 0);
91 /*
92 * These test that our matchDomainName() function works the
93 * way we expect it to.
94 */
95 assert(0 == matchDomainName("foo.com", "foo.com"));
96 assert(0 == matchDomainName(".foo.com", "foo.com"));
97 assert(0 == matchDomainName("foo.com", ".foo.com"));
98 assert(0 == matchDomainName(".foo.com", ".foo.com"));
99 assert(0 == matchDomainName("x.foo.com", ".foo.com"));
100 assert(0 == matchDomainName("y.x.foo.com", ".foo.com"));
101 assert(0 != matchDomainName("x.foo.com", "foo.com"));
102 assert(0 != matchDomainName("foo.com", "x.foo.com"));
103 assert(0 != matchDomainName("bar.com", "foo.com"));
104 assert(0 != matchDomainName(".bar.com", "foo.com"));
105 assert(0 != matchDomainName(".bar.com", ".foo.com"));
106 assert(0 != matchDomainName("bar.com", ".foo.com"));
107 assert(0 < matchDomainName("zzz.com", "foo.com"));
108 assert(0 > matchDomainName("aaa.com", "foo.com"));
109 assert(0 == matchDomainName("FOO.com", "foo.COM"));
110 assert(0 < matchDomainName("bfoo.com", "afoo.com"));
111 assert(0 > matchDomainName("afoo.com", "bfoo.com"));
112 assert(0 < matchDomainName("x-foo.com", ".foo.com"));
113
114 assert(0 == matchDomainName(".foo.com", ".foo.com", mdnRejectSubsubDomains));
115 assert(0 == matchDomainName("x.foo.com", ".foo.com", mdnRejectSubsubDomains));
116 assert(0 != matchDomainName("y.x.foo.com", ".foo.com", mdnRejectSubsubDomains));
117 assert(0 != matchDomainName(".x.foo.com", ".foo.com", mdnRejectSubsubDomains));
118
119 assert(0 == matchDomainName("*.foo.com", "x.foo.com", mdnHonorWildcards));
120 assert(0 == matchDomainName("*.foo.com", ".x.foo.com", mdnHonorWildcards));
121 assert(0 == matchDomainName("*.foo.com", ".foo.com", mdnHonorWildcards));
122 assert(0 != matchDomainName("*.foo.com", "foo.com", mdnHonorWildcards));
123
124 /* more cases? */
125 }
126
127 /**
128 * Parse the scheme name from string b, into protocol type.
129 * The string must be 0-terminated.
130 */
131 AnyP::ProtocolType
132 urlParseProtocol(const char *b)
133 {
134 // make e point to the ':' character
135 const char *e = b + strcspn(b, ":");
136 int len = e - b;
137
138 /* test common stuff first */
139
140 if (strncasecmp(b, "http", len) == 0)
141 return AnyP::PROTO_HTTP;
142
143 if (strncasecmp(b, "ftp", len) == 0)
144 return AnyP::PROTO_FTP;
145
146 if (strncasecmp(b, "https", len) == 0)
147 return AnyP::PROTO_HTTPS;
148
149 if (strncasecmp(b, "file", len) == 0)
150 return AnyP::PROTO_FTP;
151
152 if (strncasecmp(b, "coap", len) == 0)
153 return AnyP::PROTO_COAP;
154
155 if (strncasecmp(b, "coaps", len) == 0)
156 return AnyP::PROTO_COAPS;
157
158 if (strncasecmp(b, "gopher", len) == 0)
159 return AnyP::PROTO_GOPHER;
160
161 if (strncasecmp(b, "wais", len) == 0)
162 return AnyP::PROTO_WAIS;
163
164 if (strncasecmp(b, "cache_object", len) == 0)
165 return AnyP::PROTO_CACHE_OBJECT;
166
167 if (strncasecmp(b, "urn", len) == 0)
168 return AnyP::PROTO_URN;
169
170 if (strncasecmp(b, "whois", len) == 0)
171 return AnyP::PROTO_WHOIS;
172
173 if (len > 0)
174 return AnyP::PROTO_UNKNOWN;
175
176 return AnyP::PROTO_NONE;
177 }
178
179 /*
180 * Parse a URI/URL.
181 *
182 * Stores parsed values in the `request` argument.
183 *
184 * This abuses HttpRequest as a way of representing the parsed url
185 * and its components.
186 * method is used to switch parsers and to init the HttpRequest.
187 * If method is Http::METHOD_CONNECT, then rather than a URL a hostname:port is
188 * looked for.
189 * The url is non const so that if its too long we can NULL-terminate it in place.
190 */
191
192 /*
193 * This routine parses a URL. Its assumed that the URL is complete -
194 * ie, the end of the string is the end of the URL. Don't pass a partial
195 * URL here as this routine doesn't have any way of knowing whether
196 * its partial or not (ie, it handles the case of no trailing slash as
197 * being "end of host with implied path of /".
198 */
199 bool
200 urlParse(const HttpRequestMethod& method, char *url, HttpRequest &request)
201 {
202 LOCAL_ARRAY(char, proto, MAX_URL);
203 LOCAL_ARRAY(char, login, MAX_URL);
204 LOCAL_ARRAY(char, host, MAX_URL);
205 LOCAL_ARRAY(char, urlpath, MAX_URL);
206 char *t = NULL;
207 char *q = NULL;
208 int port;
209 AnyP::ProtocolType protocol = AnyP::PROTO_NONE;
210 int l;
211 int i;
212 const char *src;
213 char *dst;
214 proto[0] = host[0] = urlpath[0] = login[0] = '\0';
215
216 if ((l = strlen(url)) + Config.appendDomainLen > (MAX_URL - 1)) {
217 /* terminate so it doesn't overflow other buffers */
218 *(url + (MAX_URL >> 1)) = '\0';
219 debugs(23, DBG_IMPORTANT, "urlParse: URL too large (" << l << " bytes)");
220 return false;
221 }
222 if (method == Http::METHOD_CONNECT) {
223 port = CONNECT_PORT;
224
225 if (sscanf(url, "[%[^]]]:%d", host, &port) < 1)
226 if (sscanf(url, "%[^:]:%d", host, &port) < 1)
227 return false;
228
229 } else if ((method == Http::METHOD_OPTIONS || method == Http::METHOD_TRACE) &&
230 URL::Asterisk().cmp(url) == 0) {
231 protocol = AnyP::PROTO_HTTP;
232 port = 80; // or the slow way ... AnyP::UriScheme(protocol,"http").defaultPort();
233 return urlParseFinish(method, protocol, "http", url, host, SBuf(), port, request);
234 } else if (!strncmp(url, "urn:", 4)) {
235 return urnParse(method, url, request);
236 } else {
237 /* Parse the URL: */
238 src = url;
239 i = 0;
240 /* Find first : - everything before is protocol */
241 for (i = 0, dst = proto; i < l && *src != ':'; ++i, ++src, ++dst) {
242 *dst = *src;
243 }
244 if (i >= l)
245 return false;
246 *dst = '\0';
247
248 /* Then its :// */
249 if ((i+3) > l || *src != ':' || *(src + 1) != '/' || *(src + 2) != '/')
250 return false;
251 i += 3;
252 src += 3;
253
254 /* Then everything until first /; thats host (and port; which we'll look for here later) */
255 // bug 1881: If we don't get a "/" then we imply it was there
256 // bug 3074: We could just be given a "?" or "#". These also imply "/"
257 // bug 3233: whitespace is also a hostname delimiter.
258 for (dst = host; i < l && *src != '/' && *src != '?' && *src != '#' && *src != '\0' && !xisspace(*src); ++i, ++src, ++dst) {
259 *dst = *src;
260 }
261
262 /*
263 * We can't check for "i >= l" here because we could be at the end of the line
264 * and have a perfectly valid URL w/ no trailing '/'. In this case we assume we've
265 * been -given- a valid URL and the path is just '/'.
266 */
267 if (i > l)
268 return false;
269 *dst = '\0';
270
271 // bug 3074: received 'path' starting with '?', '#', or '\0' implies '/'
272 if (*src == '?' || *src == '#' || *src == '\0') {
273 urlpath[0] = '/';
274 dst = &urlpath[1];
275 } else {
276 dst = urlpath;
277 }
278 /* Then everything from / (inclusive) until \r\n or \0 - thats urlpath */
279 for (; i < l && *src != '\r' && *src != '\n' && *src != '\0'; ++i, ++src, ++dst) {
280 *dst = *src;
281 }
282
283 /* We -could- be at the end of the buffer here */
284 if (i > l)
285 return false;
286 /* If the URL path is empty we set it to be "/" */
287 if (dst == urlpath) {
288 *dst = '/';
289 ++dst;
290 }
291 *dst = '\0';
292
293 protocol = urlParseProtocol(proto);
294 port = AnyP::UriScheme(protocol).defaultPort();
295
296 /* Is there any login information? (we should eventually parse it above) */
297 t = strrchr(host, '@');
298 if (t != NULL) {
299 strncpy((char *) login, (char *) host, sizeof(login)-1);
300 login[sizeof(login)-1] = '\0';
301 t = strrchr(login, '@');
302 *t = 0;
303 strncpy((char *) host, t + 1, sizeof(host)-1);
304 host[sizeof(host)-1] = '\0';
305 // Bug 4498: URL-unescape the login info after extraction
306 rfc1738_unescape(login);
307 }
308
309 /* Is there any host information? (we should eventually parse it above) */
310 if (*host == '[') {
311 /* strip any IPA brackets. valid under IPv6. */
312 dst = host;
313 /* only for IPv6 sadly, pre-IPv6/URL code can't handle the clean result properly anyway. */
314 src = host;
315 ++src;
316 l = strlen(host);
317 i = 1;
318 for (; i < l && *src != ']' && *src != '\0'; ++i, ++src, ++dst) {
319 *dst = *src;
320 }
321
322 /* we moved in-place, so truncate the actual hostname found */
323 *dst = '\0';
324 ++dst;
325
326 /* skip ahead to either start of port, or original EOS */
327 while (*dst != '\0' && *dst != ':')
328 ++dst;
329 t = dst;
330 } else {
331 t = strrchr(host, ':');
332
333 if (t != strchr(host,':') ) {
334 /* RFC 2732 states IPv6 "SHOULD" be bracketed. allowing for times when its not. */
335 /* RFC 3986 'update' simply modifies this to an "is" with no emphasis at all! */
336 /* therefore we MUST accept the case where they are not bracketed at all. */
337 t = NULL;
338 }
339 }
340
341 // Bug 3183 sanity check: If scheme is present, host must be too.
342 if (protocol != AnyP::PROTO_NONE && host[0] == '\0') {
343 debugs(23, DBG_IMPORTANT, "SECURITY ALERT: Missing hostname in URL '" << url << "'. see access.log for details.");
344 return false;
345 }
346
347 if (t && *t == ':') {
348 *t = '\0';
349 ++t;
350 port = atoi(t);
351 }
352 }
353
354 for (t = host; *t; ++t)
355 *t = xtolower(*t);
356
357 if (stringHasWhitespace(host)) {
358 if (URI_WHITESPACE_STRIP == Config.uri_whitespace) {
359 t = q = host;
360 while (*t) {
361 if (!xisspace(*t)) {
362 *q = *t;
363 ++q;
364 }
365 ++t;
366 }
367 *q = '\0';
368 }
369 }
370
371 debugs(23, 3, "urlParse: Split URL '" << url << "' into proto='" << proto << "', host='" << host << "', port='" << port << "', path='" << urlpath << "'");
372
373 if (Config.onoff.check_hostnames && strspn(host, Config.onoff.allow_underscore ? valid_hostname_chars_u : valid_hostname_chars) != strlen(host)) {
374 debugs(23, DBG_IMPORTANT, "urlParse: Illegal character in hostname '" << host << "'");
375 return false;
376 }
377
378 /* For IPV6 addresses also check for a colon */
379 if (Config.appendDomain && !strchr(host, '.') && !strchr(host, ':'))
380 strncat(host, Config.appendDomain, SQUIDHOSTNAMELEN - strlen(host) - 1);
381
382 /* remove trailing dots from hostnames */
383 while ((l = strlen(host)) > 0 && host[--l] == '.')
384 host[l] = '\0';
385
386 /* reject duplicate or leading dots */
387 if (strstr(host, "..") || *host == '.') {
388 debugs(23, DBG_IMPORTANT, "urlParse: Illegal hostname '" << host << "'");
389 return false;
390 }
391
392 if (port < 1 || port > 65535) {
393 debugs(23, 3, "urlParse: Invalid port '" << port << "'");
394 return false;
395 }
396
397 #if HARDCODE_DENY_PORTS
398 /* These ports are filtered in the default squid.conf, but
399 * maybe someone wants them hardcoded... */
400 if (port == 7 || port == 9 || port == 19) {
401 debugs(23, DBG_CRITICAL, "urlParse: Deny access to port " << port);
402 return false;
403 }
404 #endif
405
406 if (stringHasWhitespace(urlpath)) {
407 debugs(23, 2, "urlParse: URI has whitespace: {" << url << "}");
408
409 switch (Config.uri_whitespace) {
410
411 case URI_WHITESPACE_DENY:
412 return false;
413
414 case URI_WHITESPACE_ALLOW:
415 break;
416
417 case URI_WHITESPACE_ENCODE:
418 t = rfc1738_escape_unescaped(urlpath);
419 xstrncpy(urlpath, t, MAX_URL);
420 break;
421
422 case URI_WHITESPACE_CHOP:
423 *(urlpath + strcspn(urlpath, w_space)) = '\0';
424 break;
425
426 case URI_WHITESPACE_STRIP:
427 default:
428 t = q = urlpath;
429 while (*t) {
430 if (!xisspace(*t)) {
431 *q = *t;
432 ++q;
433 }
434 ++t;
435 }
436 *q = '\0';
437 }
438 }
439
440 return urlParseFinish(method, protocol, proto, urlpath, host, SBuf(login), port, request);
441 }
442
443 /**
444 * Update request with parsed URI data. If the request arg is
445 * non-NULL, put parsed values there instead of allocating a new
446 * HttpRequest.
447 */
448 static bool
449 urlParseFinish(const HttpRequestMethod& method,
450 const AnyP::ProtocolType protocol,
451 const char *const protoStr, // for unknown protocols
452 const char *const urlpath,
453 const char *const host,
454 const SBuf &login,
455 const int port,
456 HttpRequest &request)
457 {
458 request.initHTTP(method, protocol, protoStr, urlpath);
459 request.url.host(host);
460 request.url.userInfo(login);
461 request.url.port(port);
462 return true;
463 }
464
465 static bool
466 urnParse(const HttpRequestMethod& method, char *urn, HttpRequest &request)
467 {
468 debugs(50, 5, "urnParse: " << urn);
469 request.initHTTP(method, AnyP::PROTO_URN, "urn", urn + 4);
470 return true;
471 }
472
473 void
474 URL::touch()
475 {
476 absolute_.clear();
477 authorityHttp_.clear();
478 authorityWithPort_.clear();
479 }
480
481 SBuf &
482 URL::authority(bool requirePort) const
483 {
484 if (authorityHttp_.isEmpty()) {
485
486 // both formats contain Host/IP
487 authorityWithPort_.append(host());
488 authorityHttp_ = authorityWithPort_;
489
490 // authorityForm_ only has :port if it is non-default
491 authorityWithPort_.appendf(":%u",port());
492 if (port() != getScheme().defaultPort())
493 authorityHttp_ = authorityWithPort_;
494 }
495
496 return requirePort ? authorityWithPort_ : authorityHttp_;
497 }
498
499 SBuf &
500 URL::absolute() const
501 {
502 if (absolute_.isEmpty()) {
503 // TODO: most URL will be much shorter, avoid allocating this much
504 absolute_.reserveCapacity(MAX_URL);
505
506 absolute_.append(getScheme().image());
507 absolute_.append(":",1);
508 if (getScheme() != AnyP::PROTO_URN) {
509 absolute_.append("//", 2);
510 const bool omitUserInfo = getScheme() == AnyP::PROTO_HTTP ||
511 getScheme() != AnyP::PROTO_HTTPS ||
512 userInfo().isEmpty();
513 if (!omitUserInfo) {
514 absolute_.append(userInfo());
515 absolute_.append("@", 1);
516 }
517 absolute_.append(authority());
518 }
519 absolute_.append(path());
520 }
521
522 return absolute_;
523 }
524
525 /** \todo AYJ: Performance: This is an *almost* duplicate of HttpRequest::effectiveRequestUri(). But elides the query-string.
526 * After copying it on in the first place! Would be less code to merge the two with a flag parameter.
527 * and never copy the query-string part in the first place
528 */
529 char *
530 urlCanonicalClean(const HttpRequest * request)
531 {
532 LOCAL_ARRAY(char, buf, MAX_URL);
533
534 snprintf(buf, sizeof(buf), SQUIDSBUFPH, SQUIDSBUFPRINT(request->effectiveRequestUri()));
535 buf[sizeof(buf)-1] = '\0';
536
537 // URN, CONNECT method, and non-stripped URIs can go straight out
538 if (Config.onoff.strip_query_terms && !(request->method == Http::METHOD_CONNECT || request->url.getScheme() == AnyP::PROTO_URN)) {
539 // strip anything AFTER a question-mark
540 // leaving the '?' in place
541 if (auto t = strchr(buf, '?')) {
542 *(++t) = '\0';
543 }
544 }
545
546 if (stringHasCntl(buf))
547 xstrncpy(buf, rfc1738_escape_unescaped(buf), MAX_URL);
548
549 return buf;
550 }
551
552 /**
553 * Yet another alternative to urlCanonical.
554 * This one adds the https:// parts to Http::METHOD_CONNECT URL
555 * for use in error page outputs.
556 * Luckily we can leverage the others instead of duplicating.
557 */
558 const char *
559 urlCanonicalFakeHttps(const HttpRequest * request)
560 {
561 LOCAL_ARRAY(char, buf, MAX_URL);
562
563 // method CONNECT and port HTTPS
564 if (request->method == Http::METHOD_CONNECT && request->url.port() == 443) {
565 snprintf(buf, MAX_URL, "https://%s/*", request->url.host());
566 return buf;
567 }
568
569 // else do the normal complete canonical thing.
570 return urlCanonicalClean(request);
571 }
572
573 /*
574 * Test if a URL is relative.
575 *
576 * RFC 2396, Section 5 (Page 17) implies that in a relative URL, a '/' will
577 * appear before a ':'.
578 */
579 bool
580 urlIsRelative(const char *url)
581 {
582 const char *p;
583
584 if (url == NULL) {
585 return (false);
586 }
587 if (*url == '\0') {
588 return (false);
589 }
590
591 for (p = url; *p != '\0' && *p != ':' && *p != '/'; ++p);
592
593 if (*p == ':') {
594 return (false);
595 }
596 return (true);
597 }
598
599 /*
600 * Convert a relative URL to an absolute URL using the context of a given
601 * request.
602 *
603 * It is assumed that you have already ensured that the URL is relative.
604 *
605 * If NULL is returned it is an indication that the method in use in the
606 * request does not distinguish between relative and absolute and you should
607 * use the url unchanged.
608 *
609 * If non-NULL is returned, it is up to the caller to free the resulting
610 * memory using safe_free().
611 */
612 char *
613 urlMakeAbsolute(const HttpRequest * req, const char *relUrl)
614 {
615
616 if (req->method.id() == Http::METHOD_CONNECT) {
617 return (NULL);
618 }
619
620 char *urlbuf = (char *)xmalloc(MAX_URL * sizeof(char));
621
622 if (req->url.getScheme() == AnyP::PROTO_URN) {
623 // XXX: this is what the original code did, but it seems to break the
624 // intended behaviour of this function. It returns the stored URN path,
625 // not converting the given one into a URN...
626 snprintf(urlbuf, MAX_URL, SQUIDSBUFPH, SQUIDSBUFPRINT(req->url.absolute()));
627 return (urlbuf);
628 }
629
630 SBuf authorityForm = req->url.authority(); // host[:port]
631 const SBuf &scheme = req->url.getScheme().image();
632 size_t urllen = snprintf(urlbuf, MAX_URL, SQUIDSBUFPH "://" SQUIDSBUFPH "%s" SQUIDSBUFPH,
633 SQUIDSBUFPRINT(scheme),
634 SQUIDSBUFPRINT(req->url.userInfo()),
635 !req->url.userInfo().isEmpty() ? "@" : "",
636 SQUIDSBUFPRINT(authorityForm));
637
638 // if the first char is '/' assume its a relative path
639 // XXX: this breaks on scheme-relative URLs,
640 // but we should not see those outside ESI, and rarely there.
641 // XXX: also breaks on any URL containing a '/' in the query-string portion
642 if (relUrl[0] == '/') {
643 xstrncpy(&urlbuf[urllen], relUrl, MAX_URL - urllen - 1);
644 } else {
645 SBuf path = req->url.path();
646 SBuf::size_type lastSlashPos = path.rfind('/');
647
648 if (lastSlashPos == SBuf::npos) {
649 // replace the whole path with the given bit(s)
650 urlbuf[urllen] = '/';
651 ++urllen;
652 xstrncpy(&urlbuf[urllen], relUrl, MAX_URL - urllen - 1);
653 } else {
654 // replace only the last (file?) segment with the given bit(s)
655 ++lastSlashPos;
656 if (lastSlashPos > MAX_URL - urllen - 1) {
657 // XXX: crops bits in the middle of the combined URL.
658 lastSlashPos = MAX_URL - urllen - 1;
659 }
660 SBufToCstring(&urlbuf[urllen], path.substr(0,lastSlashPos));
661 urllen += lastSlashPos;
662 if (urllen + 1 < MAX_URL) {
663 xstrncpy(&urlbuf[urllen], relUrl, MAX_URL - urllen - 1);
664 }
665 }
666 }
667
668 return (urlbuf);
669 }
670
671 int
672 matchDomainName(const char *h, const char *d, uint flags)
673 {
674 int dl;
675 int hl;
676
677 const bool hostIncludesSubdomains = (*h == '.');
678 while ('.' == *h)
679 ++h;
680
681 hl = strlen(h);
682
683 if (hl == 0)
684 return -1;
685
686 dl = strlen(d);
687
688 /*
689 * Start at the ends of the two strings and work towards the
690 * beginning.
691 */
692 while (xtolower(h[--hl]) == xtolower(d[--dl])) {
693 if (hl == 0 && dl == 0) {
694 /*
695 * We made it all the way to the beginning of both
696 * strings without finding any difference.
697 */
698 return 0;
699 }
700
701 if (0 == hl) {
702 /*
703 * The host string is shorter than the domain string.
704 * There is only one case when this can be a match.
705 * If the domain is just one character longer, and if
706 * that character is a leading '.' then we call it a
707 * match.
708 */
709
710 if (1 == dl && '.' == d[0])
711 return 0;
712 else
713 return -1;
714 }
715
716 if (0 == dl) {
717 /*
718 * The domain string is shorter than the host string.
719 * This is a match only if the first domain character
720 * is a leading '.'.
721 */
722
723 if ('.' == d[0]) {
724 if (flags & mdnRejectSubsubDomains) {
725 // Check for sub-sub domain and reject
726 while(--hl >= 0 && h[hl] != '.');
727 if (hl < 0) {
728 // No sub-sub domain found, but reject if there is a
729 // leading dot in given host string (which is removed
730 // before the check is started).
731 return hostIncludesSubdomains ? 1 : 0;
732 } else
733 return 1; // sub-sub domain, reject
734 } else
735 return 0;
736 } else
737 return 1;
738 }
739 }
740
741 /*
742 * We found different characters in the same position (from the end).
743 */
744
745 // If the h has a form of "*.foo.com" and d has a form of "x.foo.com"
746 // then the h[hl] points to '*', h[hl+1] to '.' and d[dl] to 'x'
747 // The following checks are safe, the "h[hl + 1]" in the worst case is '\0'.
748 if ((flags & mdnHonorWildcards) && h[hl] == '*' && h[hl + 1] == '.')
749 return 0;
750
751 /*
752 * If one of those character is '.' then its special. In order
753 * for splay tree sorting to work properly, "x-foo.com" must
754 * be greater than ".foo.com" even though '-' is less than '.'.
755 */
756 if ('.' == d[dl])
757 return 1;
758
759 if ('.' == h[hl])
760 return -1;
761
762 return (xtolower(h[hl]) - xtolower(d[dl]));
763 }
764
765 /*
766 * return true if we can serve requests for this method.
767 */
768 int
769 urlCheckRequest(const HttpRequest * r)
770 {
771 int rc = 0;
772 /* protocol "independent" methods
773 *
774 * actually these methods are specific to HTTP:
775 * they are methods we recieve on our HTTP port,
776 * and if we had a FTP listener would not be relevant
777 * there.
778 *
779 * So, we should delegate them to HTTP. The problem is that we
780 * do not have a default protocol from the client side of HTTP.
781 */
782
783 if (r->method == Http::METHOD_CONNECT)
784 return 1;
785
786 // we support OPTIONS and TRACE directed at us (with a 501 reply, for now)
787 // we also support forwarding OPTIONS and TRACE, except for the *-URI ones
788 if (r->method == Http::METHOD_OPTIONS || r->method == Http::METHOD_TRACE)
789 return (r->header.getInt64(Http::HdrType::MAX_FORWARDS) == 0 || r->url.path() != URL::Asterisk());
790
791 if (r->method == Http::METHOD_PURGE)
792 return 1;
793
794 /* does method match the protocol? */
795 switch (r->url.getScheme()) {
796
797 case AnyP::PROTO_URN:
798
799 case AnyP::PROTO_HTTP:
800
801 case AnyP::PROTO_CACHE_OBJECT:
802 rc = 1;
803 break;
804
805 case AnyP::PROTO_FTP:
806
807 if (r->method == Http::METHOD_PUT)
808 rc = 1;
809
810 case AnyP::PROTO_GOPHER:
811
812 case AnyP::PROTO_WAIS:
813
814 case AnyP::PROTO_WHOIS:
815 if (r->method == Http::METHOD_GET)
816 rc = 1;
817 else if (r->method == Http::METHOD_HEAD)
818 rc = 1;
819
820 break;
821
822 case AnyP::PROTO_HTTPS:
823 #if USE_OPENSSL
824 rc = 1;
825 #elif USE_GNUTLS
826 rc = 1;
827 #else
828 /*
829 * Squid can't originate an SSL connection, so it should
830 * never receive an "https:" URL. It should always be
831 * CONNECT instead.
832 */
833 rc = 0;
834 #endif
835 break;
836
837 default:
838 break;
839 }
840
841 return rc;
842 }
843
844 /*
845 * Quick-n-dirty host extraction from a URL. Steps:
846 * Look for a colon
847 * Skip any '/' after the colon
848 * Copy the next SQUID_MAXHOSTNAMELEN bytes to host[]
849 * Look for an ending '/' or ':' and terminate
850 * Look for login info preceeded by '@'
851 */
852
853 class URLHostName
854 {
855
856 public:
857 char * extract(char const *url);
858
859 private:
860 static char Host [SQUIDHOSTNAMELEN];
861 void init(char const *);
862 void findHostStart();
863 void trimTrailingChars();
864 void trimAuth();
865 char const *hostStart;
866 char const *url;
867 };
868
869 char *
870 urlHostname(const char *url)
871 {
872 return URLHostName().extract(url);
873 }
874
875 char URLHostName::Host[SQUIDHOSTNAMELEN];
876
877 void
878 URLHostName::init(char const *aUrl)
879 {
880 Host[0] = '\0';
881 url = aUrl;
882 }
883
884 void
885 URLHostName::findHostStart()
886 {
887 if (NULL == (hostStart = strchr(url, ':')))
888 return;
889
890 ++hostStart;
891
892 while (*hostStart != '\0' && *hostStart == '/')
893 ++hostStart;
894
895 if (*hostStart == ']')
896 ++hostStart;
897 }
898
899 void
900 URLHostName::trimTrailingChars()
901 {
902 char *t;
903
904 if ((t = strchr(Host, '/')))
905 *t = '\0';
906
907 if ((t = strrchr(Host, ':')))
908 *t = '\0';
909
910 if ((t = strchr(Host, ']')))
911 *t = '\0';
912 }
913
914 void
915 URLHostName::trimAuth()
916 {
917 char *t;
918
919 if ((t = strrchr(Host, '@'))) {
920 ++t;
921 memmove(Host, t, strlen(t) + 1);
922 }
923 }
924
925 char *
926 URLHostName::extract(char const *aUrl)
927 {
928 init(aUrl);
929 findHostStart();
930
931 if (hostStart == NULL)
932 return NULL;
933
934 xstrncpy(Host, hostStart, SQUIDHOSTNAMELEN);
935
936 trimTrailingChars();
937
938 trimAuth();
939
940 return Host;
941 }
942
943 URL::URL(AnyP::UriScheme const &aScheme) :
944 scheme_(aScheme),
945 hostIsNumeric_(false),
946 port_(0)
947 {
948 *host_=0;
949 }
950