Exemple #1
0
void Chord::init(int index){
	if(validate == false){
		validate = true;
		cout << endl << "This program is written by Lim Chee Yeong 4933643." << endl << endl;

		// if the size is not power of two, change the size to 32
		if(!(index == 1 || index == 2 || index == 4 || index == 8 || index == 16 || 
			index == 32 || index == 64 || index == 128 || index == 256 || index == 512 || 
			index == 1024 || index == 2048 || index == 4096 || index == 8192 || 
			index == 16384 || index == 32768 || index == 65536 || index == 131072 || 
			index == 262144 || index == 524288 || index == 1048576 || index == 2097152 || 
			index == 4194304 || index == 8388608 || index == 16777216 || index == 33554432 || 
			index == 67108864 || index == 134217728 || index == 268435456 || 
			index == 536870912 || index == 1073741824 || index == 2147483648)){
			cout << "Chord size is not power of two, set size to 32." << endl;
			index = 32;
		}
		maxSize = index; // 
		cout << "INITIAZE CHORD" << endl;

		int fingerIndex = log2(index);
		node.resize(index, Node(false, fingerIndex));
		addPeer(0);
	} else {
		cout << "CHORD EXISTED." << endl 
			<< "Skipping initiate CHORD, directly proceed." << endl;
	}
}
void CellAutomataAgent::handlePeerConnectionRequest(PPtr<KString> role,
    const k_guid_t& guid)
{
  if(role->equals(R_OUTPUT)) {
    addPeer(R_OUTPUT, guid);
  }
}
Exemple #3
0
SignalProxy::SignalProxy(ProxyMode mode, QIODevice* device, QObject* parent)
  : QObject(parent)
{
  setProxyMode(mode);
  addPeer(device);
  init();
}
Exemple #4
0
void Chord::run(string file){
	read(file); // Read Command from file

	// For each command, perform the repective function
	for(vector<Command>::iterator c = cmd.begin(); c != cmd.end(); c++){
		if (c->command.compare("init") == 0) {
			init(c->peer);
		}
		if (c->command.compare("addpeer") == 0) {
			addPeer(c->peer);
			updateFinger();
		}
		if (c->command.compare("insert") == 0) {
			insert(c->peer, c->message);
		}
		if (c->command.compare("print") == 0) {
			print(c->peer);
		}
		if (c->command.compare("delete") == 0) {
			Delete(c->peer, c->message);
		}
		if (c->command.compare("removepeer") == 0) {
			removePeer(c->peer);
			updateFinger();
		}
	}
}
Exemple #5
0
Serializable::Peers* SerializableEntityManager::fromJson(const QJsonObject& json, const ContactMethod* cm)
{
    //Check if the object is already loaded
    QStringList sha1List;
    QJsonArray as = json["sha1s"].toArray();
    for (int i = 0; i < as.size(); ++i) {
        sha1List.append(as[i].toString());
    }

    if (sha1List.isEmpty())
        return nullptr;

    QByteArray sha1 = sha1List[0].toLatin1();

    if (sha1List.size() > 1) {
        sha1 = mashSha1s(sha1List);
    }

    if (m_hPeers[sha1])
        return m_hPeers[sha1];

    //Load from json
    Serializable::Peers* p = new Serializable::Peers();
    p->read(json);
    m_hPeers[sha1] = p;

    //TODO Remove in 2016
    //Some older versions of the file don't store necessary values, fix that
    if (cm && p->peers.isEmpty())
        addPeer(p,cm);

    return p;
}
Exemple #6
0
void mtt::FileTransfer::handshakeFinished(PeerCommunication* p)
{
	LOG_APPEND("handshake " << p->getAddressName());
	if (!torrent->files.progress.empty())
		p->sendBitfield(torrent->files.progress.toBitfield());

	addPeer(p);
}
Exemple #7
0
void ToxGroupCall::playAudioBuffer(const ToxPk& peer, const int16_t* data, int samples,
                                   unsigned channels, int sampleRate)
{
    if (!havePeer(peer)) {
        addPeer(peer);
    }
    const auto& source = peers.find(peer);
    if (source->second) {
        source->second->playAudioBuffer(data, samples, channels, sampleRate);
    }
}
Exemple #8
0
Serializable::Peers* SerializableEntityManager::peer(const ContactMethod* cm)
{
    const QByteArray sha1 = cm->sha1();
    Serializable::Peers* p = m_hPeers[sha1];

    if (!p) {
        p = new Serializable::Peers();
        p->sha1s << sha1;

        addPeer(p,cm);

        m_hPeers[sha1] = p;
    }

    return p;
}
Exemple #9
0
Media::TextRecording* Media::TextRecording::fromJson(const QList<QJsonObject>& items, const ContactMethod* cm)
{
    TextRecording* t = new TextRecording();

    //Load the history data
    for (const QJsonObject& obj : items) {
        Serializable::Peers* p = SerializableEntityManager::fromJson(obj,cm);
        t->d_ptr->m_lAssociatedPeers << p;
    }

    //Create the model
    t->instantMessagingModel();

    //Reconstruct the conversation
    //TODO do it right, right now it flatten the graph
    for (const Serializable::Peers* p : t->d_ptr->m_lAssociatedPeers) {
        for (const Serializable::Group* g : p->groups) {
            for (Serializable::Message* m : g->messages) {
                ::TextMessageNode* n  = new ::TextMessageNode();
                n->m_pMessage         = m                      ;
                if (!n->m_pMessage->contactMethod) {
                    n->m_pMessage->contactMethod = const_cast<ContactMethod*>(cm); //TODO remove in 2016
                    n->m_pMessage->authorSha1 = cm->sha1();

                    if (p->peers.isEmpty())
                        addPeer(const_cast<Serializable::Peers*>(p), cm);
                }
                n->m_pContactMethod   = m->contactMethod;
                t->d_ptr->m_pImModel->addRowBegin();
                t->d_ptr->m_lNodes << n;
                t->d_ptr->m_pImModel->addRowEnd();
            }
        }
    }

    return t;
}
void PeerInformationSocket::processPacket(const QHostAddress &address, const QByteArray &packetArray)
{
  const char *data = packetArray.constData();
  CITP_PINF_PLoc *packet = (CITP_PINF_PLoc*)data;

  // CITP header
  if (packet->CITPPINFHeader.CITPHeader.Cookie != COOKIE_CITP)
    {
      return;
    }

  if (packet->CITPPINFHeader.CITPHeader.VersionMajor != 0x01)
    {
      qDebug() << "Invalid VersionMajor value:" << packet->CITPPINFHeader.CITPHeader.VersionMajor;
      return;
    }

  if (packet->CITPPINFHeader.CITPHeader.VersionMinor != 0x00)
    {
      qDebug() << "Invalid VersionMinor value:" << packet->CITPPINFHeader.CITPHeader.VersionMinor;
      return;
    }
  //packet->CITPPINFHeader.CITPHeader.Reserved[0] = 0x00;
  //packet->CITPPINFHeader.CITPHeader.Reserved[1] = 0x00; 
  //packet->CITPPINFHeader.CITPHeader.MessageSize = bufferLen;
  //packet->CITPPINFHeader.CITPHeader.MessagePartCount = 0x01;
  //packet->CITPPINFHeader.CITPHeader.MessagePart = 0x01; // XXX - doc says 0-based?
  
  if (packet->CITPPINFHeader.CITPHeader.ContentType != COOKIE_PINF)
    {
      return;
    }

  // PINF header
  if (packet->CITPPINFHeader.ContentType != COOKIE_PINF_PLOC)
    {
      return;
    }

  // PLoc data
  quint16 listeningPort = packet->ListeningTCPPort;
  if (0 == listeningPort)
    {
      // XXX - uncomment if we don't want non-listeners
      //return;
    }
  
  // type
  int offset = sizeof(struct CITP_PINF_PLoc);
  QString typeString(packetArray.constData()+offset);
  //memcpy(buffer + offset, typeString.toAscii().constData(), typeString.size());
  
  // name
  offset += typeString.size() + 1;
  QString nameString(packetArray.constData()+offset);
  //memcpy(buffer + offset, name.toAscii().constData(), name.size());

  // state
  offset += nameString.size() + 1;
  QString stateString(packetArray.constData()+offset);
  //memcpy(buffer + offset, state.toAscii().constData(), state.size());

  // XXX - these strings are going out of scope because they are implicitly shared
  // from the original buffer

  addPeer(address, listeningPort, typeString, nameString, stateString);
}
Exemple #11
0
void ToxGroupCall::onAudioSinkInvalidated(ToxPk peerId)
{
    removePeer(peerId);
    addPeer(peerId);
}
CmdUndiscover::CmdUndiscover(Peer* peer) {
	addPeer(peer);
}
Media::TextRecording* Media::TextRecording::fromJson(const QList<QJsonObject>& items, const ContactMethod* cm, CollectionInterface* backend)
{
    TextRecording* t = new TextRecording();
    if (backend)
        t->setCollection(backend);

    ConfigurationManagerInterface& configurationManager = ConfigurationManager::instance();

    //Load the history data
    for (const QJsonObject& obj : items) {
        Serializable::Peers* p = SerializableEntityManager::fromJson(obj,cm);
        t->d_ptr->m_lAssociatedPeers << p;
    }

    //Create the model
    bool statusChanged = false; // if a msg status changed during parsing, we need to re-save the model
    t->instantMessagingModel();

    //Reconstruct the conversation
    //TODO do it right, right now it flatten the graph
    for (const Serializable::Peers* p : t->d_ptr->m_lAssociatedPeers) {
        //Seems old version didn't store that
        if (p->peers.isEmpty())
            continue;
        // TODO: for now assume the convo is with only 1 CM at a time
        auto peerCM = p->peers.at(0)->m_pContactMethod;

        // get the latest timestamp to set last used
        time_t lastUsed = 0;
        for (const Serializable::Group* g : p->groups) {
            for (Serializable::Message* m : g->messages) {
                ::TextMessageNode* n  = new ::TextMessageNode();
                n->m_pMessage         = m                      ;
                if (!n->m_pMessage->contactMethod) {
                    if (cm) {
                        n->m_pMessage->contactMethod = const_cast<ContactMethod*>(cm); //TODO remove in 2016
                        n->m_pMessage->authorSha1 = cm->sha1();

                        if (p->peers.isEmpty())
                            addPeer(const_cast<Serializable::Peers*>(p), cm);
                    } else {
                        if (p->m_hSha1.contains(n->m_pMessage->authorSha1)) {
                            n->m_pMessage->contactMethod = p->m_hSha1[n->m_pMessage->authorSha1];
                        } else {
                            // message was outgoing and author sha1 was set to that of the sending account
                            n->m_pMessage->contactMethod = peerCM;
                            n->m_pMessage->authorSha1 = peerCM->sha1();
                        }
                    }
                }
                n->m_pContactMethod   = m->contactMethod;
                t->d_ptr->m_pImModel->addRowBegin();
                t->d_ptr->m_lNodes << n;
                t->d_ptr->m_pImModel->addRowEnd();

                if (lastUsed < n->m_pMessage->timestamp)
                    lastUsed = n->m_pMessage->timestamp;
                if (m->id) {
                    int status = configurationManager.getMessageStatus(m->id);
                    t->d_ptr->m_hPendingMessages[m->id] = n;
                    if (t->d_ptr->updateMessageStatus(m, static_cast<TextRecording::Status>(status)))
                        statusChanged = true;
                }
            }
        }

        if (statusChanged)
            t->save();

        // update the timestamp of the CM
        peerCM->setLastUsed(lastUsed);
    }

    return t;
}
	bool HTTPTracker::updateData(const QByteArray & data)
	{
//#define DEBUG_PRINT_RESPONSE
#ifdef DEBUG_PRINT_RESPONSE
		Out(SYS_TRK | LOG_DEBUG) << "Data : " << endl;
		Out(SYS_TRK | LOG_DEBUG) << QString(data) << endl;
#endif
		// search for dictionary, there might be random garbage infront of the data
		int i = 0;
		while (i < data.size())
		{
			if (data[i] == 'd')
				break;
			i++;
		}

		if (i == data.size())
		{
			failures++;
			failed(i18n("Invalid response from tracker"));
			return false;
		}

		BDecoder dec(data, false, i);
		BNode* n = 0;
		try
		{
			n = dec.decode();
		}
		catch (...)
		{
			failures++;
			failed(i18n("Invalid data from tracker"));
			return false;
		}

		if (!n || n->getType() != BNode::DICT)
		{
			failures++;
			failed(i18n("Invalid response from tracker"));
			return false;
		}

		BDictNode* dict = (BDictNode*)n;
		if (dict->getData("failure reason"))
		{
			BValueNode* vn = dict->getValue("failure reason");
			error = vn->data().toString();
			delete n;
			failures++;
			failed(error);
			return false;
		}

		if (dict->getData("warning message"))
		{
			BValueNode* vn = dict->getValue("warning message");
			warning = vn->data().toString();
		}
		else
			warning.clear();

		BValueNode* vn = dict->getValue("interval");

		// if no interval is specified, use 5 minutes
		if (vn)
			interval = vn->data().toInt();
		else
			interval = 5 * 60;

		vn = dict->getValue("incomplete");
		if (vn)
			leechers = vn->data().toInt();

		vn = dict->getValue("complete");
		if (vn)
			seeders = vn->data().toInt();

		BListNode* ln = dict->getList("peers");
		if (!ln)
		{
			// no list, it might however be a compact response
			vn = dict->getValue("peers");
			if (vn && vn->data().getType() == Value::STRING)
			{
				QByteArray arr = vn->data().toByteArray();
				for (int i = 0;i < arr.size();i += 6)
				{
					Uint8 buf[6];
					for (int j = 0;j < 6;j++)
						buf[j] = arr[i + j];

					Uint32 ip = ReadUint32(buf, 0);
					addPeer(net::Address(ip, ReadUint16(buf, 4)), false);
				}
			}
		}
		else
		{
			for (Uint32 i = 0;i < ln->getNumChildren();i++)
			{
				BDictNode* dict = dynamic_cast<BDictNode*>(ln->getChild(i));

				if (!dict)
					continue;

				BValueNode* ip_node = dict->getValue("ip");
				BValueNode* port_node = dict->getValue("port");

				if (!ip_node || !port_node)
					continue;

				net::Address addr(ip_node->data().toString(), port_node->data().toInt());
				addPeer(addr, false);
			}
		}

		// Check for IPv6 compact peers
		vn = dict->getValue("peers6");
		if (vn && vn->data().getType() == Value::STRING)
		{
			QByteArray arr = vn->data().toByteArray();
			for (int i = 0;i < arr.size();i += 18)
			{
				Q_IPV6ADDR ip;
				memcpy(ip.c, arr.data() + i, 16);
				quint16 port = ReadUint16((const Uint8*)arr.data() + i, 16);

				addPeer(net::Address(ip, port), false);
			}
		}

		delete n;
		return true;
	}
