use of gnu.getopt.Getopt in project gate-core by GateNLP.
the class Main method processArgs.
/**
* Process arguments and set up member fields appropriately.
* Will shut down the process (via System.exit) if there are
* incorrect arguments, or if the arguments ask for something
* simple like printing the help message.
*/
public static void processArgs(String[] args) {
Getopt g = new Getopt("GATE main", args, "hd:ei:");
int c;
while ((c = g.getopt()) != -1) switch(c) {
// -h
case 'h':
help();
usage();
System.exit(STATUS_NORMAL);
break;
// -d creole-dir
case 'd':
String urlString = g.getOptarg();
URL u = null;
try {
u = new URL(urlString);
} catch (MalformedURLException e) {
Err.prln("Bad URL: " + urlString);
Err.prln(e);
System.exit(STATUS_ERROR);
}
pendingCreoleUrls.add(u);
Out.prln("CREOLE Directory " + urlString + " queued for registration");
break;
// -i gate.xml site-wide init file
case 'i':
String optionString = g.getOptarg();
@SuppressWarnings("unused") URL u2 = null;
File f = new File(optionString);
try {
u2 = f.toURI().toURL();
} catch (MalformedURLException e) {
Err.prln("Bad initialisation file: " + optionString);
Err.prln(e);
System.exit(STATUS_ERROR);
}
Gate.setSiteConfigFile(f);
if (DEBUG)
Out.prln("Initialisation file " + optionString + " recorded for initialisation");
break;
case '?':
// leave the warning to getopt
System.exit(STATUS_ERROR);
break;
default:
// shouldn't happen!
Err.prln("getopt() returned " + c + "\n");
System.exit(STATUS_ERROR);
break;
}
// getopt switch
}
use of gnu.getopt.Getopt in project spoon by INRIA.
the class Daikon method read_options.
// /////////////////////////////////////////////////////////////////////////
// Read in the command line options
// Return {decls, dtrace, spinfo, map} files.
protected static FileOptions read_options(String[] args, String usage) {
if (args.length == 0) {
System.out.println("Daikon error: no files supplied on command line.");
System.out.println(usage);
throw new Daikon.TerminationMessage();
}
// LinkedHashSet because it can be confusing to users if files (of the
// same type) are gratuitously processed in a different order than they
// were supplied on the command line.
HashSet<File> decl_files = new LinkedHashSet<File>();
HashSet<String> dtrace_files = new LinkedHashSet<String>();
/* either file names or "-"*/
HashSet<File> spinfo_files = new LinkedHashSet<File>();
HashSet<File> map_files = new LinkedHashSet<File>();
LongOpt[] longopts = new LongOpt[] { // Control output
new LongOpt(help_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(no_text_output_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(format_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(show_progress_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(no_show_progress_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(noversion_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(output_num_samples_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(files_from_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(omit_from_output_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), // Control invariant detection
new LongOpt(conf_limit_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(list_type_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(no_dataflow_hierarchy_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(suppress_redundant_SWITCH, LongOpt.NO_ARGUMENT, null, 0), // Process only part of the trace file
new LongOpt(ppt_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(ppt_omit_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(var_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(var_omit_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), // Configuration options
new LongOpt(server_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(config_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(config_option_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), // Debugging
new LongOpt(debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(track_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(disc_reason_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(mem_stat_SWITCH, LongOpt.NO_ARGUMENT, null, 0) };
Getopt g = new Getopt("daikon.Daikon", args, "ho:", longopts);
int c;
while ((c = g.getopt()) != -1) {
switch(c) {
case 0:
// got a long option
String option_name = longopts[g.getLongind()].getName();
// Control output
if (help_SWITCH.equals(option_name)) {
System.out.println(usage);
throw new Daikon.TerminationMessage();
} else if (no_text_output_SWITCH.equals(option_name)) {
no_text_output = true;
} else if (format_SWITCH.equals(option_name)) {
String format_name = g.getOptarg();
Daikon.output_format = OutputFormat.get(format_name);
if (Daikon.output_format == null) {
throw new Daikon.TerminationMessage("Unknown output format: --format " + format_name);
}
} else if (show_progress_SWITCH.equals(option_name)) {
show_progress = true;
LogHelper.setLevel("daikon.Progress", LogHelper.FINE);
} else if (no_show_progress_SWITCH.equals(option_name)) {
show_progress = false;
} else if (noversion_SWITCH.equals(option_name)) {
noversion_output = true;
} else if (output_num_samples_SWITCH.equals(option_name)) {
output_num_samples = true;
} else if (files_from_SWITCH.equals(option_name)) {
String files_from_filename = g.getOptarg();
try {
for (String filename : new TextFile(files_from_filename)) {
// Ignore blank lines in file.
if (filename.equals("")) {
continue;
}
// This code is duplicated below outside the options loop.
// These aren't "endsWith()" because there might be a suffix
// on the end (eg, a date, or ".gz").
File file = new File(filename);
if (!file.exists()) {
throw new Daikon.TerminationMessage("File " + filename + " not found.");
}
if (filename.indexOf(".decls") != -1) {
decl_files.add(file);
} else if (filename.indexOf(".dtrace") != -1) {
dtrace_files.add(filename);
} else if (filename.indexOf(".spinfo") != -1) {
spinfo_files.add(file);
} else if (filename.indexOf(".map") != -1) {
map_files.add(file);
} else {
throw new Daikon.TerminationMessage("Unrecognized file extension: " + filename);
}
}
} catch (IOException e) {
throw new RuntimeException(String.format("Error reading --files_from file: %s", files_from_filename));
}
break;
} else if (omit_from_output_SWITCH.equals(option_name)) {
String f = g.getOptarg();
for (int i = 0; i < f.length(); i++) {
if ("0rs".indexOf(f.charAt(i)) == -1)
throw new Daikon.TerminationMessage("omit_from_output flag letter '" + f.charAt(i) + "' is unknown");
omit_types[f.charAt(i)] = true;
}
omit_from_output = true;
} else // Control invariant detection
if (conf_limit_SWITCH.equals(option_name)) {
double limit = Double.parseDouble(g.getOptarg());
if ((limit < 0.0) || (limit > 1.0)) {
throw new Daikon.TerminationMessage(conf_limit_SWITCH + " must be between [0..1]");
}
Configuration.getInstance().apply("daikon.inv.Invariant.confidence_limit", String.valueOf(limit));
} else if (list_type_SWITCH.equals(option_name)) {
try {
String list_type_string = g.getOptarg();
ProglangType.list_implementors.add(list_type_string);
} catch (Exception e) {
throw new Daikon.TerminationMessage("Problem parsing " + list_type_SWITCH + " option: " + e);
}
break;
} else if (no_dataflow_hierarchy_SWITCH.equals(option_name)) {
use_dataflow_hierarchy = false;
} else if (suppress_redundant_SWITCH.equals(option_name)) {
suppress_redundant_invariants_with_simplify = true;
} else // Process only part of the trace file
if (ppt_regexp_SWITCH.equals(option_name)) {
if (ppt_regexp != null)
throw new Daikon.TerminationMessage("multiple --" + ppt_regexp_SWITCH + " regular expressions supplied on command line");
String regexp_string = g.getOptarg();
try {
// System.out.println("Regexp = " + regexp_string);
ppt_regexp = Pattern.compile(regexp_string);
} catch (Exception e) {
throw new Daikon.TerminationMessage("Bad regexp " + regexp_string + " for " + ppt_regexp_SWITCH + ": " + e.getMessage());
}
break;
} else if (ppt_omit_regexp_SWITCH.equals(option_name)) {
if (ppt_omit_regexp != null)
throw new Daikon.TerminationMessage("multiple --" + ppt_omit_regexp_SWITCH + " regular expressions supplied on command line");
String regexp_string = g.getOptarg();
try {
// System.out.println("Regexp = " + regexp_string);
ppt_omit_regexp = Pattern.compile(regexp_string);
} catch (Exception e) {
throw new Daikon.TerminationMessage("Bad regexp " + regexp_string + " for " + ppt_omit_regexp_SWITCH + ": " + e.getMessage());
}
break;
} else if (var_regexp_SWITCH.equals(option_name)) {
if (var_regexp != null)
throw new Daikon.TerminationMessage("multiple --" + var_regexp_SWITCH + " regular expressions supplied on command line");
String regexp_string = g.getOptarg();
try {
// System.out.println("Regexp = " + regexp_string);
var_regexp = Pattern.compile(regexp_string);
} catch (Exception e) {
throw new Daikon.TerminationMessage("Bad regexp " + regexp_string + " for " + var_regexp_SWITCH + ": " + e.getMessage());
}
break;
} else if (var_omit_regexp_SWITCH.equals(option_name)) {
if (var_omit_regexp != null)
throw new Daikon.TerminationMessage("multiple --" + var_omit_regexp_SWITCH + " regular expressions supplied on command line");
String regexp_string = g.getOptarg();
try {
// System.out.println("Regexp = " + regexp_string);
var_omit_regexp = Pattern.compile(regexp_string);
} catch (Exception e) {
throw new Daikon.TerminationMessage("Bad regexp " + regexp_string + " for " + var_omit_regexp_SWITCH + ": " + e.getMessage());
}
break;
} else if (server_SWITCH.equals(option_name)) {
String input_dir = g.getOptarg();
server_dir = new File(input_dir);
if (!server_dir.isDirectory() || !server_dir.canRead() || !server_dir.canWrite())
throw new RuntimeException("Could not open config file in server directory " + server_dir);
break;
// Configuration options
} else if (config_SWITCH.equals(option_name)) {
String config_file = g.getOptarg();
try {
InputStream stream = new FileInputStream(config_file);
Configuration.getInstance().apply(stream);
} catch (IOException e) {
throw new Daikon.TerminationMessage(// Is this the only possible reason for an IOException?
"Could not open config file " + config_file);
}
break;
} else if (config_option_SWITCH.equals(option_name)) {
String item = g.getOptarg();
try {
Configuration.getInstance().apply(item);
} catch (daikon.config.Configuration.ConfigException e) {
throw new Daikon.TerminationMessage(e);
}
break;
} else if (debugAll_SWITCH.equals(option_name)) {
Global.debugAll = true;
} else if (debug_SWITCH.equals(option_name)) {
LogHelper.setLevel(g.getOptarg(), LogHelper.FINE);
} else if (track_SWITCH.equals(option_name)) {
LogHelper.setLevel("daikon.Debug", LogHelper.FINE);
String error = Debug.add_track(g.getOptarg());
if (error != null) {
throw new Daikon.TerminationMessage("Error parsing track argument '" + g.getOptarg() + "' - " + error);
}
} else if (disc_reason_SWITCH.equals(option_name)) {
try {
PrintInvariants.discReasonSetup(g.getOptarg());
} catch (IllegalArgumentException e) {
throw new Daikon.TerminationMessage(e);
}
} else if (mem_stat_SWITCH.equals(option_name)) {
use_mem_monitor = true;
} else {
throw new Daikon.TerminationMessage("Unknown option " + option_name + " on command line");
}
break;
case 'h':
System.out.println(usage);
throw new Daikon.TerminationMessage();
case 'o':
String inv_filename = g.getOptarg();
if (inv_file != null) {
throw new Daikon.TerminationMessage("multiple serialization output files supplied on command line: " + inv_file + " " + inv_filename);
}
inv_file = new File(inv_filename);
if (!UtilMDE.canCreateAndWrite(inv_file)) {
throw new Daikon.TerminationMessage("Cannot write to serialization output file " + inv_file);
}
break;
//
case '?':
// break; // getopt() already printed an error
System.out.println(usage);
throw new Daikon.TerminationMessage();
//
default:
System.out.println("getopt() returned " + c);
break;
}
}
// processing only to bail out at the end.
for (int i = g.getOptind(); i < args.length; i++) {
String filename = args[i];
File file = null;
if (!filename.equals("-") && !filename.equals("+")) {
file = new File(filename);
if (!file.exists()) {
throw new Daikon.TerminationMessage("File " + file + " not found.");
}
filename = file.toString();
}
// (eg, a date or ".gz").
if (filename.indexOf(".decls") != -1) {
decl_files.add(file);
} else if (filename.indexOf(".dtrace") != -1) {
dtrace_files.add(filename);
// specified on the command line.
if (inv_file == null) {
String basename;
// This puts the .inv file in the current directory.
basename = new File(filename).getName();
// This puts the .inv file in the same directory as the .dtrace file.
// basename = filename;
int base_end = basename.indexOf(".dtrace");
String inv_filename = basename.substring(0, base_end) + ".inv.gz";
inv_file = new File(inv_filename);
if (!UtilMDE.canCreateAndWrite(inv_file)) {
throw new Daikon.TerminationMessage("Cannot write to file " + inv_file);
}
}
} else if (filename.indexOf(".spinfo") != -1) {
spinfo_files.add(file);
} else if (filename.indexOf(".map") != -1) {
map_files.add(file);
} else if (filename.equals("-") || filename.equals("+")) {
dtrace_files.add(filename);
} else {
throw new Daikon.TerminationMessage("Unrecognized file type: " + file);
}
}
// Set the fuzzy float comparison ratio. This needs to be done after
// any configuration options (which may set the ratio) are processed.
Global.fuzzy.set_rel_diff(Invariant.dkconfig_fuzzy_ratio);
// Setup ppt_max_name based on the specified percentage of ppts to process
if (dkconfig_ppt_perc != 100) {
ppt_max_name = setup_ppt_perc(decl_files, dkconfig_ppt_perc);
System.out.println("Max ppt name = " + ppt_max_name);
}
// Validate guardNulls option
PrintInvariants.validateGuardNulls();
return new FileOptions(decl_files, dtrace_files, spinfo_files, map_files);
}
use of gnu.getopt.Getopt in project i2p.i2p by i2p.
the class SU3File method main.
/**
* Parses command line arguments when this class is used from the command
* line.
* Exits 1 on failure so this can be used in scripts.
*
* @param args Command line parameters.
*/
public static void main(String[] args) {
boolean ok = false;
try {
// defaults
String stype = null;
String ctype = null;
String ftype = null;
String kfile = null;
String crlfile = null;
String kspass = KeyStoreUtil.DEFAULT_KEYSTORE_PASSWORD;
boolean error = false;
boolean shouldVerify = true;
Getopt g = new Getopt("SU3File", args, "t:c:f:k:xp:r:");
int c;
while ((c = g.getopt()) != -1) {
switch(c) {
case 't':
stype = g.getOptarg();
break;
case 'c':
ctype = g.getOptarg();
break;
case 'f':
ftype = g.getOptarg();
break;
case 'k':
kfile = g.getOptarg();
break;
case 'r':
crlfile = g.getOptarg();
break;
case 'x':
shouldVerify = false;
break;
case 'p':
kspass = g.getOptarg();
break;
case '?':
case ':':
default:
error = true;
}
}
int idx = g.getOptind();
String cmd = args[idx];
List<String> a = new ArrayList<String>(Arrays.asList(args).subList(idx + 1, args.length));
if (error) {
showUsageCLI();
} else if ("showversion".equals(cmd)) {
ok = showVersionCLI(a.get(0));
} else if ("sign".equals(cmd)) {
// speed things up by specifying a small PRNG buffer size
Properties props = new Properties();
props.setProperty("prng.bufferSize", "16384");
new I2PAppContext(props);
ok = signCLI(stype, ctype, ftype, a.get(0), a.get(1), a.get(2), a.get(3), a.get(4), "", kspass);
} else if ("bulksign".equals(cmd)) {
Properties props = new Properties();
props.setProperty("prng.bufferSize", "16384");
new I2PAppContext(props);
ok = bulkSignCLI(stype, ctype, a.get(0), a.get(1), a.get(2), a.get(3), kspass);
} else if ("verifysig".equals(cmd)) {
ok = verifySigCLI(a.get(0), kfile);
} else if ("keygen".equals(cmd)) {
Properties props = new Properties();
props.setProperty("prng.bufferSize", "16384");
new I2PAppContext(props);
ok = genKeysCLI(stype, a.get(0), a.get(1), crlfile, a.get(2), kspass);
} else if ("extract".equals(cmd)) {
ok = extractCLI(a.get(0), a.get(1), shouldVerify, kfile);
} else {
showUsageCLI();
}
} catch (NoSuchElementException nsee) {
showUsageCLI();
} catch (IndexOutOfBoundsException ioobe) {
showUsageCLI();
}
if (!ok)
System.exit(1);
}
use of gnu.getopt.Getopt in project i2p.i2p by i2p.
the class PrivateKeyFile method main.
/**
* Create a new PrivateKeyFile, or modify an existing one, with various
* types of Certificates.
*
* Changing a Certificate does not change the public or private keys.
* But it does change the Destination Hash, which effectively makes it
* a new Destination. In other words, don't change the Certificate on
* a Destination you've already registered in a hosts.txt key add form.
*
* Copied and expanded from that in Destination.java
*/
public static void main(String[] args) {
int hashEffort = HASH_EFFORT;
String stype = null;
String hostname = null;
int mode = 0;
boolean error = false;
Getopt g = new Getopt("pkf", args, "t:nuxhse:c:a:");
int c;
while ((c = g.getopt()) != -1) {
switch(c) {
case 'c':
stype = g.getOptarg();
break;
case 't':
stype = g.getOptarg();
case 'n':
case 'u':
case 'x':
case 'h':
case 's':
if (mode == 0)
mode = c;
else
error = true;
break;
case 'a':
hostname = g.getOptarg();
if (mode == 0)
mode = c;
else
error = true;
break;
case 'e':
hashEffort = Integer.parseInt(g.getOptarg());
break;
case '?':
case ':':
default:
error = true;
break;
}
// switch
}
// while
int remaining = args.length - g.getOptind();
int reqd = mode == 's' ? 2 : 1;
if (error || remaining != reqd) {
usage();
System.exit(1);
}
String filearg = args[g.getOptind()];
I2PClient client = I2PClientFactory.createClient();
try {
File f = new File(filearg);
boolean exists = f.exists();
PrivateKeyFile pkf = new PrivateKeyFile(f, client);
Destination d;
if (stype != null) {
SigType type = SigType.parseSigType(stype);
if (type == null)
throw new IllegalArgumentException("Signature type " + stype + " is not supported");
d = pkf.createIfAbsent(type);
} else {
d = pkf.createIfAbsent();
}
if (exists)
System.out.println("Original Destination:");
else
System.out.println("Created Destination:");
System.out.println(pkf);
verifySignature(d);
switch(mode) {
case 0:
// we are done
break;
case 'n':
// Cert constructor generates a null cert
pkf.setCertType(Certificate.CERTIFICATE_TYPE_NULL);
System.out.println("New destination with null cert is:");
break;
case 'u':
pkf.setCertType(99);
System.out.println("New destination with unknown cert is:");
break;
case 'x':
pkf.setCertType(Certificate.CERTIFICATE_TYPE_HIDDEN);
System.out.println("New destination with hidden cert is:");
break;
case 'h':
System.out.println("Estimating hashcash generation time, stand by...");
System.out.println(estimateHashCashTime(hashEffort));
pkf.setHashCashCert(hashEffort);
System.out.println("New destination with hashcash cert is:");
break;
case 's':
// Sign dest1 with dest2's Signing Private Key
PrivateKeyFile pkf2 = new PrivateKeyFile(args[g.getOptind() + 1]);
pkf.setSignedCert(pkf2);
System.out.println("New destination with signed cert is:");
break;
case 't':
// KeyCert
SigType type = SigType.parseSigType(stype);
if (type == null)
throw new IllegalArgumentException("Signature type " + stype + " is not supported");
pkf.setKeyCert(type);
System.out.println("New destination with key cert is:");
break;
case 'a':
// addressbook auth
OrderedProperties props = new OrderedProperties();
HostTxtEntry he = new HostTxtEntry(hostname, d.toBase64(), props);
he.sign(pkf.getSigningPrivKey());
System.out.println("Addressbook Authentication String:");
OutputStreamWriter out = new OutputStreamWriter(System.out);
he.write(out);
out.flush();
System.out.println("");
return;
default:
// shouldn't happen
usage();
return;
}
if (mode != 0) {
System.out.println(pkf);
pkf.write();
verifySignature(pkf.getDestination());
}
} catch (I2PException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
use of gnu.getopt.Getopt in project i2p.i2p by i2p.
the class BundleRouterInfos method main.
/**
* Usage: PersistentDataStore -i configDir -o toDir -c count
*
* Copy a random selection of 'count' router infos from configDir/netDb
* to 'toDir'. Skip your own router info, and old, hidden, unreachable, and
* introduced routers, and those from bad countries.
*
* @since 0.9.15
*/
public static void main(String[] args) {
Getopt g = new Getopt("PersistentDataStore", args, "i:o:c:");
String in = System.getProperty("user.home") + "/.i2p";
String out = "netDb";
int count = 200;
boolean error = false;
int c;
while ((c = g.getopt()) != -1) {
switch(c) {
case 'i':
in = g.getOptarg();
break;
case 'o':
out = g.getOptarg();
break;
case 'c':
String scount = g.getOptarg();
try {
count = Integer.parseInt(scount);
} catch (NumberFormatException nfe) {
error = true;
}
break;
case '?':
case ':':
default:
error = true;
}
}
if (error) {
usage();
System.exit(1);
}
Properties props = new Properties();
props.setProperty(GeoIP.PROP_GEOIP_DIR, System.getProperty("user.dir") + "/installer/resources");
GeoIP geoIP = new GeoIP(new I2PAppContext(props));
File confDir = new File(in);
File dbDir = new File(confDir, "netDb");
if (!dbDir.exists()) {
System.out.println("NetDB directory " + dbDir + " does not exist");
System.exit(1);
}
File myFile = new File(confDir, "router.info");
File toDir = new File(out);
toDir.mkdirs();
InputStream fis = null;
Hash me = null;
try {
fis = new BufferedInputStream(new FileInputStream(myFile));
RouterInfo ri = new RouterInfo();
// true = verify sig on read
ri.readBytes(fis, true);
me = ri.getIdentity().getHash();
} catch (IOException e) {
// System.out.println("Can't determine our identity");
} catch (DataFormatException e) {
// System.out.println("Can't determine our identity");
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ioe) {
}
}
int routerCount = 0;
List<File> toRead = new ArrayList<File>(2048);
for (int j = 0; j < Base64.ALPHABET_I2P.length(); j++) {
File subdir = new File(dbDir, PersistentDataStore.DIR_PREFIX + Base64.ALPHABET_I2P.charAt(j));
File[] files = subdir.listFiles(PersistentDataStore.RI_FILTER);
if (files == null)
continue;
routerCount += files.length;
for (int i = 0; i < files.length; i++) {
toRead.add(files[i]);
}
}
if (toRead.isEmpty()) {
System.out.println("No files to copy in " + dbDir);
System.exit(1);
}
Collections.shuffle(toRead);
int copied = 0;
long tooOld = System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000L;
Map<String, String> ipMap = new HashMap<String, String>(count);
for (File file : toRead) {
if (copied >= count)
break;
Hash key = PersistentDataStore.getRouterInfoHash(file.getName());
if (key == null) {
System.out.println("Skipping bad " + file);
continue;
}
if (key.equals(me)) {
System.out.println("Skipping my RI");
continue;
}
fis = null;
try {
fis = new BufferedInputStream(new FileInputStream(file));
RouterInfo ri = new RouterInfo();
// true = verify sig on read
ri.readBytes(fis, true);
try {
fis.close();
} catch (IOException ioe) {
}
fis = null;
if (ri.getPublished() < tooOld) {
System.out.println("Skipping too old " + key);
continue;
}
if (ri.getCapabilities().contains("U")) {
System.out.println("Skipping unreachable " + key);
continue;
}
if (ri.getCapabilities().contains("K")) {
System.out.println("Skipping slow " + key);
continue;
}
Collection<RouterAddress> addrs = ri.getAddresses();
if (addrs.isEmpty()) {
System.out.println("Skipping hidden " + key);
continue;
}
boolean hasIntro = false;
boolean hasIPv4 = false;
boolean dupIP = false;
for (RouterAddress addr : addrs) {
if ("SSU".equals(addr.getTransportStyle()) && addr.getOption("ihost0") != null) {
hasIntro = true;
break;
}
String host = addr.getHost();
if (host != null && host.contains(".")) {
hasIPv4 = true;
geoIP.add(host);
String old = ipMap.put(host, file.getName());
if (old != null && !old.equals(file.getName())) {
dupIP = true;
break;
}
}
}
if (dupIP) {
System.out.println("Skipping dup IP " + key);
continue;
}
if (hasIntro) {
System.out.println("Skipping introduced " + key);
continue;
}
if (!hasIPv4) {
System.out.println("Skipping IPv6-only " + key);
continue;
}
File toFile = new File(toDir, file.getName());
// We could call ri.write() to avoid simultaneous change by the router
boolean ok = FileUtil.copy(file, toFile, true, true);
if (ok)
copied++;
else
System.out.println("Failed copy of " + file + " to " + toDir);
} catch (IOException e) {
System.out.println("Skipping bad " + file);
} catch (DataFormatException e) {
System.out.println("Skipping bad " + file);
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ioe) {
}
}
}
if (copied > 0) {
// now do all the geoip lookups, and delete any bad countries
geoIP.blockingLookup();
for (Map.Entry<String, String> e : ipMap.entrySet()) {
String co = geoIP.get(e.getKey());
if (co != null) {
if (BadCountries.contains(co)) {
String name = e.getValue();
File toFile = new File(toDir, name);
if (toFile.delete()) {
String full = geoIP.fullName(co);
if (full == null)
full = co;
System.out.println("Skipping " + full + ": " + name);
copied--;
}
}
}
}
}
if (copied > 0) {
System.out.println("Copied " + copied + " router info files to " + toDir);
} else {
System.out.println("Failed to copy any files to " + toDir);
System.exit(1);
}
}
Aggregations