~ubuntu-branches/ubuntu/feisty/apache2/feisty

« back to all changes in this revision

Viewing changes to modules/mappers/mod_speling.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Barth
  • Date: 2006-12-09 21:05:45 UTC
  • mfrom: (0.6.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20061209210545-h70s0xaqc2v8vqr2
Tags: 2.2.3-3.2
* Non-maintainer upload.
* 043_ajp_connection_reuse: Patch from upstream Bugzilla, fixing a critical
  issue with regard to connection reuse in mod_proxy_ajp.
  Closes: #396265

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Licensed to the Apache Software Foundation (ASF) under one or more
 
2
 * contributor license agreements.  See the NOTICE file distributed with
 
3
 * this work for additional information regarding copyright ownership.
 
4
 * The ASF licenses this file to You under the Apache License, Version 2.0
 
5
 * (the "License"); you may not use this file except in compliance with
 
6
 * the License.  You may obtain a copy of the License at
 
7
 *
 
8
 *     http://www.apache.org/licenses/LICENSE-2.0
 
9
 *
 
10
 * Unless required by applicable law or agreed to in writing, software
 
11
 * distributed under the License is distributed on an "AS IS" BASIS,
 
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
13
 * See the License for the specific language governing permissions and
 
14
 * limitations under the License.
 
15
 */
 
16
 
 
17
#include "apr.h"
 
18
#include "apr_file_io.h"
 
19
#include "apr_strings.h"
 
20
#include "apr_lib.h"
 
21
 
 
22
#define APR_WANT_STRFUNC
 
23
#include "apr_want.h"
 
24
 
 
25
#define WANT_BASENAME_MATCH
 
26
 
 
27
#include "httpd.h"
 
28
#include "http_core.h"
 
29
#include "http_config.h"
 
30
#include "http_request.h"
 
31
#include "http_log.h"
 
32
 
 
33
/* mod_speling.c - by Alexei Kosut <akosut@organic.com> June, 1996
 
34
 *
 
35
 * This module is transparent, and simple. It attempts to correct
 
36
 * misspellings of URLs that users might have entered, namely by checking
 
37
 * capitalizations. If it finds a match, it sends a redirect.
 
38
 *
 
39
 * Sep-1999 Hugo Haas <hugo@w3.org>
 
40
 * o Added a CheckCaseOnly option to check only miscapitalized words.
 
41
 *
 
42
 * 08-Aug-1997 <Martin.Kraemer@Mch.SNI.De>
 
43
 * o Upgraded module interface to apache_1.3a2-dev API (more NULL's in
 
44
 *   speling_module).
 
45
 * o Integrated tcsh's "spelling correction" routine which allows one
 
46
 *   misspelling (character insertion/omission/typo/transposition).
 
47
 *   Rewrote it to ignore case as well. This ought to catch the majority
 
48
 *   of misspelled requests.
 
49
 * o Commented out the second pass where files' suffixes are stripped.
 
50
 *   Given the better hit rate of the first pass, this rather ugly
 
51
 *   (request index.html, receive index.db ?!?!) solution can be
 
52
 *   omitted.
 
53
 * o wrote a "kind of" html page for mod_speling
 
54
 *
 
55
 * Activate it with "CheckSpelling On"
 
56
 */
 
57
 
 
58
module AP_MODULE_DECLARE_DATA speling_module;
 
59
 
 
60
typedef struct {
 
61
    int enabled;
 
62
    int case_only;
 
63
} spconfig;
 
64
 
 
65
/*
 
66
 * Create a configuration specific to this module for a server or directory
 
67
 * location, and fill it with the default settings.
 
68
 *
 
69
 * The API says that in the absence of a merge function, the record for the
 
70
 * closest ancestor is used exclusively.  That's what we want, so we don't
 
71
 * bother to have such a function.
 
72
 */
 
73
 
 
74
static void *mkconfig(apr_pool_t *p)
 
75
{
 
76
    spconfig *cfg = apr_pcalloc(p, sizeof(spconfig));
 
77
 
 
78
    cfg->enabled = 0;
 
79
    cfg->case_only = 0;
 
80
    return cfg;
 
81
}
 
82
 
 
83
/*
 
84
 * Respond to a callback to create configuration record for a server or
 
85
 * vhost environment.
 
86
 */
 
87
static void *create_mconfig_for_server(apr_pool_t *p, server_rec *s)
 
88
{
 
89
    return mkconfig(p);
 
90
}
 
91
 
 
92
/*
 
93
 * Respond to a callback to create a config record for a specific directory.
 
94
 */
 
95
static void *create_mconfig_for_directory(apr_pool_t *p, char *dir)
 
96
{
 
97
    return mkconfig(p);
 
98
}
 
99
 
 
100
/*
 
101
 * Define the directives specific to this module.  This structure is referenced
 
102
 * later by the 'module' structure.
 
103
 */
 
104
static const command_rec speling_cmds[] =
 
105
{
 
106
    AP_INIT_FLAG("CheckSpelling", ap_set_flag_slot,
 
107
                  (void*)APR_OFFSETOF(spconfig, enabled), OR_OPTIONS,
 
108
                 "whether or not to fix miscapitalized/misspelled requests"),
 
109
    AP_INIT_FLAG("CheckCaseOnly", ap_set_flag_slot,
 
110
                  (void*)APR_OFFSETOF(spconfig, case_only), OR_OPTIONS, 
 
111
                 "whether or not to fix only miscapitalized requests"),
 
112
    { NULL }
 
113
};
 
114
 
 
115
typedef enum {
 
116
    SP_IDENTICAL = 0,
 
117
    SP_MISCAPITALIZED = 1,
 
118
    SP_TRANSPOSITION = 2,
 
119
    SP_MISSINGCHAR = 3,
 
120
    SP_EXTRACHAR = 4,
 
121
    SP_SIMPLETYPO = 5,
 
122
    SP_VERYDIFFERENT = 6
 
123
} sp_reason;
 
124
 
 
125
static const char *sp_reason_str[] =
 
126
{
 
127
    "identical",
 
128
    "miscapitalized",
 
129
    "transposed characters",
 
130
    "character missing",
 
131
    "extra character",
 
132
    "mistyped character",
 
133
    "common basename",
 
134
};
 
135
 
 
136
typedef struct {
 
137
    const char *name;
 
138
    sp_reason quality;
 
139
} misspelled_file;
 
140
 
 
141
/*
 
142
 * spdist() is taken from Kernighan & Pike,
 
143
 *  _The_UNIX_Programming_Environment_
 
144
 * and adapted somewhat to correspond better to psychological reality.
 
145
 * (Note the changes to the return values)
 
146
 *
 
147
 * According to Pollock and Zamora, CACM April 1984 (V. 27, No. 4),
 
148
 * page 363, the correct order for this is:
 
149
 * OMISSION = TRANSPOSITION > INSERTION > SUBSTITUTION
 
150
 * thus, it was exactly backwards in the old version. -- PWP
 
151
 *
 
152
 * This routine was taken out of tcsh's spelling correction code
 
153
 * (tcsh-6.07.04) and re-converted to apache data types ("char" type
 
154
 * instead of tcsh's NLS'ed "Char"). Plus it now ignores the case
 
155
 * during comparisons, so is a "approximate strcasecmp()".
 
156
 * NOTE that is still allows only _one_ real "typo",
 
157
 * it does NOT try to correct multiple errors.
 
158
 */
 
159
 
 
160
static sp_reason spdist(const char *s, const char *t)
 
161
{
 
162
    for (; apr_tolower(*s) == apr_tolower(*t); t++, s++) {
 
163
        if (*t == '\0') {
 
164
            return SP_MISCAPITALIZED;   /* exact match (sans case) */
 
165
        }
 
166
    }
 
167
    if (*s) {
 
168
        if (*t) {
 
169
            if (s[1] && t[1] && apr_tolower(*s) == apr_tolower(t[1])
 
170
                && apr_tolower(*t) == apr_tolower(s[1])
 
171
                && strcasecmp(s + 2, t + 2) == 0) {
 
172
                return SP_TRANSPOSITION;        /* transposition */
 
173
            }
 
174
            if (strcasecmp(s + 1, t + 1) == 0) {
 
175
                return SP_SIMPLETYPO;   /* 1 char mismatch */
 
176
            }
 
177
        }
 
178
        if (strcasecmp(s + 1, t) == 0) {
 
179
            return SP_EXTRACHAR;        /* extra character */
 
180
        }
 
181
    }
 
182
    if (*t && strcasecmp(s, t + 1) == 0) {
 
183
        return SP_MISSINGCHAR;  /* missing character */
 
184
    }
 
185
    return SP_VERYDIFFERENT;    /* distance too large to fix. */
 
186
}
 
187
 
 
188
static int sort_by_quality(const void *left, const void *rite)
 
189
{
 
190
    return (int) (((misspelled_file *) left)->quality)
 
191
        - (int) (((misspelled_file *) rite)->quality);
 
192
}
 
193
 
 
194
static int check_speling(request_rec *r)
 
195
{
 
196
    spconfig *cfg;
 
197
    char *good, *bad, *postgood, *url;
 
198
    apr_finfo_t dirent;
 
199
    int filoc, dotloc, urlen, pglen;
 
200
    apr_array_header_t *candidates = NULL;
 
201
    apr_dir_t          *dir;
 
202
 
 
203
    cfg = ap_get_module_config(r->per_dir_config, &speling_module);
 
204
    if (!cfg->enabled) {
 
205
        return DECLINED;
 
206
    }
 
207
 
 
208
    /* We only want to worry about GETs */
 
209
    if (r->method_number != M_GET) {
 
210
        return DECLINED;
 
211
    }
 
212
 
 
213
    /* We've already got a file of some kind or another */
 
214
    if (r->finfo.filetype != 0) {
 
215
        return DECLINED;
 
216
    }
 
217
 
 
218
    /* Not a file request */
 
219
    if (r->proxyreq || !r->filename) {
 
220
        return DECLINED;
 
221
    }
 
222
 
 
223
    /* This is a sub request - don't mess with it */
 
224
    if (r->main) {
 
225
        return DECLINED;
 
226
    }
 
227
 
 
228
    /* we default to reject path info (same as core handler) */
 
229
    if ((r->used_path_info != AP_REQ_ACCEPT_PATH_INFO) &&
 
230
        r->path_info && *r->path_info) {
 
231
        return DECLINED;
 
232
    }
 
233
 
 
234
    /*
 
235
     * The request should end up looking like this:
 
236
     * r->uri: /correct-url/mispelling/more
 
237
     * r->filename: /correct-file/mispelling r->path_info: /more
 
238
     *
 
239
     * So we do this in steps. First break r->filename into two pieces
 
240
     */
 
241
 
 
242
    filoc = ap_rind(r->filename, '/');
 
243
    /*
 
244
     * Don't do anything if the request doesn't contain a slash, or
 
245
     * requests "/"
 
246
     */
 
247
    if (filoc == -1 || strcmp(r->uri, "/") == 0) {
 
248
        return DECLINED;
 
249
    }
 
250
 
 
251
    /* good = /correct-file */
 
252
    good = apr_pstrndup(r->pool, r->filename, filoc);
 
253
    /* bad = mispelling */
 
254
    bad = apr_pstrdup(r->pool, r->filename + filoc + 1);
 
255
    /* postgood = mispelling/more */
 
256
    postgood = apr_pstrcat(r->pool, bad, r->path_info, NULL);
 
257
 
 
258
    urlen = strlen(r->uri);
 
259
    pglen = strlen(postgood);
 
260
 
 
261
    /* Check to see if the URL pieces add up */
 
262
    if (strcmp(postgood, r->uri + (urlen - pglen))) {
 
263
        return DECLINED;
 
264
    }
 
265
 
 
266
    /* url = /correct-url */
 
267
    url = apr_pstrndup(r->pool, r->uri, (urlen - pglen));
 
268
 
 
269
    /* Now open the directory and do ourselves a check... */
 
270
    if (apr_dir_open(&dir, good, r->pool) != APR_SUCCESS) {
 
271
        /* Oops, not a directory... */
 
272
        return DECLINED;
 
273
    }
 
274
 
 
275
    candidates = apr_array_make(r->pool, 2, sizeof(misspelled_file));
 
276
 
 
277
    dotloc = ap_ind(bad, '.');
 
278
    if (dotloc == -1) {
 
279
        dotloc = strlen(bad);
 
280
    }
 
281
 
 
282
    while (apr_dir_read(&dirent, APR_FINFO_DIRENT, dir) == APR_SUCCESS) {
 
283
        sp_reason q;
 
284
 
 
285
        /*
 
286
         * If we end up with a "fixed" URL which is identical to the
 
287
         * requested one, we must have found a broken symlink or some such.
 
288
         * Do _not_ try to redirect this, it causes a loop!
 
289
         */
 
290
        if (strcmp(bad, dirent.name) == 0) {
 
291
            apr_dir_close(dir);
 
292
            return OK;
 
293
        }
 
294
 
 
295
        /*
 
296
         * miscapitalization errors are checked first (like, e.g., lower case
 
297
         * file, upper case request)
 
298
         */
 
299
        else if (strcasecmp(bad, dirent.name) == 0) {
 
300
            misspelled_file *sp_new;
 
301
 
 
302
            sp_new = (misspelled_file *) apr_array_push(candidates);
 
303
            sp_new->name = apr_pstrdup(r->pool, dirent.name);
 
304
            sp_new->quality = SP_MISCAPITALIZED;
 
305
        }
 
306
 
 
307
        /*
 
308
         * simple typing errors are checked next (like, e.g.,
 
309
         * missing/extra/transposed char)
 
310
         */
 
311
        else if ((cfg->case_only == 0)
 
312
                 && ((q = spdist(bad, dirent.name)) != SP_VERYDIFFERENT)) {
 
313
            misspelled_file *sp_new;
 
314
 
 
315
            sp_new = (misspelled_file *) apr_array_push(candidates);
 
316
            sp_new->name = apr_pstrdup(r->pool, dirent.name);
 
317
            sp_new->quality = q;
 
318
        }
 
319
 
 
320
        /*
 
321
         * The spdist() should have found the majority of the misspelled
 
322
         * requests.  It is of questionable use to continue looking for
 
323
         * files with the same base name, but potentially of totally wrong
 
324
         * type (index.html <-> index.db).
 
325
         * I would propose to not set the WANT_BASENAME_MATCH define.
 
326
         *      08-Aug-1997 <Martin.Kraemer@Mch.SNI.De>
 
327
         *
 
328
         * However, Alexei replied giving some reasons to add it anyway:
 
329
         * > Oh, by the way, I remembered why having the
 
330
         * > extension-stripping-and-matching stuff is a good idea:
 
331
         * >
 
332
         * > If you're using MultiViews, and have a file named foobar.html,
 
333
         * > which you refer to as "foobar", and someone tried to access
 
334
         * > "Foobar", mod_speling won't find it, because it won't find
 
335
         * > anything matching that spelling. With the extension-munging,
 
336
         * > it would locate "foobar.html". Not perfect, but I ran into
 
337
         * > that problem when I first wrote the module.
 
338
         */
 
339
        else {
 
340
#ifdef WANT_BASENAME_MATCH
 
341
            /*
 
342
             * Okay... we didn't find anything. Now we take out the hard-core
 
343
             * power tools. There are several cases here. Someone might have
 
344
             * entered a wrong extension (.htm instead of .html or vice
 
345
             * versa) or the document could be negotiated. At any rate, now
 
346
             * we just compare stuff before the first dot. If it matches, we
 
347
             * figure we got us a match. This can result in wrong things if
 
348
             * there are files of different content types but the same prefix
 
349
             * (e.g. foo.gif and foo.html) This code will pick the first one
 
350
             * it finds. Better than a Not Found, though.
 
351
             */
 
352
            int entloc = ap_ind(dirent.name, '.');
 
353
            if (entloc == -1) {
 
354
                entloc = strlen(dirent.name);
 
355
            }
 
356
 
 
357
            if ((dotloc == entloc)
 
358
                && !strncasecmp(bad, dirent.name, dotloc)) {
 
359
                misspelled_file *sp_new;
 
360
 
 
361
                sp_new = (misspelled_file *) apr_array_push(candidates);
 
362
                sp_new->name = apr_pstrdup(r->pool, dirent.name);
 
363
                sp_new->quality = SP_VERYDIFFERENT;
 
364
            }
 
365
#endif
 
366
        }
 
367
    }
 
368
    apr_dir_close(dir);
 
369
 
 
370
    if (candidates->nelts != 0) {
 
371
        /* Wow... we found us a mispelling. Construct a fixed url */
 
372
        char *nuri;
 
373
        const char *ref;
 
374
        misspelled_file *variant = (misspelled_file *) candidates->elts;
 
375
        int i;
 
376
 
 
377
        ref = apr_table_get(r->headers_in, "Referer");
 
378
 
 
379
        qsort((void *) candidates->elts, candidates->nelts,
 
380
              sizeof(misspelled_file), sort_by_quality);
 
381
 
 
382
        /*
 
383
         * Conditions for immediate redirection:
 
384
         *     a) the first candidate was not found by stripping the suffix
 
385
         * AND b) there exists only one candidate OR the best match is not
 
386
         *        ambiguous
 
387
         * then return a redirection right away.
 
388
         */
 
389
        if (variant[0].quality != SP_VERYDIFFERENT
 
390
            && (candidates->nelts == 1
 
391
                || variant[0].quality != variant[1].quality)) {
 
392
 
 
393
            nuri = ap_escape_uri(r->pool, apr_pstrcat(r->pool, url,
 
394
                                                     variant[0].name,
 
395
                                                     r->path_info, NULL));
 
396
            if (r->parsed_uri.query)
 
397
                nuri = apr_pstrcat(r->pool, nuri, "?", r->parsed_uri.query, NULL);
 
398
 
 
399
            apr_table_setn(r->headers_out, "Location",
 
400
                          ap_construct_url(r->pool, nuri, r));
 
401
 
 
402
            ap_log_rerror(APLOG_MARK, APLOG_INFO, APR_SUCCESS,
 
403
                          r,
 
404
                          ref ? "Fixed spelling: %s to %s from %s"
 
405
                              : "Fixed spelling: %s to %s",
 
406
                          r->uri, nuri, ref);
 
407
 
 
408
            return HTTP_MOVED_PERMANENTLY;
 
409
        }
 
410
        /*
 
411
         * Otherwise, a "[300] Multiple Choices" list with the variants is
 
412
         * returned.
 
413
         */
 
414
        else {
 
415
            apr_pool_t *p;
 
416
            apr_table_t *notes;
 
417
            apr_pool_t *sub_pool;
 
418
            apr_array_header_t *t;
 
419
            apr_array_header_t *v;
 
420
 
 
421
 
 
422
            if (r->main == NULL) {
 
423
                p = r->pool;
 
424
                notes = r->notes;
 
425
            }
 
426
            else {
 
427
                p = r->main->pool;
 
428
                notes = r->main->notes;
 
429
            }
 
430
 
 
431
            if (apr_pool_create(&sub_pool, p) != APR_SUCCESS)
 
432
                return DECLINED;
 
433
 
 
434
            t = apr_array_make(sub_pool, candidates->nelts * 8 + 8,
 
435
                              sizeof(char *));
 
436
            v = apr_array_make(sub_pool, candidates->nelts * 5,
 
437
                              sizeof(char *));
 
438
 
 
439
            /* Generate the response text. */
 
440
 
 
441
            *(const char **)apr_array_push(t) =
 
442
                          "The document name you requested (<code>";
 
443
            *(const char **)apr_array_push(t) = ap_escape_html(sub_pool, r->uri);
 
444
            *(const char **)apr_array_push(t) =
 
445
                           "</code>) could not be found on this server.\n"
 
446
                           "However, we found documents with names similar "
 
447
                           "to the one you requested.<p>"
 
448
                           "Available documents:\n<ul>\n";
 
449
 
 
450
            for (i = 0; i < candidates->nelts; ++i) {
 
451
                char *vuri;
 
452
                const char *reason;
 
453
 
 
454
                reason = sp_reason_str[(int) (variant[i].quality)];
 
455
                /* The format isn't very neat... */
 
456
                vuri = apr_pstrcat(sub_pool, url, variant[i].name, r->path_info,
 
457
                                  (r->parsed_uri.query != NULL) ? "?" : "",
 
458
                                  (r->parsed_uri.query != NULL)
 
459
                                      ? r->parsed_uri.query : "",
 
460
                                  NULL);
 
461
                *(const char **)apr_array_push(v) = "\"";
 
462
                *(const char **)apr_array_push(v) = ap_escape_uri(sub_pool, vuri);
 
463
                *(const char **)apr_array_push(v) = "\";\"";
 
464
                *(const char **)apr_array_push(v) = reason;
 
465
                *(const char **)apr_array_push(v) = "\"";
 
466
 
 
467
                *(const char **)apr_array_push(t) = "<li><a href=\"";
 
468
                *(const char **)apr_array_push(t) = ap_escape_uri(sub_pool, vuri);
 
469
                *(const char **)apr_array_push(t) = "\">";
 
470
                *(const char **)apr_array_push(t) = ap_escape_html(sub_pool, vuri);
 
471
                *(const char **)apr_array_push(t) = "</a> (";
 
472
                *(const char **)apr_array_push(t) = reason;
 
473
                *(const char **)apr_array_push(t) = ")\n";
 
474
 
 
475
                /*
 
476
                 * when we have printed the "close matches" and there are
 
477
                 * more "distant matches" (matched by stripping the suffix),
 
478
                 * then we insert an additional separator text to suggest
 
479
                 * that the user LOOK CLOSELY whether these are really the
 
480
                 * files she wanted.
 
481
                 */
 
482
                if (i > 0 && i < candidates->nelts - 1
 
483
                    && variant[i].quality != SP_VERYDIFFERENT
 
484
                    && variant[i + 1].quality == SP_VERYDIFFERENT) {
 
485
                    *(const char **)apr_array_push(t) =
 
486
                                   "</ul>\nFurthermore, the following related "
 
487
                                   "documents were found:\n<ul>\n";
 
488
                }
 
489
            }
 
490
            *(const char **)apr_array_push(t) = "</ul>\n";
 
491
 
 
492
            /* If we know there was a referring page, add a note: */
 
493
            if (ref != NULL) {
 
494
                *(const char **)apr_array_push(t) =
 
495
                               "Please consider informing the owner of the "
 
496
                               "<a href=\"";
 
497
                *(const char **)apr_array_push(t) = ap_escape_uri(sub_pool, ref);
 
498
                *(const char **)apr_array_push(t) = "\">referring page</a> "
 
499
                               "about the broken link.\n";
 
500
            }
 
501
 
 
502
 
 
503
            /* Pass our apr_table_t to http_protocol.c (see mod_negotiation): */
 
504
            apr_table_setn(notes, "variant-list", apr_array_pstrcat(p, t, 0));
 
505
 
 
506
            apr_table_mergen(r->subprocess_env, "VARIANTS",
 
507
                            apr_array_pstrcat(p, v, ','));
 
508
 
 
509
            apr_pool_destroy(sub_pool);
 
510
 
 
511
            ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
 
512
                         ref ? "Spelling fix: %s: %d candidates from %s"
 
513
                             : "Spelling fix: %s: %d candidates",
 
514
                         r->uri, candidates->nelts, ref);
 
515
 
 
516
            return HTTP_MULTIPLE_CHOICES;
 
517
        }
 
518
    }
 
519
 
 
520
    return OK;
 
521
}
 
522
 
 
523
static void register_hooks(apr_pool_t *p)
 
524
{
 
525
    ap_hook_fixups(check_speling,NULL,NULL,APR_HOOK_LAST);
 
526
}
 
527
 
 
528
module AP_MODULE_DECLARE_DATA speling_module =
 
529
{
 
530
    STANDARD20_MODULE_STUFF,
 
531
    create_mconfig_for_directory,  /* create per-dir config */
 
532
    NULL,                          /* merge per-dir config */
 
533
    create_mconfig_for_server,     /* server config */
 
534
    NULL,                          /* merge server config */
 
535
    speling_cmds,                  /* command apr_table_t */
 
536
    register_hooks                 /* register hooks */
 
537
};