1 /* Support for Robot Exclusion Standard (RES).
2 Copyright (C) 2001, 2006, 2007 Free Software Foundation, Inc.
4 This file is part of Wget.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or (at
9 your option) any later version.
11 This program is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Wget. If not, see <http://www.gnu.org/licenses/>.
19 In addition, as a special exception, the Free Software Foundation
20 gives permission to link the code of its release of Wget with the
21 OpenSSL project's "OpenSSL" library (or with modified versions of it
22 that use the same license as the "OpenSSL" library), and distribute
23 the linked executables. You must obey the GNU General Public License
24 in all respects for all of the code used other than "OpenSSL". If you
25 modify this file, you may extend this exception to your version of the
26 file, but you are not obligated to do so. If you do not wish to do
27 so, delete this exception statement from your version. */
29 /* This file implements the Robot Exclusion Standard (RES).
31 RES is a simple protocol that enables site admins to signalize to
32 the web crawlers that certain parts of the site should not be
33 accessed. All the admin needs to do is create a "robots.txt" file
34 in the web server root, and use simple commands to allow or
35 disallow access to certain parts of the site.
37 The first specification was written by Martijn Koster in 1994, and
38 is still available at <http://www.robotstxt.org/wc/norobots.html>.
39 In 1996, Martijn wrote an Internet Draft specifying an improved RES
40 specification; however, that work was apparently abandoned since
41 the draft has expired in 1997 and hasn't been replaced since. The
43 <http://www.robotstxt.org/wc/norobots-rfc.html>.
45 This file implements RES as specified by the draft. Note that this
46 only handles the "robots.txt" support. The META tag that controls
47 whether the links should be followed is handled in `html-url.c'.
51 * The end-of-line comment recognition is more in the spirit of the
52 Bourne Shell (as specified by RES-1994). That means that
53 "foo#bar" is taken literally, whereas "foo #bar" is interpreted
54 as "foo". The Draft apparently specifies that both should be
57 * We don't recognize sole CR as the line ending.
59 * We don't implement expiry mechanism for /robots.txt specs. I
60 consider it non-necessary for a relatively short-lived
61 application such as Wget. Besides, it is highly questionable
62 whether anyone deploys the recommended expiry scheme for
65 Entry points are functions res_parse, res_parse_from_file,
66 res_match_path, res_register_specs, res_get_specs, and
90 bool user_agent_exact_p;
96 struct path_info *paths;
99 /* Parsing the robot spec. */
101 /* Check whether AGENT (a string of length LENGTH) equals "wget" or
102 "*". If it is either of them, *matches is set to one. If it is
103 "wget", *exact_match is set to one. */
106 match_user_agent (const char *agent, int length,
107 bool *matches, bool *exact_match)
109 if (length == 1 && *agent == '*')
112 *exact_match = false;
114 else if (BOUNDED_EQUAL_NO_CASE (agent, agent + length, "wget"))
122 *exact_match = false;
126 /* Add a path specification between PATH_B and PATH_E as one of the
130 add_path (struct robot_specs *specs, const char *path_b, const char *path_e,
131 bool allowedp, bool exactp)
134 if (path_b < path_e && *path_b == '/')
135 /* Our path representation doesn't use a leading slash, so remove
138 pp.path = strdupdelim (path_b, path_e);
139 pp.allowedp = allowedp;
140 pp.user_agent_exact_p = exactp;
142 if (specs->count > specs->size)
144 if (specs->size == 0)
148 specs->paths = xrealloc (specs->paths,
149 specs->size * sizeof (struct path_info));
151 specs->paths[specs->count - 1] = pp;
154 /* Recreate SPECS->paths with only those paths that have
155 user_agent_exact_p set to true. */
158 prune_non_exact (struct robot_specs *specs)
160 struct path_info *newpaths;
163 for (i = 0; i < specs->count; i++)
164 if (specs->paths[i].user_agent_exact_p)
166 newpaths = xnew_array (struct path_info, cnt);
167 for (i = 0, j = 0; i < specs->count; i++)
168 if (specs->paths[i].user_agent_exact_p)
169 newpaths[j++] = specs->paths[i];
171 xfree (specs->paths);
172 specs->paths = newpaths;
177 #define EOL(p) ((p) >= lineend)
179 #define SKIP_SPACE(p) do { \
180 while (!EOL (p) && c_isspace (*p)) \
184 #define FIELD_IS(string_literal) \
185 BOUNDED_EQUAL_NO_CASE (field_b, field_e, string_literal)
187 /* Parse textual RES specs beginning with SOURCE of length LENGTH.
188 Return a specs objects ready to be fed to res_match_path.
190 The parsing itself is trivial, but creating a correct SPECS object
191 is trickier than it seems, because RES is surprisingly byzantine if
192 you attempt to implement it correctly.
194 A "record" is a block of one or more `User-Agent' lines followed by
195 one or more `Allow' or `Disallow' lines. Record is accepted by
196 Wget if one of the `User-Agent' lines was "wget", or if the user
199 After all the lines have been read, we examine whether an exact
200 ("wget") user-agent field was specified. If so, we delete all the
201 lines read under "User-Agent: *" blocks because we have our own
202 Wget-specific blocks. This enables the admin to say:
211 This means that to Wget and to Google, /cgi-bin is disallowed,
212 whereas for all other crawlers, everything is disallowed.
213 res_parse is implemented so that the order of records doesn't
214 matter. In the case above, the "User-Agent: *" could have come
215 after the other one. */
218 res_parse (const char *source, int length)
222 const char *p = source;
223 const char *end = source + length;
225 /* true if last applicable user-agent field matches Wget. */
226 bool user_agent_applies = false;
228 /* true if last applicable user-agent field *exactly* matches
230 bool user_agent_exact = false;
232 /* whether we ever encountered exact user agent. */
233 bool found_exact = false;
235 /* count of allow/disallow lines in the current "record", i.e. after
236 the last `user-agent' instructions. */
237 int record_count = 0;
239 struct robot_specs *specs = xnew0 (struct robot_specs);
243 const char *lineend, *lineend_real;
244 const char *field_b, *field_e;
245 const char *value_b, *value_e;
249 lineend_real = memchr (p, '\n', end - p);
254 lineend = lineend_real;
256 /* Before doing anything else, check whether the line is empty
259 if (EOL (p) || *p == '#')
262 /* Make sure the end-of-line comments are respected by setting
263 lineend to a location preceding the first comment. Real line
264 ending remains in lineend_real. */
265 for (lineend = p; lineend < lineend_real; lineend++)
266 if ((lineend == p || c_isspace (*(lineend - 1)))
270 /* Ignore trailing whitespace in the same way. */
271 while (lineend > p && c_isspace (*(lineend - 1)))
277 while (!EOL (p) && (c_isalnum (*p) || *p == '-'))
282 if (field_b == field_e || EOL (p) || *p != ':')
284 DEBUGP (("Ignoring malformed line %d", line_count));
295 /* Finally, we have a syntactically valid line. */
296 if (FIELD_IS ("user-agent"))
298 /* We have to support several cases:
305 ... matching record ...
309 ... non-matching record ...
312 ... matching record, but will be pruned later ...
314 We have to respect `User-Agent' at the beginning of each
315 new record simply because we don't know if we're going to
316 encounter "Wget" among the agents or not. Hence,
317 match_user_agent is called when record_count != 0.
319 But if record_count is 0, we have to keep calling it
320 until it matches, and if that happens, we must not call
321 it any more, until the next record. Hence the other part
323 if (record_count != 0 || user_agent_applies == false)
324 match_user_agent (value_b, value_e - value_b,
325 &user_agent_applies, &user_agent_exact);
326 if (user_agent_exact)
330 else if (FIELD_IS ("allow"))
332 if (user_agent_applies)
334 add_path (specs, value_b, value_e, true, user_agent_exact);
338 else if (FIELD_IS ("disallow"))
340 if (user_agent_applies)
342 bool allowed = false;
343 if (value_b == value_e)
344 /* Empty "disallow" line means everything is *allowed*! */
346 add_path (specs, value_b, value_e, allowed, user_agent_exact);
352 DEBUGP (("Ignoring unknown field at line %d", line_count));
363 /* We've encountered an exactly matching user-agent. Throw out
364 all the stuff with user-agent: *. */
365 prune_non_exact (specs);
367 else if (specs->size > specs->count)
369 /* add_path normally over-allocates specs->paths. Reallocate it
370 to the correct size in order to conserve some memory. */
371 specs->paths = xrealloc (specs->paths,
372 specs->count * sizeof (struct path_info));
373 specs->size = specs->count;
379 /* The same like res_parse, but first map the FILENAME into memory,
380 and then parse it. */
383 res_parse_from_file (const char *filename)
385 struct robot_specs *specs;
386 struct file_memory *fm = read_file (filename);
389 logprintf (LOG_NOTQUIET, _("Cannot open %s: %s"),
390 filename, strerror (errno));
393 specs = res_parse (fm->content, fm->length);
399 free_specs (struct robot_specs *specs)
402 for (i = 0; i < specs->count; i++)
403 xfree (specs->paths[i].path);
404 xfree_null (specs->paths);
408 /* Matching of a path according to the specs. */
410 /* If C is '%' and (ptr[1], ptr[2]) form a hexadecimal number, and if
411 that number is not a numerical representation of '/', decode C and
412 advance the pointer. */
414 #define DECODE_MAYBE(c, ptr) do { \
415 if (c == '%' && c_isxdigit (ptr[1]) && c_isxdigit (ptr[2])) \
417 char decoded = X2DIGITS_TO_NUM (ptr[1], ptr[2]); \
418 if (decoded != '/') \
426 /* The inner matching engine: return true if RECORD_PATH matches
427 URL_PATH. The rules for matching are described at
428 <http://www.robotstxt.org/wc/norobots-rfc.txt>, section 3.2.2. */
431 matches (const char *record_path, const char *url_path)
433 const char *rp = record_path;
434 const char *up = url_path;
444 DECODE_MAYBE(rc, rp);
445 DECODE_MAYBE(uc, up);
451 /* Iterate through all paths in SPECS. For the first one that
452 matches, return its allow/reject status. If none matches,
453 retrieval is by default allowed. */
456 res_match_path (const struct robot_specs *specs, const char *path)
461 for (i = 0; i < specs->count; i++)
462 if (matches (specs->paths[i].path, path))
464 bool allowedp = specs->paths[i].allowedp;
465 DEBUGP (("%s path %s because of rule `%s'.\n",
466 allowedp ? "Allowing" : "Rejecting",
467 path, specs->paths[i].path));
473 /* Registering the specs. */
475 static struct hash_table *registered_specs;
477 /* Stolen from cookies.c. */
478 #define SET_HOSTPORT(host, port, result) do { \
479 int HP_len = strlen (host); \
480 result = alloca (HP_len + 1 + numdigit (port) + 1); \
481 memcpy (result, host, HP_len); \
482 result[HP_len] = ':'; \
483 number_to_string (result + HP_len + 1, port); \
486 /* Register RES specs that below to server on HOST:PORT. They will
487 later be retrievable using res_get_specs. */
490 res_register_specs (const char *host, int port, struct robot_specs *specs)
492 struct robot_specs *old;
494 SET_HOSTPORT (host, port, hp);
496 if (!registered_specs)
497 registered_specs = make_nocase_string_hash_table (0);
499 if (hash_table_get_pair (registered_specs, hp, &hp_old, &old))
503 hash_table_put (registered_specs, hp_old, specs);
507 hash_table_put (registered_specs, xstrdup (hp), specs);
511 /* Get the specs that belong to HOST:PORT. */
514 res_get_specs (const char *host, int port)
517 SET_HOSTPORT (host, port, hp);
518 if (!registered_specs)
520 return hash_table_get (registered_specs, hp);
523 /* Loading the robots file. */
525 #define RES_SPECS_LOCATION "/robots.txt"
527 /* Retrieve the robots.txt from the server root of the server that
528 serves URL. The file will be named according to the currently
529 active rules, and the file name will be returned in *file.
531 Return true if robots were retrieved OK, false otherwise. */
534 res_retrieve_file (const char *url, char **file)
537 char *robots_url = uri_merge (url, RES_SPECS_LOCATION);
538 int saved_ts_val = opt.timestamping;
539 int saved_sp_val = opt.spider;
541 logputs (LOG_VERBOSE, _("Loading robots.txt; please ignore errors.\n"));
543 opt.timestamping = false;
545 err = retrieve_url (robots_url, file, NULL, NULL, NULL, false);
546 opt.timestamping = saved_ts_val;
547 opt.spider = saved_sp_val;
550 if (err != RETROK && *file != NULL)
552 /* If the file is not retrieved correctly, but retrieve_url
553 allocated the file name, deallocate is here so that the
554 caller doesn't have to worry about it. */
558 return err == RETROK;
562 is_robots_txt_url (const char *url)
564 char *robots_url = uri_merge (url, RES_SPECS_LOCATION);
565 bool ret = are_urls_equal (url, robots_url);
575 if (registered_specs)
577 hash_table_iterator iter;
578 for (hash_table_iterate (registered_specs, &iter);
579 hash_table_iter_next (&iter);
583 free_specs (iter.value);
585 hash_table_destroy (registered_specs);
586 registered_specs = NULL;
593 test_is_robots_txt_url()
598 bool expected_result;
600 { "http://www.yoyodyne.com/robots.txt", true },
601 { "http://www.yoyodyne.com/somepath/", false },
602 { "http://www.yoyodyne.com/somepath/robots.txt", false },
605 for (i = 0; i < sizeof(test_array)/sizeof(test_array[0]); ++i)
607 mu_assert ("test_is_robots_txt_url: wrong result",
608 is_robots_txt_url (test_array[i].url) == test_array[i].expected_result);