~ubuntu-branches/ubuntu/oneiric/libapache-mod-jk/oneiric

« back to all changes in this revision

Viewing changes to jk/native/isapi/jk_isapi_plugin.c

  • Committer: Bazaar Package Importer
  • Author(s): Steve Kowalik
  • Date: 2006-08-05 16:30:53 UTC
  • mfrom: (1.1.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20060805163053-myf66gm6j1a21ps6
Tags: 1:1.2.18-1ubuntu1
Merge from Debian unstable.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 *  Copyright 1999-2004 The Apache Software Foundation
3
 
 *
4
 
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 
 *  you may not use this file except in compliance with the License.
6
 
 *  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
 
 * Description: ISAPI plugin for Tomcat                                    *
19
 
 * Author:      Andy Armstrong <andy@tagish.com>                           *
20
 
 * Version:     $Revision: 1.8 $                                           *
21
 
 ***************************************************************************/
22
 
 
23
 
/* Based on the the server redirector which was, in turn, based on the IIS 
24
 
 * redirector by Gal Shachor <shachor@il.ibm.com>
25
 
 */
26
 
 
27
 
#include "config.h"
28
 
#include "inifile.h"
29
 
#include "poolbuf.h"
30
 
 
31
 
/* ISAPI stuff */
32
 
#include <httpext.h>
33
 
#include <httpfilt.h>
34
 
#include <wininet.h>
35
 
 
36
 
/* JK stuff */
37
 
#include "jk_global.h"
38
 
#include "jk_util.h"
39
 
#include "jk_map.h"
40
 
#include "jk_pool.h"
41
 
#include "jk_service.h"
42
 
#include "jk_worker.h"
43
 
#include "jk_uri_worker_map.h"
44
 
 
45
 
#include <stdarg.h>
46
 
#define NOERROR 0
47
 
 
48
 
#include <stdlib.h>
49
 
#include <stdio.h>
50
 
#include <string.h>
51
 
 
52
 
#if !defined(DLLEXPORT)
53
 
#ifdef WIN32
54
 
#define DLLEXPORT __declspec(dllexport)
55
 
#else
56
 
#define DLLEXPORT
57
 
#endif
58
 
#endif
59
 
 
60
 
#define VERSION                         "2.0"
61
 
#define VERSION_STRING          "Jakarta/ISAPI/" VERSION
62
 
 
63
 
/* What we call ourselves */
64
 
#define FILTERDESC                      "Apache Tomcat Interceptor (" VERSION_STRING ")"
65
 
#define SERVERDFLT                      "Microsoft IIS"
66
 
 
67
 
/* Registry location of configuration data */
68
 
#define REGISTRY_LOCATION       "Software\\Apache Software Foundation\\Jakarta Isapi Redirector\\2.0"
69
 
 
70
 
/* Name of INI file relative to whatever the 'current' directory is when the filter is
71
 
 * loaded. Certainly on Linux this is the the server data directory -- it seems likely that
72
 
 * it's the same on other platforms
73
 
 */
74
 
#define ININAME                         "libtomcat.ini"
75
 
 
76
 
/* Names of registry keys/ini items that contain commands to start, stop Tomcat */
77
 
#define TOMCAT_START            "tomcat_start"
78
 
#define TOMCAT_STOP                     "tomcat_stop"
79
 
#define TOMCAT_STARTSTOP_TO     30000   /* 30 seconds */
80
 
 
81
 
static int initDone = JK_FALSE;
82
 
static jk_uri_worker_map_t *uw_map = NULL;
83
 
static jk_logger_t *logger = NULL;
84
 
 
85
 
static int logLevel = JK_LOG_EMERG_LEVEL;
86
 
static jk_pool_t cfgPool;
87
 
 
88
 
static const char *logFile;
89
 
static const char *workerFile;
90
 
static const char *workerMountFile;
91
 
static const char *tomcatStart;
92
 
static const char *tomcatStop;
93
 
 
94
 
#if defined(JK_VERSION) && JK_VERSION >= MAKEVERSION(1, 2, 0, 1)
95
 
static jk_worker_env_t worker_env;
96
 
#endif
97
 
 
98
 
static char *crlf = "\r\n";
99
 
 
100
 
typedef enum
101
 
{ HDR, BODY } rq_state;
102
 
 
103
 
typedef struct private_ws
104
 
{
105
 
    jk_pool_t p;
106
 
 
107
 
    /* Passed in by server, used to access various methods and data.
108
 
     */
109
 
    LPEXTENSION_CONTROL_BLOCK lpEcb;
110
 
 
111
 
    /* True iff the response headers have been sent
112
 
     */
113
 
    int responseStarted;
114
 
 
115
 
    rq_state state;
116
 
 
117
 
    poolbuf hdr;
118
 
    poolbuf body;
119
 
 
120
 
} private_ws_t;
121
 
 
122
 
/* These three functions are called back (indirectly) by
123
 
 * Tomcat during request processing. StartResponse() sends
124
 
 * the headers associated with the response.
125
 
 */
126
 
static int JK_METHOD StartResponse(jk_ws_service_t *s, int status,
127
 
                                   const char *reason,
128
 
                                   const char *const *hdrNames,
129
 
                                   const char *const *hdrValues,
130
 
                                   unsigned hdrCount);
131
 
/* Read() is called by Tomcat to read from the request body (if any).
132
 
 */
133
 
static int JK_METHOD Read(jk_ws_service_t *s, void *b, unsigned l,
134
 
                          unsigned *a);
135
 
/* Write() is called by Tomcat to send data back to the client.
136
 
 */
137
 
static int JK_METHOD Write(jk_ws_service_t *s, const void *b, unsigned l);
138
 
 
139
 
static int ReadInitData(void);
140
 
 
141
 
#ifndef USE_INIFILE
142
 
static const char *GetRegString(HKEY hkey, const char *key);
143
 
#endif
144
 
 
145
 
//static unsigned int ParsedRequest(PHTTP_FILTER_CONTEXT *context, FilterParsedRequest *reqData);
146
 
 
147
 
/* Case insentive memcmp() clone
148
 
 */
149
 
#ifdef HAVE_MEMICMP
150
 
#define NoCaseMemCmp(ci, cj, l) _memicmp((void *) (ci), (void *) (cj), (l))
151
 
#else
152
 
static int NoCaseMemCmp(const char *ci, const char *cj, int len)
153
 
{
154
 
    if (0 == memcmp(ci, cj, len))
155
 
        return 0;
156
 
    while (len > 0) {
157
 
        int cmp = tolower(*ci) - tolower(*cj);
158
 
        if (cmp != 0)
159
 
            return cmp;
160
 
        ci++;
161
 
        cj++;
162
 
        len--;
163
 
    }
164
 
    return 0;
165
 
}
166
 
#endif
167
 
 
168
 
/* Case insentive strcmp() clone
169
 
 */
170
 
#ifdef HAVE_STRICMP
171
 
#define NoCaseStrCmp(si, sj) _stricmp((void *) (si), (void *) (sj))
172
 
#else
173
 
static int NoCaseStrCmp(const char *si, const char *sj)
174
 
{
175
 
    if (0 == strcmp(si, sj))
176
 
        return 0;
177
 
 
178
 
    while (*si && tolower(*si) == tolower(*sj))
179
 
        si++, sj++;
180
 
 
181
 
    return tolower(*si) - tolower(*sj);
182
 
}
183
 
#endif
184
 
 
185
 
/* Case insensitive substring search.
186
 
 * str          string to search
187
 
 * slen         length of string to search
188
 
 * ptn          pattern to search for
189
 
 * plen         length of pattern
190
 
 * returns      1 if there's a match otherwise 0
191
 
 */
192
 
static int FindPathElem(const char *str, int slen, const char *ptn, int plen)
193
 
{
194
 
    const char *sp = str;
195
 
 
196
 
    while (slen >= plen) {
197
 
        /* We're looking for a match for the specified string bounded by
198
 
         * the start of the string, \ or / at the left and the end of the
199
 
         * string, \ or / at the right. We look for \ as well as / on the
200
 
         * suspicion that a Windows hosted server might accept URIs
201
 
         * containing \.
202
 
         */
203
 
        if (NoCaseMemCmp(sp, ptn, plen) == 0 &&
204
 
            (sp == str || *sp == '\\' || *sp == '/') &&
205
 
            (*sp == '\0' || *sp == '\\' || *sp == '/'))
206
 
            return 1;
207
 
        slen--;
208
 
        sp++;
209
 
    }
210
 
    return 0;
211
 
}
212
 
 
213
 
static void LogMessage(char *msg, unsigned short code, ...)
214
 
{
215
 
    va_list ap;
216
 
 
217
 
    if (code != NOERROR)
218
 
        printf("Error %d: ", code);
219
 
 
220
 
    va_start(ap, code);
221
 
    vprintf(msg, ap);
222
 
    va_end(ap);
223
 
    printf("\n");
224
 
}
225
 
 
226
 
/* Get the value of a server (CGI) variable as a string
227
 
 */
228
 
static int GetVariable(private_ws_t * ws, char *hdrName,
229
 
                       char *buf, DWORD bufsz, char **dest, const char *dflt)
230
 
{
231
 
    LPEXTENSION_CONTROL_BLOCK lpEcb = ws->lpEcb;
232
 
 
233
 
    if (lpEcb->
234
 
        GetServerVariable(lpEcb->ConnID, hdrName, buf, (LPDWORD) & bufsz)) {
235
 
        if (bufsz > 0)
236
 
            buf[bufsz - 1] = '\0';
237
 
        *dest = jk_pool_strdup(&ws->p, buf);
238
 
        return JK_TRUE;
239
 
    }
240
 
 
241
 
    *dest = jk_pool_strdup(&ws->p, dflt);
242
 
    return JK_FALSE;
243
 
}
244
 
 
245
 
/* Get the value of a server (CGI) variable as an integer
246
 
 */
247
 
static int GetVariableInt(private_ws_t * ws, char *hdrName,
248
 
                          char *buf, DWORD bufsz, int *dest, int dflt)
249
 
{
250
 
    LPEXTENSION_CONTROL_BLOCK lpEcb = ws->lpEcb;
251
 
 
252
 
    if (lpEcb->
253
 
        GetServerVariable(lpEcb->ConnID, hdrName, buf, (LPDWORD) & bufsz)) {
254
 
        if (bufsz > 0)
255
 
            buf[bufsz - 1] = '\0';
256
 
        *dest = atoi(buf);
257
 
        return JK_TRUE;
258
 
    }
259
 
 
260
 
    *dest = dflt;
261
 
    return JK_FALSE;
262
 
}
263
 
 
264
 
/* Get the value of a server (CGI) variable as a boolean switch
265
 
 */
266
 
static int GetVariableBool(private_ws_t * ws, char *hdrName,
267
 
                           char *buf, DWORD bufsz, int *dest, int dflt)
268
 
{
269
 
    LPEXTENSION_CONTROL_BLOCK lpEcb = ws->lpEcb;
270
 
 
271
 
    if (lpEcb->
272
 
        GetServerVariable(lpEcb->ConnID, hdrName, buf, (LPDWORD) & bufsz)) {
273
 
        if (bufsz > 0)
274
 
            buf[bufsz - 1] = '\0';
275
 
        if (isdigit(buf[0]))
276
 
            *dest = atoi(buf) != 0;
277
 
        else if (NoCaseStrCmp(buf, "yes") == 0
278
 
                 || NoCaseStrCmp(buf, "on") == 0)
279
 
            *dest = 1;
280
 
        else
281
 
            *dest = 0;
282
 
        return JK_TRUE;
283
 
    }
284
 
 
285
 
    *dest = dflt;
286
 
    return JK_FALSE;
287
 
}
288
 
 
289
 
/* A couple of utility macros to supply standard arguments to GetVariable() and
290
 
 * GetVariableInt().
291
 
 */
292
 
#define GETVARIABLE(name, dest, dflt)           GetVariable(ws, (name), workBuf, sizeof(workBuf), (dest), (dflt))
293
 
#define GETVARIABLEINT(name, dest, dflt)        GetVariableInt(ws, (name), workBuf, sizeof(workBuf), (dest), (dflt))
294
 
#define GETVARIABLEBOOL(name, dest, dflt)       GetVariableBool(ws, (name), workBuf, sizeof(workBuf), (dest), (dflt))
295
 
 
296
 
/* Return 1 iff the supplied string contains "web-inf" (in any case
297
 
 * variation. We don't allow URIs containing web-inf, although
298
 
 * FindPathElem() actually looks for the string bounded by path punctuation
299
 
 * or the ends of the string, so web-inf must appear as a single element
300
 
 * of the supplied URI
301
 
 */
302
 
static int BadURI(const char *uri)
303
 
{
304
 
    static char *wi = "web-inf";
305
 
    return FindPathElem(uri, strlen(uri), wi, strlen(wi));
306
 
}
307
 
 
308
 
/* Replacement for strcat() that updates a buffer pointer. It's
309
 
 * probably marginal, but this should be more efficient that strcat()
310
 
 * in cases where the string being concatenated to gets long because
311
 
 * strcat() has to count from start of the string each time.
312
 
 */
313
 
static void Append(char **buf, const char *str)
314
 
{
315
 
    int l = strlen(str);
316
 
    memcpy(*buf, str, l);
317
 
    (*buf)[l] = '\0';
318
 
    *buf += l;
319
 
}
320
 
 
321
 
/* Start the response by sending any headers. Invoked by Tomcat. I don't
322
 
 * particularly like the fact that this always allocates memory, but
323
 
 * perhaps jk_pool_alloc() is efficient.
324
 
 */
325
 
static int JK_METHOD StartResponse(jk_ws_service_t *s, int status,
326
 
                                   const char *reason,
327
 
                                   const char *const *hdrNames,
328
 
                                   const char *const *hdrValues,
329
 
                                   unsigned hdrCount)
330
 
{
331
 
    DEBUG(("StartResponse()\n"));
332
 
    jk_log(logger, JK_LOG_DEBUG, "Into jk_ws_service_t::StartResponse\n");
333
 
 
334
 
    if (status < 100 || status > 1000) {
335
 
        jk_log(logger, JK_LOG_ERROR,
336
 
               "jk_ws_service_t::StartResponse, invalid status %d\n", status);
337
 
        return JK_FALSE;
338
 
    }
339
 
 
340
 
    if (s && s->ws_private) {
341
 
        private_ws_t *p = s->ws_private;
342
 
 
343
 
        if (!p->responseStarted) {
344
 
            char *statBuf;
345
 
            char *hdrBuf;
346
 
            size_t statLen;
347
 
 
348
 
            p->responseStarted = JK_TRUE;
349
 
 
350
 
            if (NULL == reason)
351
 
                reason = "";
352
 
 
353
 
            /* TODO: coallesce the to jk_pool_alloc() calls into a single
354
 
             * buffer alloc
355
 
             */
356
 
            statLen = 4 + strlen(reason);
357
 
            statBuf = jk_pool_alloc(&p->p, statLen + 1);
358
 
 
359
 
            /* slightly quicker than sprintf() we hope */
360
 
            statBuf[0] = (status / 100) % 10 + '0';
361
 
            statBuf[1] = (status / 10) % 10 + '0';
362
 
            statBuf[2] = (status / 1) % 10 + '0';
363
 
            statBuf[3] = ' ';
364
 
            strcpy(statBuf + 4, reason);
365
 
 
366
 
            /* Build a single string containing all the headers
367
 
             * because that's what the server needs.
368
 
             */
369
 
            if (hdrCount > 0) {
370
 
                unsigned i;
371
 
                unsigned hdrLen;
372
 
                char *bufp;
373
 
 
374
 
                for (i = 0, hdrLen = 3; i < hdrCount; i++)
375
 
                    hdrLen += strlen(hdrNames[i]) + strlen(hdrValues[i]) + 4;
376
 
 
377
 
                hdrBuf = jk_pool_alloc(&p->p, hdrLen);
378
 
                bufp = hdrBuf;
379
 
 
380
 
                for (i = 0; i < hdrCount; i++) {
381
 
                    Append(&bufp, hdrNames[i]);
382
 
                    Append(&bufp, ": ");
383
 
                    Append(&bufp, hdrValues[i]);
384
 
                    Append(&bufp, crlf);
385
 
                }
386
 
 
387
 
                Append(&bufp, crlf);
388
 
            }
389
 
            else {
390
 
                hdrBuf = crlf;
391
 
            }
392
 
 
393
 
            DEBUG(("%d %s\n%s", status, reason, hdrBuf));
394
 
 
395
 
            /* TODO: check API docs for this */
396
 
            if (!p->lpEcb->ServerSupportFunction(p->lpEcb->ConnID,
397
 
                                                 HSE_REQ_SEND_RESPONSE_HEADER,
398
 
                                                 statBuf, (LPDWORD) & statLen,
399
 
                                                 (LPDWORD) hdrBuf)) {
400
 
                jk_log(logger, JK_LOG_ERROR,
401
 
                       "jk_ws_service_t::start_response, ServerSupportFunction failed\n");
402
 
                return JK_FALSE;
403
 
            }
404
 
 
405
 
        }
406
 
        return JK_TRUE;
407
 
    }
408
 
 
409
 
    jk_log(logger, JK_LOG_ERROR,
410
 
           "jk_ws_service_t::StartResponse, NULL parameters\n");
411
 
 
412
 
    return JK_FALSE;
413
 
}
414
 
 
415
 
static int JK_METHOD Read(jk_ws_service_t *s, void *bytes, unsigned len,
416
 
                          unsigned *countp)
417
 
{
418
 
#if 0
419
 
    DEBUG(("Read(%p, %p, %u, %p)\n", s, bytes, len, countp));
420
 
    jk_log(logger, JK_LOG_DEBUG, "Into jk_ws_service_t::Read\n");
421
 
 
422
 
    if (s && s->ws_private && bytes && countp) {
423
 
        private_ws_t *p = s->ws_private;
424
 
 
425
 
        /* Copy data from the server's buffer. Although it seems slightly
426
 
         * improbably we're believing that the server always buffers the
427
 
         * entire request in memory. Not properly tested yet.
428
 
         */
429
 
        if (len > p->reqSize)
430
 
            len = p->reqSize;
431
 
        memcpy(bytes, p->reqBuffer, len);
432
 
        p->reqBuffer += len;
433
 
        p->reqSize -= len;
434
 
        *countp = len;
435
 
        return JK_TRUE;
436
 
    }
437
 
 
438
 
    jk_log(logger, JK_LOG_ERROR, "jk_ws_service_t::Read, NULL parameters\n");
439
 
 
440
 
#endif
441
 
    return JK_FALSE;
442
 
}
443
 
 
444
 
static int JK_METHOD Write(jk_ws_service_t *s, const void *bytes,
445
 
                           unsigned len)
446
 
{
447
 
    DEBUG(("Write(%p, %p, %u)\n", s, bytes, len));
448
 
    jk_log(logger, JK_LOG_DEBUG, "Into jk_ws_service_t::Write\n");
449
 
 
450
 
    if (s && s->ws_private && bytes) {
451
 
        private_ws_t *p = s->ws_private;
452
 
        DWORD dwLen = len;
453
 
 
454
 
        /* Make sure the response has really started. I'm almost certain
455
 
         * this isn't necessary, but it was in the ISAPI code, so it's in
456
 
         * here too.
457
 
         */
458
 
        if (!p->responseStarted)
459
 
            StartResponse(s, 200, NULL, NULL, NULL, 0);
460
 
 
461
 
        DEBUG(("Writing %d bytes of content\n", len));
462
 
 
463
 
        /* Send the data */
464
 
        if (len > 0) {
465
 
            if (!p->lpEcb->
466
 
                WriteClient(p->lpEcb->ConnID, (LPVOID) bytes, &dwLen, 0)) {
467
 
                jk_log(logger, JK_LOG_ERROR,
468
 
                       "jk_ws_service_t::Write, WriteClient failed\n");
469
 
                return JK_FALSE;
470
 
            }
471
 
        }
472
 
 
473
 
        return JK_TRUE;
474
 
    }
475
 
 
476
 
    jk_log(logger, JK_LOG_ERROR, "jk_ws_service_t::Write, NULL parameters\n");
477
 
 
478
 
    return JK_FALSE;
479
 
}
480
 
 
481
 
static int RunProg(const char *cmd)
482
 
{
483
 
#ifdef WIN32
484
 
    STARTUPINFO si;
485
 
    PROCESS_INFORMATION pi;
486
 
 
487
 
    ZeroMemory(&si, sizeof(si));
488
 
    si.cb = sizeof(si);         // Start the child process.
489
 
    si.dwFlags = STARTF_USESHOWWINDOW;
490
 
    si.wShowWindow = SW_SHOWMAXIMIZED;
491
 
 
492
 
    if (!CreateProcess
493
 
        (NULL, (char *)cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
494
 
        DWORD err = GetLastError();
495
 
        LogMessage("Command \"%s\" (error %u)", NOERROR, cmd, err);
496
 
        return FALSE;
497
 
    }
498
 
 
499
 
    if (WAIT_OBJECT_0 ==
500
 
        WaitForSingleObject(pi.hProcess, TOMCAT_STARTSTOP_TO))
501
 
        return TRUE;
502
 
 
503
 
    LogMessage("Command \"%s\" didn't complete in time", NOERROR, cmd);
504
 
    return FALSE;
505
 
 
506
 
#else
507
 
    int err = system(cmd);
508
 
    if (0 == err)
509
 
        return 1;
510
 
    LogMessage("Command \"%s\" failed (error %d)", NOERROR, cmd, err);
511
 
    return 0;
512
 
#endif
513
 
}
514
 
 
515
 
/* Called when the filter is unloaded. Free various resources and
516
 
 * display a banner.
517
 
 */
518
 
BOOL WINAPI TerminateFilter(DWORD dwFlags)
519
 
{
520
 
    if (initDone) {
521
 
        uri_worker_map_free(&uw_map, logger);
522
 
        wc_close(logger);
523
 
        if (logger)
524
 
            jk_close_file_logger(&logger);
525
 
 
526
 
        initDone = JK_FALSE;
527
 
    }
528
 
 
529
 
    if (NULL != tomcatStop && '\0' != *tomcatStop) {
530
 
        LogMessage("Attempting to stop Tomcat: %s", NOERROR, tomcatStop);
531
 
        RunProg(tomcatStop);
532
 
    }
533
 
 
534
 
    LogMessage(FILTERDESC " unloaded", NOERROR);
535
 
 
536
 
    jk_close_pool(&cfgPool);
537
 
 
538
 
    return TRUE;
539
 
}
540
 
 
541
 
/* Called when the server loads the filter. Reads a load of config data from
542
 
 * the registry and elsewhere and displays a banner.
543
 
 */
544
 
BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
545
 
{
546
 
    jk_open_pool(&cfgPool, NULL, 0);    /* empty pool for config data */
547
 
 
548
 
    if (!ReadInitData())
549
 
        goto initFailed;
550
 
 
551
 
    if (!jk_open_file_logger(&logger, logFile, logLevel))
552
 
        logger = NULL;
553
 
 
554
 
    if (NULL != tomcatStart && '\0' != *tomcatStart) {
555
 
        LogMessage("Attempting to start Tomcat: %s", NOERROR, tomcatStart);
556
 
        RunProg(tomcatStart);
557
 
    }
558
 
 
559
 
    pVer->dwFilterVersion = pVer->dwServerFilterVersion;
560
 
 
561
 
    //if (pVer->dwFilterVersion > HTTP_FILTER_REVISION)
562
 
    //    pVer->dwFilterVersion = HTTP_FILTER_REVISION;
563
 
 
564
 
    /* Come back and check these... */
565
 
    pVer->dwFlags = SF_NOTIFY_ORDER_HIGH |
566
 
        SF_NOTIFY_SECURE_PORT |
567
 
        SF_NOTIFY_NONSECURE_PORT | SF_NOTIFY_PREPROC_HEADERS;
568
 
 
569
 
    strcpy(pVer->lpszFilterDesc, FILTERDESC);
570
 
 
571
 
    /* Banner */
572
 
    LogMessage("%s loaded", NOERROR, pVer->lpszFilterDesc);
573
 
 
574
 
    return TRUE;
575
 
 
576
 
  initFailed:
577
 
    LogMessage("Error loading %s", NOERROR, FILTERDESC);
578
 
 
579
 
    return FALSE;
580
 
}
581
 
 
582
 
/* Read parameters from the registry
583
 
 */
584
 
static int ReadInitData(void)
585
 
{
586
 
    int ok = JK_TRUE;
587
 
    const char *v;
588
 
 
589
 
#ifdef USE_INIFILE
590
 
// Using an INIFILE
591
 
 
592
 
#define GETV(key) inifile_lookup(key)
593
 
 
594
 
    ERRTYPE e;
595
 
 
596
 
    if (e = inifile_read(&cfgPool, ININAME), ERRNONE != e) {
597
 
        LogMessage("Error reading: %s, %s", NOERROR, ININAME, ERRTXT(e));
598
 
        return JK_FALSE;
599
 
    }
600
 
 
601
 
#else
602
 
// Using the registry
603
 
#define GETV(key) GetRegString(hkey, key)
604
 
 
605
 
    HKEY hkey;
606
 
    long rc;
607
 
 
608
 
    rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGISTRY_LOCATION, (DWORD) 0,
609
 
                      KEY_READ, &hkey);
610
 
    if (ERROR_SUCCESS != rc)
611
 
        return JK_FALSE;
612
 
 
613
 
#endif
614
 
 
615
 
#define GETVNB(tag, var) \
616
 
        var = GETV(tag); \
617
 
        if (NULL == var) \
618
 
        { \
619
 
                LogMessage("%s not defined in %s", NOERROR, tag, ININAME); \
620
 
                ok = JK_FALSE; \
621
 
        }
622
 
 
623
 
    GETVNB(JK_LOG_FILE_TAG, logFile)
624
 
        GETVNB(JK_LOG_LEVEL_TAG, v);
625
 
    GETVNB(JK_WORKER_FILE_TAG, workerFile);
626
 
    GETVNB(JK_MOUNT_FILE_TAG, workerMountFile);
627
 
 
628
 
    logLevel = (NULL == v) ? 0 : jk_parse_log_level(v);
629
 
 
630
 
    tomcatStart = GETV(TOMCAT_START);
631
 
    tomcatStop = GETV(TOMCAT_STOP);
632
 
 
633
 
#ifndef USE_INIFILE
634
 
    RegCloseKey(hkey);
635
 
#endif
636
 
 
637
 
    return ok;
638
 
}
639
 
 
640
 
#ifndef USE_INIFILE
641
 
static const char *GetRegString(HKEY hkey, const char *key)
642
 
{
643
 
    DWORD type = 0;
644
 
    DWORD sz = 0;
645
 
    LONG rc;
646
 
    char *val;
647
 
 
648
 
    rc = RegQueryValueEx(hkey, key, (LPDWORD) 0, &type, NULL, &sz);
649
 
    if (rc != ERROR_SUCCESS || type != REG_SZ)
650
 
        return NULL;
651
 
 
652
 
    if (val = jk_pool_alloc(&cfgPool, sz), NULL == val)
653
 
        return NULL;
654
 
 
655
 
    rc = RegQueryValueEx(hkey, key, (LPDWORD) 0, &type, val, &sz);
656
 
    if (rc == ERROR_SUCCESS)
657
 
        return val;
658
 
 
659
 
    return NULL;
660
 
}
661
 
#endif
662
 
 
663
 
/* Main entry point for the filter. Called by the server for every HTTP request.
664
 
 */
665
 
DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc,
666
 
                            DWORD dwNotificationType, LPVOID pvNotification)
