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");
 }
Ejemplo n.º 2
0
 public void onGeneratedURI(FreenetURI uri, BaseClientPutter state, ObjectContainer container) {
   if (logMINOR) Logger.minor(this, "Generated URI for " + darknetOpennetString + " ARK: " + uri);
   long l = uri.getSuggestedEdition();
   if (l < crypto.myARKNumber) {
     Logger.error(
         this,
         "Inserted "
             + darknetOpennetString
             + " ARK edition # lower than attempted: "
             + l
             + " expected "
             + crypto.myARKNumber);
   } else if (l > crypto.myARKNumber) {
     if (logMINOR)
       Logger.minor(
           this,
           darknetOpennetString + " ARK number moving from " + crypto.myARKNumber + " to " + l);
     crypto.myARKNumber = l;
     if (crypto.isOpennet) node.writeOpennetFile();
     else node.writeNodeFile();
     // We'll broadcast the new ARK edition to our connected peers via a differential node
     // reference
     SimpleFieldSet fs = new SimpleFieldSet(true);
     fs.putSingle("ark.number", Long.toString(crypto.myARKNumber));
     node.peers.locallyBroadcastDiffNodeRef(fs, !crypto.isOpennet, crypto.isOpennet);
   }
 }
Ejemplo n.º 3
0
 /** Create a DirPutFile from a SimpleFieldSet. */
 public static DirPutFile create(
     SimpleFieldSet subset, String identifier, boolean global, BucketFactory bf)
     throws MessageInvalidException {
   String name = subset.get("Name");
   if (name == null)
     throw new MessageInvalidException(
         ProtocolErrorMessage.MISSING_FIELD, "Missing field Name", identifier, global);
   String contentTypeOverride = subset.get("Metadata.ContentType");
   if (contentTypeOverride != null
       && (!contentTypeOverride.equals(""))
       && !DefaultMIMETypes.isPlausibleMIMEType(contentTypeOverride)) {
     throw new MessageInvalidException(
         ProtocolErrorMessage.BAD_MIME_TYPE,
         "Bad MIME type in Metadata.ContentType",
         identifier,
         global);
   }
   String type = subset.get("UploadFrom");
   if ((type == null) || type.equalsIgnoreCase("direct")) {
     return DirectDirPutFile.create(name, contentTypeOverride, subset, identifier, global, bf);
   } else if (type.equalsIgnoreCase("disk")) {
     return DiskDirPutFile.create(name, contentTypeOverride, subset, identifier, global);
   } else if (type.equalsIgnoreCase("redirect")) {
     return RedirectDirPutFile.create(name, contentTypeOverride, subset, identifier, global);
   } else {
     throw new MessageInvalidException(
         ProtocolErrorMessage.INVALID_FIELD,
         "Unsupported or unknown UploadFrom: " + type,
         identifier,
         global);
   }
 }
 private static FreenetURI insertData(File dataFile) throws IOException {
   long startInsertTime = System.currentTimeMillis();
   InetAddress localhost = InetAddress.getByName("127.0.0.1");
   Socket sock = new Socket(localhost, 9481);
   OutputStream sockOS = sock.getOutputStream();
   InputStream sockIS = sock.getInputStream();
   System.out.println("Connected to node.");
   LineReadingInputStream lis = new LineReadingInputStream(sockIS);
   OutputStreamWriter osw = new OutputStreamWriter(sockOS, "UTF-8");
   osw.write(
       "ClientHello\nExpectedVersion=0.7\nName=BootstrapPullTest-"
           + System.currentTimeMillis()
           + "\nEnd\n");
   osw.flush();
   String name = lis.readLine(65536, 128, true);
   SimpleFieldSet fs = new SimpleFieldSet(lis, 65536, 128, true, true, false, true);
   if (!name.equals("NodeHello")) {
     System.err.println("No NodeHello from insertor node!");
     System.exit(EXIT_INSERTER_PROBLEM);
   }
   System.out.println("Connected to " + sock);
   osw.write(
       "ClientPut\nIdentifier=test-insert\nURI=CHK@\nVerbosity=1023\nUploadFrom=direct\nMaxRetries=-1\nDataLength="
           + TEST_SIZE
           + "\nData\n");
   osw.flush();
   InputStream is = new FileInputStream(dataFile);
   FileUtil.copy(is, sockOS, TEST_SIZE);
   System.out.println("Sent data");
   while (true) {
     name = lis.readLine(65536, 128, true);
     fs = new SimpleFieldSet(lis, 65536, 128, true, true, false, true);
     System.out.println("Got FCP message: \n" + name);
     System.out.print(fs.toOrderedString());
     if (name.equals("ProtocolError")) {
       System.err.println("Protocol error when inserting data.");
       System.exit(EXIT_INSERTER_PROBLEM);
     }
     if (name.equals("PutFailed")) {
       System.err.println("Insert failed");
       System.exit(EXIT_INSERT_FAILED);
     }
     if (name.equals("PutSuccessful")) {
       long endInsertTime = System.currentTimeMillis();
       FreenetURI uri = new FreenetURI(fs.get("URI"));
       System.out.println(
           "RESULT: Insert took "
               + (endInsertTime - startInsertTime)
               + "ms ("
               + TimeUtil.formatTime(endInsertTime - startInsertTime)
               + ") to "
               + uri
               + " .");
       sockOS.close();
       sockIS.close();
       sock.close();
       return uri;
     }
   }
 }
  /**
   * 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");
  }
Ejemplo n.º 8
0
 public SimpleFieldSet exportFieldSet(Config.RequestType configRequestType, boolean withDefaults) {
   SimpleFieldSet fs = new SimpleFieldSet(true);
   @SuppressWarnings("unchecked")
   Map.Entry<String, Option<?>>[] entries = new Map.Entry[map.size()];
   // FIXME is any locking at all necessary here? After it has finished init, it's constant...
   synchronized (this) {
     entries = map.entrySet().toArray(entries);
   }
   if (logMINOR) Logger.minor(this, "Prefix=" + prefix);
   for (Map.Entry<String, Option<?>> entry : entries) {
     String key = entry.getKey();
     Option<?> o = entry.getValue();
     if (logMINOR)
       Logger.minor(
           this, "Key=" + key + " value=" + o.getValueString() + " default=" + o.isDefault());
     if (configRequestType == Config.RequestType.CURRENT_SETTINGS
         && (!withDefaults)
         && o.isDefault()
         && (!o.forceWrite)) {
       if (logMINOR) Logger.minor(this, "Skipping " + key + " - " + o.isDefault());
       continue;
     }
     switch (configRequestType) {
       case CURRENT_SETTINGS:
         fs.putSingle(key, o.getValueString());
         break;
       case DEFAULT_SETTINGS:
         fs.putSingle(key, o.getDefault());
         break;
       case SORT_ORDER:
         fs.put(key, o.getSortOrder());
         break;
       case EXPERT_FLAG:
         fs.put(key, o.isExpert());
         break;
       case FORCE_WRITE_FLAG:
         fs.put(key, o.isForcedWrite());
         break;
       case SHORT_DESCRIPTION:
         fs.putSingle(key, o.getLocalisedShortDesc());
         break;
       case LONG_DESCRIPTION:
         fs.putSingle(key, o.getLocalisedLongDesc());
         break;
       case DATA_TYPE:
         fs.putSingle(key, o.getDataTypeStr());
         break;
       default:
         Logger.error(this, "Unknown config request type value: " + configRequestType);
         break;
     }
     if (logMINOR)
       Logger.minor(this, "Key=" + prefix + '.' + key + " value=" + o.getValueString());
   }
   return fs;
 }
  private void addIdentities(SimpleFieldSet sfs) {
    // System.out.println("Adding all identities");

    // clear current identities (requests refresh
    identities.clear();

    // iterate over identities and store them (for resolving nick later on)
    int i = 0;
    try {
      while (!sfs.getString("Identity" + i).equals("")) {
        HashMap<String, String> identity = new HashMap<String, String>();
        identity.put("ID", sfs.getString("RequestURI" + i).split("/")[0].replace("USK@", ""));
        identity.put("nick", sfs.getString("Nickname" + i));
        identity.put("Value", sfs.getString("Value" + i));
        identity.put("Identity", sfs.getString("Identity" + i));

        // System.out.println("Added identity: " + identity.get("nick"));

        // check that the identity isn't already in the map
        boolean add = true;
        for (Map<String, String> existingIdentity : identities) {
          if (existingIdentity.get("ID").equals(identity.get("ID"))) add = false;
        }

        if (add) identities.add(identity);
        i++;
      }
    } catch (FSParseException e) { // triggered when we've reached the end of the identity list
      locked_all = false;
    }

    // FIXME: hack for broken WoT (from the perspective of freenet2/freenet1 on testnet)
    if (Frirc.DEBUG) {
      HashMap<String, String> identity = new HashMap<String, String>();
      identity.put(
          "ID",
          "67gJMSsyOg0OqifgD-Aebtw8XwKVx~vjVuRbo0WXsI4,4tbrCVGd3fvNTAwUxVZFFzaqoskEp85HgBkwpe~hiD0,AQACAAE");
      identity.put("nick", "freenet1");
      identity.put("Value", "100");
      identities.add(identity);

      HashMap<String, String> identity2 = new HashMap<String, String>();
      identity2.put(
          "ID",
          "enQbW4kdLsYqFCLtq~a4OquE5uwKa3nHFqLih64j5KU,ROkkyPxiFajC2N7RUs4oRVw2iotEp-hOV4EID0BRC9g,AQACAAE");
      identity2.put("nick", "freenet2");
      identity2.put("Value", "100");
      identities.add(identity2);
    }
  }
  /**
   * 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;
  }
Ejemplo n.º 11
0
 public String getRawOption(String name) {
   if (config instanceof PersistentConfig) {
     PersistentConfig pc = (PersistentConfig) config;
     if (pc.finishedInit)
       throw new IllegalStateException(
           "getRawOption("
               + name
               + ") on "
               + this
               + " but persistent config has been finishedInit() already!");
     SimpleFieldSet fs = pc.origConfigFileContents;
     if (fs == null) return null;
     return fs.get(prefix + SimpleFieldSet.MULTI_LEVEL_CHAR + name);
   } else return null;
 }
Ejemplo n.º 12
0
 public SimpleFieldSet toFieldSet() {
   if (freed) {
     Logger.error(this, "Cannot serialize because already freed: " + this);
     return null;
   }
   SimpleFieldSet fs = new SimpleFieldSet(false);
   fs.putSingle("Type", "DelayedFreeBucket");
   if (bucket instanceof SerializableToFieldSetBucket) {
     fs.put("Underlying", ((SerializableToFieldSetBucket) bucket).toFieldSet());
   } else {
     Logger.error(this, "Cannot serialize underlying bucket: " + bucket);
     return null;
   }
   return fs;
 }
  /**
   * 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);
  }
  /**
   * Sends a blocking FCP message to the WoT plugin, checks whether the reply is really the expected
   * reply message and throws an exception if not. Also checks whether the reply is an error message
   * and throws an exception if it is. Therefore, the purpose of this function is that the callee
   * can assume that no errors occurred if no exception is thrown.
   *
   * @param params The params of the FCP message.
   * @param expectedReplyMessage The excepted content of the "Message" field of the SimpleFieldSet
   *     of the reply message.
   * @return The unmodified HashResult object which was returned by the PluginTalker.
   * @throws WoTDisconnectedException If the connection to WoT was lost.
   * @throws Exception If the WoT plugin replied with an error message or not with the expected
   *     message.
   */
  private PluginTalkerBlocking.Result sendFCPMessageBlocking(
      SimpleFieldSet params, Bucket data, String expectedReplyMessage) throws Exception {
    if (mTalker == null) throw new WoTDisconnectedException();

    PluginTalkerBlocking.Result result;
    try {
      result = mTalker.sendBlocking(params, data);
    } catch (PluginNotFoundException e) {
      throw new WoTDisconnectedException();
    }

    if (result.params.get("Message").equals("Error")) {
      final String description = result.params.get("Description");

      if (description.indexOf("UnknownIdentityException") >= 0)
        throw new NoSuchIdentityException(description);

      throw new Exception(
          "FCP message " + result.params.get("OriginalMessage") + " failed: " + description);
    }

    if (result.params.get("Message").equals(expectedReplyMessage) == false)
      throw new Exception(
          "FCP message "
              + params.get("Message")
              + " received unexpected reply: "
              + result.params.get("Message"));

    return result;
  }
  /**
   * Method called upon receiving an FCP message, determines message type and calls correct method
   */
  @Override
  public void onReply(String plugin, String channel, SimpleFieldSet sfs, Bucket arg3) {
    try {
      // System.out.println("Message received = " + sfs.get("Message"));

      if (sfs.getString("Message").equals("OwnIdentities")) {
        addOwnIdentities(sfs);
      } else if (sfs.getString("Message").equals("Identities")) {
        addIdentities(sfs);
      } else {
        // System.out.println("Message received = " + sfs.get("OriginalMessage"));
        // System.out.println("Message received = " + sfs.get("Description"));
      }
    } catch (FSParseException e) { // no message field, shouldn't happen
      e.printStackTrace();
    }
  }
