File: nslog.c

package info (click to toggle)
aolserver 3.4.2-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 22,692 kB
  • ctags: 33,612
  • sloc: ansic: 171,340; tcl: 10,218; sh: 3,821; cpp: 2,779; makefile: 2,041; yacc: 1,648; perl: 456; php: 13
file content (741 lines) | stat: -rw-r--r-- 17,395 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
/*
 * The contents of this file are subject to the AOLserver Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://aolserver.com/.
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
 * the License for the specific language governing rights and limitations
 * under the License.
 *
 * The Original Code is AOLserver Code and related documentation
 * distributed by AOL.
 * 
 * The Initial Developer of the Original Code is America Online,
 * Inc. Portions created by AOL are Copyright (C) 1999 America Online,
 * Inc. All Rights Reserved.
 *
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU General Public License (the "GPL"), in which case the
 * provisions of GPL are applicable instead of those above.  If you wish
 * to allow use of your version of this file only under the terms of the
 * GPL and not to allow others to use your version of this file under the
 * License, indicate your decision by deleting the provisions above and
 * replace them with the notice and other provisions required by the GPL.
 * If you do not delete the provisions above, a recipient may use your
 * version of this file under either the License or the GPL.
 */


/* 
 * nslog.c --
 *
 *	This file implements the access log using NCSA Common Log format.
 */

static const char *RCSID = "@(#) $Header: /cvsroot/aolserver/aolserver/nslog/nslog.c,v 1.7 2000/12/12 22:54:27 kriston Exp $, compiled: " __DATE__ " " __TIME__;

#include "ns.h"
#include <sys/stat.h>	/* mkdir */
#include <ctype.h>	/* isspace */

#define LOG_COMBINED	1
#define LOG_FMTTIME	2

/*
 * Exported variables
 */

NS_EXPORT int Ns_ModuleVersion = 1; 		/* Needed for AOLserver */

typedef struct {
    char	   *module;
    Ns_Mutex	    lock;
    int             fd;
    char           *file;
    char           *rollfmt;
    int		    flags;
    int             maxbackup;
    int             maxlines;
    int             curlines;
    int             suppressquery;
    Ns_DString      buffer;
    char          **extheaders;
} Log;


/*
 * Local functions defined in this file
 */
static Ns_Callback LogRollCallback;
static Ns_Callback LogCloseCallback;
static Ns_TraceProc LogTrace;
static int LogFlush(Log *logPtr, Ns_DString *dsPtr);
static int LogOpen(Log *logPtr);
static int LogRoll(Log *logPtr);
static int LogClose(Log *logPtr);
static void LogConfigExtHeaders(Log *logPtr, char *path);
static Ns_ArgProc LogArg;
static Tcl_CmdProc LogCmd;
static Ns_TclInterpInitProc AddCmds;

/*
 * Static variables defined in this file
 */


/*
 *----------------------------------------------------------------------
 *
 * Ns_ModuleInit --
 *
 *	Module initialization routine.
 *
 * Results:
 *	NS_OK.
 *
 * Side effects:
 *	Log file is opened, trace routine is registered, and, if
 *	configured, log file roll signal and scheduled procedures 
 *	are registered.
 *
 *----------------------------------------------------------------------
 */

