/**
   * Get a set of introduction puzzle IDs which the given own identity might solve.
   *
   * <p>The puzzle's data is not returned because when generating HTML for displaying the puzzles we
   * must reference them with a IMG-tag and we cannot embed the data of the puzzles in the IMG-tag
   * because embedding image-data has only recently been added to browsers and many do not support
   * it yet.
   *
   * @param ownIdentity The identity which wants to solve the puzzles.
   * @param amount The amount of puzzles to request.
   * @return A list of the IDs of the puzzles. The amount might be less than the requested amount
   *     and even zero if WoT has not downloaded puzzles yet.
   * @throws Exception
   */
  public List<String> getIntroductionPuzzles(WoTOwnIdentity ownIdentity, int amount)
      throws Exception {
    ArrayList<String> puzzleIDs = new ArrayList<String>(amount + 1);

    SimpleFieldSet params = new SimpleFieldSet(true);
    params.putOverwrite("Message", "GetIntroductionPuzzles");
    params.putOverwrite("Identity", ownIdentity.getID());
    params.putOverwrite("Type", "Captcha"); // TODO: Don't hardcode the String
    params.put("Amount", amount);

    try {
      SimpleFieldSet result = sendFCPMessageBlocking(params, null, "IntroductionPuzzles").params;

      for (int idx = 0; ; idx++) {
        String id = result.get("Puzzle" + idx);

        if (id == null
            || id.equals("")) /* TODO: Figure out whether the second condition is necessary */
          break;

        puzzleIDs.add(id);
      }
    } catch (PluginNotFoundException e) {
      Logger.error(this, "Getting puzzles failed", e);
    }

    return puzzleIDs;
  }
 private synchronized void addFreetalkContext(WoTIdentity oid) throws Exception {
   SimpleFieldSet params = new SimpleFieldSet(true);
   params.putOverwrite("Message", "AddContext");
   params.putOverwrite("Identity", oid.getID());
   params.putOverwrite("Context", Freetalk.WOT_CONTEXT);
   sendFCPMessageBlocking(params, null, "ContextAdded");
 }
  /**
   * Not synchronized, the involved identity might be deleted during the query - which is not really
   * a problem.
   */
  public List<WoTTrust> getReceivedTrusts(Identity trustee) throws Exception {
    List<WoTTrust> result = new ArrayList<WoTTrust>();

    SimpleFieldSet request = new SimpleFieldSet(true);
    request.putOverwrite("Message", "GetTrusters");
    request.putOverwrite("Context", "");
    request.putOverwrite("Identity", trustee.getID());
    try {
      SimpleFieldSet answer = sendFCPMessageBlocking(request, null, "Identities").params;
      for (int idx = 0; ; idx++) {
        String id = answer.get("Identity" + idx);
        if (id == null
            || id.equals("")) /* TODO: Figure out whether the second condition is necessary */
          break;
        try {
          final WoTTrust trust =
              new WoTTrust(
                  getIdentity(id),
                  trustee,
                  (byte) Integer.parseInt(answer.get("Value" + idx)),
                  answer.get("Comment" + idx));
          mWoTCache.putTrust(trust);
          result.add(trust);
        } catch (NoSuchIdentityException e) {
        } catch (InvalidParameterException e) {
        }
      }
    } catch (PluginNotFoundException e) {
      throw new WoTDisconnectedException();
    }
    return result;
  }
  /**
   * Register the frirc context with an identity of your own
   *
   * @param own_identity
   */
  public void addOwnIdentityContext(Map<String, String> own_identity) {
    SimpleFieldSet sfs = new SimpleFieldSet(true);
    sfs.putOverwrite("Message", "AddContext");
    sfs.putOverwrite("Identity", own_identity.get("Identity"));
    sfs.putOverwrite("Context", "FrIRC");

    talker.send(sfs, null);
  }
  /**
   * Not synchronized, the involved identities might be deleted during the query - which is not
   * really a problem.
   */
  private String getProperty(OwnIdentity truster, Identity target, String property)
      throws Exception {
    SimpleFieldSet sfs = new SimpleFieldSet(true);
    sfs.putOverwrite("Message", "GetIdentity");
    sfs.putOverwrite("Truster", truster.getID());
    sfs.putOverwrite("Identity", target.getID());

    return sendFCPMessageBlocking(sfs, null, "Identity").params.get(property);
  }
  public void solveIntroductionPuzzle(WoTOwnIdentity ownIdentity, String puzzleID, String solution)
      throws Exception {
    SimpleFieldSet params = new SimpleFieldSet(true);
    params.putOverwrite("Message", "SolveIntroductionPuzzle");
    params.putOverwrite("Identity", ownIdentity.getID());
    params.putOverwrite("Puzzle", puzzleID);
    params.putOverwrite("Solution", solution);

    sendFCPMessageBlocking(params, null, "PuzzleSolved");
  }
  /**
   * Not synchronized, the involved identity might be deleted during the query - which is not really
   * a problem.
   */
  public int getReceivedTrustsCount(Identity trustee) throws Exception {
    SimpleFieldSet request = new SimpleFieldSet(true);
    request.putOverwrite("Message", "GetTrustersCount");
    request.putOverwrite("Identity", trustee.getID());
    request.putOverwrite("Context", Freetalk.WOT_CONTEXT);

    try {
      SimpleFieldSet answer = sendFCPMessageBlocking(request, null, "TrustersCount").params;
      return Integer.parseInt(answer.get("Value"));
    } catch (PluginNotFoundException e) {
      throw new WoTDisconnectedException();
    }
  }
  public synchronized WoTOwnIdentity createOwnIdentity(
      String newNickname,
      boolean publishesTrustList,
      boolean publishesIntroductionPuzzles,
      boolean autoSubscribeToNewBoards,
      boolean displayImages)
      throws Exception {

    Logger.normal(this, "Creating new own identity via FCP, nickname: " + newNickname);

    SimpleFieldSet params = new SimpleFieldSet(true);
    params.putOverwrite("Message", "CreateIdentity");
    params.putOverwrite("Nickname", newNickname);
    params.putOverwrite("PublishTrustList", publishesTrustList ? "true" : "false");
    params.putOverwrite(
        "PublishIntroductionPuzzles", publishesIntroductionPuzzles ? "true" : "false");
    params.putOverwrite("Context", Freetalk.WOT_CONTEXT);
    PluginTalkerBlocking.Result result = sendFCPMessageBlocking(params, null, "IdentityCreated");

    WoTOwnIdentity identity =
        new WoTOwnIdentity(
            result.params.get("ID"),
            new FreenetURI(result.params.get("RequestURI")),
            new FreenetURI(result.params.get("InsertURI")),
            newNickname,
            autoSubscribeToNewBoards,
            displayImages);

    identity.initializeTransient(mFreetalk);

    Logger.normal(this, "Created WoTOwnidentity via FCP, now storing... " + identity);

    synchronized (mFreetalk.getTaskManager()) { // Required by onNewOwnidentityAdded
      synchronized (db.lock()) {
        try {
          identity.initializeTransient(mFreetalk);
          identity.storeWithoutCommit();
          onNewOwnIdentityAdded(identity);
          identity.checkedCommit(this);
          Logger.normal(this, "Stored new WoTOwnIdentity " + identity);

        } catch (RuntimeException e) {
          Persistent.checkedRollbackAndThrow(db, this, e);
        }
      }
    }

    return identity;
  }
  /**
   * Not synchronized, the involved identities might be deleted during the query or some other WoT
   * client might modify the trust value during the query - which is not really a problem, you
   * should not be modifying trust values of your own identity with multiple clients simultaneously.
   */
  public void setTrust(OwnIdentity truster, Identity trustee, byte trust, String comment)
      throws Exception {
    WoTOwnIdentity wotTruster = (WoTOwnIdentity) truster;
    WoTIdentity wotTrustee = (WoTIdentity) trustee;

    SimpleFieldSet request = new SimpleFieldSet(true);
    request.putOverwrite("Message", "SetTrust");
    request.putOverwrite("Truster", wotTruster.getID());
    request.putOverwrite("Trustee", wotTrustee.getID());
    request.putOverwrite("Value", Integer.toString(trust));
    request.putOverwrite("Comment", comment);

    sendFCPMessageBlocking(request, null, "TrustSet");
    mWoTCache.putTrust(wotTruster, wotTrustee, trust);
  }
  /**
   * Fetches the identities with positive score from WoT and stores them in the database.
   *
   * @throws Exception
   */
  private void fetchIdentities() throws Exception {
    // parseIdentities() acquires and frees the WoTIdentityManager-lock for each identity to allow
    // other threads to access the identity manager while the
    // parsing is in progress. Therefore, we do not take the lock for the whole execution of this
    // function.
    synchronized (this) {
      if (mIdentityFetchInProgress) return;

      long now = CurrentTimeUTC.getInMillis();
      if ((now - mLastIdentityFetchTime) < MINIMAL_IDENTITY_FETCH_DELAY) return;

      mIdentityFetchInProgress = true;
    }

    try {
      Logger.normal(this, "Requesting identities with positive score from WoT ...");
      SimpleFieldSet p1 = new SimpleFieldSet(true);
      p1.putOverwrite("Message", "GetIdentitiesByScore");
      p1.putOverwrite("Selection", "+");
      p1.putOverwrite("Context", Freetalk.WOT_CONTEXT);
      parseIdentities(sendFCPMessageBlocking(p1, null, "Identities").params, false);

      synchronized (this) {
        // We must update the fetch-time after the parsing and only if the parsing succeeded:
        // If we updated before the parsing and parsing failed or took ages (the thread sometimes
        // takes 2 hours to execute, don't ask me why)
        // then the garbage collector would delete identities.
        mLastIdentityFetchTime = CurrentTimeUTC.getInMillis();
      }
    } finally {
      synchronized (this) {
        mIdentityFetchInProgress = false;
      }
    }

    // We usually call garbageCollectIdentities() after calling this function, it updates the cache
    // already...
    // if(mShortestUniqueNicknameCacheNeedsUpdate)
    //	updateShortestUniqueNicknameCache();
  }
  public synchronized WoTOwnIdentity createOwnIdentity(
      String newNickname,
      boolean publishesTrustList,
      boolean publishesIntroductionPuzzles,
      boolean autoSubscribeToNewBoards,
      boolean displayImages,
      FreenetURI newRequestURI,
      FreenetURI newInsertURI)
      throws Exception {
    Logger.normal(this, "Creating new own identity via FCP, nickname: " + newNickname);

    SimpleFieldSet params = new SimpleFieldSet(true);
    params.putOverwrite("Message", "CreateIdentity");
    params.putOverwrite("Nickname", newNickname);
    params.putOverwrite("PublishTrustList", publishesTrustList ? "true" : "false");
    params.putOverwrite(
        "PublishIntroductionPuzzles",
        publishesTrustList && publishesIntroductionPuzzles ? "true" : "false");
    params.putOverwrite("Context", Freetalk.WOT_CONTEXT);
    params.putOverwrite("RequestURI", newRequestURI.toString());
    params.putOverwrite("InsertURI", newInsertURI.toString());
    PluginTalkerBlocking.Result result = sendFCPMessageBlocking(params, null, "IdentityCreated");

    /* We take the URIs which were returned by the WoT plugin instead of the requested ones because this allows the identity to work
     * even if the WoT plugin ignores our requested URIs: If we just stored the URIs we requested, we would store an identity with
     * wrong URIs which would result in the identity not being useable. */
    WoTOwnIdentity identity =
        new WoTOwnIdentity(
            result.params.get("ID"),
            new FreenetURI(result.params.get("RequestURI")),
            new FreenetURI(result.params.get("InsertURI")),
            newNickname,
            autoSubscribeToNewBoards,
            displayImages);

    identity.initializeTransient(mFreetalk);

    Logger.normal(this, "Created WoTOwnidentity via FCP, now storing... " + identity);

    synchronized (mFreetalk.getTaskManager()) {
      synchronized (db.lock()) {
        try {
          identity.storeWithoutCommit();
          onNewOwnIdentityAdded(identity);
          identity.checkedCommit(this);
          Logger.normal(this, "Stored new WoTOwnIdentity " + identity);
        } catch (RuntimeException e) {
          Persistent.checkedRollback(db, this, e);
        }
      }
    }

    return identity;
  }
  private synchronized void sendFCPAllIdentities(Map<String, String> identity) {
    PluginTalker talker;
    try {
      talker = pr.getPluginTalker(this, Frirc.WoT_NAMESPACE, "");
      SimpleFieldSet sfs = new SimpleFieldSet(true);
      sfs.putOverwrite("Message", "GetTrustees");
      sfs.putOverwrite(
          "Identity",
          identity.get("ID")
              .split(",")[
              0]); // a personal identity (associated through source) (only pass the ID, not the
      // full SSK)
      sfs.putOverwrite(
          "Context", "FrIRC"); // empty means selecting all identities no matter the context
      talker.send(sfs, null); // send message to WoT plugin

      if (Frirc.DEBUG)
        System.out.println("requested identities for identity " + identity.get("ID").split(",")[0]);
    } catch (PluginNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public IntroductionPuzzle getIntroductionPuzzle(String id) throws Exception {
    SimpleFieldSet params = new SimpleFieldSet(true);
    params.putOverwrite("Message", "GetIntroductionPuzzle");
    params.putOverwrite("Puzzle", id);

    try {
      SimpleFieldSet result = sendFCPMessageBlocking(params, null, "IntroductionPuzzle").params;

      try {
        return new IntroductionPuzzle(
            id, result.get("MimeType"), Base64.decodeStandard(result.get("Data")));
      } catch (RuntimeException e) {
        Logger.error(this, "Parsing puzzle failed", e);
      } catch (IllegalBase64Exception e) {
        Logger.error(this, "Parsing puzzle failed", e);
      }

      return null;
    } catch (PluginNotFoundException e) {
      Logger.error(this, "Getting puzzles failed", e);

      return null;
    }
  }
Ejemplo n.º 14
0
  // This is distinct from the ClientGetMessage code, as later on it will be radically
  // different (it can store detailed state).
  @Override
  public synchronized SimpleFieldSet getFieldSet() {
    SimpleFieldSet fs = new SimpleFieldSet(false); // we will need multi-level later...
    fs.putSingle("Type", "GET");
    fs.putSingle("URI", uri.toString(false, false));
    fs.putSingle("Identifier", identifier);
    fs.putSingle("Verbosity", Integer.toString(verbosity));
    fs.putSingle("PriorityClass", Short.toString(priorityClass));
    fs.putSingle("ReturnType", ClientGetMessage.returnTypeString(returnType));
    fs.putSingle("Persistence", persistenceTypeString(persistenceType));
    fs.putSingle("ClientName", client.name);
    if (targetFile != null) fs.putSingle("Filename", targetFile.getPath());
    if (tempFile != null) fs.putSingle("TempFilename", tempFile.getPath());
    if (clientToken != null) fs.putSingle("ClientToken", clientToken);
    fs.putSingle("IgnoreDS", Boolean.toString(fctx.ignoreStore));
    fs.putSingle("DSOnly", Boolean.toString(fctx.localRequestOnly));
    fs.putSingle("MaxRetries", Integer.toString(fctx.maxNonSplitfileRetries));
    fs.putSingle("Finished", Boolean.toString(finished));
    fs.putSingle("Succeeded", Boolean.toString(succeeded));
    if (fctx.allowedMIMETypes != null)
      fs.putOverwrite(
          "AllowedMIMETypes",
          (String[]) fctx.allowedMIMETypes.toArray(new String[fctx.allowedMIMETypes.size()]));
    if (finished) {
      if (succeeded) {
        fs.putSingle("FoundDataLength", Long.toString(foundDataLength));
        fs.putSingle("FoundDataMimeType", foundDataMimeType);
        if (postFetchProtocolErrorMessage != null) {
          fs.put("PostFetchProtocolError", postFetchProtocolErrorMessage.getFieldSet());
        }
      } else {
        if (getFailedMessage != null) {
          fs.put("GetFailed", getFailedMessage.getFieldSet(false));
        }
      }
    }
    // Return bucket
    if (returnType == ClientGetMessage.RETURN_TYPE_DIRECT
        && !(succeeded == false && returnBucket == null)) {
      bucketToFS(fs, "ReturnBucket", false, returnBucket);
    }
    fs.putSingle("Global", Boolean.toString(client.isGlobalQueue));
    fs.put("BinaryBlob", binaryBlob);
    fs.put("StartupTime", startupTime);
    if (finished) fs.put("CompletionTime", completionTime);

    return fs;
  }
Ejemplo n.º 15
0
  public void update() {
    logMINOR = Logger.shouldLog(Logger.MINOR, this);
    if (logMINOR) Logger.minor(this, "update()");
    if (!checkIPUpdated()) return;
    // We'll broadcast the new physical.udp entry to our connected peers via a differential node
    // reference
    // We'll err on the side of caution and not update our peer to an empty physical.udp entry using
    // a differential node reference
    SimpleFieldSet nfs = crypto.exportPublicFieldSet(false, false, true);
    String[] entries = nfs.getAll("physical.udp");
    if (entries != null) {
      SimpleFieldSet fs = new SimpleFieldSet(true);
      fs.putOverwrite("physical.udp", entries);
      if (logMINOR)
        Logger.minor(this, darknetOpennetString + " ref's physical.udp is '" + fs.toString() + "'");
      node.peers.locallyBroadcastDiffNodeRef(fs, !crypto.isOpennet, crypto.isOpennet);
    } else {
      if (logMINOR) Logger.minor(this, darknetOpennetString + " ref's physical.udp is null");
    }
    // Proceed with inserting the ARK
    if (logMINOR)
      Logger.minor(this, "Inserting " + darknetOpennetString + " ARK because peers list changed");

    if (inserter != null) {
      // Already inserting.
      // Re-insert after finished.
      synchronized (this) {
        shouldInsert = true;
      }

      return;
    }
    // Otherwise need to start an insert
    if (node.noConnectedPeers()) {
      // Can't start an insert yet
      synchronized (this) {
        shouldInsert = true;
      }
      return;
    }

    startInserter();
  }
  private synchronized boolean connectToWoT() {
    if (mTalker != null) {
        /* Old connection exists */
      SimpleFieldSet sfs = new SimpleFieldSet(true);
      sfs.putOverwrite("Message", "Ping");
      try {
        mTalker.sendBlocking(sfs, null); /* Verify that the old connection is still alive */
        return true;
      } catch (PluginNotFoundException e) {
        mTalker = null;
        /* Do not return, try to reconnect in next try{} block */
      }
    }

    try {
      mTalker = new PluginTalkerBlocking(mFreetalk.getPluginRespirator());
      mFreetalk.handleWotConnected();
      return true;
    } catch (PluginNotFoundException e) {
      mFreetalk.handleWotDisconnected();
      return false;
    }
  }
 /** Retrieve the personal WoT identities to associate with nicknames */
 private void sendFCPOwnIdentities() {
   SimpleFieldSet sfs = new SimpleFieldSet(true);
   sfs.putOverwrite("Message", "GetOwnIdentities");
   talker.send(sfs, null);
 }