667
 
{
668
 
#if 0
669
 
    switch (dwNotificationType) {
670
 
    case kFilterParsedRequest:
671
 
        return ParsedRequest(context, (FilterParsedRequest *) eventData);
672
 
    default:
673
 
        break;
674
 
    }
675
 
    return kFilterNotHandled;
676
 
#endif
677
 
 
678
 
    return SF_STATUS_REQ_NEXT_NOTIFICATION;
679
 
}
680
 
 
681
 
/* Send a simple response. Used when we don't want to bother Tomcat,
682
 
 * which in practice means for various error conditions that we can
683
 
 * detect internally.
684
 
 */
685
 
static void SimpleResponse(PHTTP_FILTER_CONTEXT * context, int status,
686
 
                           char *reason, char *body)
687
 
{
688
 
#if 0
689
 
    FilterResponseHeaders frh;
690
 
    int rc, errID;
691
 
    char hdrBuf[35];
692
 
 
693
 
    sprintf(hdrBuf, "Content-type: text/html%s%s", crlf, crlf);
694
 
 
695
 
    frh.responseCode = status;
696
 
    frh.reasonText = reason;
697
 
    frh.headerText = hdrBuf;
698
 
 
699
 
    rc = context->ServerSupport(context, kWriteResponseHeaders, &frh, NULL, 0,
700
 
                                &errID);
701
 
    rc = context->WriteClient(context, body, strlen(body), 0, &errID);
702
 
#endif
703
 
}
704
 
 
705
 
