List of usage examples for java.net InetAddress toString
public String toString()
From source file:net.wastl.webmail.server.WebMailServlet.java
/** * Handle a request to the WebMail servlet. This is the central method of * the WebMailServlet. It first gathers all of the necessary information * from the client, then either creates or gets a Session and executes the * URL handler for the given path./*from w w w.j a va2s . c om*/ */ public void service(ServletRequest req1, ServletResponse res1) throws ServletException { final HttpServletRequest req = (HttpServletRequest) req1; final HttpServletResponse res = (HttpServletResponse) res1; final HTTPRequestHeader http_header = new HTTPRequestHeader(); if (req.getServletPath().equals("/admin")) try { log.debug("Forwarding /admin request back to self"); req.getRequestDispatcher("WebMail/admin").forward(req1, res1); return; } catch (IOException ioe) { log.fatal("Forward from '/admin' failed", ioe); throw new ServletException(ioe.getMessage()); } final Enumeration en = req.getHeaderNames(); while (en.hasMoreElements()) { final String s = (String) en.nextElement(); http_header.setHeader(s, req.getHeader(s)); } http_header.setPath(req.getPathInfo() == null ? "/" : req.getPathInfo()); InetAddress addr; try { addr = InetAddress.getByName(req.getRemoteHost()); } catch (final UnknownHostException e) { try { addr = InetAddress.getByName(req.getRemoteAddr()); } catch (final Exception ex) { throw new ServletException("Remote host must identify!"); } } HTMLDocument content = null; final int err_code = 400; HTTPSession sess = null; /* * Here we try to parse the MIME content that the Client sent in his * POST since the JServ doesn't do that for us:-( At least we can use * the functionality provided by the standalone server where we need to * parse the content ourself anyway. */ try { final BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream()); /* * First we try to use the Servlet API's methods to parse the * parameters. Unfortunately, it doesn't know how to handle MIME * multipart POSTs, so we will have to handle that ourselves */ /* * First get all the parameters and set their values into * http_header */ Enumeration enum2 = req.getParameterNames(); while (enum2.hasMoreElements()) { final String s = (String) enum2.nextElement(); http_header.setContent(s, req.getParameter(s)); // log.info("Parameter "+s); } /* Then we set all the headers in http_header */ enum2 = req.getHeaderNames(); while (enum2.hasMoreElements()) { final String s = (String) enum2.nextElement(); http_header.setHeader(s, req.getHeader(s)); } /* * In Servlet API 2.2 we might want to fetch the attributes also, * but this doesn't work in API 2.0, so we leave it commented out */ // enum2=req.getAttributeNames(); // while(enum2.hasMoreElements()) { // String s=(String)enum2.nextElement(); // log.info("Attribute "+s); // } /* Now let's try to handle multipart/form-data posts */ if (req.getContentType() != null && req.getContentType().toUpperCase().startsWith("MULTIPART/FORM-DATA")) { final int size = Integer.parseInt(WebMailServer.getStorage().getConfig("max attach size")); final MultipartParser mparser = new MultipartParser(req, size); Part p; while ((p = mparser.readNextPart()) != null) { if (p.isFile()) { final ByteStore bs = ByteStore.getBinaryFromIS(((FilePart) p).getInputStream(), size); bs.setName(((FilePart) p).getFileName()); bs.setContentType(getStorage().getMimeType(((FilePart) p).getFileName())); http_header.setContent(p.getName(), bs); log.info("File name " + bs.getName()); log.info("Type " + bs.getContentType()); } else if (p.isParam()) { http_header.setContent(p.getName(), ((ParamPart) p).getStringValue()); } // log.info("Parameter "+p.getName()); } } try { final String url = http_header.getPath(); try { /* Find out about the session id */ sess = req.getSession(false) == null ? null : (HTTPSession) req.getSession(false).getAttribute("webmail.session"); /* * If the user was logging on, he doesn't have a session id, * so generate one. If he already had one, all the better, * we will take the old one */ if (sess == null && url.startsWith("/login")) { sess = newSession(req, http_header); } else if (sess == null && url.startsWith("/admin/login")) { http_header.setHeader("LOGIN", "Administrator"); sess = newAdminSession(req, http_header); } if (sess == null && !url.equals("/") && !url.startsWith("/passthrough") && !url.startsWith("/admin")) { content = getURLHandler().handleURL("/logout", sess, http_header); } else { /* Ensure that the session state is up-to-date */ if (sess != null) { sess.setEnv(); } /* Let the URLHandler determine the result of the query */ content = getURLHandler().handleURL(url, sess, http_header); } } catch (final InvalidPasswordException e) { log.error("Connection to " + addr.toString() + ": Authentication failed!"); if (url.startsWith("/admin/login")) { content = getURLHandler().handleURL("/admin", null, http_header); } else if (url.startsWith("/login")) { content = getURLHandler().handleURL("/", null, http_header); } else // content=new // HTMLErrorMessage(getStorage(),e.getMessage()); throw new ServletException("Invalid URL called!"); } catch (final Exception ex) { content = getURLHandler().handleException(ex, sess, http_header); log.debug("Some strange error while handling request", ex); } /* * Set some HTTP headers: Date is now, the document should * expire in 5 minutes, proxies and clients shouldn't cache it * and all WebMail documents must be revalidated when they think * they don't have to follow the "no-cache". */ res.setDateHeader("Date:", System.currentTimeMillis()); res.setDateHeader("Expires", System.currentTimeMillis() + 300000); res.setHeader("Pragma", "no-cache"); res.setHeader("Cache-Control", "must-revalidate"); synchronized (out) { res.setStatus(content.getReturnCode()); if (content.hasHTTPHeader()) { final Enumeration enumVar = content.getHTTPHeaderKeys(); while (enumVar.hasMoreElements()) { final String s = (String) enumVar.nextElement(); res.setHeader(s, content.getHTTPHeader(s)); } } /* * What we will send is an image or some other sort of * binary */ if (content instanceof HTMLImage) { final HTMLImage img = (HTMLImage) content; /* * the HTMLImage class provides us with most of the * necessary information that we want to send */ res.setHeader("Content-Type", img.getContentType()); res.setHeader("Content-Transfer-Encoding", img.getContentEncoding()); res.setHeader("Content-Length", "" + img.size()); res.setHeader("Connection", "Keep-Alive"); /* Send 8k junks */ int offset = 0; while (offset + chunk_size < img.size()) { out.write(img.toBinary(), offset, chunk_size); offset += chunk_size; } out.write(img.toBinary(), offset, img.size() - offset); out.flush(); out.close(); } else { final byte[] encoded_content = content.toString().getBytes("UTF-8"); /* * We are sending HTML text. Set the encoding to UTF-8 * for Unicode messages */ res.setHeader("Content-Length", "" + (encoded_content.length + 2)); res.setHeader("Connection", "Keep-Alive"); res.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); out.write(encoded_content); out.write("\r\n".getBytes()); out.flush(); out.close(); } } } catch (final DocumentNotFoundException e) { log.info("Connection to " + addr.toString() + ": Could not handle request (" + err_code + ") (Reason: " + e.getMessage() + ")"); throw new ServletException("Error: " + e.getMessage(), e); // res.setStatus(err_code); // res.setHeader("Content-type","text/html"); // res.setHeader("Connection","close"); // content=new HTMLErrorMessage(getStorage(),e.getMessage()); // out.write((content+"\r\n").getBytes("UTF-8")); // out.write("</HTML>\r\n".getBytes()); // out.flush(); // out.close(); } } catch (final Exception e) { log.info("Connection to " + addr.toString() + " closed unexpectedly", e); throw new ServletException(e.getMessage()); } }
From source file:jp.ne.sakura.kkkon.java.net.inetaddress.testapp.android.NetworkConnectionCheckerTestApp.java
/** Called when the activity is first created. */ @Override//from ww w . j av a 2 s . co m public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { NetworkConnectionChecker.initialize(); } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("reachable="); layout.addView(tv); this.textView = tv; Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); { Button btn = new Button(this); btn.setText("disp isReachable"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean isReachable = NetworkConnectionChecker.isReachable(); Toast toast = Toast.makeText(context, "IsReachable=" + isReachable, Toast.LENGTH_LONG); toast.show(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("upload http AsyncTask"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(0.0.0.0)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { destHost = InetAddress.getByName("0.0.0.0"); if (null != destHost) { try { if (destHost.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + destHost.toString() + " reachable"); } else { Log.d(TAG, "destHost=" + destHost.toString() + " not reachable"); } } catch (IOException e) { } } } catch (UnknownHostException e) { } Log.d(TAG, "destHost=" + destHost); } }); thread.start(); try { thread.join(1000); } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(www.google.com)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { Log.d(TAG, "start"); try { InetAddress dest = InetAddress.getByName("www.google.com"); if (null == dest) { dest = destHost; } if (null != dest) { final String[] uris = new String[] { "http://www.google.com/", "https://www.google.com/" }; for (final String destURI : uris) { URI uri = null; try { uri = new URI(destURI); } catch (URISyntaxException e) { //Log.d( TAG, e.toString() ); } if (null != uri) { URL url = null; try { url = uri.toURL(); } catch (MalformedURLException ex) { Log.d(TAG, "got exception:" + ex.toString(), ex); } URLConnection conn = null; if (null != url) { Log.d(TAG, "openConnection before"); try { conn = url.openConnection(); if (null != conn) { conn.setConnectTimeout(3 * 1000); conn.setReadTimeout(3 * 1000); } } catch (IOException e) { //Log.d( TAG, "got Exception" + e.toString(), e ); } Log.d(TAG, "openConnection after"); if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int responceCode = -1; try { Log.d(TAG, "getResponceCode before"); responceCode = httpConn.getResponseCode(); Log.d(TAG, "getResponceCode after"); } catch (IOException ex) { Log.d(TAG, "got exception:" + ex.toString(), ex); } Log.d(TAG, "responceCode=" + responceCode); if (0 < responceCode) { isReachable = true; destHost = dest; } Log.d(TAG, " HTTP ContentLength=" + httpConn.getContentLength()); httpConn.disconnect(); Log.d(TAG, " HTTP ContentLength=" + httpConn.getContentLength()); } } } // if uri if (isReachable) { //break; } } // for uris } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } Log.d(TAG, "end"); } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { Log.d(TAG, "start"); try { InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp"); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); } destHost = dest; } catch (IOException e) { } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } Log.d(TAG, "end"); } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp) support proxy"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { String target = null; { ProxySelector proxySelector = ProxySelector.getDefault(); Log.d(TAG, "proxySelector=" + proxySelector); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { Log.d(TAG, e.toString()); } List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { Log.d(TAG, " proxy=" + proxy); if (null != proxy) { if (Proxy.Type.HTTP == proxy.type()) { final SocketAddress sa = proxy.address(); if (sa instanceof InetSocketAddress) { final InetSocketAddress isa = (InetSocketAddress) sa; target = isa.getHostName(); break; } } } } } } } if (null == target) { target = "kkkon.sakura.ne.jp"; } InetAddress dest = InetAddress.getByName(target); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); { ProxySelector proxySelector = ProxySelector.getDefault(); //Log.d( TAG, "proxySelector=" + proxySelector ); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { //Log.d( TAG, e.toString() ); } if (null != uri) { List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { //Log.d( TAG, " proxy=" + proxy ); if (null != proxy) { if (Proxy.Type.HTTP == proxy.type()) { URL url = uri.toURL(); URLConnection conn = null; if (null != url) { try { conn = url.openConnection(proxy); if (null != conn) { conn.setConnectTimeout( 3 * 1000); conn.setReadTimeout(3 * 1000); } } catch (IOException e) { Log.d(TAG, "got Exception" + e.toString(), e); } if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; if (0 < httpConn .getResponseCode()) { isReachable = true; } Log.d(TAG, " HTTP ContentLength=" + httpConn .getContentLength()); Log.d(TAG, " HTTP res=" + httpConn .getResponseCode()); //httpConn.setInstanceFollowRedirects( false ); //httpConn.setRequestMethod( "HEAD" ); //conn.connect(); httpConn.disconnect(); Log.d(TAG, " HTTP ContentLength=" + httpConn .getContentLength()); Log.d(TAG, " HTTP res=" + httpConn .getResponseCode()); } } } } } } } } } } destHost = dest; } catch (IOException e) { Log.d(TAG, "got Excpetion " + e.toString()); } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } setContentView(layout); }
From source file:com.vuze.plugin.azVPN_Air.Checker.java
private boolean callRPCforPort(InetAddress bindIP, StringBuilder sReply) { InetAddress[] resolve = null; try {/*from ww w .ja v a 2s . c o m*/ String user = getDefaultUsername(); String pass = null; if (user == null || user.length() == 0) { user = config.getPluginStringParameter(PluginAir.CONFIG_USER); pass = new String(config.getPluginByteParameter(PluginAir.CONFIG_P, new byte[0]), "utf-8"); } else { pass = getPassword(); } if (user == null || user.length() == 0 || pass == null || pass.length() == 0) { addReply(sReply, CHAR_WARN, "airvpn.rpc.nocreds"); return false; } // If Vuze has a proxy set up (Tools->Options->Connection->Proxy), then // we'll need to disable it for the URL AEProxySelector selector = AEProxySelectorFactory.getSelector(); if (selector != null) { resolve = SystemDefaultDnsResolver.INSTANCE.resolve(VPN_DOMAIN); for (InetAddress address : resolve) { selector.setProxy(new InetSocketAddress(address, 443), Proxy.NO_PROXY); } } RequestConfig requestConfig; StringBuffer token = new StringBuffer(); boolean skipLoginPage = false; boolean alreadyLoggedIn = false; PortInfo[] ports = null; if (httpClientContext == null) { httpClientContext = HttpClientContext.create(); } else { PluginAir.log("Have existing context. Trying to grab port list without logging in."); ports = scrapePorts(bindIP, token); // assume no token means we aren't logged in if (token.length() > 0) { PluginAir.log("Valid ports page. Skipping Login"); skipLoginPage = true; alreadyLoggedIn = true; } else { ports = null; } } if (!skipLoginPage) { String loginURL = null; String authKey = null; PluginAir.log("Getting Login post URL and auth_key"); HttpGet getLoginPage = new HttpGet(VPN_LOGIN_URL); requestConfig = RequestConfig.custom().setLocalAddress(bindIP).setConnectTimeout(10000).build(); getLoginPage.setConfig(requestConfig); CloseableHttpClient httpClientLoginPage = HttpClients.createDefault(); CloseableHttpResponse loginPageResponse = httpClientLoginPage.execute(getLoginPage, httpClientContext); BufferedReader rd = new BufferedReader( new InputStreamReader(loginPageResponse.getEntity().getContent())); Pattern patAuthKey = Pattern.compile(REGEX_AuthKey); String line = ""; while ((line = rd.readLine()) != null) { if (line.contains("<form") && line.matches(".*id=['\"]login['\"].*")) { Matcher matcher = Pattern.compile(REGEX_ActionURL).matcher(line); if (matcher.find()) { loginURL = matcher.group(1); if (authKey != null) { break; } } } Matcher matcherAuthKey = patAuthKey.matcher(line); if (matcherAuthKey.find()) { authKey = matcherAuthKey.group(1); if (loginURL != null) { break; } } if (line.contains("['member_id']") && line.matches(".*parseInt\\s*\\(\\s*[1-9][0-9]*\\s*.*")) { alreadyLoggedIn = true; } } rd.close(); if (loginURL == null) { PluginAir.log("Could not scrape Login URL. Using default"); loginURL = "https://airvpn.org/index.php?app=core&module=global§ion=login&do=process"; } if (authKey == null) { addReply(sReply, CHAR_WARN, "airvpn.rpc.noauthkey"); return false; } loginURL = UrlUtils.unescapeXML(loginURL); /////////////////////////////// if (alreadyLoggedIn) { PluginAir.log("Already Logged In"); } else { PluginAir.log("Login URL:" + loginURL); //https://airvpn.org/index.php?app=core&module=global§ion=login&do=process //https://airvpn.org/index.php?app=core&module=global§ion=login&do=process HttpPost httpPostLogin = new HttpPost(loginURL); requestConfig = RequestConfig.custom().setLocalAddress(bindIP).setConnectTimeout(10000).build(); httpPostLogin.setConfig(requestConfig); CloseableHttpClient httpClient = HttpClients.createDefault(); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("ips_username", user)); urlParameters.add(new BasicNameValuePair("ips_password", pass)); urlParameters.add(new BasicNameValuePair("auth_key", authKey)); urlParameters.add(new BasicNameValuePair("invisible", "1")); urlParameters.add(new BasicNameValuePair("inline_invisible", "1")); httpPostLogin.setEntity(new UrlEncodedFormEntity(urlParameters)); CloseableHttpResponse response = httpClient.execute(httpPostLogin, httpClientContext); rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = ""; while ((line = rd.readLine()) != null) { } PluginAir.log("Login Result: " + response.getStatusLine().toString()); } } //////////////////////////// if (ports == null) { ports = scrapePorts(bindIP, token); } PluginAir.log("Found Ports: " + Arrays.toString(ports)); int existingIndex = ourPortInList(ports); if (existingIndex >= 0) { addReply(sReply, CHAR_GOOD, "airvpn.port.from.rpc.match", new String[] { ports[existingIndex].port }); return true; } boolean gotPort = false; // There's a limit of 20 ports. If [0] isn't ours and 20 of them are // created, then assume our detection of "ours" is broke and just use // the first one if ((ports.length > 0 && ports[0].ourBinding) || ports.length == 20) { int port = Integer.parseInt(ports[0].port); gotPort = true; addReply(sReply, CHAR_GOOD, "airvpn.port.from.rpc", new String[] { Integer.toString(port) }); changePort(port, sReply); } else { // create port ports = createPort(bindIP, token); if (ports.length == 0) { // form post should have got the new port, but if it didn't, try // reloading the ports page again. token.setLength(0); ports = scrapePorts(bindIP, token); } PluginAir.log("Added a port. Ports: " + Arrays.toString(ports)); existingIndex = ourPortInList(ports); if (existingIndex >= 0) { addReply(sReply, CHAR_GOOD, "airvpn.port.from.rpc.match", new String[] { ports[existingIndex].port }); return true; } if ((ports.length > 0 && ports[0].ourBinding) || ports.length == 20) { int port = Integer.parseInt(ports[0].port); gotPort = true; addReply(sReply, CHAR_GOOD, "airvpn.port.from.rpc", new String[] { Integer.toString(port) }); changePort(port, sReply); } } if (!gotPort) { addReply(sReply, CHAR_WARN, "airvpn.rpc.no.connect", new String[] { bindIP.toString() }); return false; } } catch (Exception e) { e.printStackTrace(); addReply(sReply, CHAR_BAD, "airvpn.rpc.no.connect", new String[] { bindIP + ": " + e.getMessage() }); return false; } finally { AEProxySelector selector = AEProxySelectorFactory.getSelector(); if (selector != null && resolve != null) { for (InetAddress address : resolve) { AEProxySelectorFactory.getSelector().removeProxy(new InetSocketAddress(address, 443)); } } } return true; }
From source file:com.vuze.plugin.azVPN_Helper.Checker_AirVPN.java
@Override protected boolean callRPCforPort(InetAddress bindIP, StringBuilder sReply) { InetAddress[] resolve = null; try {//from w ww. j a v a2 s. c o m String user = getDefaultUsername(); String pass = null; if (user == null || user.length() == 0) { user = config.getPluginStringParameter(PluginConstants.CONFIG_USER); pass = new String(config.getPluginByteParameter(PluginConstants.CONFIG_P, new byte[0]), "utf-8"); } else { pass = getPassword(); } if (user == null || user.length() == 0 || pass == null || pass.length() == 0) { addReply(sReply, CHAR_WARN, "airvpn.rpc.nocreds"); return false; } // If Vuze has a proxy set up (Tools->Options->Connection->Proxy), then // we'll need to disable it for the URL AEProxySelector selector = AEProxySelectorFactory.getSelector(); if (selector != null) { resolve = SystemDefaultDnsResolver.INSTANCE.resolve(VPN_DOMAIN); for (InetAddress address : resolve) { selector.setProxy(new InetSocketAddress(address, 443), Proxy.NO_PROXY); } } RequestConfig requestConfig; StringBuffer token = new StringBuffer(); boolean skipLoginPage = false; boolean alreadyLoggedIn = false; PortInfo[] ports = null; if (httpClientContext == null) { httpClientContext = HttpClientContext.create(); } else { PluginVPNHelper.log("Have existing context. Trying to grab port list without logging in."); ports = scrapePorts(bindIP, token); // assume no token means we aren't logged in if (token.length() > 0) { PluginVPNHelper.log("Valid ports page. Skipping Login"); skipLoginPage = true; alreadyLoggedIn = true; if (ports == null) { addReply(sReply, CHAR_WARN, "airvpn.vpnhelper.rpc.notconnected"); return false; } } else { ports = null; } } if (!skipLoginPage) { String loginURL = null; String authKey = null; PluginVPNHelper.log("Getting Login post URL and auth_key"); HttpGet getLoginPage = new HttpGet(VPN_LOGIN_URL); requestConfig = RequestConfig.custom().setLocalAddress(bindIP).setConnectTimeout(15000).build(); getLoginPage.setConfig(requestConfig); getLoginPage.setHeader("User-Agent", USER_AGENT); CloseableHttpClient httpClientLoginPage = HttpClients.createDefault(); CloseableHttpResponse loginPageResponse = httpClientLoginPage.execute(getLoginPage, httpClientContext); BufferedReader rd = new BufferedReader( new InputStreamReader(loginPageResponse.getEntity().getContent())); Pattern patAuthKey = Pattern.compile(REGEX_AuthKey); String line = ""; while ((line = rd.readLine()) != null) { if (line.contains("<form") && line.matches(".*id=['\"]login['\"].*")) { Matcher matcher = Pattern.compile(REGEX_ActionURL).matcher(line); if (matcher.find()) { loginURL = matcher.group(1); if (authKey != null) { break; } } } Matcher matcherAuthKey = patAuthKey.matcher(line); if (matcherAuthKey.find()) { authKey = matcherAuthKey.group(1); if (loginURL != null) { break; } } if (line.contains("['member_id']") && line.matches(".*parseInt\\s*\\(\\s*[1-9][0-9]*\\s*.*")) { alreadyLoggedIn = true; } } rd.close(); if (loginURL == null) { PluginVPNHelper.log("Could not scrape Login URL. Using default"); loginURL = "https://airvpn.org/index.php?app=core&module=global§ion=login&do=process"; } if (authKey == null) { addReply(sReply, CHAR_WARN, "vpnhelper.rpc.noauthkey"); return false; } loginURL = UrlUtils.unescapeXML(loginURL); /////////////////////////////// if (alreadyLoggedIn) { PluginVPNHelper.log("Already Logged In"); } else { PluginVPNHelper.log("Login URL:" + loginURL); //https://airvpn.org/index.php?app=core&module=global§ion=login&do=process //https://airvpn.org/index.php?app=core&module=global§ion=login&do=process HttpPost httpPostLogin = new HttpPost(loginURL); requestConfig = RequestConfig.custom().setLocalAddress(bindIP).setConnectTimeout(15000).build(); httpPostLogin.setConfig(requestConfig); httpPostLogin.setHeader("User-Agent", USER_AGENT); CloseableHttpClient httpClient = HttpClients.createDefault(); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("ips_username", user)); urlParameters.add(new BasicNameValuePair("ips_password", pass)); urlParameters.add(new BasicNameValuePair("auth_key", authKey)); urlParameters.add(new BasicNameValuePair("referer", "http://airvpn.org/")); urlParameters.add(new BasicNameValuePair("anonymous", "1")); urlParameters.add(new BasicNameValuePair("rememberMe", "1")); httpPostLogin.setEntity(new UrlEncodedFormEntity(urlParameters)); CloseableHttpResponse response = httpClient.execute(httpPostLogin, httpClientContext); rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = ""; while ((line = rd.readLine()) != null) { } PluginVPNHelper.log("Login Result: " + response.getStatusLine().toString()); } } //////////////////////////// if (ports == null) { ports = scrapePorts(bindIP, token); if (ports == null && token.length() > 0) { addReply(sReply, CHAR_WARN, "airvpn.vpnhelper.rpc.notconnected"); return false; } } PluginVPNHelper.log("Found Ports: " + Arrays.toString(ports)); int existingIndex = ourPortInList(ports); if (existingIndex >= 0) { addReply(sReply, CHAR_GOOD, "vpnhelper.port.from.rpc.match", new String[] { ports[existingIndex].port }); return true; } boolean gotPort = false; // There's a limit of 20 ports. If [0] isn't ours and 20 of them are // created, then assume our detection of "ours" is broke and just use // the first one if (ports != null && ((ports.length > 0 && ports[0].ourBinding) || ports.length == 20)) { int port = Integer.parseInt(ports[0].port); gotPort = true; addReply(sReply, CHAR_GOOD, "vpnhelper.port.from.rpc", new String[] { Integer.toString(port) }); changePort(port, sReply); } else if (ports != null) { // create port ports = createPort(bindIP, token); if (ports.length == 0) { // form post should have got the new port, but if it didn't, try // reloading the ports page again. token.setLength(0); ports = scrapePorts(bindIP, token); } PluginVPNHelper.log("Added a port. Ports: " + Arrays.toString(ports)); existingIndex = ourPortInList(ports); if (existingIndex >= 0) { addReply(sReply, CHAR_GOOD, "vpnhelper.port.from.rpc.match", new String[] { ports[existingIndex].port }); return true; } if ((ports.length > 0 && ports[0].ourBinding) || ports.length == 20) { int port = Integer.parseInt(ports[0].port); gotPort = true; addReply(sReply, CHAR_GOOD, "vpnhelper.port.from.rpc", new String[] { Integer.toString(port) }); changePort(port, sReply); } } if (!gotPort) { addReply(sReply, CHAR_WARN, "vpnhelper.rpc.no.connect", new String[] { bindIP.toString() }); return false; } } catch (Exception e) { e.printStackTrace(); addReply(sReply, CHAR_BAD, "vpnhelper.rpc.no.connect", new String[] { bindIP + ": " + e.getMessage() }); return false; } finally { AEProxySelector selector = AEProxySelectorFactory.getSelector(); if (selector != null && resolve != null) { for (InetAddress address : resolve) { AEProxySelectorFactory.getSelector().removeProxy(new InetSocketAddress(address, 443)); } } } return true; }