Exemple #15
0
static void* control_thread(void *vptr) {
  struct tree_t* tree = vptr;
  void* sock = getSocket(tree);

  while (1) {
    message_struct* msg = NULL;
    msg = sn_rcvmsg(sock);

    if (msg != NULL) {

      switch (msg->type) {
        case REQ_MOVE:
          print_error ("Request move from %s\n", msg->node_params.pid);
          ;int prmve = movePeer(tree, msg->node_params.pid);
          if (prmve != 0) {
            switch (prmve) {
              case -1:
                print_error ("Memory Error in moving peer\n");
                break;
              case -2:
                print_error ("Peer Not Found in Tree in moving peer\n");
                break;
              case -3:
                print_error ("No Empty Slots in moving peer\n");
                break;
            }
          }
          printTree (tree);
          break;

        case REQ_JOIN:
          print_error ("Request join from %s\n", msg->node_params.pid);
          ;int pradd = addPeer (tree, msg->node_params.peerbw,
                                msg->node_params.pid, msg->node_params.addr,
                                msg->node_params.port);
          if (pradd != 0) {
              switch (pradd) {
                case -1:
                  print_error ("Memory Error in adding peer\n");
                  break;
                case -2:
                  print_error ("No Empty Slots in adding peer\n");
                  break;
              }
          }
          printTree (tree);
          break;
        
        case REM_NODE:
          print_error ("Request drop node %s\n", msg->node_params.pid);
          ;int prremove = removePeer (tree, msg->node_params.pid);
          
          if (pradd != 0) {
              switch (pradd) {
                case -1:
                  print_error ("Memory Error in adding peer\n");
                  break;
              }
          }
          printTree (tree);
          break;

        case REQ_EXIT:
          print_error ("Request exit from %s\n", msg->node_params.pid);
          ;int prrmv = removePeer (tree, msg->node_params.pid);
          if (prrmv == -1) {
            print_error ("Memory Error in remove peer\n");
          }
          printTree (tree);
      }
    }
  }

  return NULL;
}