Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public String getPlanetURL(String planet) {
}

StringBuilder url = new StringBuilder();
url.append(WebloggerRuntimeConfig.getProperty("site.absoluteurl"));
url.append(WebloggerRuntimeConfig.getAbsoluteContextURL());
url.append('/').append(planet).append('/');

return url.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,28 @@
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.apache.roller.util.RollerConstants;
import org.apache.roller.weblogger.config.runtime.RuntimeConfigDefs;
import org.apache.roller.weblogger.config.runtime.RuntimeConfigDefsParser;
import org.apache.roller.weblogger.WebloggerException;
import org.apache.roller.weblogger.business.PropertiesManager;
import org.apache.roller.weblogger.business.WebloggerFactory;
import org.apache.roller.weblogger.pojos.RuntimeConfigProperty;
import org.apache.roller.weblogger.pojos.User;
import org.apache.roller.weblogger.ui.rendering.util.cache.PlanetCache;
import org.apache.roller.weblogger.ui.rendering.util.cache.SiteWideCache;
import org.apache.roller.weblogger.ui.rendering.util.cache.WeblogFeedCache;
import org.apache.roller.weblogger.ui.rendering.util.cache.WeblogPageCache;


/**
Expand All @@ -49,7 +63,15 @@ public final class WebloggerRuntimeConfig {

// special case for our context urls
private static String relativeContextURL = null;
private static String absoluteContextURL = null;

// absolute url derived from the request being handled on this thread, used
// only while site.absoluteurl is unset and never kept past that request
private static final ThreadLocal<RequestURLs> requestURLs =
new ThreadLocal<>();
private static final AtomicBoolean absoluteURLWarningLogged =
new AtomicBoolean(false);
private static final AtomicBoolean localURLWarningLogged =
new AtomicBoolean(false);


// prevent instantiations
Expand Down Expand Up @@ -169,34 +191,240 @@ public static String getRuntimeConfigDefsAsString() {


/**
* Special method which sets the non-persisted absolute url to this site.
* The urls seen by the request being handled on this thread. The value of
* site.absoluteurl is read once per request, the first time it's needed,
* so that all links built for a request and the cache key its content is
* stored under agree, even if an administrator sets the property while
* the request is being handled.
*/
private static final class RequestURLs {
private final String requestURL;
private String siteURL;
private boolean siteURLRead;

private RequestURLs(String requestURL) {
this.requestURL = requestURL;
}
}


