📄 html-parse.c
字号:
/* HTML parser for Wget. Copyright (C) 1998, 2000, 2003 Free Software Foundation, Inc.This file is part of GNU Wget.GNU Wget is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2 of the License, or (atyour option) any later version.GNU Wget is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with Wget; if not, write to the Free SoftwareFoundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.In addition, as a special exception, the Free Software Foundationgives permission to link the code of its release of Wget with theOpenSSL project's "OpenSSL" library (or with modified versions of itthat use the same license as the "OpenSSL" library), and distributethe linked executables. You must obey the GNU General Public Licensein all respects for all of the code used other than "OpenSSL". If youmodify this file, you may extend this exception to your version of thefile, but you are not obligated to do so. If you do not wish to doso, delete this exception statement from your version. *//* The only entry point to this module is map_html_tags(), which see. *//* TODO: - Allow hooks for callers to process contents outside tags. This is needed to implement handling <style> and <script>. The taginfo structure already carries the information about where the tags are, but this is not enough, because one would also want to skip the comments. (The funny thing is that for <style> and <script> you *don't* want to skip comments!) - Create a test suite for regression testing. *//* HISTORY: This is the third HTML parser written for Wget. The first one was written some time during the Geturl 1.0 beta cycle, and was very inefficient and buggy. It also contained some very complex code to remember a list of parser states, because it was supposed to be reentrant. The second HTML parser was written for Wget 1.4 (the first version by the name `Wget'), and was a complete rewrite. Although the new parser behaved much better and made no claims of reentrancy, it still shared many of the fundamental flaws of the old version -- it only regarded HTML in terms tag-attribute pairs, where the attribute's value was a URL to be returned. Any other property of HTML, such as <base href=...>, or strange way to specify a URL, such as <meta http-equiv=Refresh content="0; URL=..."> had to be crudely hacked in -- and the caller had to be aware of these hacks. Like its predecessor, this parser did not support HTML comments. After Wget 1.5.1 was released, I set out to write a third HTML parser. The objectives of the new parser were to: (1) provide a clean way to analyze HTML lexically, (2) separate interpretation of the markup from the parsing process, (3) be as correct as possible, e.g. correctly skipping comments and other SGML declarations, (4) understand the most common errors in markup and skip them or be relaxed towrds them, and (5) be reasonably efficient (no regexps, minimum copying and minimum or no heap allocation). I believe this parser meets all of the above goals. It is reasonably well structured, and could be relatively easily separated from Wget and used elsewhere. While some of its intrinsic properties limit its value as a general-purpose HTML parser, I believe that, with minimum modifications, it could serve as a backend for one. Due to time and other constraints, this parser was not integrated into Wget until the version 1.7. *//* DESCRIPTION: The single entry point of this parser is map_html_tags(), which works by calling a function you specify for each tag. The function gets called with the pointer to a structure describing the tag and its attributes. *//* To test as standalone, compile with `-DSTANDALONE -I.'. You'll still need Wget headers to compile. */#include <config.h>#ifdef STANDALONE# define I_REALLY_WANT_CTYPE_MACROS#endif#include <stdio.h>#include <stdlib.h>#ifdef HAVE_STRING_H# include <string.h>#else# include <strings.h>#endif#include <assert.h>#include "wget.h"#include "html-parse.h"#ifdef STANDALONE# undef xmalloc# undef xrealloc# undef xfree# define xmalloc malloc# define xrealloc realloc# define xfree free# undef ISSPACE# undef ISDIGIT# undef ISXDIGIT# undef ISALPHA# undef ISALNUM# undef TOLOWER# undef TOUPPER# define ISSPACE(x) isspace (x)# define ISDIGIT(x) isdigit (x)# define ISXDIGIT(x) isxdigit (x)# define ISALPHA(x) isalpha (x)# define ISALNUM(x) isalnum (x)# define TOLOWER(x) tolower (x)# define TOUPPER(x) toupper (x)struct hash_table { int dummy;};static void *hash_table_get (const struct hash_table *ht, void *ptr){ return ptr;}#else /* not STANDALONE */# include "hash.h"#endif/* Pool support. A pool is a resizable chunk of memory. It is first allocated on the stack, and moved to the heap if it needs to be larger than originally expected. map_html_tags() uses it to store the zero-terminated names and values of tags and attributes. Thus taginfo->name, and attr->name and attr->value for each attribute, do not point into separately allocated areas, but into different parts of the pool, separated only by terminating zeros. This ensures minimum amount of allocation and, for most tags, no allocation because the entire pool is kept on the stack. */struct pool { char *contents; /* pointer to the contents. */ int size; /* size of the pool. */ int tail; /* next available position index. */ int resized; /* whether the pool has been resized using malloc. */ char *orig_contents; /* original pool contents, usually stack-allocated. used by POOL_FREE to restore the pool to the initial state. */ int orig_size;};/* Initialize the pool to hold INITIAL_SIZE bytes of storage. */#define POOL_INIT(p, initial_storage, initial_size) do { \ struct pool *P = (p); \ P->contents = (initial_storage); \ P->size = (initial_size); \ P->tail = 0; \ P->resized = 0; \ P->orig_contents = P->contents; \ P->orig_size = P->size; \} while (0)/* Grow the pool to accomodate at least SIZE new bytes. If the pool already has room to accomodate SIZE bytes of data, this is a no-op. */#define POOL_GROW(p, increase) \ GROW_ARRAY ((p)->contents, (p)->size, (p)->tail + (increase), \ (p)->resized, char)/* Append text in the range [beg, end) to POOL. No zero-termination is done. */#define POOL_APPEND(p, beg, end) do { \ const char *PA_beg = (beg); \ int PA_size = (end) - PA_beg; \ POOL_GROW (p, PA_size); \ memcpy ((p)->contents + (p)->tail, PA_beg, PA_size); \ (p)->tail += PA_size; \} while (0)/* Append one character to the pool. Can be used to zero-terminate pool strings. */#define POOL_APPEND_CHR(p, ch) do { \ char PAC_char = (ch); \ POOL_GROW (p, 1); \ (p)->contents[(p)->tail++] = PAC_char; \} while (0)/* Forget old pool contents. The allocated memory is not freed. */#define POOL_REWIND(p) (p)->tail = 0/* Free heap-allocated memory for contents of POOL. This calls xfree() if the memory was allocated through malloc. It also restores `contents' and `size' to their original, pre-malloc values. That way after POOL_FREE, the pool is fully usable, just as if it were freshly initialized with POOL_INIT. */#define POOL_FREE(p) do { \ struct pool *P = p; \ if (P->resized) \ xfree (P->contents); \ P->contents = P->orig_contents; \ P->size = P->orig_size; \ P->tail = 0; \ P->resized = 0; \} while (0)/* Used for small stack-allocated memory chunks that might grow. Like DO_REALLOC, this macro grows BASEVAR as necessary to take NEEDED_SIZE items of TYPE. The difference is that on the first resize, it will use malloc+memcpy rather than realloc. That way you can stack-allocate the initial chunk, and only resort to heap allocation if you stumble upon large data. After the first resize, subsequent ones are performed with realloc, just like DO_REALLOC. */#define GROW_ARRAY(basevar, sizevar, needed_size, resized, type) do { \ long ga_needed_size = (needed_size); \ long ga_newsize = (sizevar); \ while (ga_newsize < ga_needed_size) \ ga_newsize <<= 1; \ if (ga_newsize != (sizevar)) \ { \ if (resized) \ basevar = (type *)xrealloc (basevar, ga_newsize * sizeof (type)); \ else \ { \ void *ga_new = xmalloc (ga_newsize * sizeof (type)); \ memcpy (ga_new, basevar, (sizevar) * sizeof (type)); \ (basevar) = ga_new; \ resized = 1; \ } \ (sizevar) = ga_newsize; \ } \} while (0)#define AP_DOWNCASE 1#define AP_PROCESS_ENTITIES 2#define AP_TRIM_BLANKS 4/* Copy the text in the range [BEG, END) to POOL, optionally performing operations specified by FLAGS. FLAGS may be any combination of AP_DOWNCASE, AP_PROCESS_ENTITIES and AP_TRIM_BLANKS with the following meaning: * AP_DOWNCASE -- downcase all the letters; * AP_PROCESS_ENTITIES -- process the SGML entities and write out the decoded string. Recognized entities are <, >, &, ",   and the numerical entities. * AP_TRIM_BLANKS -- ignore blanks at the beginning and at the end of text. */static voidconvert_and_copy (struct pool *pool, const char *beg, const char *end, int flags){ int old_tail = pool->tail; int size; /* First, skip blanks if required. We must do this before entities are processed, so that blanks can still be inserted as, for instance, ` '. */ if (flags & AP_TRIM_BLANKS) { while (beg < end && ISSPACE (*beg)) ++beg; while (end > beg && ISSPACE (end[-1])) --end; } size = end - beg; if (flags & AP_PROCESS_ENTITIES) { /* Grow the pool, then copy the text to the pool character by character, processing the encountered entities as we go along. It's safe (and necessary) to grow the pool in advance because processing the entities can only *shorten* the string, it can never lengthen it. */ const char *from = beg; char *to; POOL_GROW (pool, end - beg); to = pool->contents + pool->tail; while (from < end) { if (*from != '&') *to++ = *from++; else { const char *save = from; int remain; if (++from == end) goto lose; remain = end - from; /* Process numeric entities "&#DDD;" and "&#xHH;". */ if (*from == '#') { int numeric = 0, digits = 0; ++from; if (*from == 'x') { ++from; for (; from < end && ISXDIGIT (*from); from++, digits++) numeric = (numeric << 4) + XDIGIT_TO_NUM (*from); } else { for (; from < end && ISDIGIT (*from); from++, digits++) numeric = (numeric * 10) + (*from - '0'); } if (!digits) goto lose; numeric &= 0xff; *to++ = numeric; }#define FROB(x) (remain >= (sizeof (x) - 1) \ && 0 == memcmp (from, x, sizeof (x) - 1) \ && (*(from + sizeof (x) - 1) == ';' \ || remain == sizeof (x) - 1 \ || !ISALNUM (*(from + sizeof (x) - 1)))) else if (FROB ("lt")) *to++ = '<', from += 2; else if (FROB ("gt")) *to++ = '>', from += 2; else if (FROB ("amp")) *to++ = '&', from += 3; else if (FROB ("quot")) *to++ = '\"', from += 4; /* We don't implement the proposed "Added Latin 1" entities (except for nbsp), because it is unnecessary in the context of Wget, and would require hashing to work efficiently. */ else if (FROB ("nbsp")) *to++ = 160, from += 4; else goto lose;#undef FROB /* If the entity was followed by `;', we step over the `;'. Otherwise, it was followed by either a non-alphanumeric or EOB, in which case we do nothing. */ if (from < end && *from == ';') ++from; continue; lose: /* This was not an entity after all. Back out. */ from = save; *to++ = *from++; } } /* Verify that we haven't exceeded the original size. (It shouldn't happen, hence the assert.) */ assert (to - (pool->contents + pool->tail) <= end - beg); /* Make POOL's tail point to the position following the string we've written. */ pool->tail = to - pool->contents; POOL_APPEND_CHR (pool, '\0'); } else { /* Just copy the text to the pool. */ POOL_APPEND (pool, beg, end); POOL_APPEND_CHR (pool, '\0'); } if (flags & AP_DOWNCASE) { char *p = pool->contents + old_tail; for (; *p; p++) *p = TOLOWER (*p); }}/* Originally we used to adhere to rfc 1866 here, and allowed only letters, digits, periods, and hyphens as names (of tags or attributes). However, this broke too many pages which used proprietary or strange attributes, e.g. <img src="a.gif" v:shapes="whatever">. So now we allow any character except: * whitespace * 8-bit and control chars * characters that clearly cannot be part of name: '=', '>', '/'. This only affects attribute and tag names; attribute values allow an even greater variety of characters. */#define NAME_CHAR_P(x) ((x) > 32 && (x) < 127 \ && (x) != '=' && (x) != '>' && (x) != '/')#ifdef STANDALONEstatic int comment_backout_count;#endif/* Advance over an SGML declaration, such as <!DOCTYPE ...>. In strict comments mode, this is used for skipping over comments as well. To recap: any SGML declaration may have comments associated with it, e.g. <!MY-DECL -- isn't this fun? -- foo bar> An HTML comment is merely an empty declaration (<!>) with a comment attached, like this: <!-- some stuff here --> Several comments may be embedded in one comment declaration: <!-- have -- -- fun --> Whitespace is allowed between and after the comments, but not before the first comment. Additionally, this function attempts to handle double quotes in SGML declarations correctly. */static const char *advance_declaration (const char *beg, const char *end){ const char *p = beg; char quote_char = '\0'; /* shut up, gcc! */ char ch; enum { AC_S_DONE, AC_S_BACKOUT, AC_S_BANG, AC_S_DEFAULT, AC_S_DCLNAME, AC_S_DASH1, AC_S_DASH2, AC_S_COMMENT, AC_S_DASH3, AC_S_DASH4, AC_S_QUOTE1, AC_S_IN_QUOTE, AC_S_QUOTE2 } state = AC_S_BANG; if (beg == end) return beg; ch = *p++; /* It looked like a good idea to write this as a state machine, but now I wonder... */ while (state != AC_S_DONE && state != AC_S_BACKOUT) { if (p == end) state = AC_S_BACKOUT; switch (state) { case AC_S_DONE: case AC_S_BACKOUT: break; case AC_S_BANG: if (ch == '!') { ch = *p++; state = AC_S_DEFAULT; } else state = AC_S_BACKOUT; break; case AC_S_DEFAULT: switch (ch) { case '-': state = AC_S_DASH1; break; case ' ': case '\t': case '\r': case '\n': ch = *p++; break; case '>': state = AC_S_DONE; break; case '\'': case '\"': state = AC_S_QUOTE1; break; default: if (NAME_CHAR_P (ch)) state = AC_S_DCLNAME; else state = AC_S_BACKOUT; break; } break; case AC_S_DCLNAME: if (ch == '-') state = AC_S_DASH1; else if (NAME_CHAR_P (ch)) ch = *p++;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -