Ejemplo n.º 1
0
 /** Handle internal commands */
 private void internalCommand(ObjectConnection oc, Message message, String command, String data) {
   if (command.equals("CONNECT_DEL")) {
     try {
       oc.write("OK");
     } catch (Exception e) {
     }
     this.removeConnectInfo(message.getSender());
   } else if (command.equals("CONNECT_GET")) {
     try {
       oc.write("OK");
     } catch (Exception e) {
     }
     this.getConnectInfo(data, oc);
   } else if (command.equals("CONNECT_LIST")) {
     try {
       oc.write("OK");
     } catch (Exception e) {
     }
     this.getUserList(oc);
   } else if (command.equals("PLUGIN_LIST")) {
     try {
       oc.write("OK");
     } catch (Exception e) {
     }
     this.sendPluginList(oc, message.getSender().getName());
   } else if (command.equals("PLUGIN_GET")) {
     try {
       oc.write("OK");
     } catch (Exception e) {
     }
     this.sendPlugin(oc, data);
   } else if (command.equals("STARTUP_PLUGINS")) {
     try {
       oc.write("OK");
     } catch (Exception e) {
     }
     this.getStartupPlugin(oc, message.getSender().getName());
   } else {
     try {
       oc.write("FAILED Unknown command");
     } catch (Exception e) {
     }
   }
 }
Ejemplo n.º 2
0
  /**
   * Handles a message. Knows type "collectiveUpdate-"+name only. It is the responsibility of the
   * owner to propagate messages of this type using this method.
   */
  public boolean handleMessage(Message m, Object o) {

    if (!shouldLive || !m.getType().equals("collectiveUpdate-" + name)) return false;

    final String logSender = observer + "#collectiveUpdate";

    Logger.debug(logSender, "Update from " + m.getSender());

    /**/
    if (!m.getRecipient().name.equals(contributor.getName()))
      Logger.warning(
          logSender,
          "Recipient and my contributor are not the same:\n"
              + "Recipient: "
              + m.getRecipient().name
              + "\n"
              + "Contributor: "
              + contributor.getName(),
          null);
    /**/

    Collective c = (Collective) o;

    // --- reset array representations
    cacheCollection = null;
    commandCollection = null;

    // --- remove possible garbage
    cache.remove(m.getRecipient().name);
    c.cache.remove(m.getRecipient().name);
    cache.remove(m.getSender().name);
    c.cache.remove(m.getSender().name);

    // --- sending our contributions
    if (contributor == null)
      Logger.warning(logSender, "Non-contributor observer is known by " + m.getSender(), null);
    updateLocalInfo();
    m.setReply(this);

    // --- update containers
    repairSenderAddress(c, m.getSender());
    merge(c);
    observer.collectiveUpdated((ContributionBox) cache.get(m.getSender().name));

    return true;
  }
