#include #include #include #include "defines.h" void write_to_file(char *user, char *log, char *tdir){ char *fname = NULL; FILE *log_fd; /* Allocate memory for filename string */ if(tdir == NULL) fname = (char *)calloc(strlen(user) + 6, sizeof(char)); else fname = (char *)calloc(strlen(tdir) + strlen(user) + 6, sizeof(char)); if(fname == NULL){ perror("calloc"); exit(-1); } if(tdir == NULL) sprintf(fname,"%s.log",user); else sprintf(fname,"%s/%s.log",tdir,user); /* Append log entry to USERNAME.log */ if((log_fd = fopen(fname, "a")) != NULL){ fprintf(log_fd, "%s", log); fclose(log_fd); } else printf("Warning - failed to open %s for writing", fname); free(fname); } int main(int argc, char *argv[]){ char *read_buff = NULL; char *user = NULL; char fd_buff[LINE_SIZE]; int user_size; FILE *log_fd; if(argc < 2){ printf("Usage:\n"); printf("%s logfile \n", argv[0]); exit(-1); } /* Open the apache logfile we should split */ if((log_fd = fopen(argv[1], "r")) == NULL){ perror("fopen"); exit(-1); } while(!feof(log_fd)){ /* Initialize read_buff variable */ read_buff = (char *)calloc(2,sizeof(char)); /* Keep reading until we get to the end of the line, increase read_buff variable to contain the newly aquired data */ while(strstr((char *)read_buff, "\n") == NULL){ memset(fd_buff, 0, LINE_SIZE); fgets(fd_buff, LINE_SIZE - 1, log_fd); /* if fd_buff[0] we reached EOF and there's no more work to do */ if(fd_buff[0] == 0){ fclose(log_fd); exit(1); } /* Allocate more memory to read_buff */ read_buff = realloc((char *)read_buff, strlen(read_buff) + strlen(fd_buff) + 3); if(read_buff == NULL){ perror("realloc"); exit(-1); } strcat(read_buff, fd_buff); /* Zero out fd_buff */ memset(fd_buff,0, LINE_SIZE); } /* Search for a username in [PID]: [USERNAME] form */ if(strstr(read_buff, "]: [") != NULL){ user_size = strlen(strstr(read_buff, "]: [") + 4) - strlen(strstr(strstr(read_buff, "]: [") + 4,"]")); user = (char *)calloc(user_size + 2, sizeof(char)); strncpy(user,strstr(read_buff, "]: [") + 4, user_size); write_to_file(user, read_buff, argv[2]); free(user); } /* Free buffers before next run */ free(read_buff); } fclose(log_fd); return(1); }