Ejemplo n.º 16
0
 public MyRequestThrottle(
     int rtt, String string, SimpleFieldSet fs, int size, boolean realTime) {
   roundTripTime =
       new BootstrappingDecayingRunningAverage(
           rtt, 10, MINUTES.toMillis(5), 10, fs == null ? null : fs.subset("RoundTripTime"));
   this.size = size;
   this.realTime = realTime;
 }
  /**
   * 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;
  }
  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;
  }
Ejemplo n.º 19
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();
  }
  /**
   * Process the WoT fcp message containing our identities and add them to the local store
   *
   * @param sfs
   */
  private void addOwnIdentities(SimpleFieldSet sfs) {
    int i = 0;
    try {
      while (!sfs.getString("Identity" + i).equals("")) {
        HashMap<String, String> identity = new HashMap<String, String>();
        identity.put("ID", sfs.getString("RequestURI" + i).split("/")[0].replace("USK@", ""));
        identity.put("insertID", sfs.getString("InsertURI" + i).split("/")[0].replace("USK@", ""));
        identity.put("nick", sfs.getString("Nickname" + i));
        identity.put("Identity", sfs.getString("Identity" + i));

        ownIdentities.add(identity);
        if (Frirc.DEBUG)
          System.out.println(
              "Identity added from WoT: " + identity.get("nick") + " (" + identity.get("ID") + ")");
        ++i;
      }
    } catch (FSParseException e) { // triggered when we've reached the end of the identity list
      locked_own = new Boolean(false);
    }
  }
  public int getGivenTrustsCount(Identity trustee, int selection) throws Exception {
    SimpleFieldSet request = new SimpleFieldSet(true);
    request.putOverwrite("Message", "GetTrusteesCount");
    request.putOverwrite("Identity", trustee.getID());
    request.putOverwrite("Context", Freetalk.WOT_CONTEXT);

    if (selection > 0) request.putOverwrite("Selection", "+");
    else if (selection == 0) request.putOverwrite("Selection", "0");
    else request.putOverwrite("Selection", "-");

    try {
      SimpleFieldSet answer = sendFCPMessageBlocking(request, null, "TrusteesCount").params;
      return Integer.parseInt(answer.get("Value"));
    } catch (PluginNotFoundException e) {
      throw new WoTDisconnectedException();
    }
  }
  /**
   * 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();
  }
Ejemplo n.º 23
0
  public ProbeRequest(SimpleFieldSet fs) throws MessageInvalidException {
    /* If not defined in the field set Identifier will be null. As adding a null value to the field set does
     * not actually add something under the key, it will also be omitted in the response messages.
     */
    this.identifier = fs.get(IDENTIFIER);

    try {
      this.type = Type.valueOf(fs.get(TYPE));

      // If HTL is not specified default to MAX_HTL.
      this.htl = fs.get(HTL) == null ? Probe.MAX_HTL : fs.getByte(HTL);

      if (this.htl < 0) {
        throw new MessageInvalidException(
            ProtocolErrorMessage.INVALID_MESSAGE, "hopsToLive cannot be negative.", null, false);
      }

    } catch (IllegalArgumentException e) {
      throw new MessageInvalidException(
          ProtocolErrorMessage.INVALID_MESSAGE,
          "Unrecognized parse probe type \"" + fs.get(TYPE) + "\": " + e,
          null,
          false);
    } catch (FSParseException e) {
      // Getting a String from a SimpleFieldSet does not throw - it can at worst return null.
      throw new MessageInvalidException(
          ProtocolErrorMessage.INVALID_MESSAGE,
          "Unable to parse hopsToLive \"" + fs.get(HTL) + "\": " + e,
          null,
          false);
    }
  }
  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;
    }
  }
  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();
    }
  }
Ejemplo n.º 26
0
 /** Persist the throttle data to a SimpleFieldSet. */
 SimpleFieldSet persistToFieldSet() {
   SimpleFieldSet fs = new SimpleFieldSet(false);
   fs.put("ThrottleWindow", throttleWindowBulk.exportFieldSet(false));
   fs.put("ThrottleWindowRT", throttleWindowRT.exportFieldSet(false));
   fs.put("ThrottleWindowCHK", throttleWindowCHK.exportFieldSet(false));
   fs.put("ThrottleWindowSSK", throttleWindowCHK.exportFieldSet(false));
   fs.put("CHKRequestThrottle", chkRequestThrottleBulk.exportFieldSet());
   fs.put("SSKRequestThrottle", sskRequestThrottleBulk.exportFieldSet());
   fs.put("CHKInsertThrottle", chkInsertThrottleBulk.exportFieldSet());
   fs.put("SSKInsertThrottle", sskInsertThrottleBulk.exportFieldSet());
   fs.put("CHKRequestThrottleRT", chkRequestThrottleRT.exportFieldSet());
   fs.put("SSKRequestThrottleRT", sskRequestThrottleRT.exportFieldSet());
   fs.put("CHKInsertThrottleRT", chkInsertThrottleRT.exportFieldSet());
   fs.put("SSKInsertThrottleRT", sskInsertThrottleRT.exportFieldSet());
   return fs;
 }
  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;
  }