/* Called to reject a URI that contains the string "web-inf". We block
706
 
 * these because they may indicate an attempt to invoke arbitrary code.
707
 
 */
708
 
static DWORD RejectBadURI(PHTTP_FILTER_CONTEXT * context)
709
 
{
710
 
    static char *msg =
711
 
        "<HTML><BODY><H1>Access is Forbidden</H1></BODY></HTML>";
712
 
 
713
 
    SimpleResponse(context, 403, "Forbidden", msg);
714
 
    return SF_STATUS_REQ_NEXT_NOTIFICATION;
715
 
}
716
 
 
717
 
/* Allocate space for a string given a start pointer and an end pointer
718
 
 * and return a pointer to the allocated, copied string.
719
 
 */
720
 
static char *MemDup(private_ws_t * ws, const char *start, const char *end)
721
 
{
722
 
    char *out = NULL;
723
 
 
724
 
    if (start != NULL && end != NULL && end > start) {
725
 
        int len = end - start;
726
 
        out = jk_pool_alloc(&ws->p, len + 1);
727
 
        memcpy(out, start, len);
728
 
        out[len] = '\0';
729
 
    }
730
 
 
731
 
    return out;
732
 
}
733
 
 
734
 
/* Given all the HTTP headers as a single string parse them into individual
735
 
 * name, value pairs. Called twice: once to work out how many headers there
736
 
 * are, then again to copy them.
737
 
 */
