/*************************************************************************** * * 通用代码 * 常用函数 * 程序日志输出 * 读取解析配置文件 * 代码转换函数 * * Author : Li Bo Feng * * Update History * DATE OWNER DESCRIPTION * ----------- ------------ ----------- * 2010-01-19 Li Bo Feng Generated * ***************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ab_map.h" #include "ab_code.h" #define MAX_LINE_BUFFER_LENGTH 1024 static int ablog_level = -1; static int _ablog_stdout = 1; static int ablog_keep_hours = 120; static FILE *_ablog_file = NULL; static struct pattern_instance ablog_filename = {"", "", "", {0}, 0, 0, 0, MAX_FILEPATH_LENGTH, ""}; static int _ablog_print = 0; int ablog_print() { return _ablog_print; } int ablog_file() { return ablog_filename.pattern[0]; } int ablog_stdout() { return _ablog_stdout; } void set_log_filename(char *filepath_pattern) { if (_ablog_print == 0) { _ablog_print = get_log_print_level(); } strncpy(ablog_filename.pattern, filepath_pattern, MAX_FILEPATH_LENGTH); ablog_filename.expiration_ct = 0; ablog_filename.expiration_vt = 0; } void set_log_keephours(int keep_hours) { if (_ablog_print == 0) { _ablog_print = get_log_print_level(); } ablog_keep_hours = keep_hours; } void set_log_stdout(int yn) { if (_ablog_print == 0) { _ablog_print = get_log_print_level(); } _ablog_stdout = yn ? 1 : 0; } static int initialized = 0; static time_t vt_offset = 0; static int tzone_hours = 0; static long code_string_mapping = 0; function_on_ablog_reinitialized on_ablog_reinitialized = 0; static pthread_mutex_t thread_mut; void init_coding() { if (initialized == 0) { pthread_mutex_init(&thread_mut, NULL); // 虚拟时间偏移 time_t vt = parse_time(getenv("VIRTUAL_TIME"), NULL); vt_offset = vt == 0 ? 0 : vt - time(0); // 当前时区偏移 time_t tzone = 0; tzone_hours = localtime(&tzone)->tm_hour; // 初始化返回码-字符串映射 code_string_mapping = new_mapping(); // 初始化完毕 initialized = 1; } } static char _code_string[50]; void set_code_string(int n, char *string) { sprintf(_code_string, "%d", n); put_string_mapping(code_string_mapping, _code_string, string); } char *code_string(int n) { sprintf(_code_string, "%d", n); char *ret = (char *)get_string_mapping(code_string_mapping, _code_string); if (ret) { return ret; } sprintf(_code_string, "code %d[0x%08X]", n, n); return _code_string; } void clear_coding() { clear_pattern_instance(&ablog_filename); clear_mapping(); } /** * 虚拟当前时间 virtual_current_time * 根据环境变量指定的 VIRTUAL_TIME = `date +"%Y-%m-%d %H:%M:%S"`确定时间偏移 * 返回计算后的虚拟当前时间 * 使用此函数前必须在main开始时调用 init_coding(); */ time_t vtime() { return time(0) + vt_offset; } static time_t t_debug_flag = 0; static time_t t_debug_pid_flag = 0; static int b_debug_current_process = 0; int debug_current_process() { if (t_debug_flag < time(0)) { t_debug_flag = time(0) + 60; if (access("debug.pid", 0) == 0) { if (t_debug_pid_flag == 0) { t_debug_pid_flag = 1; } } else { t_debug_pid_flag = 0; b_debug_current_process = 0; } } if (t_debug_pid_flag > 0 && t_debug_pid_flag < time(0)) { t_debug_pid_flag = time(0) + 5; char debug_file[50]; sprintf(debug_file, "debug.%d", getpid()); if (access(debug_file, 0) == 0) { b_debug_current_process = 1; } else { b_debug_current_process = 0; } } return b_debug_current_process; } time_t _replace_time_pattern(char *buf, int buf_len, time_t st, char CoS) { time_t expiration_t = -1; struct tm *tms = localtime(&st); int n = (replace_string(buf, CoS == 'C' ? "[yyyy]" : "[YYYY]", format_int("%04d", (tms->tm_year + 1900)), buf, buf_len)); n |= (replace_string(buf, CoS == 'C' ? "[mm]" : "[MM]", format_int("%02d", (tms->tm_mon + 1)), buf, buf_len)); n |= (replace_string(buf, CoS == 'C' ? "[dd]" : "[DD]", format_int("%02d", tms->tm_mday), buf, buf_len)); if (n) { // 每天检查是否需要切换文件 expiration_t = ((((st / 3600)) + tzone_hours + 24) / 24 * 24 - tzone_hours) * 3600; } if (replace_string(buf, CoS == 'C' ? "[hh]" : "[HH]", format_int("%02d", tms->tm_hour), buf, buf_len)) { // 每小时检查是否需要切换文件 expiration_t = (st + 3600) / 3600 * 3600; } if (replace_string(buf, CoS == 'C' ? "[mi]" : "[MI]", format_int("%02d", tms->tm_min), buf, buf_len)) { // 每分钟检查是否需要切换文件,主要用于测试 expiration_t = (st + 60) / 60 * 60; } return expiration_t; } void clear_pattern_instance(struct pattern_instance *pi) { if (pi->regex[0] != 0) { regfree(&pi->reg); pi->regex[0] = 0; } } int instantiated_pattern(struct pattern_instance *pi) { time_t vt = vtime(); time_t ct = time(0); if ((pi->expiration_ct >= 0 && ct >= pi->expiration_ct) || (pi->expiration_vt >= 0 && vt >= pi->expiration_vt)) { strncpy(pi->instance, pi->pattern, pi->instance_buf_len); replace_string(pi->instance, "[PID]", format_int("%d", getpid()), pi->instance, pi->instance_buf_len); replace_string(pi->instance, "[pid]", format_int("%d", getpid()), pi->instance, pi->instance_buf_len); if (strcmp(pi->last_pattern, pi->pattern) != 0) { char regex[MAX_FILEPATH_LENGTH]; strncpy(regex, pi->pattern, MAX_FILEPATH_LENGTH); // 正则表达式通配符 replace_string(regex, "\\", "\\\\", regex, MAX_FILEPATH_LENGTH); replace_string(regex, ".", "\\.", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "|", "\\|", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "(", "\\(", regex, MAX_FILEPATH_LENGTH); replace_string(regex, ")", "\\)", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "{", "\\{", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "}", "\\}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "*", "\\*", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "+", "\\+", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "?", "\\?", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "^", "\\^", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "$", "\\$", regex, MAX_FILEPATH_LENGTH); // 临时转义[] replace_string(regex, "&", "&a", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "[", "&[", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "]", "&]", regex, MAX_FILEPATH_LENGTH); // 文件名支持定义内容转义 replace_string(regex, "&[PID&]", "[0-9]*", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[pid&]", "[0-9]*", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[YYYY&]", "[0-9]{4}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[yyyy&]", "[0-9]{4}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[MM&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[mm&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[DD&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[dd&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[HH&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[hh&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[MI&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&[mi&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH); // []转义 replace_string(regex, "&[", "\\[", regex, MAX_FILEPATH_LENGTH); replace_string(regex, "&]", "\\]", regex, MAX_FILEPATH_LENGTH); // 恢复临时转义 replace_string(regex, "&a", "&", regex, MAX_FILEPATH_LENGTH); if (pi->regex[0] != 0) { regfree(&pi->reg); pi->regex[0] = 0; } if (regex[0] != 0) { int reti = regcomp(&pi->reg, regex, REG_EXTENDED); if (reti != 0) { char errbuf[256]; regerror(reti, &pi->reg, errbuf, sizeof(errbuf)); log_println("ABLOG_INIT", __FILE__, __LINE__, "ERROR:%s", errbuf); } else { strncpy(pi->regex, regex, MAX_FILEPATH_LENGTH); } } strncpy(pi->last_pattern, pi->pattern, MAX_FILEPATH_LENGTH); } pi->expiration_ct = _replace_time_pattern(pi->instance, pi->instance_buf_len, ct, 'C'); pi->expiration_vt = _replace_time_pattern(pi->instance, pi->instance_buf_len, vt, 'V'); pi->instantiated_time = time(0); return 1; } return 0; } int matched_logfile_pattern(struct pattern_instance *pi, char *filepath) { if (pi->regex[0] != 0) { int reti = regexec(&pi->reg, filepath, 0, NULL, 0); if (reti == 0) { // log_println("I", __FILE__, __LINE__, "%s match %s", filepath, pi->regex); return 1; // 匹配成功 } if (reti == REG_NOMATCH) { // log_println("I", __FILE__, __LINE__, "%s not match %s", filepath, pi->regex); return 0; // 不匹配 } char errbuf[256]; regerror(reti, &pi->reg, errbuf, sizeof(errbuf)); log_println("E", __FILE__, __LINE__, "%s", errbuf); } return 0; } int lock_file(char *filename, int wait) { int lockfd = open(filename, O_RDWR | O_CREAT, 0666); if (lockfd) { int flock_cmd = wait ? F_SETLKW : F_SETLK; static struct flock flock_args; flock_args.l_type = F_WRLCK; flock_args.l_start = 0; flock_args.l_whence = SEEK_SET; flock_args.l_len = 0; flock_args.l_pid = getpid(); if (fcntl(lockfd, flock_cmd, &flock_args) == 0) { return lockfd; } close(lockfd); } return 0; } int unlock_file(int lockfd) { int ret = 0; if (lockfd) { int flock_cmd = F_SETLK; static struct flock flock_args; flock_args.l_type = F_UNLCK; flock_args.l_start = 0; flock_args.l_whence = SEEK_SET; flock_args.l_len = 0; flock_args.l_pid = getpid(); if (fcntl(lockfd, flock_cmd, &flock_args) == 0) { ret = 1; } close(lockfd); } return ret; } int _ablog_lock(char *dir) { int ret = 0; char buf[MAX_LINE_BUFFER_LENGTH]; char lock_filename[MAX_FILEPATH_LENGTH]; sprintf(lock_filename, "%s%s", dir, ".lock"); int ablog_lockfd = lock_file(lock_filename, 0); if (ablog_lockfd) { memset(buf, 0, sizeof(buf)); read(ablog_lockfd, buf, sizeof(buf)); time_t t = parse_time(buf, NULL); if (t < time(0)) { strcpy(buf, time_string(time(0) + 60)); lseek(ablog_lockfd, 0, SEEK_SET); write(ablog_lockfd, buf, strlen(buf)); ret = 1; } unlock_file(ablog_lockfd); } else { log_println("ABLOG_FILE", __FILE__, __LINE__, "lock file[%s] failed.", lock_filename); } return ret; } int _ablog_rm_old_files(struct pattern_instance *pi, char *dir, time_t time_before) { // if (!_ablog_lock(dir)) // { // // log_println("ABLOG_FILE", __FILE__, __LINE__, "lock dir failed: %s", dir); // return -1; // } DIR *od = opendir(dir); if (od == NULL) { // log_println("ABLOG_FILE", __FILE__, __LINE__, "open dir failed: %s", dir); return -1; } char file[MAX_FILEPATH_LENGTH]; struct stat file_stat; struct dirent *ent; int n = 0; while ((ent = readdir(od)) != NULL) { if (ent->d_name[0] != '.') { sprintf(file, "%s%s", dir, ent->d_name); if (matched_logfile_pattern(pi, file)) { stat(file, &file_stat); // printf("%32s %s ", namelist[i]->d_name, time_string(file_stat.st_mtime)); if (S_ISREG(file_stat.st_mode) && file_stat.st_mtime < time_before) { remove(file); n++; log_println("ABLOG_FILE", __FILE__, __LINE__, "remove old log file: %s", file); } // printf("\n"); } } } closedir(od); if (n > 0) { log_println("ABLOG_FILE", __FILE__, __LINE__, "%d old log files removed", n); } return n; } int remove_old_log_files(time_t time_before) { if (strlen(ablog_filename.instance) == 0) { return 0; } char buf[MAX_FILEPATH_LENGTH]; strcpy(buf, ablog_filename.instance); char *c = buf + strlen(buf) - 1; while (*c != '/' && c >= buf) { *c = '\0'; --c; } if (buf[0] == 0) { strcpy(buf, "./"); } return _ablog_rm_old_files(&ablog_filename, buf, time_before); } void _ablog_set_log_file() { if (instantiated_pattern(&ablog_filename)) { if (_ablog_file) { fclose(_ablog_file); } if (strlen(ablog_filename.instance) > 0) { if (mk_parent_dir(ablog_filename.instance) != 0) { _ablog_stdout = 1; log_println("ABLOG_FILE", __FILE__, __LINE__, "make parent dir error, '%s'", ablog_filename.instance); } // printf("ablog_filename.instance=%s\n", ablog_filename.instance); _ablog_file = fopen(ablog_filename.instance, "a"); if (!_ablog_file) { _ablog_stdout = 1; log_println("ABLOG_FILE", __FILE__, __LINE__, "File append error, '%s'", ablog_filename.instance); } // else // { // log_println("ABLOG_FILE", __FILE__, __LINE__, "%s", ablog_filename.instance); // } } if (on_ablog_reinitialized) { on_ablog_reinitialized(); } remove_old_log_files(time(0) - ablog_keep_hours * 3600); } } void mc_print_log(long mtc, char *info, char *file, int line) { log_println("MEMORY_CHECK", file, line, "malloc %ld, %s", mtc, info); } static int ablog_level_setting = LPL_All; #define CHECK_ABLOG_CLASS(N) (strcasecmp(#N, buf) == 0) ? LPL_##N #define SHOW_ABLOG_CLASS(N) (ablog_level & LPL_##N) ? #N int get_log_print_level() { if (ablog_level == -1) { init_coding(); parse_int(getenv("ABLOG_KEEP_HOURS"), &ablog_keep_hours, ablog_keep_hours); parse_int(getenv("ABLOG_STDOUT"), &_ablog_stdout, _ablog_stdout); char *sf = getenv("ABLOG_FILE"); if (sf) { strncpy(ablog_filename.pattern, sf, MAX_FILEPATH_LENGTH); } _ablog_set_log_file(); // 重定向内存检查输出 mc_print = mc_print_log; char buf[32]; char *lpls = getenv("ABLOG_CLASS"); if (lpls) { ablog_level = 0; while (*lpls) { buf[0] = 0; lpls = split_string_next(lpls, ',', buf, sizeof(buf)); int n = CHECK_ABLOG_CLASS(All) : CHECK_ABLOG_CLASS(Error) : CHECK_ABLOG_CLASS(Metrics) : CHECK_ABLOG_CLASS(State) : CHECK_ABLOG_CLASS(Detail) : CHECK_ABLOG_CLASS(Flow) : CHECK_ABLOG_CLASS(Flow_Public) : CHECK_ABLOG_CLASS(Flow_Private) : CHECK_ABLOG_CLASS(Flow_Restricted) : CHECK_ABLOG_CLASS(Flow_Minor) : 0; if (n != 0) { log_println("ABLOG_CLASS", __FILE__, __LINE__, "configured ablog class #%02X %s", n, buf); ablog_level |= n; } } } else { ablog_level = ablog_level_setting; } if (vt_offset != 0) { log_println("VIRTUAL_TIME", __FILE__, __LINE__, "configured virtual time [%s]", time_string(vtime())); } ablog_level_setting = ablog_level; } return debug_current_process() ? LPL_All : ablog_level_setting; } /** * 输出一行日志信息 */ void log_println(const char *func, const char *file, int line, const char *format, ...) { if (ablog_file()) { va_list vl; va_start(vl, format); log_println_vl(1, func, file, line, format, vl); va_end(vl); } if (ablog_stdout()) { va_list vl; va_start(vl, format); log_println_vl(0, func, file, line, format, vl); va_end(vl); } } void log_println_vl(int fileout, const char *func, const char *file, int line, const char *format, va_list vl) { struct timeval tv; gettimeofday(&tv, NULL); FILE *fout = stdout; if (fileout) { _ablog_set_log_file(); fout = _ablog_file; if (!fout) { return; } } pthread_mutex_lock(&thread_mut); fprintf(fout, "%s.%03ld[%s]:", time_string(tv.tv_sec), (tv.tv_usec / 1000l), func); vfprintf(fout, format, vl); fprintf(fout, " (%s:%d)\n", file, line); fflush(fout); pthread_mutex_unlock(&thread_mut); } /** * 解析十六进制数 * 解析结果通过输出参数o返回 * 解析失败返回0,解析成功返回非0 */ int parse_hex(char *s, int *o, int default_value) { int x = 0; int i = 0; int n = 0; int c, t; *o = default_value; if (s) { for (; isspace((int)s[i]); i++) ; if (s[i] == 'h' || s[i] == 'H' || s[i] == 'x' || s[i] == 'X') { i++; } else if (s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) { i += 2; } for (; (c = s[i]) != 0 && !isspace((int)c); i++, n++) { t = c >= '0' && c <= '9' ? (c - '0') : c >= 'A' && c <= 'F' ? (c - 'A' + 10) : c >= 'a' && c <= 'f' ? (c - 'a' + 10) : -1; if (t == -1) { return 0; } x <<= 4; x |= t; } for (; isspace((int)s[i]); i++) ; if (s[i] != 0 || n == 0) { return 0; } *o = x; } return n; } /** * 解析十进制数 * 解析结果通过输出参数o返回 * 解析失败返回0,解析成功返回非0 */ int parse_int(char *s, int *o, int default_value) { int x = 0; int i = 0; int n = 0; int c, t; *o = default_value; if (s) { for (; isspace((int)s[i]); i++) ; for (; (c = s[i]) != 0; i++, n++) { t = c >= '0' && c <= '9' ? (c - '0') : -1; if (t == -1) { return 0; } x = x * 10 + t; } for (; isspace((int)s[i]); i++) ; if (s[i] != 0 || n == 0) { return 0; } *o = x; } return n; } /** * 解析十进制数 * 解析结果通过输出参数o返回 * 解析失败返回0,解析成功返回非0 */ int parse_double(char *s, double *o, double default_value) { int signal = 1; double x = 0; double t = 0; int i = 0; int n = 0; int c; *o = default_value; if (s) { for (; isspace((int)s[i]); i++) ; if ((c = s[i]) == '-' || c == '+') { signal = c == '-' ? -1 : 1; i++; } for (; (c = s[i]) >= '0' && c <= '9'; i++, n++) { x = x * 10 + (c - '0'); } if ((c = s[i]) == '.') { i++; t = 1; for (; (c = s[i]) >= '0' && c <= '9'; i++, n++) { t /= 10; x = x + t * (c - '0'); } } for (; isspace((int)s[i]); i++) ; if (s[i] != 0 || n == 0) { return 0; } *o = signal * x; } return n; } /** * 格式化数字字符串 */ static char int_string_buffer[20][100]; static int int_string_buffer_i = 0; char *format_int(char *format, int n) { int_string_buffer_i++; if (int_string_buffer_i >= 20) { int_string_buffer_i = 0; } sprintf(int_string_buffer[int_string_buffer_i], format, n); return int_string_buffer[int_string_buffer_i]; } char *format_long(char *format, long n) { int_string_buffer_i++; if (int_string_buffer_i >= 20) { int_string_buffer_i = 0; } sprintf(int_string_buffer[int_string_buffer_i], format, n); return int_string_buffer[int_string_buffer_i]; } char *format_double(char *format, double n) { int_string_buffer_i++; if (int_string_buffer_i >= 20) { int_string_buffer_i = 0; } sprintf(int_string_buffer[int_string_buffer_i], format, n); return int_string_buffer[int_string_buffer_i]; } char *int_string(int n) { return format_int("%d", n); } /** * 解析格式为 yyyy-MM-dd HH:mm:ss[.SSS] 的时间字符串 * 返回标准时间秒数,毫秒值通过输出参数ms返回 * 解析失败返回 0 */ time_t parse_time(char *stime, long *ms) { if (stime == NULL || stime[0] == 0) { return 0; } char *c = stime; while ((isspace((int)*c))) { c++; } if (*c == 0) { return 0; } char timestr[25]; strncpy(timestr, c, 24); struct tm tm; memset(&tm, 0, sizeof(tm)); int rms = 0; sscanf(timestr, "%d-%d-%d %d:%d:%d.%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &rms); if (ms != NULL) { *ms = rms; } tm.tm_year -= 1900; tm.tm_mon -= 1; tm.tm_isdst = 0; time_t time_t = mktime(&tm); return time_t; } /** * 解析格式为 yyyy-MM-dd HH:mm:ss[.SSS] 的时间字符串 * 返回timeval形式 */ struct timeval parse_time_tv(char *stime) { struct timeval tv; tv.tv_usec = 0; long milliseconds; tv.tv_sec = parse_time(stime, &milliseconds); tv.tv_usec = milliseconds * 1000; // microseconds return tv; } /** * 解析格式为 yyyy-MM-dd HH:mm:ss[.SSS] 的时间字符串 * 返回标准时间毫秒数 */ long parse_time_lms(char *stime) { long ms = 0; long lms = 1000L * parse_time(stime, &ms); return lms + ms; } /** * 格式化时间字符串 * 返回格式为 yyyy-MM-dd HH:mm:ss的时间字符串 */ static char time_string_buffer[20][25]; static int time_string_buffer_i = 0; char *time_string(time_t seconds) { time_string_buffer_i++; if (time_string_buffer_i >= 20) { time_string_buffer_i = 0; } struct tm *tmp = localtime(&seconds); tmp->tm_year = tmp->tm_year + 1900; tmp->tm_mon = tmp->tm_mon + 1; sprintf(time_string_buffer[time_string_buffer_i], "%4d-%02d-%02d %02d:%02d:%02d", tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec); return time_string_buffer[time_string_buffer_i]; } /** * 格式化时间字符串 * 返回格式为 yyyy-MM-dd HH:mm:ss.SSS的时间字符串 */ char *time_tv_string(struct timeval tv) { time_string_buffer_i++; if (time_string_buffer_i >= 20) { time_string_buffer_i = 0; } time_t seconds = tv.tv_sec; int dms = (int)(tv.tv_usec / 1000); struct tm *tmp = localtime(&seconds); tmp->tm_year = tmp->tm_year + 1900; tmp->tm_mon = tmp->tm_mon + 1; sprintf(time_string_buffer[time_string_buffer_i], "%4d-%02d-%02d %02d:%02d:%02d.%03d", tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, dms); return time_string_buffer[time_string_buffer_i]; } /** * 格式化时间字符串 * 返回格式为 yyyy-MM-dd HH:mm:ss.SSS的时间字符串 */ char *time_lms_string(time_long milliseconds) { time_string_buffer_i++; if (time_string_buffer_i >= 20) { time_string_buffer_i = 0; } time_t seconds = milliseconds / 1000; int dms = (int)(milliseconds % 1000); struct tm *tmp = localtime(&seconds); tmp->tm_year = tmp->tm_year + 1900; tmp->tm_mon = tmp->tm_mon + 1; sprintf(time_string_buffer[time_string_buffer_i], "%4d-%02d-%02d %02d:%02d:%02d.%03d", tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, dms); return time_string_buffer[time_string_buffer_i]; } /** * MUST recv_buf length >= strlen(source) + 1 */ char **split_string(char *source, char split_char, char *recv_buf, int recv_buf_bytes, char **recv_buf_array, int recv_buf_array_size) { ABLOG_Entry(Public, split_string); int iout = 0; int n = 0; char *recv; char *scur = NULL; char *snext = source; while (*snext) { scur = snext; recv_buf_array[iout] = recv_buf; recv = recv_buf; iout++; if (iout >= recv_buf_array_size) { split_char = 0; snext += strlen(scur); } else { snext = split_string_next(scur, split_char, recv, recv_buf_bytes); } n = snext - scur; recv_buf_bytes -= n; if (recv_buf_bytes <= 0) { ABLOG_(Error, "[W] substring[%d] is too long, length[%d], %s...", iout, n, recv); } recv_buf += n; } while (iout < recv_buf_array_size) { recv_buf_array[iout] = 0; iout++; } ABLOG_Return(recv_buf_array); } /** * 分割字符串 source * 按指定字符 split_char 分割 * 通过 recv_buf 接收分割出来的字符串 * 接收缓冲区长度 recv_buf_len * 返回下一分割段的起始位置,没有下一段时*source应该为0; */ char *split_string_next(char *source, char split_char, char *recv_buf, int recv_buf_len) { char c; int n = 0; while ((c = *source) && c != split_char) { if (n < recv_buf_len - 1) { *recv_buf = c; recv_buf++; } source++; n++; } *recv_buf = 0; if (split_char != 0 && c == split_char) { source++; } return source; } int replace_string(char *source, char *find, char *replace, char *recv_buf, int recv_buf_len) { int n = 0; // 原字符串 char *temp_buf = 0; if (source == recv_buf) { temp_buf = (char *)malloc(strlen(source) + 1); strcpy(temp_buf, source); source = temp_buf; } int rbfl = recv_buf_len; // 开始替换 char *found = strstr(source, find); if (rbfl > 0 && found) { int snfl = strlen(find); int snrl = strlen(replace); do { int cpyn = (found - source); if (cpyn >= 0) { cpyn = cpyn < rbfl ? cpyn : rbfl; memcpy(recv_buf, source, cpyn); source = found + snfl; recv_buf += cpyn; rbfl -= cpyn; } if (rbfl > 0) { cpyn = snrl < rbfl ? snrl : rbfl; memcpy(recv_buf, replace, cpyn); recv_buf += cpyn; rbfl -= cpyn; } found = strstr(source, find); n++; } while (rbfl > 0 && found); } if (rbfl > 0) { strncpy(recv_buf, source, rbfl); } if (temp_buf) { free(temp_buf); } return n; } char *toUpperCase(const char *str, char *rbuf) { for (; *str; str++, rbuf++) { *rbuf = toupper((int)*str); } *rbuf = 0; return rbuf; } char *trimRight(const char *str, char *rbuf) { char *c = (char *)str; if (rbuf == 0) { rbuf = c; } c += strlen(str) - 1; while (isspace((int)*c) && c >= str) { --c; } if (c < str) { rbuf[0] = 0; } else { memcpy(rbuf, str, c - str + 1); rbuf[c - str + 1] = 0; } return rbuf; } char *trimLeft(const char *str, char *rbuf) { char *c = (char *)str; if (rbuf == 0) { rbuf = c; } while ((isspace((int)*c)) != 0) { c++; } strcpy(rbuf, c); return rbuf; } // char *trim(const char *str, char *rbuf) // { // if (rbuf == 0) // { // rbuf = (char *)str; // } // trimLeft(str, rbuf); // trimRight(rbuf, rbuf); // return rbuf; // } // long read_mapping_file(int fd) // { // ABLOG_Entry(Public, read_mapping_file); // long ret_map_id = new_mapping(); // int flen = lseek(fd, 0, SEEK_END); // char *buf = MALLOC(flen + 1); // memset(buf, 0, flen + 1); // lseek(fd, 0, SEEK_SET); // read(fd, buf, flen); // char *line_buffer = buf; // while (line_buffer[0]) // { // char *newline = strstr(line_buffer, "\n"); // if (newline) // { // newline[0] = 0; // } // trimLeft(line_buffer, 0); // if (line_buffer[0] != '#' && strlen(line_buffer) > 0) // { // char *kv[2]; // split_string(line_buffer, '=', line_buffer, flen + 1, kv, 2); // char *key = trim(kv[0], 0); // char *value = trim(kv[1], 0); // ABLOG_Printf(Detail, (ABLOG, "[D] %s=%s", key, value)); // put_string_mapping(ret_map_id, key, value); // } // line_buffer = newline ? newline + 1 : 0; // } // FREE(buf); // ABLOG_Return_Long(ret_map_id); // } int write_mapping_file(int fd, long mid) { ABLOG_Entry(Public, read_mapping_file); MapEntry me = items_mapping(mid); lseek(fd, 0, SEEK_SET); ftruncate(fd, 0); while (me) { write(fd, me->key, strlen(me->key)); write(fd, "=", 1); write(fd, me->value, strlen(me->value)); write(fd, "\r\n", 2); me = me->next; } ABLOG_Return_Int(lseek(fd, 0, SEEK_END)); } #define DIR_MODE (S_IRWXU | S_IRWXG | S_IRWXO) int mk_dir(char *dir) { DIR *mydir = NULL; if ((mydir = opendir(dir)) == NULL) // 判断目录 { int ret = mk_parent_dir(dir); if (ret != 0) { return ret; } ret = mkdir(dir, DIR_MODE); // 创建目录 if (ret != 0) { // printf("%s created failed!\n", dir); return ret; } // printf("%s created sucess!\n", dir); } // else printf("%s exist!\n", dir); return 0; } int mk_parent_dir(char *filepath) { char *pIndex = rindex(filepath, '/'); if (pIndex != NULL && pIndex != filepath) { char pdir[512] = {0}; int msg_size = pIndex - filepath; memcpy(pdir, filepath, msg_size); // printf("%s\n", pdir); return mk_dir(pdir); } return 0; }