/* $Id: convert-geoip.c,v 1.3 2006/11/01 20:00:15 maxim Exp $ * * converts MaxMind Geo-IP DB to own format of ip-ranges * */ #include #include #include #include #include "configure.h" #include "common/settings.h" #include "common/ip_ranges.h" #include "common/misc.h" #include "common/str.h" int convert() { IPRanges* countries = newIPRanges("countries"); unsigned count = 1, prevfrom = 0, prevto = 0, prev = 0; char str[LONG_STR]; char filename[PATH_LEN]; FILE* file; snprintf(filename, PATH_LEN, "conf/countries.ips.%d", getpid()); if (!(file = fopen(filename, "w"))) return message(SYS|ERROR, "cannot open %s", filename); fprintf(file, "%s %d\n", ip2string(0), 0); while(fgets(str, LONG_STR, stdin)) { char fromStr[SHORT_STR], toStr[SHORT_STR], from_[SHORT_STR], to_[SHORT_STR], code_[SHORT_STR], name_[SHORT_STR]; unsigned from, to; short code; char* c; split(str, ",", SHORT_STR, fromStr, toStr, from_, to_, code_, name_, NULL); from = strtoul(from_ + 1, NULL, 10); to = strtoul(to_ + 1, NULL, 10); strtolower(code_ + 1); if ((c = strchr(code_ + 1, '"'))) *c = 0; code = code2id(countries, code_ + 1); if (prevto >= from) { message(MESSAGE, "skip unsorted: %s", str); continue; } prevfrom = from; prevto = to; if (code < 0) { message(MESSAGE, "unknown country: %s (%s)", code_ + 1, name_); code = 0; } if (prev != code) { fprintf(file, "%s %d\n", ip2string(from), code); prev = code; count++; } } if (prevto && prevto != 0xFFFFFFFFU) { fprintf(file, "%s %d\n", ip2string(prevto + 1), 0); count++; } if (fclose(file)) return message(SYS|ERROR, "cannot close %s", filename); if (rename(filename, "conf/countries.ips")) return message(SYS|ERROR, "cannot rename %s -> %s", filename, "conf/countries.ips"); debug("%d ranges created", count); return OK; } int main() { progName = "convert-geoip"; if (chdir(ROOT)) return 1; return !convert(); }