Ejemplo n.º 3
0
    public void run() {
      String messageString;
      long lastActivity = System.currentTimeMillis();
      while (keeprunning) {
        try {
          if (in.ready()) {
            messageString = in.readLine();

            if (messageString == null) continue;
            Message m = new Message(messageString);

            if (m.getCommand().matches("\\d+"))
              try {
                int intcommand = Integer.parseInt(m.getCommand());
                if (intcommand == Constants.RPL_ENDOFMOTD) {
                  System.err.println("MOTD SEEN, must be connected.");
                  if (connected) joinChannels();
                  connected = true;
                } else if (intcommand == Constants.ERR_NICKNAMEINUSE) {
                  System.err.println("NICKNAMEINUSE");
                  namecount++;
                  BotStats.getInstance().setBotname(botdefaultname + namecount);
                  new Message("", "NICK", BotStats.getInstance().getBotname(), "").send();
                  new Message(
                          "",
                          "USER",
                          BotStats.getInstance().getBotname()
                              + " nowhere.com "
                              + BotStats.getInstance().getServername(),
                          BotStats.getInstance().getClientName()
                              + " v."
                              + BotStats.getInstance().getVersion())
                      .send();
                  System.err.println("Setting nick to:" + botdefaultname + namecount);
                }
              } catch (NumberFormatException nfe) {
                // we ignore this
                System.err.println("Unknown command:" + m.getCommand());
              }

            if (m.getCommand().equals("PING")) {
              outqueue.add(new Message("", "PONG", "", m.getTrailing()));
              if (debug) System.out.println("PUNG at " + new Date());
            } else if (BotStats.getInstance().containsIgnoreName(m.getSender())) {
              if (debug) System.out.println("Ignored: " + m);
            } else {
              inqueue.add(m); // add to inqueue
              if (debug) System.out.println(m.toString());
              // System.out.println("Inbuffer: prefix: " + m.prefix + " params: " + m.params + "
              // trailing:"
              // + m.trailing + " command:" + m.command + " sender: " + m.sender + "\n    "
              // + "isCTCP:" + m.isCTCP + " isPrivate:" + m.isPrivate + " CTCPCommand:" +
              // m.CTCPCommand
              // + " CTCPMessage:" + m.CTCPMessage);
            }

            lastActivity = System.currentTimeMillis();
          } else {
            if (System.currentTimeMillis() - lastActivity > 400000) {
              System.err.println("400 seconds since last activity! Attempting reconnect");
              in.close();
              oh.disconnect();
              keeprunning = false;
              reconnect();
              return;
            }
            sleep(100);
          }
        } catch (IOException ioe) {
          System.out.println("EOF on connection: " + ioe.getMessage());
        } catch (InterruptedException ie) {
          System.out.println("Interrupted: " + ie.getMessage());
        } catch (Exception e) {
          System.err.println("Unexpected exception in InputHandler :");
          e.printStackTrace();
        }
      }
    }
Ejemplo n.º 4
0
  /**
   * Authenticate users
   *
   * @param oc the streams
   * @param ci the ConnectInfo
   */
  private void authentification(ObjectConnection oc, Message message, String data) {
    String passwd = null;
    String name = null;
    String authenticationServer = null;
    String hostname = null;
    int port = 0;
    StringTokenizer stk = new StringTokenizer(data, " ");

    try {
      passwd = stk.nextToken();
      hostname = stk.nextToken();
      port = Integer.parseInt(stk.nextToken());
    } catch (Exception ex) {
      Logging.getLogger().warning("#Err > Incorrect authentication message.");
      try {
        oc.write("BAD_MESSAGE");
      } catch (Exception e) {
      }

      return;
    }

    name = message.getSender().getName();
    authenticationServer = message.getSender().getAuthenticationServer();
    UserConcept user = null;

    try {
      user = store.getUserStore().getUser(message.getSender().getName());
    } catch (Exception e) {
      e.printStackTrace();
    }

    // password ok
    if (user != null && store.getUserStore().checkUserPassword(user, passwd)) {
      // disconnect already connected user
      if (isAlreadyKnown(message.getSender())) {
        ConnectInfo oldUser = getCompleteConnectInfo(message.getSender());
        try {
          ObjectConnection myoc = this.sendMessageTo(oldUser, "Client", "DISCONNECT");
          myoc.close();
        } catch (Exception e) {
          // we can't do much here, the client might have crashed
        }
        this.removeConnectInfo(oldUser);
      }

      connections.add(
          new ConnectInfo(
              name, authenticationServer, hostname, port, user.getPublicKey(), "Client"));
      try {
        oc.write("AUTH_ACCEPTED " + user.getPrivateKey());
      } catch (Exception e) {
        e.printStackTrace();
      }
      this.sendUserList();
    } else {
      try {
        oc.write("NOT_VALID_USER");
      } catch (Exception e) {
      }
    }
  }
