use of org.apache.commons.httpclient.HttpMethod in project zm-mailbox by Zimbra.
the class TestPreAuthServlet method testShouldNotAllowPreAuthGetCookieReuse.
public void testShouldNotAllowPreAuthGetCookieReuse() throws Exception {
Account account = TestUtil.getAccount("user1");
AuthToken authToken = new ZimbraAuthToken(account);
System.out.println(authToken.isRegistered());
HttpClient client = new HttpClient();
Server localServer = Provisioning.getInstance().getLocalServer();
String protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);
String url = protoHostPort + PRE_AUTH_URL;
//allow first request
HttpMethod method = new GetMethod(url);
NameValuePair[] queryStringPairArray = new NameValuePair[] { new NameValuePair("isredirect", "1"), new NameValuePair("authtoken", authToken.getEncoded()) };
method.setQueryString(queryStringPairArray);
int respCode = HttpClientUtil.executeMethod(client, method);
//reject second request
method = new GetMethod(url);
method.setQueryString(queryStringPairArray);
respCode = HttpClientUtil.executeMethod(client, method);
Assert.assertEquals(400, respCode);
}
use of org.apache.commons.httpclient.HttpMethod in project zm-mailbox by Zimbra.
the class TestPreAuthServlet method testPreAuthAccountNotActive.
public void testPreAuthAccountNotActive() throws Exception {
String user = "user1";
Account acct = TestUtil.getAccount(user);
Provisioning prov = Provisioning.getInstance();
Map<String, Object> attrs = new HashMap<String, Object>();
attrs.put(Provisioning.A_zimbraAccountStatus, "maintenance");
prov.modifyAttrs(acct, attrs);
System.out.println("Before the test:");
System.out.println(Provisioning.A_zimbraAccountStatus + ": " + acct.getAttr(Provisioning.A_zimbraAccountStatus));
System.out.println();
String preAuthKey = setUpDomain();
String preAuthUrl = genPreAuthUrl(preAuthKey, user, false, false);
System.out.println("preAuthKey=" + preAuthKey);
System.out.println("preAuth=" + preAuthUrl);
Server localServer = Provisioning.getInstance().getLocalServer();
String protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);
String url = protoHostPort + preAuthUrl;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
try {
int respCode = HttpClientUtil.executeMethod(client, method);
int statusCode = method.getStatusCode();
String statusLine = method.getStatusLine().toString();
System.out.println("respCode=" + respCode);
System.out.println("statusCode=" + statusCode);
System.out.println("statusLine=" + statusLine);
assertEquals(400, statusCode);
} catch (HttpException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
method.releaseConnection();
}
//revert account status back to active
attrs = new HashMap<String, Object>();
attrs.put(Provisioning.A_zimbraAccountStatus, "active");
prov.modifyAttrs(acct, attrs);
System.out.println("After the test:");
System.out.println(Provisioning.A_zimbraAccountStatus + ": " + acct.getAttr(Provisioning.A_zimbraAccountStatus));
System.out.println();
}
use of org.apache.commons.httpclient.HttpMethod in project zm-mailbox by Zimbra.
the class ElasticSearchIndex method deleteIndex.
@Override
public void deleteIndex() {
HttpMethod method = new DeleteMethod(ElasticSearchConnector.actualUrl(indexUrl));
try {
ElasticSearchConnector connector = new ElasticSearchConnector();
int statusCode = connector.executeMethod(method);
if (statusCode == HttpStatus.SC_OK) {
boolean ok = connector.getBooleanAtJsonPath(new String[] { "ok" }, false);
boolean acknowledged = connector.getBooleanAtJsonPath(new String[] { "acknowledged" }, false);
if (!ok || !acknowledged) {
ZimbraLog.index.debug("Delete index status ok=%b acknowledged=%b", ok, acknowledged);
}
} else {
String error = connector.getStringAtJsonPath(new String[] { "error" });
if (error != null && error.startsWith("IndexMissingException")) {
ZimbraLog.index.debug("Unable to delete index for key=%s. Index is missing", key);
} else {
ZimbraLog.index.error("Problem deleting index for key=%s error=%s", key, error);
}
}
} catch (HttpException e) {
ZimbraLog.index.error("Problem Deleting index with key=" + key, e);
} catch (IOException e) {
ZimbraLog.index.error("Problem Deleting index with key=" + key, e);
}
haveMappingInfo = false;
}
use of org.apache.commons.httpclient.HttpMethod in project zm-mailbox by Zimbra.
the class ExchangeFreeBusyProvider method getFreeBusyForHost.
public List<FreeBusy> getFreeBusyForHost(String host, ArrayList<Request> req) throws IOException {
ArrayList<FreeBusy> ret = new ArrayList<FreeBusy>();
int fb_interval = LC.exchange_free_busy_interval_min.intValueWithinRange(5, 1444);
Request r = req.get(0);
ServerInfo serverInfo = (ServerInfo) r.data;
if (serverInfo == null) {
ZimbraLog.fb.warn("no exchange server info for user " + r.email);
return ret;
}
if (!serverInfo.enabled) {
return ret;
}
String url = constructGetUrl(serverInfo, req);
ZimbraLog.fb.debug("fetching fb from url=" + url);
HttpMethod method = new GetMethod(url);
Element response = null;
try {
int status = sendRequest(method, serverInfo);
if (status != 200)
return getEmptyList(req);
if (ZimbraLog.fb.isDebugEnabled()) {
Header cl = method.getResponseHeader("Content-Length");
int contentLength = 10240;
if (cl != null)
contentLength = Integer.valueOf(cl.getValue());
String buf = new String(com.zimbra.common.util.ByteUtil.readInput(method.getResponseBodyAsStream(), contentLength, contentLength), "UTF-8");
ZimbraLog.fb.debug(buf);
response = Element.parseXML(buf);
} else
response = Element.parseXML(method.getResponseBodyAsStream());
} catch (XmlParseException e) {
ZimbraLog.fb.warn("error parsing fb response from exchange", e);
return getEmptyList(req);
} catch (IOException e) {
ZimbraLog.fb.warn("error parsing fb response from exchange", e);
return getEmptyList(req);
} finally {
method.releaseConnection();
}
for (Request re : req) {
String fb = getFbString(response, re.email);
ret.add(new ExchangeUserFreeBusy(fb, re.email, fb_interval, re.start, re.end));
}
return ret;
}
use of org.apache.commons.httpclient.HttpMethod in project zm-mailbox by Zimbra.
the class ProxyServlet method doProxy.
private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ZimbraLog.clearContext();
boolean isAdmin = isAdminRequest(req);
AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true);
if (authToken == null) {
String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
if (zAuthToken != null) {
try {
authToken = AuthProvider.getAuthToken(zAuthToken);
if (authToken.isExpired()) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
return;
}
if (!authToken.isRegistered()) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
return;
}
if (isAdmin && !authToken.isAdmin()) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
return;
}
} catch (AuthTokenException e) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
return;
}
}
}
if (authToken == null) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
return;
}
// get the posted body before the server read and parse them.
byte[] body = copyPostedData(req);
// sanity check
String target = req.getParameter(TARGET_PARAM);
if (target == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
// check for permission
URL url = new URL(target);
if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
// determine whether to return the target inline or store it as an upload
String uploadParam = req.getParameter(UPLOAD_PARAM);
boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));
HttpMethod method = null;
try {
HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
HttpProxyUtil.configureProxy(client);
String reqMethod = req.getMethod();
if (reqMethod.equalsIgnoreCase("GET")) {
method = new GetMethod(target);
} else if (reqMethod.equalsIgnoreCase("POST")) {
PostMethod post = new PostMethod(target);
if (body != null)
post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
method = post;
} else if (reqMethod.equalsIgnoreCase("PUT")) {
PutMethod put = new PutMethod(target);
if (body != null)
put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
method = put;
} else if (reqMethod.equalsIgnoreCase("DELETE")) {
method = new DeleteMethod(target);
} else {
ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
// handle basic auth
String auth, user, pass;
auth = req.getParameter(AUTH_PARAM);
user = req.getParameter(USER_PARAM);
pass = req.getParameter(PASS_PARAM);
if (auth != null && user != null && pass != null) {
if (!auth.equals(AUTH_BASIC)) {
ZimbraLog.zimlet.info("unsupported auth type: " + auth);
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
HttpState state = new HttpState();
state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
client.setState(state);
method.setDoAuthentication(true);
}
Enumeration headers = req.getHeaderNames();
while (headers.hasMoreElements()) {
String hdr = (String) headers.nextElement();
ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
if (canProxyHeader(hdr)) {
ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
if (hdr.equalsIgnoreCase("x-host"))
method.getParams().setVirtualHost(req.getHeader(hdr));
else
method.addRequestHeader(hdr, req.getHeader(hdr));
}
}
try {
if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
method.setFollowRedirects(true);
}
HttpClientUtil.executeMethod(client, method);
} catch (HttpException ex) {
ZimbraLog.zimlet.info("exception while proxying " + target, ex);
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode();
// workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
Header ctHeader = method.getResponseHeader("Content-Type");
String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue();
InputStream targetResponseBody = method.getResponseBodyAsStream();
if (asUpload) {
String filename = req.getParameter(FILENAME_PARAM);
if (filename == null || filename.equals(""))
filename = new ContentType(contentType).getParameter("name");
if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null)
filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()).getParameter("filename");
if (filename == null || filename.equals(""))
filename = "unknown";
List<Upload> uploads = null;
if (targetResponseBody != null) {
try {
Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId());
uploads = Arrays.asList(up);
} catch (ServiceException e) {
if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
else
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
}
resp.setStatus(status);
FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
} else {
resp.setStatus(status);
resp.setContentType(contentType);
for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName()))
resp.addHeader(h.getName(), h.getValue());
if (targetResponseBody != null)
ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
}
} finally {
if (method != null)
method.releaseConnection();
}
}
Aggregations