NS_EXPORT int
Ns_ModuleInit(char *server, char *module)
{
    char 	*path;
    int 	 opt, hour;
    Log		*logPtr;
    static int	 first = 1;

    /*
     * Register the info callbacks just once.
     */

    if (first) {
	Ns_RegisterProcInfo((void *)LogRollCallback, "logroll", LogArg);
	Ns_RegisterProcInfo((void *)LogCloseCallback, "logclose", LogArg);
	first = 0;
    }

    /*
     * Initialize the log buffer.
     */

    logPtr = ns_calloc(1, sizeof(Log));
    logPtr->fd = -1;
    logPtr->module = module;
    Ns_MutexInit2(&logPtr->lock, "nslog");
    Ns_DStringInit(&logPtr->buffer);

    /*
     * Determine the log file name which, if not
     * absolute, is expected to exist in the module
     * specific directory.  The module directory is
     * created if necessary.
     */

    path = Ns_ConfigGetPath(server, module, NULL);
    logPtr->file = Ns_ConfigGet(path, "file");
    if (logPtr->file == NULL) {
    	logPtr->file = "access.log";
    }
    if (Ns_PathIsAbsolute(logPtr->file) == NS_FALSE) {
    	Ns_DString 	 ds;

	Ns_DStringInit(&ds);
	Ns_ModulePath(&ds, server, module, NULL, NULL);
	if (mkdir(ds.string, 0755) != 0 && errno != EEXIST
	    && errno != EISDIR) {
	    Ns_Log(Error, "nslog: mkdir(%s) failed: %s", 
		   ds.string, strerror(errno));
	    Ns_DStringFree(&ds);
	    return NS_ERROR;
	}
    	Ns_DStringTrunc(&ds, 0);
	Ns_ModulePath(&ds, server, module, logPtr->file, NULL);
	logPtr->file = Ns_DStringExport(&ds);
    }

    /*
     * Get parameters from configuration file
     */

    logPtr->rollfmt = Ns_ConfigGet(path, "rollfmt");
    if (!Ns_ConfigGetInt(path, "maxbuffer", &logPtr->maxlines)) {
	logPtr->maxlines = 0;
    }
    if (!Ns_ConfigGetInt(path, "maxbackup", &logPtr->maxbackup) || logPtr->maxbackup < 1) {
        logPtr->maxbackup = 100;
    }
    if (!Ns_ConfigGetBool(path, "formattedTime", &opt)) {
	opt = 1;
    }
    if (opt) {
	logPtr->flags |= LOG_FMTTIME;
    }
    if (!Ns_ConfigGetBool(path, "logcombined", &opt)) {
        opt = 1;
    }
    if (opt) {
	logPtr->flags |= LOG_COMBINED;
    }

    if (!Ns_ConfigGetBool(path, "suppressquery", &logPtr->suppressquery)) {
	logPtr->suppressquery = 0;
    }

    /*
     * Schedule various log roll and shutdown options.
     */

    if (!Ns_ConfigGetInt(path, "rollhour", &hour) ||
	hour < 0 || hour > 23) {
	hour = 0;
    }
    if (!Ns_ConfigGetBool(path, "rolllog", &opt)) {
        opt = 1;
    }
    if (opt) {
        Ns_ScheduleDaily((Ns_SchedProc *) LogRollCallback, logPtr, 0, hour, 0, NULL);
    }
    if (!Ns_ConfigGetBool(path, "rollonsignal", &opt)) {
        opt = 0;;
    }
    if (opt) {
        Ns_RegisterAtSignal(LogRollCallback, logPtr);
    }

    LogConfigExtHeaders(logPtr, path);

    /*
     * Open the log and register the trace.
     */

    if (LogOpen(logPtr) != NS_OK) {
	return NS_ERROR;
    }
    Ns_RegisterServerTrace(server, LogTrace, logPtr);
    Ns_RegisterAtShutdown(LogCloseCallback, logPtr);
    Ns_TclInitInterps(server, AddCmds, logPtr);
    return NS_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * LogTrace --
 *
 *	Trace routine for appending the log with the current connection
 *	results.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Entry is appended to the open log.
 *
 *----------------------------------------------------------------------
 */

static void
LogTrace(void *arg, Ns_Conn *conn)
{
    Ns_DString     ds;
    register char *p;
    int            quote, n, status, i;
    char           buf[100];
    Log		  *logPtr = arg;
    
    Ns_DStringInit(&ds);

    /*
     * Append the peer address and auth user (if any).
     */

    Ns_DStringAppend(&ds, Ns_ConnPeer(conn));
    if (conn->authUser == NULL) {
    	Ns_DStringAppend(&ds, " - - ");
    } else {
    	p = conn->authUser;
	quote = 0;
	while (*p != '\0') {
	    if (isspace((unsigned char) *p)) {
	    	quote = 1;
	    	break;
	    }
	    ++p;
    	}
	if (quote) {
    	    Ns_DStringVarAppend(&ds, " - \"", conn->authUser, "\" ", NULL);
	} else {
    	    Ns_DStringVarAppend(&ds, " - ", conn->authUser, " ", NULL);
	}
    }

    /*
     * Append a common log format time stamp including GMT offset.
     */

    if (!(logPtr->flags & LOG_FMTTIME)) {
	sprintf(buf, "[%ld]", (long) time(NULL));
    } else {
	Ns_LogTime(buf);
    }
    Ns_DStringAppend(&ds, buf);

    /*
     * Append the request line.
     */

    if (conn->request && conn->request->line) {
	
	if (logPtr->suppressquery) {
	    /*
	     * Don't display query data.
	     * NB: Side-effect is that the real URI is returned, so places
	     * where trailing slash returns "index.html" logs as "index.html".
	     */
	    Ns_DStringVarAppend(&ds, " \"", conn->request->url, "\" ", NULL);
	} else {
	    Ns_DStringVarAppend(&ds, " \"", conn->request->line, "\" ", NULL);
	}
    } else {
	Ns_DStringAppend(&ds, " \"\"");
    }

    /*
     * Construct and append the HTTP status code and bytes sent.
     */

    n = Ns_ConnResponseStatus(conn);
    sprintf(buf, "%d %u ", n ? n : 200, Ns_ConnContentSent(conn));
    Ns_DStringAppend(&ds, buf);

    if ((logPtr->flags & LOG_COMBINED)) {

	/*
	 * Append the referer and user-agent headers (if any).
	 */

	Ns_DStringAppend(&ds, "\"");
	if ((p = Ns_SetIGet(conn->headers, "referer"))) {
	    Ns_DStringAppend(&ds, p);
	}
	Ns_DStringAppend(&ds, "\" \"");
	if ((p = Ns_SetIGet(conn->headers, "user-agent"))) {
	    Ns_DStringAppend(&ds, p);
	}
	Ns_DStringAppend(&ds, "\"");

    }

    /*
     * Append the extended headers (if any).
     */
    for (i=0; logPtr->extheaders[i] != NULL; i++) {
	if ((p = Ns_SetIGet(conn->headers, logPtr->extheaders[i]))) {
	    Ns_DStringAppend(&ds, " \"");
	    Ns_DStringAppend(&ds, p);
	    Ns_DStringAppend(&ds, "\"");
	} else {
	    Ns_DStringAppend(&ds, " -");
	}
    }

    /*
     * Append the trailing newline and buffer and/or flush the line.
     */

    status = NS_OK;
    Ns_DStringAppend(&ds, "\n");
    Ns_MutexLock(&logPtr->lock);
    if (logPtr->maxlines <= 0) {
	status = LogFlush(logPtr, &ds);
    } else {
	Ns_DStringNAppend(&logPtr->buffer, ds.string, ds.length);
	if (++logPtr->curlines > logPtr->maxlines) {
	    status = LogFlush(logPtr, &logPtr->buffer);
	    logPtr->curlines = 0;
	}
    }
    Ns_MutexUnlock(&logPtr->lock);
    Ns_DStringFree(&ds);
    if (status != NS_OK) {
	Ns_Log(Error, "nslog: failed to flush log: %s", strerror(errno));
    }
}


/*
 *----------------------------------------------------------------------
 *
 * LogCmd --
 *
 *	Implement the ns_accesslog command.
 *
 * Results:
 *	Standard Tcl result.
 *
 * Side effects:
 *	Depends on command.
 *
 *----------------------------------------------------------------------
 */

static int
AddCmds(Tcl_Interp *interp, void *arg)
{
    Tcl_CreateCommand(interp, "ns_accesslog", LogCmd, arg, NULL);
    return TCL_OK;
}

static int
LogCmd(ClientData arg, Tcl_Interp *interp, int argc, char **argv)
{
    char *rollfile;
    int status;
    Log *logPtr = arg;

    if (argc < 2) {
	Tcl_AppendResult(interp, "wrong # args: should be: \"",
	    argv[0], " command ?arg?\"", NULL);
	return TCL_ERROR;
    }
    if (STREQ(argv[1], "file")) {
	Tcl_SetResult(interp, logPtr->file, TCL_STATIC);
    } else if (STREQ(argv[1], "roll")) {
	if (argc != 2 && argc != 3) {
	    Tcl_AppendResult(interp, "wrong # args: should be: \"",
	    	argv[0], " ", argv[1], " ?file?\"", NULL);
	    return TCL_ERROR;
	}
    	Ns_MutexLock(&logPtr->lock);
	if (argc == 2) {
	    status = LogRoll(logPtr);
	} else {
	    rollfile = argv[2];
	    status = NS_OK;
    	    if (access(rollfile, F_OK) == 0) {
		status = Ns_RollFile(rollfile, logPtr->maxbackup);
	    }
	    if (status == NS_OK) {
		if (rename(logPtr->file, rollfile) != 0) {
		    status = NS_ERROR;
		} else {
	    	    LogFlush(logPtr, &logPtr->buffer);
	    	    status = LogOpen(logPtr);
		}
	    }
	}
    	Ns_MutexUnlock(&logPtr->lock);
	if (status != NS_OK) {
	    Tcl_AppendResult(interp, "could not roll \"", logPtr->file,
		"\": ", Tcl_PosixError(interp), NULL);
	    return TCL_ERROR;
	}
    } else {
	Tcl_AppendResult(interp, "unknown command \"", argv[1],
	    "\": should be file or roll", NULL);
	return TCL_ERROR;
    }
    return TCL_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * LogArg --
 *
 *	Copy log file as argument for callback query.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static void
LogArg(Tcl_DString *dsPtr, void *arg)
{
    Log *logPtr = arg;

    Tcl_DStringAppendElement(dsPtr, logPtr->file);
}


/*
 *----------------------------------------------------------------------
 *
 * LogOpen --
 *
 *      Open the access log, closing previous log if opeopen
 *
 * Results:
 *      NS_OK or NS_ERROR.
 *
 * Side effects:
 *      Log re-opened.
 *
 *----------------------------------------------------------------------
 */

static int
LogOpen(Log *logPtr)
{
    int fd;

    fd = open(logPtr->file, O_APPEND|O_WRONLY|O_CREAT|O_TEXT, 0644);
    if (fd < 0) {
    	Ns_Log(Error, "nslog: error '%s' opening '%s'",
	       strerror(errno),logPtr->file);
	return NS_ERROR;
    }
    if (logPtr->fd >= 0) {
	close(logPtr->fd);
    }
    logPtr->fd = fd;
    Ns_Log(Notice, "nslog: opened '%s'", logPtr->file);
    return NS_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * LogClose --
 *
 *      Flush and/or close the log.
 *
 * Results:
 *      NS_TRUE or NS_FALSE if log was closed.
 *
 * Side effects:
 *      Buffer entries, if any, are flushed.
 *
 *----------------------------------------------------------------------
 */

static int
LogClose(Log *logPtr)
{
    int status;

    status = NS_OK;
    if (logPtr->fd >= 0) {
	Ns_Log(Notice, "nslog: closing '%s'", logPtr->file);
	status = LogFlush(logPtr, &logPtr->buffer);
	close(logPtr->fd);
	logPtr->fd = -1;
	Ns_DStringFree(&logPtr->buffer);
    }
    return status;
}


/*
 *----------------------------------------------------------------------
 *
 * LogFlush --
 *
 *	Flush a log buffer to the open log file.  Note:  The mutex
 *	is assumed held during call. 
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Will disable the log on error.
 *
 *----------------------------------------------------------------------
 */

static int
LogFlush(Log *logPtr, Ns_DString *dsPtr)
{
    if (dsPtr->length > 0) {
    	if (logPtr->fd >= 0 &&
	    write(logPtr->fd, dsPtr->string, dsPtr->length) != dsPtr->length) {
	    Ns_Log(Error, "nslog: "
		   "logging disabled: write() failed: '%s'", strerror(errno));
	    close(logPtr->fd);
	    logPtr->fd = -1;
	}
    	Ns_DStringTrunc(dsPtr, 0);
    }
    if (logPtr->fd < 0) {
	return NS_ERROR;
    }
    return NS_OK;
}


/*
 *----------------------------------------------------------------------
 *
 * LogRoll --
 *
 *      Roll and re-open the access log.  This procedure is scheduled
 *      and/or registered at signal catching.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Files are rolled to new names.
 *
 *----------------------------------------------------------------------
 */

static int
LogRoll(Log *logPtr)
{
    int 	status;

    status = NS_OK;
    (void) LogClose(logPtr);
    if (access(logPtr->file, F_OK) == 0) {
    	if (logPtr->rollfmt == NULL) {
	    status = Ns_RollFile(logPtr->file, logPtr->maxbackup);
	} else {
	    Ns_DString  ds;
	    time_t 	now;
	    struct tm  *ptm;
	    char 	timeBuf[512];

	    now = time(NULL);
	    ptm = ns_localtime(&now);
	    strftime(timeBuf, 512, logPtr->rollfmt, ptm);
	    Ns_DStringInit(&ds);
	    Ns_DStringVarAppend(&ds, logPtr->file, ".", timeBuf, NULL);
	    if (access(ds.string, F_OK) == 0) {
		status = Ns_RollFile(ds.string, logPtr->maxbackup);
	    } else if (errno != ENOENT) {
		Ns_Log(Error, "nslog: access(%s, F_OK) failed: '%s'", 
	      	       ds.string, strerror(errno));
		status = NS_ERROR;
	    }
	    if (status == NS_OK && rename(logPtr->file, ds.string) != 0) {
	    	Ns_Log(Error, "nslog: rename(%s, %s) failed: '%s'",
		    logPtr->file, ds.string, strerror(errno));
		status = NS_ERROR;
	    }
	    Ns_DStringFree(&ds);
	    if (status == NS_OK) {
		status = Ns_PurgeFiles(logPtr->file, logPtr->maxbackup);
	    }
	}
    }
    status = LogOpen(logPtr);
    return status;
}    	


/*
 *----------------------------------------------------------------------
 *
 * LogCloseCallback, LogRollCallback -
 *
 *      Close or roll the log.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *	See LogClose and LogRoll.
 *
 *----------------------------------------------------------------------
 */

static void
LogCallback(int (proc)(Log *), void *arg, char *desc)
{
    int status;
    Log *logPtr = arg;

    Ns_MutexLock(&logPtr->lock);
    status = (*proc)(logPtr);
    Ns_MutexUnlock(&logPtr->lock);
    if (status != NS_OK) {
	Ns_Log(Error, "nslog: failed: %s '%s': '%s'",
	       desc, logPtr->file, strerror(errno));
    }
}

static void
LogCloseCallback(void *arg)
{
    LogCallback(LogClose, arg, "close");
}

static void
LogRollCallback(void *arg)
{
    LogCallback(LogRoll, arg, "roll");
}


/*
 *----------------------------------------------------------------------
 *
 * LogConfigExtHeaders
 *
 *      Parse the ExtendedHeaders configuration.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *	Sets logPtr->extheaders.
 *
 *----------------------------------------------------------------------
 */

static void
LogConfigExtHeaders(Log *logPtr, char *path)
{
    char *config = Ns_ConfigGet(path, "extendedheaders");
    char *p;
    int   i;

    if (config == NULL) {
        logPtr->extheaders = ns_calloc(1, sizeof *logPtr->extheaders);
        logPtr->extheaders[0] = NULL;
	return;
    }

    config = Ns_StrDup(config);

    /* Figure out how many extended headers there are. */

    for (i = 1, p = config; *p; p++) {
	if (*p == ',') {
	    i++;
	}
    }

    /* Initialize the extended header pointers. */

    logPtr->extheaders = ns_calloc(i + 1, sizeof *logPtr->extheaders);

    logPtr->extheaders[0] = config;

    for (i = 1, p = config; *p; p++) {
	if (*p == ',') {
	    *p = '\000';
	    logPtr->extheaders[i++] = p + 1;
	}
    }

    logPtr->extheaders[i] = NULL;

}