java.lang.Object
net.i2p.client.naming.NamingService
net.i2p.client.naming.SingleFileNamingService
A naming service based on a single file using the "hosts.txt" format. Supports adds, removes, and listeners.
All methods here are case-sensitive. Conversion to lower case is done in HostsTxtNamingService.
This does NOT provide .b32.i2p or {b64} resolution. It also does not do any caching. Use from HostsTxtNamingService or chain with another NamingService via MetaNamingService if you need those features.
Field Summary
FieldsModifier and TypeFieldDescriptionprivate longFile timestamp the current cache was read at.private final FileThe hosts file being read.private final ReentrantReadWriteLockGuards reads and writes of the file.private booleanTrue once the service is closed.Hostname to base64 key cache, guarded by _fileLock; valid when _cacheStamp >= file mtime.private longLast write time.private intCached number of entries.Fields inherited from class NamingService
_context, _listeners, _log, _updaters, PROP_IMPLModifier and TypeFieldDescriptionprotected final I2PAppContextThe app context.protected final Set<NamingServiceListener> The listeners.protected final LogThe logger.protected final Set<NamingServiceUpdater> The updaters.static final StringWhat classname should be used as the naming service impl?Constructor Summary
ConstructorsConstructorDescriptionSingleFileNamingService(I2PAppContext context, String filename) Application context.Method Summary
Modifier and TypeMethodDescriptionprivate static booleanendsWithNewline(File file) Whether the file ends with a newline.voidexport(Writer out, Properties options) Overridden for efficiency.getBase64Entries(Properties options) Overridden since we store base64 natively.getEntries(Properties options) Return all entries matching the options.private StringBetter thanDataHelper.loadProps(), doesn't load the whole file into memory, and stops when it finds a match.getName()Return the file's absolute path.getNames(Properties options) Return all known host names.private voidTakes the file read lock.private booleanTry to acquire the write lock.private voidFull-scan parse of the hosts file into _keyCache (hostname -> base64 key).lookup(String hostname, Properties lookupOptions, Properties storedOptions) Will strip a "www." prefix and retry if lookup fails.booleanput(String hostname, Destination d, Properties options) Store a hostname-destination mapping.booleanputIfAbsent(String hostname, Destination d, Properties options) Store a hostname-destination mapping if not already present.private voidReleases the file read lock.private voidReleases the file write lock.booleanremove(String hostname, Properties options) Remove a hostname from the naming service.reverseLookup(Destination dest, Properties options) Reverse lookup a destination to a hostname.voidshutdown()Parent will call when removed.intsize(Properties options) Return the number of entries.private static StringstripComment(String line) Strip an end-of-line comment and trim surrounding whitespace.static voidwriteOptions(Properties options, Writer out) Write the subscription options part of the line (including the #!).Methods inherited from class NamingService
addDestination, addDestination, addNamingService, addNamingService, createInstance, export, getConfiguration, getEntries, getNames, getNamingServices, getParent, isB32Host, isBlindedHost, isI2PHost, lookup, lookup, lookupAll, lookupAll, lookupBase32, lookupBase64, put, putAll, putIfAbsent, registerListener, registerUpdater, remove, remove, remove, removeNamingService, requestUpdate, reverseLookup, reverseLookup, reverseLookupAll, reverseLookupAll, reverseLookupAll, setConfiguration, size, start, toString, unregisterListener, unregisterUpdater, updateModifier and TypeMethodDescriptionbooleanaddDestination(String hostname, Destination d) Add a Destination to an existing hostname's entry in the addressbook.booleanaddDestination(String hostname, Destination d, Properties options) Add a Destination to an existing hostname's entry in the addressbook.booleanOnly for chaining-capable NamingServices.booleanaddNamingService(NamingService ns, boolean head) Only for chaining-capable NamingServices.static final NamingServicecreateInstance(I2PAppContext context) WARNING - for use byI2PAppContextonly - others must useI2PAppContext.namingService().voidExport in a hosts.txt format.Warning - unimplemented in any subclass.Warning - This obviously brings the whole database into memory, so use is discouraged.getNames()All known hostnames.For daisy chaining (MetaNamingService).This implementation returns null.static booleanIs this a b32 hostname? Does NOT validate the base32 part except for length.static booleanisBlindedHost(String hostname) Is this a blinded ("b33") hostname? Does NOT validate the base32 part except for length.static booleanIs this an i2p hostname?Look up a hostname.Same asNamingService.lookupBase32(String, int)but with the SHA256 Hash precalculated This implementation returns null.For NamingServices that support multiple Destinations for a single hostname, return all of them.lookupAll(String hostname, Properties lookupOptions, List<Properties> storedOptions) For NamingServices that support multiple Destinations and Properties for a single hostname, return all of them.lookupBase32(String hostname, int timeout) Lookup a Base 32 address.protected DestinationlookupBase64(String hostname) If the hostname is a valid Base64 encoded destination, return the decoded Destination.booleanput(String hostname, Destination d) Add a hostname and Destination to the addressbook.booleanputAll(Map<String, Destination> entries, Properties options) Put all the entries, each with the given options.booleanputIfAbsent(String hostname, Destination d) Add a hostname and Destination to the addressbook.voidRegister a listener for naming service changes.voidRegister an updater for the naming service.booleanDelete the entry.booleanremove(String hostname, Destination d) Remove a hostname's entry only if it contains the Destination d.booleanremove(String hostname, Destination d, Properties options) Remove a hostname's entry only if it contains the Destination d.booleanOnly for chaining-capable NamingServices.voidrequestUpdate(Properties options) Ask any registered updaters to update now.reverseLookup(Destination dest) Reverse lookup a destination.Reverse lookup a hash.reverseLookupAll(Destination dest) Reverse lookup a destination This implementation returns reverseLookupAll(dest, null).reverseLookupAll(Destination d, Properties options) Same as reverseLookupAll(dest) but with options This implementation returns the result from reverseLookup, or null.Reverse lookup a hash.booleanWarning - unimplemented in any subclass.intsize()The number of entries in this naming service.voidstart()Parent will call when added.toString()Returns a string representation of this naming service.voidUnregister a listener for naming service changes.voidUnregister an updater for the naming service.booleanupdate(String hostname, Destination d, Properties options) Fails if entry did not previously exist.
Field Details
_file
The hosts file being read._fileLock
Guards reads and writes of the file._size
private volatile int _sizeCached number of entries._lastWrite
private long _lastWriteLast write time._keyCache
_cacheStamp
private volatile long _cacheStampFile timestamp the current cache was read at._isClosed
private volatile boolean _isClosedTrue once the service is closed.
Constructor Details
SingleFileNamingService
Application context.- Parameters:
context- the application contextfilename- the hosts file name
Method Details
getName
Return the file's absolute path.- Overrides:
getNamein classNamingService- Returns:
- the file's absolute path
lookup
Will strip a "www." prefix and retry if lookup fails.- Specified by:
lookupin classNamingService- Parameters:
hostname- case-sensitive; caller should convert to lower caselookupOptions- unused, may be nullstoredOptions- unused, may be null- Returns:
- dest or null
reverseLookup
Reverse lookup a destination to a hostname.- Overrides:
reverseLookupin classNamingService- Parameters:
dest- non-null destination to look upoptions- unused, may be null- Returns:
- hostname or null
getKey
Better thanDataHelper.loadProps(), doesn't load the whole file into memory, and stops when it finds a match.- Parameters:
host- case-sensitive; caller should convert to lower case- Returns:
- the base64 destination key mapped to that hostname in the hosts file, or null if the file holds no such entry
- Throws:
IOException- if the hosts file changed and could not be re-read
loadKeyCacheLocked
Full-scan parse of the hosts file into _keyCache (hostname -> base64 key). Caller must hold the read lock. Sets _cacheStamp on success.- Throws:
IOException- if the hosts file exists but could not be read
put
Store a hostname-destination mapping.- Overrides:
putin classNamingService- Parameters:
hostname- case-sensitive; caller should convert to lower cased- the destination for the hostnameoptions- if non-null, any prefixed with '=' will be appended in subscription format- Returns:
- true if the entry was stored; this base implementation always returns false
putIfAbsent
Store a hostname-destination mapping if not already present.- Overrides:
putIfAbsentin classNamingService- Parameters:
hostname- case-sensitive; caller should convert to lower cased- the destination for the hostnameoptions- if non-null, any prefixed with '=' will be appended in subscription format- Returns:
- true if no entry existed and the new one was stored; this base implementation always returns false
writeOptions
Write the subscription options part of the line (including the #!). Only options starting with '=' (if any) are written (with the '=' stripped). Does not write a newline.- Parameters:
options- non-nullout- the writer to write to- Throws:
IOException- if the writer rejects the property data
remove
Remove a hostname from the naming service.- Overrides:
removein classNamingService- Parameters:
hostname- case-sensitive; caller should convert to lower caseoptions- unused, may be null- Returns:
- true if removed successfully, false on error or if it did not exist
getEntries
Return all entries matching the options.- Overrides:
getEntriesin classNamingService- Parameters:
options- null OK, or as follows: Key "search": return only those matching substring Key "startsWith": return only those starting with ("[0-9]" allowed) Key "skip": number of matching entries to skip Key "limit": maximum number of matching entries to return- Returns:
- the matching hostname to destination pairs, empty when the file does not exist
getBase64Entries
Overridden since we store base64 natively.- Overrides:
getBase64Entriesin classNamingService- Parameters:
options- null OK, or as follows: Key "search": return only those matching substring Key "startsWith": return only those starting with ("[0-9]" allowed)- Returns:
- all mappings (matching the options if non-null) or empty Map if none. Returned Map is not sorted.
export
Overridden for efficiency. Output is not sorted.- Overrides:
exportin classNamingService- Parameters:
out- the writer to export tooptions- unused, may be null- Throws:
IOException- if an I/O error occurs
getNames
Return all known host names.- Overrides:
getNamesin classNamingService- Parameters:
options- unused, may be null- Returns:
- all known host names, unsorted
size
Return the number of entries.- Overrides:
sizein classNamingService- Parameters:
options- unused, may be null- Returns:
- number of entries (matching the options if non-null) or -1 if unknown
shutdown
public void shutdown()Description copied from class:NamingServiceParent will call when removed. If this is the root naming service, the core will stop it. Should not be called by others.- Overrides:
shutdownin classNamingService
getReadLock
private void getReadLock()Takes the file read lock.releaseReadLock
private void releaseReadLock()Releases the file read lock.getWriteLock
private boolean getWriteLock()Try to acquire the write lock.- Returns:
- true if the lock was acquired
releaseWriteLock
private void releaseWriteLock()Releases the file write lock.stripComment
endsWithNewline
Whether the file ends with a newline.- Parameters:
file- the file to inspect- Returns:
- true if the file exists, is non-empty and ends with a newline