738
 
static int ParseHeaders(private_ws_t * ws, const char *hdrs, int hdrsz,
739
 
                        jk_ws_service_t *s)
740
 
{
741
 
    int hdrCount = 0;
742
 
    const char *limit = hdrs + hdrsz;
743
 
    const char *name, *nameEnd;
744
 
    const char *value, *valueEnd;
745
 
 
746
 
    /* Clear RECO status */
747
 
    s->reco_status = RECO_NONE;
748
 
 
749
 
    while (hdrs < limit) {
750
 
        /* Skip line *before* doing anything, cos we want to lose the first line which
751
 
         * contains the request.
752
 
         */
753
 
        while (hdrs < limit && (*hdrs != '\n' && *hdrs != '\r'))
754
 
            hdrs++;
755
 
        while (hdrs < limit && (*hdrs == '\n' || *hdrs == '\r'))
756
 
            hdrs++;
757
 
 
758
 
        if (hdrs >= limit)
759
 
            break;
760
 
 
761
 
        name = nameEnd = value = valueEnd = NULL;
762
 
 
763
 
        name = hdrs;
764
 
        while (hdrs < limit && *hdrs >= ' ' && *hdrs != ':')
765
 
            hdrs++;
766
 
        nameEnd = hdrs;
767
 
 
768
 
        if (hdrs < limit && *hdrs == ':') {
769
 
            hdrs++;
770
 
            while (hdrs < limit && (*hdrs == ' ' || *hdrs == '\t'))
771
 
                hdrs++;
772
 
            value = hdrs;
773
 
            while (hdrs < limit && *hdrs >= ' ')
774
 
                hdrs++;
775
 
            valueEnd = hdrs;
776
 
        }
777
 
 
778
 
        if (s->headers_names != NULL && s->headers_values != NULL) {
779
 
            s->headers_names[hdrCount] = MemDup(ws, name, nameEnd);
780
 
            s->headers_values[hdrCount] = MemDup(ws, value, valueEnd);
781
 
            DEBUG(("%s = %s\n", s->headers_names[hdrCount],
782
 
                   s->headers_values[hdrCount]));
783
 
        }
784
 
        hdrCount++;
785
 
    }
786
 
 
787
 
    return hdrCount;
788
 
}
789
 
 
790
 
