]> git.ipfire.org Git - thirdparty/sarg.git/blame - readlog.c
Indent the configure script for more readability.
[thirdparty/sarg.git] / readlog.c
CommitLineData
27d1fa35
FM
1/*
2 * SARG Squid Analysis Report Generator http://sarg.sourceforge.net
110ce984 3 * 1998, 2015
27d1fa35
FM
4 *
5 * SARG donations:
6 * please look at http://sarg.sourceforge.net/donations.php
7 * Support:
8 * http://sourceforge.net/projects/sarg/forums/forum/363374
9 * ---------------------------------------------------------------------
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
24 *
25 */
26
27#include "include/conf.h"
28#include "include/defs.h"
29#include "include/readlog.h"
6068ae56 30#include "include/filelist.h"
27d1fa35
FM
31
32#define REPORT_EVERY_X_LINES 5000
33#define MAX_OPEN_USER_FILES 10
34
35struct userfilestruct
36{
37 struct userfilestruct *next;
38 struct userinfostruct *user;
39 FILE *file;
40};
41
7c8c06c5
FM
42enum ExcludeReasonEnum
43{
44 //! User name too long.
45 ER_UserNameTooLong,
46 //! Squid logged an incomplete query received from the client.
47 ER_IncompleteQuery,
48 //! Log file turned over.
49 ER_LogfileTurnedOver,
7c8c06c5
FM
50 //! Excluded by exclude_string from sarg.conf.
51 ER_ExcludeString,
52 //! Unknown input log file format.
53 ER_UnknownFormat,
54 //! Line to be ignored from the input log file.
55 ER_FormatData,
56 //! Entry not withing the requested date range.
57 ER_OutOfDateRange,
58 //! Ignored week day.
59 ER_OutOfWDayRange,
60 //! Ignored hour.
61 ER_OutOfHourRange,
62 //! User is not in the include_users list.
63 ER_User,
64 //! HTTP code excluded by exclude_code file.
65 ER_HttpCode,
66 //! Invalid character found in user name.
67 ER_InvalidUserChar,
68 //! No URL in entry.
69 ER_NoUrl,
70 //! Not the IP address requested with -a.
71 ER_UntrackedIpAddr,
72 //! URL excluded by -c or exclude_hosts.
73 ER_Url,
74 //! Entry time outside of requested hour range.
75 ER_OutOfTimeRange,
76 //! Not the URL requested by -s.
77 ER_UntrackedUrl,
78 //! No user in entry.
79 ER_NoUser,
80 //! Not the user requested by -u.
81 ER_UntrackedUser,
82 //! System user.
83 ER_SysUser,
84 //! User ignored by exclude_users
85 ER_IgnoredUser,
86
87 ER_Last //!< last entry of the list
88};
89
27d1fa35
FM
90numlist weekdays = { { 0, 1, 2, 3, 4, 5, 6 }, 7 };
91numlist hours = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }, 24 };
92
27d1fa35 93extern char *userfile;
6068ae56 94extern FileListObject AccessLog;
27d1fa35 95
1c91da07
FM
96extern const struct ReadLogProcessStruct ReadSquidLog;
97extern const struct ReadLogProcessStruct ReadCommonLog;
98extern const struct ReadLogProcessStruct ReadSargLog;
99extern const struct ReadLogProcessStruct ReadExtLog;
100
101//! The list of the supported log formats.
102static const struct ReadLogProcessStruct const *LogFormats[]=
103{
104 &ReadSquidLog,
105 &ReadCommonLog,
106 &ReadSargLog,
107 &ReadExtLog
108};
109
944cf283
FM
110//! The path to the sarg log file.
111static char SargLogFile[4096]="";
112//! Handle to the sarg log file. NULL if not created.
113static FILE *fp_log=NULL;
114//! The number of records read from the input logs.
115static long int totregsl=0;
116//! The number of records kept.
117static long int totregsg=0;
118//! The number of records excluded.
119static long int totregsx=0;
120//! The beginning of a linked list of user's file.
121static struct userfilestruct *first_user_file=NULL;
122//! Count the number of occurence of each input log format.
8e501bd6 123static unsigned long int format_count[sizeof(LogFormats)/sizeof(*LogFormats)];
944cf283
FM
124//! The minimum date found in the input logs.
125static int mindate=0;
126static int maxdate=0;
7c8c06c5
FM
127//! Count the number of excluded records.
128static unsigned long int excluded_count[ER_Last];
6a943fc1
FM
129//! Earliest date found in the log.
130static int EarliestDate=-1;
131//! The earliest date in time format.
132static struct tm EarliestDateTime;
133//! Latest date found in the log.
134static int LatestDate=-1;
135//! The latest date in time format.
136static struct tm LatestDateTime;
27d1fa35 137
800eafb8
FM
138/*!
139 * Read from standard input.
140 *
141 * \param Data The file object.
142 * \param Buffer The boffer to store the data read.
143 * \param Size How many bytes to read.
144 *
145 * \return The number of bytes read.
146 */
147static int Stdin_Read(void *Data,void *Buffer,int Size)
148{
149 return(fread(Buffer,1,Size,(FILE *)Data));
150}
151
152/*!
153 * Check if end of file is reached.
154 *
155 * \param Data The file object.
156 *
157 * \return \c True if end of file is reached.
158 */
159static int Stdin_Eof(void *Data)
160{
161 return(feof((FILE *)Data));
162}
163
164/*!
165 * Mimic a close of standard input but do nothing
166 *
167 * \param Data File to close.
168 *
169 * \return EOF on error.
170 */
171static int Stdin_Close(void *Data)
172{
173 return(0);
174}
175
176/*!
177 * Open a file object to read from standard input.
178 *
179 * \return The object to pass to other function in this module.
180 */
181static FileObject *Stdin_Open(void)
182{
183 FileObject *File;
184
185 FileObject_SetLastOpenError(NULL);
186 File=calloc(1,sizeof(*File));
187 if (!File)
188 {
189 FileObject_SetLastOpenError(_("Not enough memory"));
190 return(NULL);
191 }
192 File->Data=stdin;
193 File->Read=Stdin_Read;
194 File->Eof=Stdin_Eof;
195 File->Rewind=NULL;
196 File->Close=Stdin_Close;
197 return(File);
198}
199
8b4e9578
FM
200/*!
201 * Initialize the memory structure needed by LogLine_Parse() to parse
202 * a log line.
203 *
204 * \param log_line The structure to initialize.
205 */
206void LogLine_Init(struct LogLineStruct *log_line)
207{
208 log_line->current_format=NULL;
209 log_line->current_format_idx=-1;
210 log_line->file_name="";
211 log_line->successive_errors=0;
212 log_line->total_errors=0;
213}
214
215/*!
216 * Set the name of the log file being parsed.
217 *
218 * \param log_line Data structure to parse the log line.
219 * \param file_name The name of the log file being read.
220 */
221void LogLine_File(struct LogLineStruct *log_line,const char *file_name)
222{
223 log_line->file_name=file_name;
224}
225
226/*!
227 * Parse the next line from a log file.
228 *
229 * \param log_line A buffer to store the data about the current parsing.
230 * \param log_entry The variable to store the parsed data.
231 * \param linebuf The text line read from the log file.
232 *
233 * \return
234 */
235enum ReadLogReturnCodeEnum LogLine_Parse(struct LogLineStruct *log_line,struct ReadLogStruct *log_entry,char *linebuf)
236{
237 enum ReadLogReturnCodeEnum log_entry_status=RLRC_Unknown;
238 int x;
239
240 if (log_line->current_format)
241 {
242 memset(log_entry,0,sizeof(*log_entry));
243 log_entry_status=log_line->current_format->ReadEntry(linebuf,log_entry);
244 }
245
246 // find out what line format to use
247 if (log_entry_status==RLRC_Unknown)
248 {
249 for (x=0 ; x<(int)(sizeof(LogFormats)/sizeof(*LogFormats)) ; x++)
250 {
251 if (LogFormats[x]==log_line->current_format) continue;
252 memset(log_entry,0,sizeof(*log_entry));
253 log_entry_status=LogFormats[x]->ReadEntry(linebuf,log_entry);
254 if (log_entry_status!=RLRC_Unknown)
255 {
256 log_line->current_format=LogFormats[x];
257 log_line->current_format_idx=x;
258 if (debugz>=LogLevel_Process)
259 {
260 /* TRANSLATORS: The argument is the log format name as translated by you. */
af961877 261 debuga(__FILE__,__LINE__,_("Log format identified as \"%s\" for %s\n"),_(log_line->current_format->Name),log_line->file_name);
8b4e9578
FM
262 }
263 break;
264 }
265 }
266 if (x>=(int)(sizeof(LogFormats)/sizeof(*LogFormats)))
267 {
268 if (++log_line->successive_errors>NumLogSuccessiveErrors) {
af961877 269 debuga(__FILE__,__LINE__,ngettext("%d consecutive error found in the input log file %s\n",
8b4e9578
FM
270 "%d consecutive errors found in the input log file %s\n",log_line->successive_errors),log_line->successive_errors,log_line->file_name);
271 exit(EXIT_FAILURE);
272 }
273 if (NumLogTotalErrors>=0 && ++log_line->total_errors>NumLogTotalErrors) {
af961877 274 debuga(__FILE__,__LINE__,ngettext("%d error found in the input log file (last in %s)\n",
8b4e9578
FM
275 "%d errors found in the input log file (last in %s)\n",log_line->total_errors),log_line->total_errors,log_line->file_name);
276 exit(EXIT_FAILURE);
277 }
af961877 278 debuga(__FILE__,__LINE__,_("The following line read from %s could not be parsed and is ignored\n%s\n"),log_line->file_name,linebuf);
8b4e9578
FM
279 }
280 else
281 log_line->successive_errors=0;
282 }
283
284 if (log_line->current_format_idx<0 || log_line->current_format==NULL) {
af961877 285 debuga(__FILE__,__LINE__,_("Sarg failed to determine the format of the input log file %s\n"),log_line->file_name);
8b4e9578
FM
286 exit(EXIT_FAILURE);
287 }
288 if (log_entry_status==RLRC_InternalError) {
af961877 289 debuga(__FILE__,__LINE__,_("Internal error encountered while processing %s\nSee previous message to know the reason for that error.\n"),log_line->file_name);
8b4e9578
FM
290 exit(EXIT_FAILURE);
291 }
292 return(log_entry_status);
293}
294
944cf283
FM
295/*!
296Read a single log file.
27d1fa35 297
944cf283 298\param arq The log file name to read.
27d1fa35 299*/
944cf283 300static void ReadOneLogFile(struct ReadLogDataStruct *Filter,const char *arq)
27d1fa35 301{
27d1fa35
FM
302 longline line;
303 char *linebuf;
304 char *str;
27d1fa35 305 char hora[30];
c5d6ef4b 306 char dia[128]="";
27d1fa35 307 char wuser[MAXLEN];
944cf283 308 char tmp3[MAXLEN]="";
27d1fa35
FM
309 char download_url[MAXLEN];
310 char smartfilter[MAXLEN];
27d1fa35 311 const char *url;
dc34d345 312 const char *user;
27d1fa35
FM
313 int OutputNonZero = REPORT_EVERY_X_LINES ;
314 int idata=0;
27d1fa35
FM
315 int x;
316 int hmr;
317 int nopen;
318 int maxopenfiles=MAX_OPEN_USER_FILES;
27d1fa35
FM
319 unsigned long int recs1=0UL;
320 unsigned long int recs2=0UL;
800eafb8 321 FileObject *fp_in=NULL;
27d1fa35
FM
322 bool download_flag=false;
323 bool id_is_ip;
1c91da07 324 enum ReadLogReturnCodeEnum log_entry_status;
27d1fa35
FM
325 struct stat logstat;
326 struct getwordstruct gwarea;
27d1fa35
FM
327 struct userfilestruct *prev_ufile;
328 struct userinfostruct *uinfo;
27d1fa35
FM
329 struct userfilestruct *ufile;
330 struct userfilestruct *ufile1;
c5d6ef4b 331 struct ReadLogStruct log_entry;
8b4e9578 332 struct LogLineStruct log_line;
27d1fa35 333
8b4e9578
FM
334 LogLine_Init(&log_line);
335 LogLine_File(&log_line,arq);
944cf283
FM
336 for (x=0 ; x<sizeof(LogFormats)/sizeof(*LogFormats) ; x++)
337 if (LogFormats[x]->NewFile)
338 LogFormats[x]->NewFile(arq);
27d1fa35 339
944cf283 340 if (arq[0]=='-' && arq[1]=='\0') {
800eafb8 341 fp_in=Stdin_Open();
944cf283 342 if(debug)
af961877 343 debuga(__FILE__,__LINE__,_("Reading access log file: from stdin\n"));
944cf283
FM
344 } else {
345 if (Filter->DateRange[0]!='\0') {
346 if (stat(arq,&logstat)!=0) {
af961877 347 debuga(__FILE__,__LINE__,_("Cannot get the modification time of input log file %s (%s). Processing it anyway\n"),arq,strerror(errno));
944cf283
FM
348 } else {
349 struct tm *logtime=localtime(&logstat.st_mtime);
350 if ((logtime->tm_year+1900)*10000+(logtime->tm_mon+1)*100+logtime->tm_mday<dfrom) {
af961877 351 debuga(__FILE__,__LINE__,_("Ignoring old log file %s\n"),arq);
944cf283 352 return;
27d1fa35
FM
353 }
354 }
27d1fa35 355 }
800eafb8
FM
356 fp_in=decomp(arq);
357 if (fp_in==NULL) {
358 debuga(__FILE__,__LINE__,_("Cannot open input log file \"%s\": %s\n"),arq,FileObject_GetLastOpenError());
944cf283
FM
359 exit(EXIT_FAILURE);
360 }
800eafb8 361 if (debug) debuga(__FILE__,__LINE__,_("Reading access log file: %s\n"),arq);
944cf283 362 }
27d1fa35 363
944cf283 364 download_flag=false;
27d1fa35 365
944cf283
FM
366 recs1=0UL;
367 recs2=0UL;
2f4787e6 368
944cf283 369 // pre-read the file only if we have to show stats
800eafb8 370 if (ShowReadStatistics && ShowReadPercent && fp_in->Rewind) {
944cf283
FM
371 size_t nread,i;
372 bool skipcr=false;
373 char tmp4[MAXLEN];
27d1fa35 374
800eafb8 375 while ((nread=FileObject_Read(fp_in,tmp4,sizeof(tmp4)))>0) {
944cf283
FM
376 for (i=0 ; i<nread ; i++)
377 if (skipcr) {
378 if (tmp4[i]!='\n' && tmp4[i]!='\r') {
379 skipcr=false;
27d1fa35 380 }
944cf283
FM
381 } else {
382 if (tmp4[i]=='\n' || tmp4[i]=='\r') {
383 skipcr=true;
384 recs1++;
385 }
386 }
27d1fa35 387 }
800eafb8 388 FileObject_Rewind(fp_in);
944cf283
FM
389 printf(_("SARG: Records in file: %lu, reading: %3.2f%%"),recs1,(float) 0);
390 putchar('\r');
391 fflush( stdout ) ;
392 }
27d1fa35 393
944cf283 394 if ((line=longline_create())==NULL) {
af961877 395 debuga(__FILE__,__LINE__,_("Not enough memory to read file \"%s\"\n"),arq);
944cf283
FM
396 exit(EXIT_FAILURE);
397 }
27d1fa35 398
944cf283 399 while ((linebuf=longline_read(fp_in,line))!=NULL) {
944cf283 400 lines_read++;
27d1fa35 401
944cf283
FM
402 recs2++;
403 if (ShowReadStatistics && --OutputNonZero<=0) {
404 if (recs1>0) {
405 double perc = recs2 * 100. / recs1 ;
406 printf(_("SARG: Records in file: %lu, reading: %3.2lf%%"),recs2,perc);
407 } else {
408 printf(_("SARG: Records in file: %lu"),recs2);
27d1fa35 409 }
944cf283
FM
410 putchar('\r');
411 fflush (stdout);
412 OutputNonZero = REPORT_EVERY_X_LINES ;
413 }
0c87646f 414
944cf283
FM
415 /*
416 The following checks are retained here as I don't know to
417 what format they apply. They date back to pre 2.4 versions.
418 */
419 //if(blen < 58) continue; //this test conflict with the reading of the sarg log header line
7c8c06c5
FM
420 if(strstr(linebuf,"HTTP/0.0") != 0) {//recorded by squid when encountering an incomplete query
421 excluded_count[ER_IncompleteQuery]++;
422 continue;
423 }
424 if(strstr(linebuf,"logfile turned over") != 0) {//reported by newsyslog
425 excluded_count[ER_LogfileTurnedOver]++;
426 continue;
427 }
944cf283
FM
428
429 // exclude_string
430 if(ExcludeString[0] != '\0') {
431 bool exstring=false;
432 getword_start(&gwarea,ExcludeString);
433 while(strchr(gwarea.current,':') != 0) {
434 if (getword_multisep(val1,sizeof(val1),&gwarea,':')<0) {
af961877 435 debuga(__FILE__,__LINE__,_("Invalid record in exclusion string\n"));
944cf283 436 exit(EXIT_FAILURE);
27d1fa35 437 }
944cf283 438 if((str=(char *) strstr(linebuf,val1)) != (char *) NULL ) {
27d1fa35 439 exstring=true;
944cf283
FM
440 break;
441 }
27d1fa35 442 }
944cf283
FM
443 if(!exstring && (str=(char *) strstr(linebuf,gwarea.current)) != (char *) NULL )
444 exstring=true;
7c8c06c5
FM
445 if(exstring) {
446 excluded_count[ER_ExcludeString]++;
447 continue;
448 }
944cf283 449 }
27d1fa35 450
944cf283 451 totregsl++;
4246ae8d 452 if (debugz>=LogLevel_Data)
944cf283 453 printf("BUF=%s\n",linebuf);
27d1fa35 454
944cf283 455 // process the line
8b4e9578
FM
456 log_entry_status=LogLine_Parse(&log_line,&log_entry,linebuf);
457 if (log_entry_status==RLRC_Unknown)
458 {
459 excluded_count[ER_UnknownFormat]++;
460 continue;
944cf283
FM
461 }
462 if (log_entry_status==RLRC_Ignore) {
7c8c06c5 463 excluded_count[ER_FormatData]++;
944cf283
FM
464 continue;
465 }
8b4e9578 466 format_count[log_line.current_format_idx]++;
944cf283 467
8b4e9578 468 if (!fp_log && ParsedOutputLog[0] && log_line.current_format!=&ReadSargLog) {
944cf283
FM
469 if(access(ParsedOutputLog,R_OK) != 0) {
470 my_mkdir(ParsedOutputLog);
471 }
472 if (snprintf(SargLogFile,sizeof(SargLogFile),"%s/sarg_temp.log",ParsedOutputLog)>=sizeof(SargLogFile)) {
af961877 473 debuga(__FILE__,__LINE__,_("Path too long: "));
041018b6 474 debuga_more("%s/sarg_temp.log\n",ParsedOutputLog);
1c91da07
FM
475 exit(EXIT_FAILURE);
476 }
944cf283 477 if((fp_log=MY_FOPEN(SargLogFile,"w"))==NULL) {
af961877 478 debuga(__FILE__,__LINE__,_("Cannot open file \"%s\": %s\n"),SargLogFile,strerror(errno));
1c91da07
FM
479 exit(EXIT_FAILURE);
480 }
944cf283
FM
481 fputs("*** SARG Log ***\n",fp_log);
482 }
1c91da07 483
944cf283 484 if (log_entry.Ip==NULL) {
af961877 485 debuga(__FILE__,__LINE__,_("Unknown input log file format: no IP addresses\n"));
944cf283
FM
486 break;
487 }
488 if (log_entry.User==NULL) {
af961877 489 debuga(__FILE__,__LINE__,_("Unknown input log file format: no user\n"));
944cf283
FM
490 break;
491 }
492 if (log_entry.Url==NULL) {
af961877 493 debuga(__FILE__,__LINE__,_("Unknown input log file format: no URL\n"));
944cf283
FM
494 break;
495 }
1c91da07 496
944cf283 497 idata=builddia(log_entry.EntryTime.tm_mday,log_entry.EntryTime.tm_mon+1,log_entry.EntryTime.tm_year+1900);
4246ae8d 498 if (debugz>=LogLevel_Data)
944cf283 499 printf("DATE=%s IDATA=%d DFROM=%d DUNTIL=%d\n",Filter->DateRange,idata,dfrom,duntil);
27d1fa35 500
6a943fc1
FM
501 if (EarliestDate<0 || idata<EarliestDate) {
502 EarliestDate=idata;
503 memcpy(&EarliestDateTime,&log_entry.EntryTime,sizeof(struct tm));
504 }
505 if (LatestDate<0 || idata>LatestDate) {
506 LatestDate=idata;
507 memcpy(&LatestDateTime,&log_entry.EntryTime,sizeof(struct tm));
508 }
944cf283 509 if(Filter->DateRange[0] != '\0'){
7c8c06c5
FM
510 if(idata < dfrom || idata > duntil) {
511 excluded_count[ER_OutOfDateRange]++;
512 continue;
513 }
944cf283 514 }
27d1fa35 515
944cf283 516 // Record only hours usage which is required
7c8c06c5
FM
517 if( bsearch( &( log_entry.EntryTime.tm_wday ), weekdays.list, weekdays.len, sizeof( int ), compar ) == NULL ) {
518 excluded_count[ER_OutOfWDayRange]++;
944cf283 519 continue;
7c8c06c5 520 }
27d1fa35 521
7c8c06c5
FM
522 if( bsearch( &( log_entry.EntryTime.tm_hour ), hours.list, hours.len, sizeof( int ), compar ) == NULL ) {
523 excluded_count[ER_OutOfHourRange]++;
944cf283 524 continue;
7c8c06c5 525 }
27d1fa35 526
27d1fa35 527
944cf283 528 if(strlen(log_entry.User) > MAX_USER_LEN) {
af961877 529 if (debugz>=LogLevel_Process) debuga(__FILE__,__LINE__,_("User ID too long: %s\n"),log_entry.User);
7c8c06c5 530 excluded_count[ER_UserNameTooLong]++;
944cf283
FM
531 totregsx++;
532 continue;
533 }
27d1fa35 534
944cf283
FM
535 // include_users
536 if(IncludeUsers[0] != '\0') {
537 snprintf(val1,sizeof(val1),":%s:",log_entry.User);
7c8c06c5
FM
538 if((str=(char *) strstr(IncludeUsers,val1)) == (char *) NULL ) {
539 excluded_count[ER_User]++;
27d1fa35 540 continue;
7c8c06c5 541 }
944cf283 542 }
27d1fa35 543
944cf283 544 if(vercode(log_entry.HttpCode)) {
af961877 545 if (debugz>=LogLevel_Process) debuga(__FILE__,__LINE__,_("Excluded code: %s\n"),log_entry.HttpCode);
7c8c06c5 546 excluded_count[ER_HttpCode]++;
944cf283
FM
547 totregsx++;
548 continue;
549 }
550
7c8c06c5
FM
551 if(testvaliduserchar(log_entry.User)) {
552 excluded_count[ER_InvalidUserChar]++;
944cf283 553 continue;
7c8c06c5 554 }
944cf283
FM
555
556 // replace any tab by a single space
557 for (str=log_entry.Url ; *str ; str++)
558 if (*str=='\t') *str=' ';
559 for (str=log_entry.HttpCode ; *str ; str++)
560 if (*str=='\t') *str=' ';
561
8b4e9578 562 if (log_line.current_format!=&ReadSargLog) {
944cf283
FM
563 /*
564 The full URL is not saved in sarg log. There is no point in testing the URL to detect
565 a downloaded file.
566 */
567 download_flag=is_download_suffix(log_entry.Url);
568 if (download_flag) {
569 safe_strcpy(download_url,log_entry.Url,sizeof(download_url));
27d1fa35 570 }
944cf283
FM
571 } else
572 download_flag=false;
27d1fa35 573
944cf283 574 url=process_url(log_entry.Url,LongUrl);
7c8c06c5
FM
575 if (!url || url[0] == '\0') {
576 excluded_count[ER_NoUrl]++;
577 continue;
578 }
944cf283
FM
579
580 if(addr[0] != '\0'){
7c8c06c5
FM
581 if(strcmp(addr,log_entry.Ip)!=0) {
582 excluded_count[ER_UntrackedIpAddr]++;
583 continue;
584 }
944cf283
FM
585 }
586 if(Filter->HostFilter) {
587 if(!vhexclude(url)) {
af961877 588 if (debugz>=LogLevel_Data) debuga(__FILE__,__LINE__,_("Excluded site: %s\n"),url);
7c8c06c5 589 excluded_count[ER_Url]++;
27d1fa35
FM
590 totregsx++;
591 continue;
592 }
944cf283 593 }
27d1fa35 594
944cf283
FM
595 if(Filter->StartTime >= 0 && Filter->EndTime >= 0) {
596 hmr=log_entry.EntryTime.tm_hour*100+log_entry.EntryTime.tm_min;
7c8c06c5
FM
597 if(hmr < Filter->StartTime || hmr > Filter->EndTime) {
598 excluded_count[ER_OutOfTimeRange]++;
599 continue;
600 }
944cf283 601 }
27d1fa35 602
944cf283 603 if(site[0] != '\0'){
7c8c06c5
FM
604 if(strstr(url,site)==0) {
605 excluded_count[ER_UntrackedUrl]++;
606 continue;
607 }
944cf283 608 }
27d1fa35 609
944cf283
FM
610 if(UserIp) {
611 log_entry.User=log_entry.Ip;
612 id_is_ip=true;
613 } else {
614 id_is_ip=false;
615 if ((log_entry.User[0]=='\0') || (log_entry.User[1]=='\0' && (log_entry.User[0]=='-' || log_entry.User[0]==' '))) {
616 if(RecordsWithoutUser == RECORDWITHOUTUSER_IP) {
617 log_entry.User=log_entry.Ip;
618 id_is_ip=true;
27d1fa35 619 }
7c8c06c5
FM
620 if(RecordsWithoutUser == RECORDWITHOUTUSER_IGNORE) {
621 excluded_count[ER_NoUser]++;
27d1fa35 622 continue;
7c8c06c5 623 }
944cf283
FM
624 if(RecordsWithoutUser == RECORDWITHOUTUSER_EVERYBODY)
625 log_entry.User="everybody";
27d1fa35 626 } else {
944cf283 627 if(NtlmUserFormat == NTLMUSERFORMAT_USER) {
e9ecdd7f 628 if ((str=strchr(log_entry.User,'+'))!=NULL || (str=strchr(log_entry.User,'\\'))!=NULL || (str=strchr(log_entry.User,'_'))!=NULL) {
944cf283 629 log_entry.User=str+1;
27d1fa35
FM
630 }
631 }
632 }
944cf283 633 }
27d1fa35 634
944cf283 635 if(us[0] != '\0'){
7c8c06c5
FM
636 if(strcmp(log_entry.User,us)!=0) {
637 excluded_count[ER_UntrackedUser]++;
638 continue;
639 }
944cf283 640 }
27d1fa35 641
944cf283
FM
642 if(Filter->SysUsers) {
643 snprintf(wuser,sizeof(wuser),":%s:",log_entry.User);
7c8c06c5
FM
644 if(strstr(userfile, wuser) == 0) {
645 excluded_count[ER_SysUser]++;
944cf283 646 continue;
7c8c06c5 647 }
944cf283 648 }
27d1fa35 649
944cf283
FM
650 if(Filter->UserFilter) {
651 if(!vuexclude(log_entry.User)) {
af961877 652 if (debugz>=LogLevel_Process) debuga(__FILE__,__LINE__,_("Excluded user: %s\n"),log_entry.User);
7c8c06c5 653 excluded_count[ER_IgnoredUser]++;
944cf283
FM
654 totregsx++;
655 continue;
27d1fa35 656 }
944cf283 657 }
27d1fa35 658
dc34d345
FM
659 user=process_user(log_entry.User);
660 if (log_entry.User!=user) {
661 log_entry.User=user;
662 id_is_ip=false;
663 }
944cf283 664 if (log_entry.User[0]=='\0' || (log_entry.User[1]=='\0' && (log_entry.User[0]=='-' ||
7c8c06c5
FM
665 log_entry.User[0]==' ' || log_entry.User[0]==':'))) {
666 excluded_count[ER_NoUser]++;
944cf283 667 continue;
7c8c06c5 668 }
27d1fa35 669
944cf283 670 if (log_entry.DataSize<0) log_entry.DataSize=0;
0c87646f 671
944cf283
FM
672 if (log_entry.ElapsedTime<0) log_entry.ElapsedTime=0;
673 if (Filter->max_elapsed>0 && log_entry.ElapsedTime>Filter->max_elapsed) {
674 log_entry.ElapsedTime=0;
675 }
27d1fa35 676
944cf283
FM
677 if((str=(char *) strstr(linebuf, "[SmartFilter:")) != (char *) NULL ) {
678 fixendofline(str);
679 snprintf(smartfilter,sizeof(smartfilter),"\"%s\"",str+1);
680 } else strcpy(smartfilter,"\"\"");
27d1fa35 681
944cf283
FM
682 nopen=0;
683 prev_ufile=NULL;
684 for (ufile=first_user_file ; ufile && strcmp(log_entry.User,ufile->user->id)!=0 ; ufile=ufile->next) {
685 prev_ufile=ufile;
686 if (ufile->file) nopen++;
687 }
688 if (!ufile) {
689 ufile=malloc(sizeof(*ufile));
27d1fa35 690 if (!ufile) {
af961877 691 debuga(__FILE__,__LINE__,_("Not enough memory to store the user %s\n"),log_entry.User);
944cf283
FM
692 exit(EXIT_FAILURE);
693 }
694 memset(ufile,0,sizeof(*ufile));
695 ufile->next=first_user_file;
696 first_user_file=ufile;
8e134f1a
FM
697 /*
698 * This id_is_ip stuff is just to store the string only once if the user is
699 * identified by its IP address instead of a distinct ID and IP address.
700 */
aa6ac9f2 701 uinfo=userinfo_create(log_entry.User,(id_is_ip) ? NULL : log_entry.Ip);
944cf283 702 ufile->user=uinfo;
944cf283
FM
703 nusers++;
704 } else {
705 if (prev_ufile) {
706 prev_ufile->next=ufile->next;
27d1fa35
FM
707 ufile->next=first_user_file;
708 first_user_file=ufile;
27d1fa35 709 }
944cf283 710 }
1c91da07 711#ifdef ENABLE_DOUBLE_CHECK_DATA
d6e3e724
FM
712 if (strcmp(log_entry.HttpCode,"TCP_DENIED/407")!=0) {
713 ufile->user->nbytes+=log_entry.DataSize;
714 ufile->user->elap+=log_entry.ElapsedTime;
715 }
1c91da07 716#endif
27d1fa35 717
944cf283
FM
718 if (ufile->file==NULL) {
719 if (nopen>=maxopenfiles) {
720 x=0;
721 for (ufile1=first_user_file ; ufile1 ; ufile1=ufile1->next) {
722 if (ufile1->file!=NULL) {
723 if (x>=maxopenfiles) {
724 if (fclose(ufile1->file)==EOF) {
af961877 725 debuga(__FILE__,__LINE__,_("Write error in log file of user %s: %s\n"),ufile1->user->id,strerror(errno));
944cf283 726 exit(EXIT_FAILURE);
27d1fa35 727 }
944cf283 728 ufile1->file=NULL;
27d1fa35 729 }
944cf283 730 x++;
27d1fa35
FM
731 }
732 }
27d1fa35 733 }
944cf283 734 if (snprintf (tmp3, sizeof(tmp3), "%s/%s.user_unsort", tmp, ufile->user->filename)>=sizeof(tmp3)) {
af961877 735 debuga(__FILE__,__LINE__,_("Temporary user file name too long: %s/%s.user_unsort\n"), tmp, ufile->user->filename);
27d1fa35
FM
736 exit(EXIT_FAILURE);
737 }
944cf283 738 if ((ufile->file = MY_FOPEN (tmp3, "a")) == NULL) {
af961877 739 debuga(__FILE__,__LINE__,_("(log) Cannot open temporary file %s: %s\n"), tmp3, strerror(errno));
944cf283 740 exit (1);
1c91da07 741 }
944cf283 742 }
27d1fa35 743
944cf283
FM
744 strftime(dia, sizeof(dia), "%d/%m/%Y",&log_entry.EntryTime);
745 strftime(hora,sizeof(hora),"%H:%M:%S",&log_entry.EntryTime);
27d1fa35 746
944cf283
FM
747 if (fprintf(ufile->file, "%s\t%s\t%s\t%s\t%"PRIu64"\t%s\t%ld\t%s\n",dia,hora,
748 log_entry.Ip,url,(uint64_t)log_entry.DataSize,
749 log_entry.HttpCode,log_entry.ElapsedTime,smartfilter)<=0) {
af961877 750 debuga(__FILE__,__LINE__,_("Write error in the log file of user %s\n"),log_entry.User);
944cf283
FM
751 exit(EXIT_FAILURE);
752 }
753 records_kept++;
27d1fa35 754
8b4e9578 755 if (fp_log && log_line.current_format!=&ReadSargLog) {
944cf283
FM
756 fprintf(fp_log, "%s\t%s\t%s\t%s\t%s\t%"PRIu64"\t%s\t%ld\t%s\n",dia,hora,
757 log_entry.User,log_entry.Ip,url,(uint64_t)log_entry.DataSize,
758 log_entry.HttpCode,log_entry.ElapsedTime,smartfilter);
759 }
760
761 totregsg++;
762
763 denied_write(&log_entry);
764 authfail_write(&log_entry);
88776d28 765 if (download_flag) download_write(&log_entry,download_url);
27d1fa35 766
8b4e9578 767 if (log_line.current_format!=&ReadSargLog) {
944cf283
FM
768 if (period.start.tm_year==0 || idata<mindate || compare_date(&period.start,&log_entry.EntryTime)>0){
769 mindate=idata;
770 memcpy(&period.start,&log_entry.EntryTime,sizeof(log_entry.EntryTime));
771 }
772 if (period.end.tm_year==0 || idata>maxdate || compare_date(&period.end,&log_entry.EntryTime)<0) {
773 maxdate=idata;
774 memcpy(&period.end,&log_entry.EntryTime,sizeof(log_entry.EntryTime));
27d1fa35
FM
775 }
776 }
777
4246ae8d 778 if (debugz>=LogLevel_Data){
944cf283
FM
779 printf("IP=\t%s\n",log_entry.Ip);
780 printf("USER=\t%s\n",log_entry.User);
781 printf("ELAP=\t%ld\n",log_entry.ElapsedTime);
782 printf("DATE=\t%s\n",dia);
783 printf("TIME=\t%s\n",hora);
784 //printf("FUNC=\t%s\n",fun);
785 printf("URL=\t%s\n",url);
786 printf("CODE=\t%s\n",log_entry.HttpCode);
787 printf("LEN=\t%"PRIu64"\n",(uint64_t)log_entry.DataSize);
27d1fa35
FM
788 }
789 }
790 longline_destroy(&line);
791
800eafb8
FM
792 if (FileObject_Close(fp_in)) {
793 debuga(__FILE__,__LINE__,_("Read error in \"%s\": %s\n"),arq,FileObject_GetLastCloseError());
794 exit(EXIT_FAILURE);
795 }
796 if (ShowReadStatistics) {
797 if (ShowReadPercent)
798 printf(_("SARG: Records in file: %lu, reading: %3.2f%%\n"),recs2, (float) 100 );
799 else
800 printf(_("SARG: Records in file: %lu\n"),recs2);
944cf283
FM
801 }
802}
803
7c8c06c5
FM
804/*!
805 * Display a line with the excluded entries count.
806 *
807 * \param Explain A translated string explaining the exluded count.
808 * \param Reason The reason number.
809 */
810static void DisplayExcludeCount(const char *Explain,enum ExcludeReasonEnum Reason)
811{
812 if (excluded_count[Reason]>0) {
af961877 813 debuga(__FILE__,__LINE__," %s: %lu\n",Explain,excluded_count[Reason]);
7c8c06c5
FM
814 }
815}
816
944cf283
FM
817/*!
818Read the log files.
819
820\param Filter The filtering parameters for the file to load.
821
822\retval 1 Records found.
823\retval 0 No record found.
824*/
825int ReadLogFile(struct ReadLogDataStruct *Filter)
826{
944cf283
FM
827 int x;
828 int cstatus;
829 struct userfilestruct *ufile;
830 struct userfilestruct *ufile1;
6068ae56
FM
831 FileListIterator FIter;
832 const char *file;
944cf283
FM
833
834 for (x=0 ; x<sizeof(format_count)/sizeof(*format_count) ; x++) format_count[x]=0;
7c8c06c5 835 for (x=0 ; x<sizeof(excluded_count)/sizeof(*excluded_count) ; x++) excluded_count[x]=0;
944cf283
FM
836 first_user_file=NULL;
837
838 if (!dataonly) {
839 denied_open();
840 authfail_open();
841 download_open();
842 }
843
6068ae56
FM
844 FIter=FileListIter_Open(AccessLog);
845 while ((file=FileListIter_Next(FIter))!=NULL)
846 ReadOneLogFile(Filter,file);
847 FileListIter_Close(FIter);
944cf283 848
27d1fa35 849 if(fp_log != NULL) {
27d1fa35 850 char val2[40];
944cf283 851 char val4[4096];//val4 must not be bigger than SargLogFile without fixing the strcpy below
0c87646f 852
507460ae 853 if (fclose(fp_log)==EOF) {
af961877 854 debuga(__FILE__,__LINE__,_("Write error in \"%s\": %s\n"),SargLogFile,strerror(errno));
507460ae
FM
855 exit(EXIT_FAILURE);
856 }
944cf283
FM
857 strftime(val2,sizeof(val2),"%d%m%Y_%H%M",&period.start);
858 strftime(val1,sizeof(val1),"%d%m%Y_%H%M",&period.end);
859 if (snprintf(val4,sizeof(val4),"%s/sarg-%s-%s.log",ParsedOutputLog,val2,val1)>=sizeof(val4)) {
af961877 860 debuga(__FILE__,__LINE__,_("Path too long: "));
041018b6 861 debuga_more("%s/sarg-%s-%s.log\n",ParsedOutputLog,val2,val1);
27d1fa35
FM
862 exit(EXIT_FAILURE);
863 }
944cf283 864 if (rename(SargLogFile,val4)) {
af961877 865 debuga(__FILE__,__LINE__,_("failed to rename %s to %s - %s\n"),SargLogFile,val4,strerror(errno));
27d1fa35 866 } else {
944cf283 867 strcpy(SargLogFile,val4);
27d1fa35
FM
868
869 if(strcmp(ParsedOutputLogCompress,"nocompress") != 0 && ParsedOutputLogCompress[0] != '\0') {
870 /*
871 No double quotes around ParsedOutputLogCompress because it may contain command line options. If double quotes are
872 necessary around the command name, put them in the configuration file.
873 */
944cf283 874 if (snprintf(val1,sizeof(val1),"%s \"%s\"",ParsedOutputLogCompress,SargLogFile)>=sizeof(val1)) {
af961877 875 debuga(__FILE__,__LINE__,_("Command too long: %s \"%s\"\n"),ParsedOutputLogCompress,SargLogFile);
27d1fa35
FM
876 exit(EXIT_FAILURE);
877 }
878 cstatus=system(val1);
879 if (!WIFEXITED(cstatus) || WEXITSTATUS(cstatus)) {
af961877
FM
880 debuga(__FILE__,__LINE__,_("command return status %d\n"),WEXITSTATUS(cstatus));
881 debuga(__FILE__,__LINE__,_("command: %s\n"),val1);
27d1fa35
FM
882 exit(EXIT_FAILURE);
883 }
884 }
885 }
886 if(debug)
af961877 887 debuga(__FILE__,__LINE__,_("Sarg parsed log saved as %s\n"),SargLogFile);
0c87646f 888 }
27d1fa35 889
8e53b2e7 890 denied_close();
16b013cc 891 authfail_close();
11284535 892 download_close();
27d1fa35
FM
893
894 for (ufile=first_user_file ; ufile ; ufile=ufile1) {
895 ufile1=ufile->next;
507460ae 896 if (ufile->file!=NULL && fclose(ufile->file)==EOF) {
af961877 897 debuga(__FILE__,__LINE__,_("Write error in log file of user %s: %s\n"),ufile->user->id,strerror(errno));
507460ae
FM
898 exit(EXIT_FAILURE);
899 }
27d1fa35
FM
900 free(ufile);
901 }
902
903 if (debug) {
8e501bd6 904 unsigned long int totalcount=0;
27d1fa35 905
af961877 906 debuga(__FILE__,__LINE__,_(" Records read: %ld, written: %ld, excluded: %ld\n"),totregsl,totregsg,totregsx);
27d1fa35 907
7c8c06c5
FM
908 for (x=sizeof(excluded_count)/sizeof(*excluded_count)-1 ; x>=0 && excluded_count[x]>0 ; x--);
909 if (x>=0) {
af961877 910 debuga(__FILE__,__LINE__,_("Reasons for excluded entries:\n"));
7c8c06c5
FM
911 DisplayExcludeCount(_("User name too long"),ER_UserNameTooLong);
912 DisplayExcludeCount(_("Squid logged an incomplete query received from the client"),ER_IncompleteQuery);
913 DisplayExcludeCount(_("Log file turned over"),ER_LogfileTurnedOver);
7c8c06c5
FM
914 DisplayExcludeCount(_("Excluded by \"exclude_string\" in sarg.conf"),ER_ExcludeString);
915 DisplayExcludeCount(_("Unknown input log file format"),ER_UnknownFormat);
916 DisplayExcludeCount(_("Line ignored by the input log format"),ER_FormatData);
917 DisplayExcludeCount(_("Time outside the requested date range (-d)"),ER_OutOfDateRange);
918 DisplayExcludeCount(_("Ignored week day (\"weekdays\" parameter in sarg.conf)"),ER_OutOfWDayRange);
919 DisplayExcludeCount(_("Ignored hour (\"hours\" parameter in sarg.conf)"),ER_OutOfHourRange);
920 DisplayExcludeCount(_("User is not in the \"include_users\" list"),ER_User);
921 DisplayExcludeCount(_("HTTP code excluded by \"exclude_code\" file"),ER_HttpCode);
922 DisplayExcludeCount(_("Invalid character found in user name"),ER_InvalidUserChar);
923 DisplayExcludeCount(_("No URL in entry"),ER_NoUrl);
924 DisplayExcludeCount(_("Not the IP address requested with -a"),ER_UntrackedIpAddr);
925 DisplayExcludeCount(_("URL excluded by -c or \"exclude_hosts\""),ER_Url);
926 DisplayExcludeCount(_("Entry time outside of requested hour range (-t)"),ER_OutOfTimeRange);
927 DisplayExcludeCount(_("Not the URL requested by -s"),ER_UntrackedUrl);
928 DisplayExcludeCount(_("No user in entry"),ER_NoUser);
929 DisplayExcludeCount(_("Not the user requested by -u"),ER_UntrackedUser);
930 DisplayExcludeCount(_("System user as defined by \"password\" in sarg.conf"),ER_SysUser);
931 DisplayExcludeCount(_("User ignored by \"exclude_users\""),ER_IgnoredUser);
932 }
933
1c91da07
FM
934 for (x=0 ; x<sizeof(LogFormats)/sizeof(*LogFormats) ; x++) {
935 if (format_count[x]>0) {
936 /* TRANSLATORS: It displays the number of lines found in the input log files
937 * for each supported log format. The log format name is the %s and is a string
938 * you translate somewhere else. */
af961877 939 debuga(__FILE__,__LINE__,_("%s: %lu entries\n"),_(LogFormats[x]->Name),format_count[x]);
1c91da07
FM
940 totalcount+=format_count[x];
941 }
942 }
27d1fa35 943
1c91da07 944 if (totalcount==0 && totregsg)
af961877 945 debuga(__FILE__,__LINE__,_("Log with invalid format\n"));
27d1fa35
FM
946 }
947
27d1fa35
FM
948 return((totregsg!=0) ? 1 : 0);
949}
6a943fc1
FM
950
951/*!
952 * Get the start and end date of the period covered by the log files.
953 */
b6fb8c79 954bool GetLogPeriod(struct tm *Start,struct tm *End)
6a943fc1 955{
b6fb8c79
FM
956 bool Valid=false;
957
6a943fc1
FM
958 if (EarliestDate>=0) {
959 memcpy(Start,&EarliestDateTime,sizeof(struct tm));
b6fb8c79 960 Valid=true;
6a943fc1
FM
961 } else {
962 memset(Start,0,sizeof(struct tm));
963 }
964 if (LatestDate>=0) {
965 memcpy(End,&LatestDateTime,sizeof(struct tm));
b6fb8c79 966 Valid=true;
6a943fc1
FM
967 } else {
968 memset(End,0,sizeof(struct tm));
969 }
b6fb8c79 970 return(Valid);
6a943fc1 971}