private TRTrackerAnnouncerHelper create( TOTorrent torrent, String[] networks, TOTorrentAnnounceURLSet[] sets) throws TRTrackerAnnouncerException { TRTrackerAnnouncerHelper announcer; boolean decentralised; if (sets.length == 0) { decentralised = TorrentUtils.isDecentralised(torrent.getAnnounceURL()); } else { decentralised = TorrentUtils.isDecentralised(sets[0].getAnnounceURLs()[0]); } if (decentralised) { announcer = new TRTrackerDHTAnnouncerImpl(torrent, networks, is_manual, getHelper()); } else { announcer = new TRTrackerBTAnnouncerImpl(torrent, sets, networks, is_manual, getHelper()); } for (TOTorrentAnnounceURLSet set : sets) { URL[] urls = set.getAnnounceURLs(); for (URL u : urls) { String key = u.toExternalForm(); StatusSummary summary = recent_responses.get(key); if (summary == null) { summary = new StatusSummary(announcer, u); recent_responses.put(key, summary); } else { summary.setHelper(announcer); } } } if (provider != null) { announcer.setAnnounceDataProvider(provider); } if (ip_override != null) { announcer.setIPOverride(ip_override); } return (announcer); }
protected String[] getAuthenticationDialog(final String realm, final String tracker) { final Display display = SWTThread.getInstance().getDisplay(); if (display.isDisposed()) { return (null); } final AESemaphore sem = new AESemaphore("SWTAuth"); final authDialog[] dialog = new authDialog[1]; TOTorrent torrent = TorrentUtils.getTLSTorrent(); final String torrent_name; if (torrent == null) { torrent_name = null; } else { torrent_name = TorrentUtils.getLocalisedName(torrent); } try { display.asyncExec( new AERunnable() { public void runSupport() { dialog[0] = new authDialog(sem, display, realm, tracker, torrent_name); } }); } catch (Throwable e) { Debug.printStackTrace(e); return (null); } sem.reserve(); String user = dialog[0].getUsername(); String pw = dialog[0].getPassword(); String persist = dialog[0].savePassword() ? "true" : "false"; if (user == null) { return (null); } return (new String[] {user, pw == null ? "" : pw, persist}); }
protected void setIgnoreList() { try { ignore_set = TorrentUtils.getIgnoreSet(); } catch (NoClassDefFoundError e) { return; } }
public void setTrackerURL(URL url) { List<List<String>> groups = new ArrayList<List<String>>(); List<String> group = new ArrayList<String>(); group.add(url.toExternalForm()); groups.add(group); TorrentUtils.listToAnnounceGroups(groups, getTorrent()); resetTrackerUrl(false); }
private static void writeTorrentIfExists(TOTorrent torrent) { AzureusCore core = AzureusCoreFactory.getSingleton(); if (core == null || !core.isStarted()) { return; } GlobalManager gm = core.getGlobalManager(); if (gm == null || gm.getDownloadManager(torrent) == null) { return; } try { TorrentUtils.writeToFile(torrent); } catch (TOTorrentException e) { Debug.out(e); } }
public void shareTorrent(final SelectedContentV3 currentContent, final String referer) { PlatformBuddyMessenger.startShare( referer, currentContent.isPlatformContent() ? currentContent.getHash() : null); if (!VuzeBuddyManager.isEnabled()) { VuzeBuddyManager.showDisabledDialog(); return; } // TODO : Gudy : make sure that this private detection method is reliable enough if (currentContent.getDM() != null && (TorrentUtils.isReallyPrivate(currentContent.getDM().getTorrent()))) { Utils.openMessageBox(Utils.findAnyShell(), SWT.OK, "v3.share.private", (String[]) null); return; } SWTLoginUtils.waitForLogin( new SWTLoginUtils.loginWaitListener() { public void loginComplete() { if (null != sharePage) { try { // sharePage.setShareItem(currentContent, referer); ShareWizard wizard = new ShareWizard( UIFunctionsManagerSWT.getUIFunctionsSWT().getMainShell(), SWT.DIALOG_TRIM | SWT.RESIZE); wizard.setText("Vuze - Wizard"); wizard.setSize(500, 550); com.aelitis.azureus.ui.swt.shells.friends.SharePage newSharePage = (com.aelitis.azureus.ui.swt.shells.friends.SharePage) wizard.getPage(com.aelitis.azureus.ui.swt.shells.friends.SharePage.ID); newSharePage.setShareItem(currentContent, referer); /* * Opens a centered free-floating shell */ UIFunctionsSWT uiFunctions = UIFunctionsManagerSWT.getUIFunctionsSWT(); if (null == uiFunctions) { /* * Centers on the active monitor */ Utils.centreWindow(wizard.getShell()); } else { /* * Centers on the main application window */ Utils.centerWindowRelativeTo(wizard.getShell(), uiFunctions.getMainShell()); } wizard.open(); } catch (Exception e) { e.printStackTrace(); } } } }); }
public void runSupport() { try { new URL(url_str); // determine if this is already a proper URL } catch (Throwable t) { // it's not // //check if the string is just a base32/hex-encoded torrent infohash // // String magnet_uri = UrlUtils.normaliseMagnetURI( url_str ); // // if ( magnet_uri != null ){ // // url_str = magnet_uri; // } } try { url = AddressUtils.adjustURL(new URL(url_str)); String protocol = url.getProtocol().toLowerCase(); // hack here - the magnet download process requires an additional paramter to cause it to // stall on error so the error can be reported // if ( protocol.equals( "magnet" ) || protocol.equals( "dht" )){ // // url = AddressUtils.adjustURL( new URL(url_str+"&pause_on_error=true")); // } for (int i = 0; i < 2; i++) { try { // if ( protocol.equals("https")){ // // // see ConfigurationChecker for SSL client defaults // // HttpsURLConnection ssl_con = (HttpsURLConnection)url.openConnection(); // // // allow for certs that contain IP addresses rather than dns names // // ssl_con.setHostnameVerifier( // new HostnameVerifier() // { // public boolean // verify( // String host, // SSLSession session ) // { // return( true ); // } // }); // // con = ssl_con; // // }else{ // con = (HttpURLConnection) url.openConnection(); // } con.setRequestProperty( "User-Agent", Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION); if (referrer != null && referrer.length() > 0) { con.setRequestProperty("Referer", referrer); } if (request_properties != null) { Iterator it = request_properties.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); // currently this code doesn't support gzip/deflate... if (!key.equalsIgnoreCase("Accept-Encoding")) { con.setRequestProperty(key, value); } } } this.con.connect(); break; // }catch( SSLException e ){ // // if ( i == 0 ){ // // if ( SESecurityManager.installServerCertificates( url ) != null ){ // // // certificate has been installed // // continue; // retry with new certificate // } // } // // throw( e ); // } catch (IOException e) { if (i == 0) { URL retry_url = UrlUtils.getIPV4Fallback(url); if (retry_url != null) { url = retry_url; } else { throw (e); } } } } int response = this.con.getResponseCode(); if (!ignoreReponseCode) { if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { this.error(response, Integer.toString(response) + ": " + this.con.getResponseMessage()); return; } } /* Map headerFields = this.con.getHeaderFields(); System.out.println("Header of download of " + url_str); for (Iterator iter = headerFields.keySet().iterator(); iter.hasNext();) { String s = (String) iter.next(); System.out.println(s + ":" + headerFields.get(s)); } */ filename = this.con.getHeaderField("Content-Disposition"); if ((filename != null) && filename .toLowerCase() .matches(".*attachment.*")) // Some code to handle b0rked servers. while (filename.toLowerCase().charAt(0) != 'a') filename = filename.substring(1); if ((filename == null) || !filename.toLowerCase().startsWith("attachment") || (filename.indexOf('=') == -1)) { String tmp = this.url.getFile(); if (tmp.length() == 0 || tmp.equals("/")) { filename = url.getHost(); } else if (tmp.startsWith("?")) { // probably a magnet URI - use the hash // magnet:?xt=urn:sha1:VGC53ZWCUXUWVGX7LQPVZIYF4L6RXSU6 String query = tmp.toUpperCase(); int pos = query.indexOf("XT=URN:SHA1:"); if (pos == -1) { pos = query.indexOf("XT=URN:BTIH:"); } if (pos != -1) { pos += 12; int p2 = query.indexOf("&", pos); if (p2 == -1) { filename = query.substring(pos); } else { filename = query.substring(pos, p2); } } else { filename = "Torrent" + (long) (Math.random() * Long.MAX_VALUE); } filename += ".tmp"; } else { if (tmp.lastIndexOf('/') != -1) tmp = tmp.substring(tmp.lastIndexOf('/') + 1); // remove any params in the url int param_pos = tmp.indexOf('?'); if (param_pos != -1) { tmp = tmp.substring(0, param_pos); } filename = URLDecoder.decode(tmp, Constants.DEFAULT_ENCODING); } } else { filename = filename.substring(filename.indexOf('=') + 1); if (filename.startsWith("\"") && filename.endsWith("\"")) filename = filename.substring(1, filename.lastIndexOf('\"')); filename = URLDecoder.decode(filename, Constants.DEFAULT_ENCODING); // not sure of this piece of logic here but I'm not changing it at the moment File temp = new File(filename); filename = temp.getName(); } filename = FileUtil.convertOSSpecificChars(filename, false); // directoryname = // COConfigurationManager.getDirectoryParameter("General_sDefaultTorrent_Directory"); // boolean useTorrentSave = COConfigurationManager.getBooleanParameter("Save Torrent // Files"); directoryname = "D:\\Development\\testDownloads\\"; boolean useTorrentSave = true; if (file_str != null) { // not completely sure about the whole logic in this block File temp = new File(file_str); // if we're not using a default torrent save dir if (!useTorrentSave || directoryname.length() == 0) { // if it's already a dir if (temp.isDirectory()) { // use it directoryname = temp.getCanonicalPath(); } // it's a file else { // so use its parent dir directoryname = temp.getCanonicalFile().getParent(); } } // if it's a file if (!temp.isDirectory()) { // set the file name filename = temp.getName(); } } // what would happen here if directoryname == null and file_str == null?? this.state = STATE_INIT; this.notifyListener(); } catch (java.net.MalformedURLException e) { this.error(0, "Exception while parsing URL '" + url + "':" + e.getMessage()); } catch (java.net.UnknownHostException e) { this.error( 0, "Exception while initializing download of '" + url + "': Unknown Host '" + e.getMessage() + "'"); } catch (java.io.IOException ioe) { this.error(0, "I/O Exception while initializing download of '" + url + "':" + ioe.toString()); } catch (Throwable e) { this.error(0, "Exception while initializing download of '" + url + "':" + e.toString()); } if (this.state == STATE_ERROR) { return; } try { final boolean status_reader_run[] = {true}; this.state = STATE_START; notifyListener(); this.state = STATE_DOWNLOADING; notifyListener(); Thread status_reader = new AEThread("TorrentDownloader:statusreader") { public void runSupport() { boolean changed_status = false; while (true) { try { Thread.sleep(100); try { this_mon.enter(); if (!status_reader_run[0]) { break; } } finally { this_mon.exit(); } String s = con.getResponseMessage(); if (!s.equals(getStatus())) { if (!s.toLowerCase().startsWith("error:")) { if (s.toLowerCase().indexOf("alive") != -1) { if (percentDone < 10) { percentDone++; } } int pos = s.indexOf('%'); if (pos != -1) { int i; for (i = pos - 1; i >= 0; i--) { char c = s.charAt(i); if (!Character.isDigit(c) && c != ' ') { i++; break; } } try { percentDone = Integer.parseInt(s.substring(i, pos).trim()); } catch (Throwable e) { } } setStatus(s); } else { error(con.getResponseCode(), s.substring(6)); } changed_status = true; } } catch (Throwable e) { break; } } if (changed_status) { setStatus(""); } } }; status_reader.setDaemon(true); status_reader.start(); InputStream in; try { in = this.con.getInputStream(); } catch (FileNotFoundException e) { if (ignoreReponseCode) { in = this.con.getErrorStream(); } else { throw e; } } finally { try { this_mon.enter(); status_reader_run[0] = false; } finally { this_mon.exit(); } } // handle some servers that return gzip'd torrents even though we don't request it! String encoding = con.getHeaderField("content-encoding"); if (encoding != null) { if (encoding.equalsIgnoreCase("gzip")) { in = new GZIPInputStream(in); } else if (encoding.equalsIgnoreCase("deflate")) { in = new InflaterInputStream(in); } } if (this.state != STATE_ERROR) { this.file = new File(this.directoryname, filename); boolean useTempFile = false; try { this.file.createNewFile(); useTempFile = !this.file.exists(); } catch (Throwable t) { useTempFile = true; } if (useTempFile) { this.file = File.createTempFile("AZU", ".torrent", new File(this.directoryname)); this.file.createNewFile(); } FileOutputStream fileout = new FileOutputStream(this.file, false); bufBytes = 0; int size = (int) UrlUtils.getContentLength(con); this.percentDone = -1; do { if (this.cancel) { break; } try { bufBytes = in.read(buf); this.readTotal += bufBytes; if (size != 0) { this.percentDone = (100 * this.readTotal) / size; } notifyListener(); } catch (IOException e) { } if (bufBytes > 0) { fileout.write(buf, 0, bufBytes); } } while (bufBytes > 0); in.close(); fileout.flush(); fileout.close(); if (this.cancel) { this.state = STATE_CANCELLED; if (deleteFileOnCancel) { this.cleanUpFile(); } } else { if (this.readTotal <= 0) { this.error(0, "No data contained in '" + this.url.toString() + "'"); return; } // if the file has come down with a not-so-useful name then we try to rename // it to something more useful try { if (!filename.toLowerCase().endsWith(".torrent")) { TOTorrent torrent = TorrentUtils.readFromFile(file, false); String name = TorrentUtils.getLocalisedName(torrent) + ".torrent"; File new_file = new File(directoryname, name); if (file.renameTo(new_file)) { filename = name; file = new_file; } } } catch (Throwable e) { Debug.printStackTrace(e); } // TorrentUtils.setObtainedFrom( file, original_url ); this.state = STATE_FINISHED; } this.notifyListener(); } } catch (Exception e) { if (!cancel) { Debug.out("'" + this.directoryname + "' '" + filename + "'", e); } this.error(0, "Exception while downloading '" + this.url.toString() + "':" + e.getMessage()); } }
protected String[] getAuthenticationDialog(final String realm, final String location) { final Display display = SWTThread.getInstance().getDisplay(); if (display.isDisposed()) { return (null); } final AESemaphore sem = new AESemaphore("SWTAuth"); final authDialog[] dialog = new authDialog[1]; TOTorrent torrent = TorrentUtils.getTLSTorrent(); final boolean is_tracker; final String details; if (torrent == null) { is_tracker = false; details = TorrentUtils.getTLSDescription(); } else { details = TorrentUtils.getLocalisedName(torrent); is_tracker = true; } try { if (display.getThread() == Thread.currentThread()) { dialog[0] = new authDialog(sem, display, realm, is_tracker, location, details); while (!(display.isDisposed() || sem.isReleasedForever())) { if (!display.readAndDispatch()) { display.sleep(); } } if (display.isDisposed()) { return (null); } } else { display.asyncExec( new AERunnable() { public void runSupport() { dialog[0] = new authDialog(sem, display, realm, is_tracker, location, details); } }); } } catch (Throwable e) { Debug.printStackTrace(e); return (null); } sem.reserve(); String user = dialog[0].getUsername(); String pw = dialog[0].getPassword(); String persist = dialog[0].savePassword() ? "true" : "false"; if (user == null) { return (null); } return (new String[] {user, pw == null ? "" : pw, persist}); }
protected void split() throws TRTrackerAnnouncerException { String[] networks = f_provider == null ? null : f_provider.getNetworks(); TRTrackerAnnouncerHelper to_activate = null; synchronized (this) { if (stopped || destroyed) { return; } TOTorrent torrent = getTorrent(); TOTorrentAnnounceURLSet[] sets = torrent.getAnnounceURLGroup().getAnnounceURLSets(); // sanitise dht entries if (sets.length == 0) { sets = new TOTorrentAnnounceURLSet[] { torrent .getAnnounceURLGroup() .createAnnounceURLSet(new URL[] {torrent.getAnnounceURL()}) }; } else { boolean found_decentralised = false; boolean modified = false; for (int i = 0; i < sets.length; i++) { TOTorrentAnnounceURLSet set = sets[i]; URL[] urls = set.getAnnounceURLs().clone(); for (int j = 0; j < urls.length; j++) { URL u = urls[j]; if (u != null && TorrentUtils.isDecentralised(u)) { if (found_decentralised) { modified = true; urls[j] = null; } else { found_decentralised = true; } } } } if (modified) { List<TOTorrentAnnounceURLSet> s_list = new ArrayList<TOTorrentAnnounceURLSet>(); for (TOTorrentAnnounceURLSet set : sets) { URL[] urls = set.getAnnounceURLs(); List<URL> u_list = new ArrayList<URL>(urls.length); for (URL u : urls) { if (u != null) { u_list.add(u); } } if (u_list.size() > 0) { s_list.add( torrent .getAnnounceURLGroup() .createAnnounceURLSet(u_list.toArray(new URL[u_list.size()]))); } } sets = s_list.toArray(new TOTorrentAnnounceURLSet[s_list.size()]); } } List<TOTorrentAnnounceURLSet[]> new_sets = new ArrayList<TOTorrentAnnounceURLSet[]>(); if (is_manual || sets.length < 2) { new_sets.add(sets); } else { List<TOTorrentAnnounceURLSet> list = new ArrayList<TOTorrentAnnounceURLSet>(Arrays.asList(sets)); // often we have http:/xxxx/ and udp:/xxxx/ as separate groups - keep these together while (list.size() > 0) { TOTorrentAnnounceURLSet set1 = list.remove(0); boolean done = false; URL[] urls1 = set1.getAnnounceURLs(); if (urls1.length == 1) { URL url1 = urls1[0]; String prot1 = url1.getProtocol().toLowerCase(); String host1 = url1.getHost(); for (int i = 0; i < list.size(); i++) { TOTorrentAnnounceURLSet set2 = list.get(i); URL[] urls2 = set2.getAnnounceURLs(); if (urls2.length == 1) { URL url2 = urls2[0]; String prot2 = url2.getProtocol().toLowerCase(); String host2 = url2.getHost(); if (host1.equals(host2)) { if ((prot1.equals("udp") && prot2.startsWith("http")) || (prot2.equals("udp") && prot1.startsWith("http"))) { list.remove(i); new_sets.add(new TOTorrentAnnounceURLSet[] {set1, set2}); done = true; } } } } } if (!done) { new_sets.add(new TOTorrentAnnounceURLSet[] {set1}); } } } // work out the difference Iterator<TOTorrentAnnounceURLSet[]> ns_it = new_sets.iterator(); // need to copy list as we modify it and returned list ain't thread safe List<TRTrackerAnnouncerHelper> existing_announcers = new ArrayList<TRTrackerAnnouncerHelper>(announcers.getList()); List<TRTrackerAnnouncerHelper> new_announcers = new ArrayList<TRTrackerAnnouncerHelper>(); // first look for unchanged sets while (ns_it.hasNext()) { TOTorrentAnnounceURLSet[] ns = ns_it.next(); Iterator<TRTrackerAnnouncerHelper> a_it = existing_announcers.iterator(); while (a_it.hasNext()) { TRTrackerAnnouncerHelper a = a_it.next(); TOTorrentAnnounceURLSet[] os = a.getAnnounceSets(); if (same(ns, os)) { ns_it.remove(); a_it.remove(); new_announcers.add(a); break; } } } // reuse existing announcers // first remove dht ones from the equation TRTrackerAnnouncerHelper existing_dht_announcer = null; TOTorrentAnnounceURLSet[] new_dht_set = null; ns_it = new_sets.iterator(); while (ns_it.hasNext()) { TOTorrentAnnounceURLSet[] x = ns_it.next(); if (TorrentUtils.isDecentralised(x[0].getAnnounceURLs()[0])) { new_dht_set = x; ns_it.remove(); break; } } Iterator<TRTrackerAnnouncerHelper> an_it = existing_announcers.iterator(); while (an_it.hasNext()) { TRTrackerAnnouncerHelper a = an_it.next(); TOTorrentAnnounceURLSet[] x = a.getAnnounceSets(); if (TorrentUtils.isDecentralised(x[0].getAnnounceURLs()[0])) { existing_dht_announcer = a; an_it.remove(); break; } } if (existing_dht_announcer != null && new_dht_set != null) { new_announcers.add(existing_dht_announcer); } else if (existing_dht_announcer != null) { activated.remove(existing_dht_announcer); existing_dht_announcer.destroy(); } else if (new_dht_set != null) { TRTrackerAnnouncerHelper a = create(torrent, networks, new_dht_set); new_announcers.add(a); } // now do the non-dht ones ns_it = new_sets.iterator(); while (ns_it.hasNext() && existing_announcers.size() > 0) { TRTrackerAnnouncerHelper a = existing_announcers.remove(0); TOTorrentAnnounceURLSet[] s = ns_it.next(); ns_it.remove(); if (activated.contains(a) && torrent.getPrivate() && a instanceof TRTrackerBTAnnouncerImpl) { URL url = a.getTrackerURL(); if (url != null) { forceStop((TRTrackerBTAnnouncerImpl) a, networks, url); } } a.setAnnounceSets(s, networks); new_announcers.add(a); } // create any new ones required ns_it = new_sets.iterator(); while (ns_it.hasNext()) { TOTorrentAnnounceURLSet[] s = ns_it.next(); TRTrackerAnnouncerHelper a = create(torrent, networks, s); new_announcers.add(a); } // finally fix up the announcer list to represent the new state Iterator<TRTrackerAnnouncerHelper> a_it = announcers.iterator(); while (a_it.hasNext()) { TRTrackerAnnouncerHelper a = a_it.next(); if (!new_announcers.contains(a)) { a_it.remove(); try { if (activated.contains(a) && torrent.getPrivate() && a instanceof TRTrackerBTAnnouncerImpl) { URL url = a.getTrackerURL(); if (url != null) { forceStop((TRTrackerBTAnnouncerImpl) a, networks, url); } } } finally { if (Logger.isEnabled()) { Logger.log( new LogEvent( getTorrent(), LOGID, "Deactivating " + getString(a.getAnnounceSets()))); } activated.remove(a); a.destroy(); } } } a_it = new_announcers.iterator(); while (a_it.hasNext()) { TRTrackerAnnouncerHelper a = a_it.next(); if (!announcers.contains(a)) { announcers.add(a); } } if (!is_manual && announcers.size() > 0) { if (activated.size() == 0) { TRTrackerAnnouncerHelper a = announcers.get(0); if (Logger.isEnabled()) { Logger.log( new LogEvent(getTorrent(), LOGID, "Activating " + getString(a.getAnnounceSets()))); } activated.add(a); last_activation_time = SystemTime.getMonotonousTime(); if (provider != null) { to_activate = a; } } setupActivationCheck(ACT_CHECK_INIT_DELAY); } } if (to_activate != null) { if (complete) { to_activate.complete(true); } else { to_activate.update(false); } } }