Ejemplo n.º 28
0
 /** Set options from a SimpleFieldSet. Once we process an option, we must remove it. */
 public void setOptions(SimpleFieldSet sfs) {
   for (Entry<String, Option<?>> entry : map.entrySet()) {
     String key = entry.getKey();
     Option<?> o = entry.getValue();
     String val = sfs.get(key);
     if (val != null) {
       try {
         o.setValue(val);
       } catch (InvalidConfigValueException e) {
         String msg =
             "Invalid config value: "
                 + prefix
                 + SimpleFieldSet.MULTI_LEVEL_CHAR
                 + key
                 + " = "
                 + val
                 + " : error: "
                 + e;
         Logger.error(this, msg, e);
         System.err.println(msg); // might be about logging?
       } catch (NodeNeedRestartException e) {
         // Impossible
         String msg =
             "Impossible: "
                 + prefix
                 + SimpleFieldSet.MULTI_LEVEL_CHAR
                 + key
                 + " = "
                 + val
                 + " : error: "
                 + e;
         Logger.error(this, msg, e);
       }
     }
   }
 }
  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;
    }
  }
  @SuppressWarnings("unchecked")
  private void parseIdentities(SimpleFieldSet params, boolean bOwnIdentities) {
    if (bOwnIdentities) Logger.normal(this, "Parsing received own identities...");
    else Logger.normal(this, "Parsing received identities...");

    int idx;
    int ignoredCount = 0;
    int newCount = 0;

    for (idx = 0; ; idx++) {
      String identityID = params.get("Identity" + idx);
      if (identityID == null
          || identityID.equals("")) /* TODO: Figure out whether the second condition is necessary */
        break;
      String requestURI = params.get("RequestURI" + idx);
      String insertURI = bOwnIdentities ? params.get("InsertURI" + idx) : null;
      String nickname = params.get("Nickname" + idx);

      if (nickname == null || nickname.length() == 0) {
        // If an identity publishes an invalid nickname in one of its first WoT inserts then WoT
        // will return an empty
        // nickname for that identity until a new XML was published with a valid nickname. We ignore
        // the identity until
        // then to prevent confusing error logs.
        // TODO: Maybe handle this in WoT. Would require checks in many places though.
        continue;
      }

      synchronized (this) {
          /* We lock here and not during the whole function to allow other threads to execute */
        Query q = db.query(); // TODO: Encapsulate the query in a function...
        q.constrain(WoTIdentity.class);
        q.descend("mID").constrain(identityID);
        ObjectSet<WoTIdentity> result = q.execute();
        WoTIdentity id = null;

        if (result.size() == 0) {
          try {
            importIdentity(bOwnIdentities, identityID, requestURI, insertURI, nickname);
            ++newCount;
          } catch (Exception e) {
            Logger.error(this, "Importing a new identity failed.", e);
          }
        } else {
          Logger.debug(this, "Not importing already existing identity " + requestURI);
          ++ignoredCount;

          assert (result.size() == 1);
          id = result.next();
          id.initializeTransient(mFreetalk);

          if (bOwnIdentities != (id instanceof WoTOwnIdentity)) {
            // The type of the identity changed so we need to delete and re-import it.

            try {
              Logger.normal(this, "Identity type changed, replacing it: " + id);
              // We MUST NOT take the following locks because deleteIdentity does other locks
              // (MessageManager/TaskManager) which must happen before...
              // synchronized(id)
              // synchronized(db.lock())
              deleteIdentity(id, mFreetalk.getMessageManager(), mFreetalk.getTaskManager());
              importIdentity(bOwnIdentities, identityID, requestURI, insertURI, nickname);
            } catch (Exception e) {
              Logger.error(this, "Replacing a WoTIdentity with WoTOwnIdentity failed.", e);
            }

          } else { // Normal case: Update the last received time of the idefnt
            synchronized (id) {
              synchronized (db.lock()) {
                try {
                  // TODO: The thread sometimes takes hours to parse the identities and I don't know
                  // why.
                  // So right now its better to re-query the time for each identity.
                  id.setLastReceivedFromWoT(CurrentTimeUTC.getInMillis());
                  id.checkedCommit(this);
                } catch (Exception e) {
                  Persistent.checkedRollback(db, this, e);
                }
              }
            }
          }
        }
      }

      Thread.yield();
    }

    Logger.normal(
        this,
        "parseIdentities(bOwnIdentities=="
            + bOwnIdentities
            + " received "
            + idx
            + " identities. Ignored "
            + ignoredCount
            + "; New: "
            + newCount);
  }