#if 0
791
 
/* Set up all the necessary jk_* workspace based on the current HTTP request.
792
 
 */
793
 
static int InitService(private_ws_t * ws, jk_ws_service_t *s)
794
 
{
795
 
    /* This is the only fixed size buffer left. It won't be overflowed
796
 
     * because the the server API that reads into the buffer accepts a length
797
 
     * constraint, and it's unlikely ever to be exhausted because the
798
 
     * strings being will typically be short, but it's still aesthetically
799
 
     * troublesome.
800
 
     */
801
 
    char workBuf[16 * 1024];
802
 
    FilterRequest fr;
803
 
    char *hdrs, *qp;
804
 
    int hdrsz;
805
 
    int errID;
806
 
    int hdrCount;
807
 
    int rc /*, dummy */ ;
808
 
 
809
 
    static char *methodName[] =
810
 
        { "", "HEAD", "GET", "POST", "PUT", "DELETE" };
811
 
 
812
 
    rc = ws->context->GetRequest(ws->context, &fr, &errID);
813
 
 
814
 
    s->jvm_route = NULL;
815
 
    s->start_response = StartResponse;
816
 
    s->read = Read;
817
 
    s->write = Write;
818
 
 
819
 
    s->req_uri = jk_pool_strdup(&ws->p, fr.URL);
820
 
    s->query_string = NULL;
821
 
    if (qp = strchr(s->req_uri, '?'), qp != NULL) {
822
 
        *qp++ = '\0';
823
 
        if (strlen(qp))
824
 
            s->query_string = qp;
825
 
    }
826
 
 
827
 
    GETVARIABLE("AUTH_TYPE", &s->auth_type, "");
828
 
    GETVARIABLE("REMOTE_USER", &s->remote_user, "");
829
 
    GETVARIABLE("SERVER_PROTOCOL", &s->protocol, "");
830
 
    GETVARIABLE("REMOTE_HOST", &s->remote_host, "");
831
 
    GETVARIABLE("REMOTE_ADDR", &s->remote_addr, "");
832
 
    GETVARIABLE("SERVER_NAME", &s->server_name, "");
833
 
    GETVARIABLEINT("SERVER_PORT", &s->server_port, 80);
834
 
    GETVARIABLE("SERVER_SOFTWARE", &s->server_software, SERVERDFLT);
835
 
    GETVARIABLEINT("CONTENT_LENGTH", &s->content_length, 0);
836
 
 
837
 
 
838
 
    /* SSL Support
839
 
     */
840
 
    GETVARIABLEBOOL("HTTPS", &s->is_ssl, 0);
841
 
 
842
 
    if (ws->reqData->requestMethod < 0 ||
843
 
        ws->reqData->requestMethod >=
844
 
        sizeof(methodName) / sizeof(methodName[0]))
845
 
        return JK_FALSE;
846
 
 
847
 
    s->method = methodName[ws->reqData->requestMethod];
848
 
 
849
 
    s->headers_names = NULL;
850
 
    s->headers_values = NULL;
851
 
    s->num_headers = 0;
852
 
 
853
 
    s->ssl_cert_len = fr.clientCertLen;
854
 
    s->ssl_cert = fr.clientCert;
855
 
    s->ssl_cipher = NULL;       /* required by Servlet 2.3 Api */
856
 
    s->ssl_session = NULL;
857
 
 
858
 
#if defined(JK_VERSION) && JK_VERSION >= MAKEVERSION(1, 2, 0, 1)
859
 
    s->ssl_key_size = -1;       /* required by Servlet 2.3 Api, added in jtc */
860
 
#endif
861
 
 
862
 
    if (s->is_ssl) {
863
 
        int dummy;
864
 
#if 0
865
 
        char *sslNames[] = {
866
 
            "CERT_ISSUER", "CERT_SUBJECT", "CERT_COOKIE", "CERT_FLAGS",
867
 
                "CERT_SERIALNUMBER",
868
 
            "HTTPS_SERVER_SUBJECT", "HTTPS_SECRETKEYSIZE",
869
 
                "HTTPS_SERVER_ISSUER", "HTTPS_KEYSIZE"
870
 
        };
871
 
 
872
 
        char *sslValues[] = {
873
 
            NULL, NULL, NULL, NULL, NULL,
874
 
            NULL, NULL, NULL, NULL
875
 
        };
876
 
 
877
 
 
878
 
        unsigned i, varCount = 0;
879
 
#endif
880
 
 
881
 
        DEBUG(("SSL request\n"));
882
 
 
883
 
#if defined(JK_VERSION) && JK_VERSION >= MAKEVERSION(1, 2, 0, 1)
884
 
        /* Read the variable into a dummy variable: we do this for the side effect of
885
 
         * reading it into workBuf.
886
 
         */
887
 
        GETVARIABLEINT("HTTPS_KEYSIZE", &dummy, 0);
888
 
        if (workBuf[0] == '[')
889
 
            s->ssl_key_size = atoi(workBuf + 1);
890
 
#else
891
 
        (void)dummy;
892
 
#endif
893
 
 
894
 
#if 0
895
 
        for (i = 0; i < sizeof(sslNames) / sizeof(sslNames[0]); i++) {
896
 
            GETVARIABLE(sslNames[i], &sslValues[i], NULL);
897
 
            if (sslValues[i])
898
 
                varCount++;
899
 
        }
900
 
 
901
 
        /* Andy, some SSL vars must be mapped directly in  s->ssl_cipher,
902
 
         * ssl->session and s->ssl_key_size
903
 
         * ie:
904
 
         * Cipher could be "RC4-MD5"
905
 
         * KeySize 128 (bits)
906
 
         * SessionID a string containing the UniqID used in SSL dialogue
907
 
         */
908
 
        if (varCount > 0) {
909
 
            unsigned j;
910
 
 
911
 
            s->attributes_names =
912
 
                jk_pool_alloc(&ws->p, varCount * sizeof(char *));
913
 
            s->attributes_values =
914
 
                jk_pool_alloc(&ws->p, varCount * sizeof(char *));
915
 
 
916
 
            j = 0;
917
 
            for (i = 0; i < sizeof(sslNames) / sizeof(sslNames[0]); i++) {
918
 
                if (sslValues[i]) {
919
 
                    s->attributes_names[j] = sslNames[i];
920
 
                    s->attributes_values[j] = sslValues[i];
921
 
                    j++;
922
 
                }
923
 
            }
924
 
            s->num_attributes = varCount;
925
 
        }
926
 
#endif
927
 
    }
928
 
 
929
 
    /* Duplicate all the headers now */
930
 
 
931
 
    hdrsz = ws->reqData->GetAllHeaders(ws->context, &hdrs, &errID);
932
 
    DEBUG(("\nGot headers (length %d)\n--------\n%s\n--------\n\n", hdrsz,
933
 
           hdrs));
934
 
 
935
 
    s->headers_names = s->headers_values = NULL;
936
 
    hdrCount = ParseHeaders(ws, hdrs, hdrsz, s);
937
 
    DEBUG(("Found %d headers\n", hdrCount));
938
 
    s->num_headers = hdrCount;
939
 
    s->headers_names = jk_pool_alloc(&ws->p, hdrCount * sizeof(char *));
940
 
    s->headers_values = jk_pool_alloc(&ws->p, hdrCount * sizeof(char *));
941
 
    hdrCount = ParseHeaders(ws, hdrs, hdrsz, s);
942
 
 
943
 
    return JK_TRUE;
944
 
}
945
 