/**
* Set the absolute url of the request being handled on this thread. The
* InitFilter sets this at the start of each request and clears it with
* clearRequestAbsoluteContextURL() when the request is done.
*
* This property is *not* persisted in any way.
* This value is *not* persisted or shared with other threads.
*/
public static void setAbsoluteContextURL(String url) {
absoluteContextURL = url;
public static void setRequestAbsoluteContextURL(String url) {
requestURLs.set(new RequestURLs(url));
}




/**
* Forget the urls of the request handled on this thread.
*/
public static void clearRequestAbsoluteContextURL() {
requestURLs.remove();
}


/**
* The value of site.absoluteurl, or null if it is unset. Within a
* request this is the value the property had when the request first
* needed it.
*/
private static String configuredAbsoluteContextURL() {
RequestURLs request = requestURLs.get();
if (request == null) {
return liveAbsoluteContextURL();
}
if (!request.siteURLRead) {
request.siteURL = liveAbsoluteContextURL();
request.siteURLRead = true;
}
return request.siteURL;
}


private static String liveAbsoluteContextURL() {
String absURL = getProperty("site.absoluteurl");
return absURL == null || absURL.isBlank() ? null : absURL;
}


/**
* True if site.absoluteurl is set, so links can be built without a
* request. Background tasks check this before building links.
*/
public static boolean isAbsoluteContextURLSet() {
return configuredAbsoluteContextURL() != null;
}


/**
* The cache key to use for content rendered for the current request, or
* null if the content must not be cached. While site.absoluteurl is
* unset, links are built from the request's own URL, so the key includes
* it: content cached for one host name is only served to requests for
* that host name. Content rendered outside a request while the property
* is unset is not cached, because its links are incomplete.
*/
public static String cacheKey(String key) {
if (key == null || configuredAbsoluteContextURL() != null) {
return key;
}
RequestURLs request = requestURLs.get();
if (request == null || request.requestURL == null) {
return null;
}
return key + "|" + request.requestURL;
}

/**
* Saves site.absoluteurl from the current request when it is unset and the
* request comes from a global administrator, which is the case the first
* time an administrator opens the Roller UI after an upgrade.
*/
public static void saveAbsoluteContextURLForAdmin(User user) {
if (liveAbsoluteContextURL() != null || user == null
|| !user.hasGlobalPermission("admin")) {
return;
}
RequestURLs request = requestURLs.get();
try {
if (request != null && saveAbsoluteContextURLIfUnset(request.requestURL)) {
WebloggerFactory.getWeblogger().flush();
}
} catch (Exception e) {
// a lock timeout, for one, is unchecked; the request goes on
log.warn("Could not save site.absoluteurl", e);
}
}


/**
* Get the absolute url to this site.
*
* This method will just return the value of the "site.absoluteurl"
* property if it is set, otherwise it will return the non-persisted
* value which is set by the InitFilter.
* property if it is set. Otherwise it returns the url of the request
* being handled on this thread, or null when there is no such request
* (for example in background tasks).
*/
public static String getAbsoluteContextURL() {

// db prop takes priority if it exists
String absURL = getProperty("site.absoluteurl");
if(absURL != null && !absURL.isBlank()) {
String absURL = configuredAbsoluteContextURL();
if (absURL != null) {
return absURL;
}

return absoluteContextURL;

if (absoluteURLWarningLogged.compareAndSet(false, true)) {
log.warn("The site's absolute URL (site.absoluteurl) is not set, so "
+ "links in emails and feeds will use the host name of each "
+ "request. Set \"Absolute URL to site\" under Server "
+ "Admin > Configuration.");
}

RequestURLs request = requestURLs.get();
return request == null ? null : request.requestURL;
}


/**
* Save the given url as site.absoluteurl if that property is empty.
* Called when the site is being set up, by the installer and by the
* registration of the first administrator.
*
* The property is only replaced if it is still empty when it is written,
* so of several requests trying at once, only one saves its url. The
* rendering caches are cleared when the url is saved, since they hold
* content cached per host name while the property was unset.
*
* @return true if the url was saved; the caller must flush
*/
public static boolean saveAbsoluteContextURLIfUnset(String url)
throws WebloggerException {

if (url == null || url.isBlank()) {
return false;
}
if (!isPublicSiteURL(url)) {
if (localURLWarningLogged.compareAndSet(false, true)) {
log.warn("Not saving " + url + " as the site's absolute URL "
+ "(site.absoluteurl) because it isn't a public host name. "
+ "Set \"Absolute URL to site\" under Server "
+ "Admin > Configuration.");
}
return false;
}
PropertiesManager pmgr = WebloggerFactory.getWeblogger().getPropertiesManager();
RuntimeConfigProperty prop = pmgr.getProperty("site.absoluteurl");
Comment thread
mraible marked this conversation as resolved.
Resolved
String current = prop == null ? null : prop.getValue();
if (current != null && !current.isBlank()) {
return false;
}
if (prop == null) {
// the properties table is filled in at startup, so this only
// happens if that failed; a second insert would fail on flush
pmgr.saveProperty(new RuntimeConfigProperty("site.absoluteurl", url));
} else if (!pmgr.compareAndSetProperty("site.absoluteurl", current, url)) {
return false;
}
clearRenderingCaches();
log.info("Set site.absoluteurl to " + url);
return true;
}


/**
* True if the url's host looks like a public name for the site, and so
* may be saved automatically. Loopback and private addresses, and host
* names without a dot (such as "localhost" or the name of a proxy's
* backend), are left for an administrator to set.
*/
static boolean isPublicSiteURL(String url) {
String host;
try {
host = new URI(url).getHost();
} catch (URISyntaxException e) {
return false;
}
if (host == null) {
return false;
}
host = host.toLowerCase(Locale.ROOT);
if (host.startsWith("[") && host.endsWith("]")) {
host = host.substring(1, host.length() - 1);
}
if (InetAddressValidator.getInstance().isValid(host)) {
try {
// an address literal, so this doesn't look anything up
InetAddress address = InetAddress.getByName(host);
byte[] bytes = address.getAddress();
return !(address.isLoopbackAddress() || address.isAnyLocalAddress()
|| address.isLinkLocalAddress() || address.isSiteLocalAddress()
|| (address instanceof Inet6Address && (bytes[0] & 0xfe) == 0xfc));
} catch (UnknownHostException e) {
return false;
}
}
return host.indexOf('.') > 0 && !host.endsWith(".")
&& !host.endsWith(".localhost") && !host.endsWith(".local");
}


/**
* Clear the caches of rendered content, whose links may have been built
* from the url of a request.
*/
private static void clearRenderingCaches() {
WeblogPageCache.getInstance().clear();
WeblogFeedCache.getInstance().clear();
SiteWideCache.getInstance().clear();
PlanetCache.getInstance().clear();
}


/**
* Special method which sets the non-persisted relative url to this site.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class PlanetURLStrategy extends MultiPlanetURLStrategy {
@Override
public String getPlanetURL(String planet) {
StringBuilder url = new StringBuilder();
url.append(WebloggerRuntimeConfig.getProperty("site.absoluteurl"));
url.append(WebloggerRuntimeConfig.getAbsoluteContextURL());
return url.toString();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,23 @@ public WebloggerRomeFeedFetcher() {
}


/**
* Fetch a feed for a new subscription. Unlike the updater's fetch, which
* quietly skips local weblogs until site.absoluteurl is set, this says
* why a local weblog can't be added yet.
*/
@Override
public Subscription fetchSubscription(String feedURL) throws FetcherException {
if (feedURL != null && feedURL.startsWith("weblogger:")
&& !WebloggerRuntimeConfig.isAbsoluteContextURLSet()) {
throw new FetcherException("This site's weblogs can't be added "
+ "until the site's absolute URL is set. Set it under "
+ "Server Admin > Configuration.");
}
return super.fetchSubscription(feedURL);
}


@Override
public Subscription fetchSubscription(String feedURL, Date lastModified)
throws FetcherException {
Expand All @@ -75,6 +92,13 @@ public Subscription fetchSubscription(String feedURL, Date lastModified)
return super.fetchSubscription(feedURL, lastModified);
}

// the subscription and its entries store absolute links to the
// weblog, which can't be built until site.absoluteurl is set
if (!WebloggerRuntimeConfig.isAbsoluteContextURLSet()) {
log.debug("Skipping LOCAL feed until site.absoluteurl is set - " + feedURL);
return null;
}

// extract blog handle from our special feed url
String weblogHandle = null;
String[] items = feedURL.split(":", 2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import org.apache.roller.weblogger.business.runnable.RollerTaskWithLeasing;
import org.apache.roller.weblogger.business.startup.WebloggerStartup;
import org.apache.roller.weblogger.config.WebloggerConfig;
import org.apache.roller.weblogger.config.WebloggerRuntimeConfig;
import org.apache.roller.weblogger.pojos.Weblog;


Expand Down Expand Up @@ -147,6 +148,15 @@ public void runTask() {
return;
}

// subscriptions store each weblog's absolute URL, which can't be
// built until site.absoluteurl is set
if (!WebloggerRuntimeConfig.isAbsoluteContextURLSet()) {
log.warn("Not syncing local weblogs with planet subscriptions because "
+ "the site's absolute URL is not set. Set it under Server "
+ "Admin > Configuration.");
return;
}

log.info("Syncing local weblogs with planet subscriptions list");

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,9 @@ public String saveSubscription() {
addMessage("planetSubscription.success.saved");

} catch (FetcherException ex) {
addError("planetGroupSubs.error.fetchingFeed", ex.getRootCauseMessage());
// not every fetcher error wraps another exception
addError("planetGroupSubs.error.fetchingFeed", ex.getRootCause() != null
? ex.getRootCauseMessage() : ex.getMessage());

} catch (RollerException ex) {
log.error("Unexpected error saving subscription", ex);
Expand Down
Loading
Loading