-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebalizer.c
2481 lines (2235 loc) · 98.7 KB
/
webalizer.c
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
webalizer - a web server log analysis program
Copyright (C) 1997-2013 Bradford L. Barrett
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version, and provided that the above
copyright and permission notice is included with all distributed
copies of this or derived software.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/*********************************************/
/* STANDARD INCLUDES */
/*********************************************/
/* Fix broken Zlib 64 bitness */
#if _FILE_OFFSET_BITS == 64
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE 1
#endif
#endif
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <errno.h>
#include <unistd.h> /* normal stuff */
#include <locale.h>
#include <ctype.h>
#include <sys/utsname.h>
#include <zlib.h>
#include <sys/stat.h>
/* ensure getopt */
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
/* ensure sys/types */
#ifndef _SYS_TYPES_H
#include <sys/types.h>
#endif
/* Need socket header? */
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
/* some systems need this */
#ifdef HAVE_MATH_H
#include <math.h>
#endif
#ifdef USE_DNS
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <db.h>
#endif /* USE_DNS */
#ifdef USE_GEOIP
#include <maxminddb.h>
#endif
#ifdef USE_BZIP
#include <bzlib.h>
int bz2_rewind(void **, char *, char *);
#endif
#include "webalizer.h" /* main header */
#include "output.h"
#include "parser.h"
#include "preserve.h"
#include "hashtab.h"
#include "linklist.h"
#include "webalizer_lang.h" /* lang. support */
#ifdef USE_DNS
#include "dns_resolv.h"
#endif
/* internal function prototypes */
void clear_month(); /* clear monthly stuff */
char *unescape(char *); /* unescape URLs */
void print_opts(char *); /* print options */
void print_version(); /* duhh... */
int isurlchar(unsigned char, int); /* valid URL char fnc. */
void get_config(char *); /* Read a config file */
static char *save_opt(char *); /* save conf option */
void srch_string(char *); /* srch str analysis */
char *get_domain(char *); /* return domain name */
void agent_mangle(char *); /* reformat user agent */
char *our_gzgets(void *, char *, int); /* our gzgets */
int ouricmp(char *, char *); /* case ins. compare */
int isipaddr(char *); /* is IP address test */
/*********************************************/
/* GLOBAL VARIABLES */
/*********************************************/
char *version = "2.23"; /* program version */
char *editlvl = "08"; /* edit level */
char *moddate = "26-Aug-2013"; /* modification date */
char *copyright = "Copyright 1997-2013 by Bradford L. Barrett";
int verbose = 2; /* 2=verbose,1=err, 0=none */
int debug_mode = 0; /* debug mode flag */
int time_me = 0; /* timing display flag */
int local_time = 1; /* 1=localtime 0=GMT (UTC) */
int hist_gap = 0; /* 1=error w/hist, save bkp */
int ignore_hist = 0; /* history flag (1=skip) */
int ignore_state = 0; /* state flag (1=skip) */
int default_index= 1; /* default index. (1=yes) */
int hourly_graph = 1; /* hourly graph display */
int hourly_stats = 1; /* hourly stats table */
int daily_graph = 1; /* daily graph display */
int daily_stats = 1; /* daily stats table */
int ctry_graph = 1; /* country graph display */
int shade_groups = 1; /* Group shading 0=no 1=yes */
int hlite_groups = 1; /* Group hlite 0=no 1=yes */
int mangle_agent = 0; /* mangle user agents */
int incremental = 0; /* incremental mode 1=yes */
int use_https = 0; /* use 'https://' on URLs */
int htaccess = 0; /* create .htaccess? (0=no) */
int stripcgi = 1; /* strip url cgi (0=no) */
int normalize = 1; /* normalize CLF URL (0=no) */
int trimsquid = 0; /* trim squid urls (0=no) */
int searchcasei = 1; /* case insensitive search */
int visit_timeout= 1800; /* visit timeout (seconds) */
int graph_legend = 1; /* graph legend (1=yes) */
int graph_lines = 2; /* graph lines (0=none) */
int fold_seq_err = 0; /* fold seq err (0=no) */
int log_type = LOG_CLF; /* log type (default=CLF) */
int group_domains= 0; /* Group domains 0=none */
int hide_sites = 0; /* Hide ind. sites (0=no) */
int link_referrer= 0; /* Link referrers (0=no) */
char *hname = NULL; /* hostname for reports */
char *state_fname = "webalizer.current"; /* run state file name */
char *hist_fname = "webalizer.hist"; /* name of history file */
char *html_ext = "html"; /* HTML file suffix */
char *dump_ext = "tab"; /* Dump file suffix */
char *conf_fname = NULL; /* name of config file */
char *log_fname = NULL; /* log file pointer */
char *out_dir = NULL; /* output directory */
char *blank_str = ""; /* blank string */
char *geodb_fname = NULL; /* GeoDB database filename */
char *dns_cache = NULL; /* DNS cache file name */
int dns_children = 0; /* DNS children (0=don't do)*/
int cache_ips = 0; /* CacheIPs in DB (0=no) */
int cache_ttl = 7; /* DNS Cache TTL (days) */
int geodb = 0; /* Use GeoDB (0=no) */
int graph_mths = 12; /* # months in index graph */
int index_mths = 12; /* # months in index table */
int year_hdrs = 1; /* index year seperators */
int year_totals = 1; /* index year subtotals */
int use_flags = 0; /* Show flags in ctry table */
char *flag_dir = "flags"; /* location of flag icons */
#ifdef USE_GEOIP
int geoip = 0; /* Use GeoIP (0=no) */
char *geoip_db = NULL; /* GeoIP database filename */
MMDB_s geo_fp; /* GeoIP database handle */
#endif
int ntop_sites = 30; /* top n sites to display */
int ntop_sitesK = 10; /* top n sites (by kbytes) */
int ntop_urls = 30; /* top n url's to display */
int ntop_urlsK = 10; /* top n url's (by kbytes) */
int ntop_entry = 10; /* top n entry url's */
int ntop_exit = 10; /* top n exit url's */
int ntop_refs = 30; /* top n referrers "" */
int ntop_agents = 15; /* top n user agents "" */
int ntop_ctrys = 30; /* top n countries "" */
int ntop_search = 20; /* top n search strings */
int ntop_users = 20; /* top n users to display */
int all_sites = 0; /* List All sites (0=no) */
int all_urls = 0; /* List All URLs (0=no) */
int all_refs = 0; /* List All Referrers */
int all_agents = 0; /* List All User Agents */
int all_search = 0; /* List All Search Strings */
int all_users = 0; /* List All Usernames */
int dump_sites = 0; /* Dump tab delimited sites */
int dump_urls = 0; /* URLs */
int dump_refs = 0; /* Referrers */
int dump_agents = 0; /* User Agents */
int dump_users = 0; /* Usernames */
int dump_search = 0; /* Search strings */
int dump_header = 0; /* Dump header as first rec */
char *dump_path = NULL; /* Path for dump files */
int cur_year=0, cur_month=0, /* year/month/day/hour */
cur_day=0, cur_hour=0, /* tracking variables */
cur_min=0, cur_sec=0;
u_int64_t cur_tstamp=0; /* Timestamp... */
u_int64_t rec_tstamp=0;
u_int64_t req_tstamp=0;
u_int64_t epoch; /* used for timestamp adj. */
int check_dup=0; /* check for dup flag */
int gz_log=COMP_NONE; /* gziped log? (0=no) */
double t_xfer=0.0; /* monthly total xfer value */
u_int64_t t_hit=0,t_file=0,t_site=0, /* monthly total vars */
t_url=0,t_ref=0,t_agent=0,
t_page=0, t_visit=0, t_user=0;
double tm_xfer[31]; /* daily transfer totals */
u_int64_t tm_hit[31], tm_file[31], /* daily total arrays */
tm_site[31], tm_page[31],
tm_visit[31];
u_int64_t dt_site; /* daily 'sites' total */
u_int64_t ht_hit=0, mh_hit=0; /* hourly hits totals */
u_int64_t th_hit[24], th_file[24], /* hourly total arrays */
th_page[24];
double th_xfer[24];
int f_day,l_day; /* first/last day vars */
struct utsname system_info; /* system info structure */
u_int64_t ul_bogus =0; /* Dummy counter for groups */
struct log_struct log_rec; /* expanded log storage */
void *zlog_fp; /* compressed logfile ptr */
FILE *log_fp; /* regular logfile pointer */
char buffer[BUFSIZE]; /* log file record buffer */
char tmp_buf[BUFSIZE]; /* used to temp save above */
CLISTPTR *top_ctrys = NULL; /* Top countries table */
#define GZ_BUFSIZE 16384 /* our_getfs buffer size */
char f_buf[GZ_BUFSIZE]; /* our_getfs buffer */
char *f_cp=f_buf+GZ_BUFSIZE; /* pointer into the buffer */
int f_end=0; /* count to end of buffer */
char hit_color[] = "#00805c"; /* graph hit color */
char file_color[] = "#0040ff"; /* graph file color */
char site_color[] = "#ff8000"; /* graph site color */
char kbyte_color[] = "#ff0000"; /* graph kbyte color */
char page_color[] = "#00e0ff"; /* graph page color */
char visit_color[] = "#ffff00"; /* graph visit color */
char misc_color[] = "#00e0ff"; /* graph misc color */
char pie_color1[] = "#800080"; /* pie additionnal color 1 */
char pie_color2[] = "#80ffc0"; /* pie additionnal color 2 */
char pie_color3[] = "#ff00ff"; /* pie additionnal color 3 */
char pie_color4[] = "#ffc080"; /* pie additionnal color 4 */
/*********************************************/
/* MAIN - start here */
/*********************************************/
int main(int argc, char *argv[])
{
int i; /* generic counter */
char *cp1, *cp2, *cp3; /* generic char pointers */
char host_buf[MAXHOST+1]; /* used to save hostname */
NLISTPTR lptr; /* generic list pointer */
extern char *optarg; /* used for command line */
extern int optind; /* parsing routine 'getopt' */
extern int opterr;
time_t start_time, end_time; /* program timers */
float temp_time; /* temporary time storage */
int rec_year,rec_month=1,rec_day,rec_hour,rec_min,rec_sec;
int good_rec =0; /* 1 if we had a good record */
u_int64_t total_rec =0; /* Total Records Processed */
u_int64_t total_ignore=0; /* Total Records Ignored */
u_int64_t total_bad =0; /* Total Bad Records */
int max_ctry; /* max countries defined */
/* month names used for parsing logfile (shouldn't be lang specific) */
char *log_month[12]={ "jan", "feb", "mar",
"apr", "may", "jun",
"jul", "aug", "sep",
"oct", "nov", "dec"};
/* stat struct for files */
struct stat log_stat;
/* Assume that LC_CTYPE is what the user wants for non-ASCII chars */
setlocale(LC_CTYPE,"");
/* initalize epoch */
epoch=jdate(1,1,1970); /* used for timestamp adj. */
sprintf(tmp_buf,"%s/webalizer.conf",ETCDIR);
/* check for default config file */
if (!access("webalizer.conf",F_OK))
get_config("webalizer.conf");
else if (!access(tmp_buf,F_OK))
get_config(tmp_buf);
/* get command line options */
opterr = 0; /* disable parser errors */
while ((i=getopt(argc,argv,"a:A:bc:C:dD:e:E:fF:g:GhHiI:jJ:k:K:l:Lm:M:n:N:o:O:pP:qQr:R:s:S:t:Tu:U:vVwW:x:XYz:Z"))!=EOF)
{
switch (i)
{
case 'a': add_nlist(optarg,&hidden_agents); break; /* Hide agents */
case 'A': ntop_agents=atoi(optarg); break; /* Top agents */
case 'b': ignore_state=1; break; /* Ignore state file */
case 'c': get_config(optarg); break; /* Config file */
case 'C': ntop_ctrys=atoi(optarg); break; /* Top countries */
case 'd': debug_mode=1; break; /* Debug */
case 'D': dns_cache=optarg; break; /* DNS Cache filename */
case 'e': ntop_entry=atoi(optarg); break; /* Top entry pages */
case 'E': ntop_exit=atoi(optarg); break; /* Top exit pages */
case 'f': fold_seq_err=1; break; /* Fold sequence errs */
case 'F': log_type=(tolower(optarg[0])=='f')?
LOG_FTP:(tolower(optarg[0])=='s')?
LOG_SQUID:(tolower(optarg[0])=='w')?
LOG_W3C:LOG_CLF; break; /* define log type */
case 'g': group_domains=atoi(optarg); break; /* GroupDomains (0=no) */
case 'G': hourly_graph=0; break; /* no hourly graph */
case 'h': print_opts(argv[0]); break; /* help */
case 'H': hourly_stats=0; break; /* no hourly stats */
case 'i': ignore_hist=1; break; /* Ignore history */
case 'I': add_nlist(optarg,&index_alias); break; /* Index alias */
case 'j': geodb=1; break; /* Enable GeoDB */
case 'J': geodb_fname=optarg; break; /* GeoDB db filename */
case 'k': graph_mths=atoi(optarg); break; /* # months idx graph */
case 'K': index_mths=atoi(optarg); break; /* # months idx table */
case 'l': graph_lines=atoi(optarg); break; /* Graph Lines */
case 'L': graph_legend=0; break; /* Graph Legends */
case 'm': visit_timeout=atoi(optarg); break; /* Visit Timeout */
case 'M': mangle_agent=atoi(optarg); break; /* mangle user agents */
case 'n': hname=optarg; break; /* Hostname */
case 'N': dns_children=atoi(optarg); break; /* # of DNS children */
case 'o': out_dir=optarg; break; /* Output directory */
case 'O': add_nlist(optarg,&omit_page); break; /* pages not counted */
case 'p': incremental=1; break; /* Incremental run */
case 'P': add_nlist(optarg,&page_type); break; /* page view types */
case 'q': verbose=1; break; /* Quiet (verbose=1) */
case 'Q': verbose=0; break; /* Really Quiet */
case 'r': add_nlist(optarg,&hidden_refs); break; /* Hide referrer */
case 'R': ntop_refs=atoi(optarg); break; /* Top referrers */
case 's': add_nlist(optarg,&hidden_sites); break; /* Hide site */
case 'S': ntop_sites=atoi(optarg); break; /* Top sites */
case 't': msg_title=optarg; break; /* Report title */
case 'T': time_me=1; break; /* TimeMe */
case 'u': add_nlist(optarg,&hidden_urls); break; /* hide URL */
case 'U': ntop_urls=atoi(optarg); break; /* Top urls */
case 'v': verbose=2; debug_mode=1; break; /* Verbose */
case 'V': print_version(); break; /* Version */
#ifdef USE_GEOIP
case 'w': geoip=1; break; /* Enable GeoIP */
case 'W': geoip_db=optarg; break; /* GeoIP database name */
#endif
case 'x': html_ext=optarg; break; /* HTML file extension */
case 'X': hide_sites=1; break; /* Hide ind. sites */
case 'Y': ctry_graph=0; break; /* Supress ctry graph */
case 'Z': normalize=0; break; /* Dont normalize URLs */
case 'z': use_flags=1; flag_dir=optarg; break; /* Ctry flag dir */
}
}
if (argc - optind != 0) log_fname = argv[optind];
if ( log_fname && (log_fname[0]=='-')) log_fname=NULL; /* force STDIN? */
/* check for gzipped file - .gz */
if (log_fname) if (!strcmp((log_fname+strlen(log_fname)-3),".gz"))
gz_log=COMP_GZIP;
#ifdef USE_BZIP
/* check for bzip file - .bz2 */
if (log_fname) if (!strcmp((log_fname+strlen(log_fname)-4),".bz2"))
gz_log=COMP_BZIP;
#endif
/* setup our internal variables */
init_counters(); /* initalize (zero) main counters */
memset(hist, 0, sizeof(hist)); /* initalize (zero) history array */
/* add default index. alias if needed */
if (default_index) add_nlist("index.",&index_alias);
if (page_type==NULL) /* check if page types present */
{
if ((log_type==LOG_CLF)||(log_type==LOG_SQUID)||(log_type==LOG_W3C))
{
add_nlist("htm*" ,&page_type); /* if no page types specified, we */
add_nlist("cgi" ,&page_type); /* use the default ones here... */
if (!isinlist(page_type,html_ext)) add_nlist(html_ext,&page_type);
}
else add_nlist("txt" ,&page_type); /* FTP logs default to .txt */
}
for (max_ctry=0;ctry[max_ctry].desc;max_ctry++);
if (ntop_ctrys > max_ctry) ntop_ctrys = max_ctry; /* force upper limit */
if (graph_lines> 20) graph_lines= 20; /* keep graphs sane! */
if (graph_mths<12) graph_mths=12;
if (graph_mths>GRAPHMAX) graph_mths=GRAPHMAX;
if (index_mths<12) index_mths=12;
if (index_mths>HISTSIZE) index_mths=HISTSIZE;
if (log_type == LOG_FTP)
{
/* disable stuff for ftp logs */
ntop_entry=ntop_exit=0;
ntop_search=0;
}
else
{
if (search_list==NULL)
{
/* If no search engines defined, define some :) */
add_glist(".google. q=" ,&search_list);
add_glist("yahoo.com p=" ,&search_list);
add_glist("altavista.com q=" ,&search_list);
add_glist("aolsearch. query=" ,&search_list);
add_glist("ask.co q=" ,&search_list);
add_glist("eureka.com q=" ,&search_list);
add_glist("lycos.com query=" ,&search_list);
add_glist("hotbot.com MT=" ,&search_list);
add_glist("msn.com q=" ,&search_list);
add_glist("infoseek.com qt=" ,&search_list);
add_glist("webcrawler searchText=" ,&search_list);
add_glist("excite search=" ,&search_list);
add_glist("netscape.com query=" ,&search_list);
add_glist("mamma.com query=" ,&search_list);
add_glist("alltheweb.com q=" ,&search_list);
add_glist("northernlight.com qr=" ,&search_list);
}
}
/* ensure entry/exits don't exceed urls */
i=(ntop_urls>ntop_urlsK)?ntop_urls:ntop_urlsK;
if (ntop_entry>i) ntop_entry=i;
if (ntop_exit>i) ntop_exit=i;
for (i=0;i<MAXHASH;i++)
{
sm_htab[i]=sd_htab[i]=NULL; /* initalize hash tables */
um_htab[i]=NULL;
rm_htab[i]=NULL;
am_htab[i]=NULL;
sr_htab[i]=NULL;
}
/* Be polite and announce yourself... */
if (verbose>1)
{
uname(&system_info);
printf("Webalizer V%s-%s (%s %s %s) %s\n", version,editlvl,
system_info.sysname, system_info.release,
system_info.machine,language);
}
#ifndef USE_DNS
if (strstr(argv[0],"webazolver")!=0)
/* DNS support not present, aborting... */
{ printf("%s\n",msg_dns_abrt); exit(1); }
#else
/* Force sane values for cache TTL */
if (cache_ttl<1) cache_ttl=1;
if (cache_ttl>100) cache_ttl=100;
#endif /* USE_DNS */
/* open log file */
if (log_fname)
{
/* stat the file */
if ( !(lstat(log_fname, &log_stat)) )
{
/* check if the file a symlink */
if ( S_ISLNK(log_stat.st_mode) )
{
if (verbose)
fprintf(stderr,"%s %s (symlink)\n",msg_log_err,log_fname);
exit(EBADF);
}
}
if (gz_log)
{
/* open compressed file */
#ifdef USE_BZIP
if (gz_log==COMP_BZIP)
zlog_fp = BZ2_bzopen(log_fname,"rb");
else
#endif
zlog_fp = gzopen(log_fname, "rb");
if (zlog_fp==Z_NULL)
{
/* Error: Can't open log file ... */
fprintf(stderr, "%s %s (%d)\n",msg_log_err,log_fname,ENOENT);
exit(ENOENT);
}
}
else
{
/* open regular file */
log_fp = fopen(log_fname,"r");
if (log_fp==NULL)
{
/* Error: Can't open log file ... */
fprintf(stderr, "%s %s\n",msg_log_err,log_fname);
exit(1);
}
}
}
/* Using logfile ... */
if (verbose>1)
{
printf("%s %s (",msg_log_use,log_fname?log_fname:"STDIN");
if (gz_log==COMP_GZIP) printf("gzip-");
#ifdef USE_BZIP
if (gz_log==COMP_BZIP) printf("bzip-");
#endif
switch (log_type)
{
/* display log file type hint */
case LOG_CLF: printf("clf)\n"); break;
case LOG_FTP: printf("ftp)\n"); break;
case LOG_SQUID: printf("squid)\n"); break;
case LOG_W3C: printf("w3c)\n"); break;
}
}
/* switch directories if needed */
if (out_dir)
{
if (chdir(out_dir) != 0)
{
/* Error: Can't change directory to ... */
fprintf(stderr, "%s %s\n",msg_dir_err,out_dir);
exit(1);
}
}
#ifdef USE_DNS
if (strstr(argv[0],"webazolver")!=0)
{
if (!dns_children) dns_children=5; /* default dns children if needed */
if (!dns_cache)
{
/* No cache file specified, aborting... */
fprintf(stderr,"%s\n",msg_dns_nocf); /* Must have a cache file */
exit(1);
}
}
if (dns_cache && dns_children) /* run-time resolution */
{
if (dns_children > MAXCHILD) dns_children=MAXCHILD;
/* DNS Lookup (#children): */
if (verbose>1) printf("%s (%d): ",msg_dns_rslv,dns_children);
fflush(stdout);
(gz_log)?dns_resolver(zlog_fp):dns_resolver(log_fp);
#ifdef USE_BZIP
(gz_log==COMP_BZIP)?bz2_rewind(&zlog_fp, log_fname, "rb"):
#endif
(gz_log==COMP_GZIP)?gzrewind(zlog_fp):
(log_fname)?rewind(log_fp):exit(0);
}
if (strstr(argv[0],"webazolver")!=0) exit(0); /* webazolver exits here */
if (dns_cache)
{
if (!open_cache()) { dns_cache=NULL; dns_db=NULL; }
else
{
/* Using DNS cache file <filaneme> */
if (verbose>1) printf("%s %s\n",msg_dns_usec,dns_cache);
}
}
/* Open GeoDB? */
if (geodb)
{
geo_db=geodb_open(geodb_fname);
if (geo_db==NULL)
{
if (verbose) printf("%s: %s\n",msg_geo_open,
(geodb_fname)?geodb_fname:msg_geo_dflt);
if (verbose) printf("GeoDB %s\n",msg_geo_nolu);
geodb=0;
}
else if (verbose>1) printf("%s %s\n",
msg_geo_use,geodb_ver(geo_db,buffer));
#ifdef USE_GEOIP
if (geoip) geoip=0; /* Disable GeoIP if using GeoDB */
#endif
}
#endif /* USE_DNS */
#ifdef USE_GEOIP
/* open GeoIP database */
if (geoip)
{
if (geoip_db != NULL) {
int mmdb_status = MMDB_open(geoip_db, 0, &geo_fp);
if (mmdb_status != MMDB_SUCCESS) {
geoip = 0;
if (verbose) {
printf("MMDB_open failed: %s\n", MMDB_strerror(mmdb_status));
}
}
} else {
geoip = 0;
if (verbose) {
printf("No GeoIP database defined\n");
}
}
}
#endif /* USE_GEOIP */
/* Creating output in ... */
if (verbose>1)
printf("%s %s\n",msg_dir_use,out_dir?out_dir:msg_cur_dir);
/* prep hostname */
if (!hname)
{
if (uname(&system_info)) hname="localhost";
else hname=system_info.nodename;
}
/* Hostname for reports is ... */
if (strlen(hname)) if (verbose>1) printf("%s '%s'\n",msg_hostname,hname);
/* get past history */
if (ignore_hist) { if (verbose>1) printf("%s\n",msg_ign_hist); }
else get_history();
if (incremental) /* incremental processing? */
{
if ((i=restore_state())) /* restore internal data structs */
{
/* Error: Unable to restore run data (error num) */
/* if (verbose) fprintf(stderr,"%s (%d)\n",msg_bad_data,i); */
fprintf(stderr,"%s (%d)\n",msg_bad_data,i);
exit(1);
}
}
/* Allocate memory for our TOP countries array */
if (ntop_ctrys != 0)
{ if ( (top_ctrys=calloc(ntop_ctrys,sizeof(CLISTPTR))) == NULL)
/* Can't get memory, Top Countries disabled! */
{if (verbose) fprintf(stderr,"%s\n",msg_nomem_tc); ntop_ctrys=0;}}
/* get processing start time */
start_time = time(NULL);
/*********************************************/
/* MAIN PROCESS LOOP - read through log file */
/*********************************************/
while ( (gz_log)?(our_gzgets(zlog_fp,buffer,BUFSIZE) != Z_NULL):
(fgets(buffer,BUFSIZE,log_fname?log_fp:stdin) != NULL))
{
total_rec++;
if (strlen(buffer) == (BUFSIZE-1))
{
if (verbose)
{
fprintf(stderr,"%s",msg_big_rec);
if (debug_mode) fprintf(stderr,":\n%s",buffer);
else fprintf(stderr,"\n");
}
total_bad++; /* bump bad record counter */
/* get the rest of the record */
while ( (gz_log)?(our_gzgets(zlog_fp,buffer,BUFSIZE)!=Z_NULL):
(fgets(buffer,BUFSIZE,log_fname?log_fp:stdin)!=NULL))
{
if (strlen(buffer) < BUFSIZE-1)
{
if (debug_mode && verbose) fprintf(stderr,"%s\n",buffer);
break;
}
if (debug_mode && verbose) fprintf(stderr,"%s",buffer);
}
continue; /* go get next record if any */
}
/* got a record... */
strcpy(tmp_buf, buffer); /* save buffer in case of error */
if (parse_record(buffer)) /* parse the record */
{
/*********************************************/
/* PASSED MINIMAL CHECKS, DO A LITTLE MORE */
/*********************************************/
/* convert month name to lowercase */
for (i=4;i<7;i++)
log_rec.datetime[i]=tolower(log_rec.datetime[i]);
/* lowercase sitename/IPv6 addresses */
cp1=log_rec.hostname;
while (*cp1++!='\0') *cp1=tolower(*cp1);
/* get year/month/day/hour/min/sec values */
for (i=0;i<12;i++)
{
if (strncmp(log_month[i],&log_rec.datetime[4],3)==0)
{ rec_month = i+1; break; }
}
rec_year=atoi(&log_rec.datetime[8]); /* get year number (int) */
rec_day =atoi(&log_rec.datetime[1]); /* get day number */
rec_hour=atoi(&log_rec.datetime[13]); /* get hour number */
rec_min =atoi(&log_rec.datetime[16]); /* get minute number */
rec_sec =atoi(&log_rec.datetime[19]); /* get second number */
/* Kludge for Netscape server time (0-24?) error */
if (rec_hour>23) rec_hour=0;
/* minimal sanity check on date */
if ((i>=12)||(rec_min>59)||(rec_sec>60)||(rec_year<1990))
{
total_bad++; /* if a bad date, bump counter */
if (verbose)
{
fprintf(stderr,"%s: %s [%"PRIu64"]",
msg_bad_date,log_rec.datetime,total_rec);
if (debug_mode) fprintf(stderr,":\n%s\n",tmp_buf);
else fprintf(stderr,"\n");
}
continue; /* and ignore this record */
}
/*********************************************/
/* GOOD RECORD, CHECK INCREMENTAL/TIMESTAMPS */
/*********************************************/
/* Flag as a good one */
good_rec = 1;
/* get current records timestamp (seconds since epoch) */
req_tstamp=cur_tstamp;
rec_tstamp=((jdate(rec_day,rec_month,rec_year)-epoch)*86400)+
(rec_hour*3600)+(rec_min*60)+rec_sec;
/* Do we need to check for duplicate records? (incremental mode) */
if (check_dup)
{
/* check if less than/equal to last record processed */
if ( rec_tstamp <= cur_tstamp )
{
/* if it is, assume we have already processed and ignore it */
total_ignore++;
continue;
}
else
{
/* if it isn't.. disable any more checks this run */
check_dup=0;
/* now check if it's a new month */
if ( (cur_month != rec_month) || (cur_year != rec_year) )
{
clear_month();
cur_sec = rec_sec; /* set current counters */
cur_min = rec_min;
cur_hour = rec_hour;
cur_day = rec_day;
cur_month = rec_month;
cur_year = rec_year;
cur_tstamp= rec_tstamp;
f_day=l_day=rec_day; /* reset first and last day */
}
}
}
/* check for out of sequence records */
if (rec_tstamp/3600 < cur_tstamp/3600)
{
if (!fold_seq_err && ((rec_tstamp+SLOP_VAL)/3600<cur_tstamp/3600) )
{ total_ignore++; continue; }
else
{
rec_sec = cur_sec; /* if folding sequence */
rec_min = cur_min; /* errors, just make it */
rec_hour = cur_hour; /* look like the last */
rec_day = cur_day; /* good records timestamp */
rec_month = cur_month;
rec_year = cur_year;
rec_tstamp= cur_tstamp;
}
}
cur_tstamp=rec_tstamp; /* update current timestamp */
/*********************************************/
/* DO SOME PRE-PROCESS FORMATTING */
/*********************************************/
/* un-escape URL */
unescape(log_rec.url);
/* fix URL field */
cp1 = cp2 = log_rec.url;
/* handle null '-' case here... */
if (*++cp1 == '-') strcpy(log_rec.url,"/INVALID-URL");
else
{
/* strip actual URL out of request */
while ( (*cp1 != ' ') && (*cp1 != '\0') ) cp1++;
if (*cp1 != '\0')
{
/* scan to begin of actual URL field */
while ((*cp1 == ' ') && (*cp1 != '\0')) cp1++;
/* remove duplicate / if needed */
while (( *cp1=='/') && (*(cp1+1)=='/')) cp1++;
while (( *cp1!='\0')&&(*cp1!='"')) *cp2++=*cp1++;
*cp2='\0';
}
}
/* strip query portion of cgi scripts */
cp1 = log_rec.url;
while (*cp1 != '\0')
if (!isurlchar(*cp1, stripcgi)) { *cp1 = '\0'; break; }
else cp1++;
if (log_rec.url[0]=='\0')
{ log_rec.url[0]='/'; log_rec.url[1]='\0'; }
/* Normalize URL */
if (log_type==LOG_CLF && log_rec.resp_code!=RC_NOTFOUND && normalize)
{
if ( ((cp2=strstr(log_rec.url,"://"))!=NULL)&&(cp2<log_rec.url+6) )
{
cp1=cp2+3;
/* see if a '/' is present after it */
if ( (cp2=strchr(cp1,(int)'/'))==NULL) cp1--;
else cp1=cp2;
/* Ok, now shift url string */
cp2=log_rec.url; while (*cp1!='\0') *cp2++=*cp1++; *cp2='\0';
}
/* extra sanity checks on URL string */
while ((cp2=strstr(log_rec.url,"/./")))
{ cp1=cp2+2; while (*cp1!='\0') *cp2++=*cp1++; *cp2='\0'; }
if (log_rec.url[0]!='/')
{
if ( log_rec.resp_code==RC_OK ||
log_rec.resp_code==RC_PARTIALCONTENT ||
log_rec.resp_code==RC_NOMOD)
{
if (debug_mode)
fprintf(stderr,"Converted URL '%s' to '/'\n",log_rec.url);
log_rec.url[0]='/';
log_rec.url[1]='\0';
}
else
{
if (debug_mode)
fprintf(stderr,"Invalid URL: '%s'\n",log_rec.url);
strcpy(log_rec.url,"/INVALID-URL");
}
}
while ( log_rec.url[ (i=strlen(log_rec.url)-1) ] == '?' )
log_rec.url[i]='\0'; /* drop trailing ?s if any */
}
else
{
/* check for service (ie: http://) and lowercase if found */
if (((cp2=strstr(log_rec.url,"://"))!= NULL)&&(cp2<log_rec.url+6))
{
cp1=log_rec.url;
while (cp1!=cp2)
{
if ( (*cp1>='A') && (*cp1<='Z')) *cp1 += 'a'-'A';
cp1++;
}
}
}
/* strip off index.html (or any aliases) */
lptr=index_alias;
while (lptr!=NULL)
{
if ((cp1=strstr(log_rec.url,lptr->string))!=NULL)
{
if (*(cp1-1)=='/')
{
if ( !stripcgi && (cp2=strchr(cp1,'?'))!=NULL )
{ while(*cp2) *cp1++=*cp2++; *cp1='\0'; }
else *cp1='\0';
break;
}
}
lptr=lptr->next;
}
/* unescape referrer */
unescape(log_rec.refer);
/* fix referrer field */
cp1 = log_rec.refer;
cp3 = cp2 = cp1++;
if ( (*cp2 != '\0') && (*cp2 == '"') )
{
while ( *cp1 != '\0' )
{
cp3=cp2;
if (((unsigned char)*cp1<32&&(unsigned char)*cp1>0) ||
*cp1==127 || (unsigned char)*cp1=='<') *cp1=0;
else *cp2++=*cp1++;
}
*cp3 = '\0';
}
/* get query portion of cgi referrals */
cp1 = log_rec.refer;
if (*cp1 != '\0')
{
while (*cp1 != '\0')
{
if (!isurlchar(*cp1, 1))
{
/* Save query portion in log.rec.srchstr */
strncpy(log_rec.srchstr,(char *)cp1,MAXSRCH);
log_rec.srchstr[MAXSRCH - 1] = '\0';
*cp1++='\0';
break;
}
else cp1++;
}
/* handle null referrer */
if (log_rec.refer[0]=='\0')
{ log_rec.refer[0]='-'; log_rec.refer[1]='\0'; }
}
/* if HTTP request, lowercase http://sitename/ portion */
cp1 = log_rec.refer;
if ( (*cp1=='h') || (*cp1=='H'))
{
while ( (*cp1!='/') && (*cp1!='\0'))
{
if ( (*cp1>='A') && (*cp1<='Z')) *cp1 += 'a'-'A';
cp1++;
}
/* now do hostname */
if ( (*cp1=='/') && ( *(cp1+1)=='/')) {cp1++; cp1++;}
while ( (*cp1!='/') && (*cp1!='\0'))
{
if ( (*cp1>='A') && (*cp1<='Z')) *cp1 += 'a'-'A';
cp1++;
}
}
/* Do we need to mangle? */
if (mangle_agent) agent_mangle(log_rec.agent);
/* if necessary, shrink referrer to fit storage */
if (strlen(log_rec.refer)>=MAXREFH)
{
if (verbose) fprintf(stderr,"%s [%"PRIu64"]\n",
msg_big_ref,total_rec);
log_rec.refer[MAXREFH-1]='\0';
}
/* if necessary, shrink URL to fit storage */
if (strlen(log_rec.url)>=MAXURLH)
{
if (verbose) fprintf(stderr,"%s [%"PRIu64"]\n",
msg_big_req,total_rec);
log_rec.url[MAXURLH-1]='\0';
}
/* fix user agent field */
cp1 = log_rec.agent;
cp3 = cp2 = cp1++;
if ( (*cp2 != '\0') && ((*cp2 == '"')||(*cp2 == '(')) )
{
while (*cp1 != '\0') { cp3 = cp2; *cp2++ = *cp1++; }
*cp3 = '\0';
}
cp1 = log_rec.agent; /* CHANGE !!! */