#endif
946
 
 
947
 
#if 0
948
 
/* Handle an HTTP request. Works out whether Tomcat will be interested then either
949
 
 * despatches it to Tomcat or passes it back to the server.
950
 
 */
951
 
static unsigned int ParsedRequest(PHTTP_FILTER_CONTEXT * context,
952
 
                                  FilterParsedRequest * reqData)
953
 
{
954
 
    unsigned int errID;
955
 
    int rc;
956
 
    FilterRequest fr;
957
 
    int result = kFilterNotHandled;
958
 
 
959
 
    DEBUG(("\nParsedRequest starting\n"));
960
 
 
961
 
    rc = context->GetRequest(context, &fr, &errID);
962
 
 
963
 
    if (fr.URL && strlen(fr.URL)) {
964
 
        char *uri = fr.URL;
965
 
        char *workerName, *qp;
966
 
 
967
 
        if (!initDone) {
968
 
            /* One time initialisation which is deferred so that we have the name of
969
 
             * the server software to plug into worker_env
970
 
             */
971
 
            int ok = JK_FALSE;
972
 
            jk_map_t *map = NULL;
973
 
 
974
 
            DEBUG(("Initialising worker map\n"));
975
 
 
976
 
            if (jk_map_alloc(&map)) {
977
 
                if (jk_map_read_properties(map, workerMountFile))
978
 
                    if (uri_worker_map_alloc(&uw_map, map, logger))
979
 
                        ok = JK_TRUE;
980
 
                jk_map_free(&map);
981
 
            }
982
 
 
983
 
            DEBUG(("Got the URI worker map\n"));
984
 
 
985
 
            if (ok) {
986
 
                ok = JK_FALSE;
987
 
                DEBUG(("About to allocate map\n"));
988
 
                if (jk_map_alloc(&map)) {
989
 
                    DEBUG(("About to read %s\n", workerFile));
990
 
                    if (jk_map_read_properties(map, workerFile)) {
991
 
#if defined(JK_VERSION) && JK_VERSION >= MAKEVERSION(1, 2, 0, 1)
992
 
                        char server[256];
993
 
 
994
 
                        worker_env.uri_to_worker = uw_map;
995
 
                        if (context->
996
 
                            GetServerVariable(context, "SERVER_SOFTWARE",
997
 
                                              server, sizeof(server) - 1,
998
 
                                              &errID))
999
 
                            worker_env.server_name =
1000
 
                                jk_pool_strdup(&cfgPool, server);
1001
 
                        else
1002
 
                            worker_env.server_name = SERVERDFLT;
1003
 
 
1004
 
                        DEBUG(("Server name %s\n", worker_env.server_name));
1005
 
 
1006
 
                        if (wc_open(map, &worker_env, logger))
1007
 
                            ok = JK_TRUE;
1008
 
#else
1009
 
                        if (wc_open(map, logger))
1010
 
                            ok = JK_TRUE;
1011
 
#endif
1012
 
                        DEBUG(("OK = %d\n", ok));
1013
 
                    }
1014
 
 
1015
 
                    DEBUG(("Read %s, OK = %d\n", workerFile, ok));
1016
 
                    jk_map_free(&map);
1017
 
                }
1018
 
            }
1019
 
 
1020
 
            if (!ok)
1021
 
                return kFilterError;
1022
 
            initDone = JK_TRUE;
1023
 
        }
1024
 
 
1025
 
 
1026
 
        if (qp = strchr(uri, '?'), qp != NULL)
1027
 
            *qp = '\0';
1028
 
        workerName = map_uri_to_worker(uw_map, uri, logger);
1029
 
        if (qp)
1030
 
            *qp = '?';
1031
 
 
1032
 
        DEBUG(("Worker for this URL is %s\n", workerName));
1033
 
 
1034
 
        if (NULL != workerName) {
1035
 
            private_ws_t ws;
1036
 
            jk_ws_service_t s;
1037
 
            jk_pool_atom_t buf[SMALL_POOL_SIZE];
1038
 
 
1039
 
            if (BadURI(uri))
1040
 
                return RejectBadURI(context);
1041
 
 
1042
 
            /* Go dispatch the call */
1043
 
 
1044
 
            jk_init_ws_service(&s);
1045
 
            jk_open_pool(&ws.p, buf, sizeof(buf));
1046
 
 
1047
 
            ws.responseStarted = JK_FALSE;
1048
 
            ws.context = context;
1049
 
            ws.reqData = reqData;
1050
 
 
1051
 
            ws.reqSize =
1052
 
                context->GetRequestContents(context, &ws.reqBuffer, &errID);
1053
 
 
1054
 
            s.ws_private = &ws;
1055
 
            s.pool = &ws.p;
1056
 
 
1057
 
            if (InitService(&ws, &s)) {
1058
 
                jk_worker_t *worker =
1059
 
                    wc_get_worker_for_name(workerName, logger);
1060
 
 
1061
 
                jk_log(logger, JK_LOG_DEBUG,
1062
 
                       "HttpExtensionProc %s a worker for name %s\n",
1063
 
                       worker ? "got" : "could not get", workerName);
1064
 
 
1065
 
                if (worker) {
1066
 
                    jk_endpoint_t *e = NULL;
1067
 
 
1068
 
                    if (worker->get_endpoint(worker, &e, logger)) {
1069
 
                        int recover = JK_FALSE;
1070
 
 
1071
 
                        if (e->service(e, &s, logger, &recover)) {
1072
 
                            result = kFilterHandledRequest;
1073
 
                            jk_log(logger, JK_LOG_DEBUG,
1074
 
                                   "HttpExtensionProc service() returned OK\n");
1075
 
                            DEBUG(("HttpExtensionProc service() returned OK\n"));
1076
 
                        }
1077
 
                        else {
1078
 
                            result = kFilterError;
1079
 
                            jk_log(logger, JK_LOG_ERROR,
1080
 
                                   "HttpExtensionProc error, service() failed\n");
1081
 
                            DEBUG(("HttpExtensionProc error, service() failed\n"));
1082
 
                        }
1083
 
                        e->done(&e, logger);
1084
 
                    }
1085
 
                }
1086
 
                else {
1087
 
                    jk_log(logger, JK_LOG_ERROR,
1088
 
                           "HttpExtensionProc error, could not get a worker for name %s\n",
1089
 
                           workerName);
1090
 
                }
1091
 
            }
1092
 
 
1093
 
            jk_close_pool(&ws.p);
1094
 
        }
1095
 
    }
1096
 
 
1097
 
    return result;
1098
 
}
1099
 
#endif
1100
 
 
1101
 
BOOL WINAPI DllMain(HINSTANCE hInst, ULONG ulReason, LPVOID lpReserved)
1102
 
{
1103
 
    BOOL fReturn = TRUE;
1104
 
 
1105
 
    switch (ulReason) {
1106
 
 
1107
 
    case DLL_PROCESS_DETACH:
1108
 
        TerminateFilter(HSE_TERM_MUST_UNLOAD);
1109
 
        break;
1110
 
 
1111
 
    default:
1112
 
        break;
1113
 
    }
1114
 
 
1115
 
    return fReturn;
1116
 
}