Ejemplo n.º 5
0
  /**
   * Reads messages from the network. A message is either a command for the server or for an
   * internal Service.
   *
   * @param sock the Socket
   */
  private void getMessage(Socket sock) {
    int i;
    boolean alreadyConnected;
    boolean isAuthentication;

    Message message;
    byte[] signature;

    String cmd;
    String cmdData;
    StringTokenizer stk;

    ObjectConnection oc = null;

    try {
      /* streams initialization */
      oc = new ObjectConnection(sock);
      message = (Message) oc.read();
      signature = (byte[]) oc.read();
    } catch (Exception ex) {
      ex.printStackTrace();
      Logging.getLogger().warning("#Err > Unable to read message.");
      return;
    }

    // check wether a user is known or not
    alreadyConnected = isAlreadyKnown(message.getSender());

    // check if command is authentication
    isAuthentication =
        message.getApplication().equals("Server")
            && ((String) message.getData()).startsWith("AUTH");

    // signature check
    if (alreadyConnected && !isAuthentication) {
      boolean sigok = false;
      try {
        ConnectInfo ci = message.getSender();
        if (ci.verifier == null) ci = this.getCompleteConnectInfo(ci);
        sigok = ci.verifier.verify(message, signature);
      } catch (Exception e) {
        e.printStackTrace();
      }

      if (!sigok) {
        try {
          oc.write("FAILED bad signature");
        } catch (Exception e) {
        }
        Logging.getLogger().warning("#Err > bad signature: " + message.getSender());
        return;
      }
    }

    if (message.getApplication().equals("Server")) {
      cmd = null;

      try {
        stk = new StringTokenizer((String) message.getData());
        cmd = stk.nextToken();
        cmdData = stk.nextToken("\0").substring(1);
      } catch (Exception ex) {
        if (cmd == null) cmd = "";

        cmdData = "";
      }

      /* if the user asks for authentication, we try to do it and exits this method */
      if (cmd.equals("AUTH")) {
        try {
          oc.write("OK");
        } catch (Exception e) {
          e.printStackTrace();
        }

        authentification(oc, message, cmdData);
      } else if (!alreadyConnected) {
        Logging.getLogger().info("Access denied to " + message.getSender());
        try {
          oc.write("FAILED No Connection");
        } catch (Exception e) {
        }
      } else {
        internalCommand(oc, message, cmd, cmdData);
      }
    } else if (!alreadyConnected) {
      Logging.getLogger().info("Access denied to " + message.getSender());
      try {
        oc.write("FAILED No Connection");
      } catch (Exception e) {
      }
    } else {
      Service s;

      /* seek the destination service */
      boolean serviceFound = false;
      for (i = 0; i < this.services.size(); i++) {
        s = (Service) services.get(i);

        if (s.getName().equalsIgnoreCase(message.getApplication())) {
          serviceFound = true;
          UserConcept user = null;
          ServiceConcept service = null;
          try {
            user = store.getUserStore().getUser(message.getSender().getName());
            service = store.getServiceStore().getService(message.getReceiver().getName());
          } catch (Exception e) {
          }

          /* tests serviceManager for permissions */
          boolean isAutorizedService = false;
          try {
            isAutorizedService = store.getServiceStore().isAuthorizedService(user, service);
          } catch (Exception e) {
          }

          if (!isAutorizedService) {
            Logging.getLogger()
                .info(
                    "#Err > "
                        + message.getSender()
                        + " : Service denied to "
                        + message.getReceiver().getName());
            try {
              oc.write("FAILED You don't have acces to this service");
            } catch (Exception e) {
            }
          } else {
            try {
              oc.write("OK");
            } catch (Exception e) {
            }
            serviceFound = true;
            s.process(oc, message);
          }
          break;
        }
      }

      if (!serviceFound) {
        try {
          oc.write("FAILED unknown");
        } catch (Exception e) {
        }
        Logging.getLogger()
            .warning("#Err > Service " + message.getReceiver().getName() + " unknown");
      }
    }

    oc.close();
  }