Example #1
0
int SctpSocket::AddConnection(const std::string& a,port_t p)
{
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
	if (IsIpv6())
	{
		Ipv6Address ad(a, p);
		return AddConnection(ad);
	}
#endif
#endif
	Ipv4Address ad(a, p);
	return AddConnection(ad);
}
Example #2
0
/*******************************************************************************
 * axToggle::axToggle.
 ******************************************************************************/
axToggle::axToggle(axWindow* parent,
                   const axRect& rect,
                   const axToggle::Events& events,
                   const axToggle::Info& info,
                   string img_path,
                   string label,
                   axFlag flags,
                   string msg) :
// Heritage.
axPanel(parent, rect),
// Members.
_events(events),
_info(info),
_label(label),
_flags(flags),
_nCurrentImg(axTOG_NORMAL),
_selected(false),
test(1.0, 1.0, 0.0),
_msg(msg)
{
	_currentColor = &_info.normal;
    _btnImg = new axImage(img_path);
    
    if(_events.button_click)
    {
        AddConnection(Events::BUTTON_CLICK, _events.button_click);
    }
}
Example #3
0
bool C4Network2IO::Connect(const C4NetIO::addr_t &addr, C4Network2IOProtocol eProt, const C4ClientCore &nCCore, const char *szPassword) // by main thread
{
    // get network class
    C4NetIO *pNetIO = getNetIO(eProt);
    if (!pNetIO) return false;
    // already connected/connecting?
    if (GetConnectionByConnAddr(addr, pNetIO)) return true;
    // assign new connection ID, peer address isn't known yet
    uint32_t iConnID = iNextConnID++;
    C4NetIO::addr_t paddr;
    ZeroMem(&paddr, sizeof paddr);
    // create connection object and add to list
    C4Network2IOConnection *pConn = new C4Network2IOConnection();
    pConn->Set(pNetIO, eProt, paddr, addr, CS_Connect, szPassword, iConnID);
    pConn->SetCCore(nCCore);
    AddConnection(pConn);
    // connect
    if (!pConn->Connect())
    {
        // show error
        LogF("Network: could not connect to %s:%d using %s: %s", inet_ntoa(addr.sin_addr), htons(addr.sin_port),
             getNetIOName(pNetIO), pNetIO->GetError() ? pNetIO->GetError() : "");
        pNetIO->ResetError();
        // remove class
        RemoveConnection(pConn);
        return false;
    }
    // ok, wait for connection
    return true;
}
Example #4
0
// Thread that processes the accepted TCP connection
void TCPAcceptedThread(THREAD *t, void *param)
{
	TCP_ACCEPTED_PARAM *data;
	LISTENER *r;
	SOCK *s;
	CONNECTION *c;
	bool flag1;
	char tmp[128];
	// Validate arguments
	if (t == NULL || param == NULL)
	{
		return;
	}

	// Initialize
	data = (TCP_ACCEPTED_PARAM *)param;
	r = data->r;
	s = data->s;
	AddRef(r->ref);
	AddRef(s->ref);

	// Create a connection
	c = NewServerConnection(r->Cedar, s, t);

	// Register to Cedar as a transient connection
	AddConnection(c->Cedar, c);

	NoticeThreadInit(t);

	AcceptInit(s);
	StrCpy(c->ClientHostname, sizeof(c->ClientHostname), s->RemoteHostname);
	IPToStr(tmp, sizeof(tmp), &s->RemoteIP);
	if (IS_SPECIAL_PORT(s->RemotePort) == false)
	{
		SLog(r->Cedar, "LS_LISTENER_ACCEPT", r->Port, tmp, s->RemoteHostname, s->RemotePort);
	}

	// Reception
	ConnectionAccept(c);
	flag1 = c->flag1;

	// Release
	SLog(r->Cedar, "LS_CONNECTION_END_1", c->Name);
	ReleaseConnection(c);

	// Release
	if (flag1 == false)
	{
		Debug("%s %u flag1 == false\n", __FILE__, __LINE__);
		IPToStr(tmp, sizeof(tmp), &s->RemoteIP);

		if (IS_SPECIAL_PORT(s->RemotePort) == false)
		{
			SLog(r->Cedar, "LS_LISTENER_DISCONNECT", tmp, s->RemotePort);
		}
		Disconnect(s);
	}
	ReleaseSock(s);
	ReleaseListener(r);
}
bool RedisConnectionsManager::LoadConnectionsConfigFromFile(QString& config, bool saveChangesToFile)
{
    QFile conf(config);
    
    if (!conf.open(QIODevice::ReadOnly)) 
        return false;    
    
    QDomDocument xmlConf;

    if (xmlConf.setContent(&conf)) {

        QDomNodeList connectionsList = xmlConf.elementsByTagName("connection");
        
        for (int i = 0; i < connectionsList.size(); ++i) {

            QDomNode connection = connectionsList.at(i);

            if (connection.nodeName() != "connection") continue;

            RedisConnectionConfig conf = RedisConnectionConfig::createFromXml(connection);

            if (conf.isNull()) continue;

            AddConnection(new ConnectionBridge(conf));
        }        
    }
    conf.close();

    if (!saveChangesToFile)
        connectionSettingsChanged = false;    

    return true;
}
Example #6
0
PSafePtr<OpalConnection> LocalEndPoint::MakeConnection(OpalCall &call,
        const PString &remoteParty, void *userData, unsigned int options,
        OpalConnection::StringOptions *opts)
{
    std::cout << "LocalEndpoint::" << __func__ << std::endl;
    return AddConnection(CreateConnection(call, userData, options, opts));
// return OpalLocalEndPoint::MakeConnection(call, remoteParty, userData, options, opts);
}
Example #7
0
bool sg::Comm::StartClient(sf::Uint16 port, sf::IpAddress addr)
    
{//We are creating a connecting client
    NotDone = true;
    AddConnection(sg::Connection());
    std::cout << "StartClient" << std::endl;
    CommLooperThread.launch();
    return true;
}
Example #8
0
status_t
PostEvent(bluetooth_device* ndev, void* event, size_t size)
{
    struct hci_event_header* outgoingEvent = (struct hci_event_header*) event;
    status_t err;

    // Take actions on certain type of events.
    switch (outgoingEvent->ecode) {
    case HCI_EVENT_CONN_COMPLETE:
    {
        struct hci_ev_conn_complete* data
            = (struct hci_ev_conn_complete*)(outgoingEvent + 1);

        // TODO: XXX parse handle field
        HciConnection* conn = AddConnection(data->handle, BT_ACL,
                                            data->bdaddr, ndev->index);

        if (conn == NULL)
            panic("no mem for conn desc");
        conn->ndevice = ndev;
        TRACE("%s: Registered connection handle=%#x\n", __func__,
              data->handle);
        break;
    }

    case HCI_EVENT_DISCONNECTION_COMPLETE:
    {
        struct hci_ev_disconnection_complete_reply* data;

        data = (struct hci_ev_disconnection_complete_reply*)
               (outgoingEvent + 1);

        RemoveConnection(data->handle, ndev->index);
        TRACE("%s: unRegistered connection handle=%#x\n", __func__,
              data->handle);
        break;
    }

    }

    // forward to bluetooth server
    port_id port = find_port(BT_USERLAND_PORT_NAME);
    if (port != B_NAME_NOT_FOUND) {

        err = write_port_etc(port, PACK_PORTCODE(BT_EVENT, ndev->index, -1),
                             event, size, B_TIMEOUT, 1 * 1000 * 1000);

        if (err != B_OK)
            ERROR("%s: Error posting userland %s\n", __func__, strerror(err));

    } else {
        ERROR("%s: bluetooth_server not found for posting!\n", __func__);
        err = B_NAME_NOT_FOUND;
    }

    return err;
}
Example #9
0
// C4NetIO interface
bool C4Network2IO::OnConn(const C4NetIO::addr_t &PeerAddr, const C4NetIO::addr_t &ConnectAddr, const C4NetIO::addr_t *pOwnAddr, C4NetIO *pNetIO)
{
    // puncher answer? We just make sure here a connection /can/ be established, so close it instantly.
    if (pNetIO == pNetIO_UDP)
        if (PuncherAddr.sin_addr.s_addr && AddrEqual(PuncherAddr, ConnectAddr))
        {
            // got an address?
            if (pOwnAddr)
                OnPunch(*pOwnAddr);
            // this is only a test connection - close it instantly
            return false;
        }
#if(C4NET2IO_DUMP_LEVEL > 1)
    Application.InteractiveThread.ThreadLogS("OnConn: %s %s",
            C4TimeMilliseconds::Now().AsString().getData(),
            getNetIOName(pNetIO));
#endif
    // search connection
    C4Network2IOConnection *pConn = NULL;
    if (ConnectAddr.sin_addr.s_addr)
        pConn = GetConnectionByConnAddr(ConnectAddr, pNetIO);
    // not found?
    if (!pConn)
    {
        // allow connect?
        if (!fAllowConnect) return false;
        // create new connection object
        uint32_t iConnID = iNextConnID++;
        pConn = new C4Network2IOConnection();
        pConn->Set(pNetIO, getNetIOProt(pNetIO), PeerAddr, ConnectAddr, CS_Connected, NULL, iConnID);
        // add to list
        AddConnection(pConn);
    }
    else
    {
        // already closed this connection (attempt)?
        if (pConn->isClosed())
            return false;
        if (!pConn->isOpen())
        {
            // change status
            pConn->SetStatus(CS_Connected);
            pConn->SetPeerAddr(PeerAddr);
        }
    }
    // send welcome packet, if appropriate
    SendConnPackets();
#if(C4NET2IO_DUMP_LEVEL > 0)
    // log
    Application.InteractiveThread.ThreadLogS("Network: got %s connection from %s:%d", getNetIOName(pNetIO), inet_ntoa(PeerAddr.sin_addr), htons(PeerAddr.sin_port));
#endif
    // do event (disabled - unused)
    // pConn->AddRef(); PushNetEv(NE_Conn, pConn);
    // ok
    return true;
}
Example #10
0
axScrollBar::axScrollBar(axWindow* parent,
                         axWindow* handle,
                         const axRect& rect,
                         const axScrollBarEvents& events,
                         const axScrollBarInfo& info,
                         axFlag flags) :
// Heritage.
axPanel(parent, rect),
// Members.
_events(events),
_info(info),
_handle(handle),
_flags(flags),
_yClickDelta(0),
_value(0.0)
{

    axButton::Info btn_info(axColor(0.8, 0.0, 0.0),
                            axColor(0.9, 0.0, 0.0),
                            axColor(0.8, 0.0, 0.0),
                            axColor(0.8, 0.0, 0.0),
                            axColor(0.0, 0.0, 0.0),
                            axColor(0.0, 0.0, 0.0));

	//function<void (axButtonMsg)> btnFct();

//	_btn[0] = new axButton(this, 
//						   axRect(0, 0, 14, 14), 
//						   axButtonEvents(), 
//						   btn_info, 
//						   "/Users/alexarse/Project/axLib/axProjects/MidiSequencer/scrollBar_up.png");
//
//	_btn[1] = new axButton(this, 
//						   axRect(0, rect.size.y - 14, 14, 14), 
//						   axButtonEvents(), 
//						   btn_info, 
//						   "/Users/alexarse/Project/axLib/axProjects/MidiSequencer/scrollBar_down.png");

	_imgHeight = 0;
    _panelSize = rect.size;
    _sliderMaxHeight = rect.size.y - (2.0 * _imgHeight);
    
    double ratio = double(_panelSize.y - rect.size.y) / double(_panelSize.y);
    
    _sliderHeight = _sliderMaxHeight * (1.0 - ratio);
    _sliderPos = 0;
    
    _currentScrollBarColor = &_info.normal;
    
    if(_events.value_change)
    {
        AddConnection(axScrollBarEvents::VALUE_CHANGE, _events.value_change);
    }

}
void XSessionImpl::OnHandshakeComplete(const XSocketPtr& newConnection, SocketID socketID, HandshakeResult result)
{
	if (newConnection && result == HandshakeResult::Success)
	{
		AddConnection(newConnection);
	}
	else
	{
		LogInfo("Session %s: Handshake from %s failed with error %u", m_name.c_str(), newConnection ? newConnection->GetRemoteSystemName().c_str() : "unknown machine", result);
	}

	XTVERIFY(m_pendingConnections.erase(socketID));
}
Example #12
0
uint32_t BindEndpoint(char *name, uint16_t version)
{
  for (int i=0; i< MAX_CGCRPC_ENDPOINTS; i++)
  {
    if (endpoints[i].name[0] != '\0')
    {
      if ((strcmp(endpoints[i].name, name) == 0) && (endpoints[i].version == version))
      {
        return AddConnection(&endpoints[i]);
      }
    }
  }
  return 0;
}
void CBCGPGanttItemStorageBase::Serialize (CArchive& ar)
{
	if (ar.IsLoading ())
	{
		RemoveAll ();
		int nCount = 0;

		// Loading items
		ar >> nCount;

		while (nCount-- > 0)
		{
			CBCGPGanttItem* pItem = NULL;
			ar >> pItem;
			if (pItem != NULL)
			{
				ASSERT_VALID (pItem);
				pItem->m_pStorage = this;
				DoAdd (pItem);
			}
		}

		int nItems = GetCount ();

		// Loading connections
		ar >> nCount;

		while (nCount-- > 0)
		{
			int indexSrc = 0, indexDest = 0, linkType, reserved;

			ar >> indexSrc;
			ar >> indexDest;
			ar >> linkType;
			ar >> reserved;

			if (indexSrc >= 0 && indexSrc < nItems && indexDest >= 0 && indexDest < nItems)
			{
				ASSERT (indexSrc != indexDest);

				if (indexSrc != indexDest)
				{
					AddConnection (GetItem (indexSrc), GetItem (indexDest), linkType);
				}
			}
		}

		UpdateAll (BCGP_GANTT_ITEM_PROP_ALL);
	}
Example #14
0
/*******************************************************************************
 * MyButton.
 ******************************************************************************/
MyButton::MyButton(axWindow* parent,
                   const axRect& rect,
                   const axButtonEvents& events,
                   const axButtonInfo& info,
                   const axPoint& led_delta_pos):
axButton(parent, rect, axButtonEvents(GetOnClickButton()), info),
_led(nullptr),
_active(false)
{
    if(events.button_click)
    {
        AddConnection(2, events.button_click);
    }
    
    
    _led = new MyLED(parent, rect.position + led_delta_pos);
}
Example #15
0
// Инициализация соединения.
String meth::ConnectionInit(String app_name, SocketСonnections::iterator socket_connection, int transport) {
	bool persistent;
	SOCKET sd = socket_connection->sd;
	String ip = socket_connection->ip;

	if (ip.IsEmpty()) {
		throw(JSONError(-1001, "Can't determine your IP-address"));
	}

	// If this is HTTP connection then set socket handle to NULL.
	if (transport == 1) {
		sd = NULL;
	}

	// For HTTP connection !transport will return false and plugin won't try to send actions.
	String conn_id = AddConnection(app_name, ip, sd, !transport, transport);

	return "{\"conn_id\":\"" + conn_id + "\"}";
}
Example #16
0
int CNetServer::ListenThreadFunc()
{
	while (true)
	{
		SOCKET tSocket;
		if ((tSocket = accept(m_tSocketId, NULL, NULL)) == INVALID_SOCKET)
		{
			printf("accept Error! errno = %d\n", WSAGetLastError());

		}
		else
		{
			AddConnection(tSocket);
		}

		Yeild(1000);

	}

	return SUCCESS_VALUE;
}
NetConnection* NetworkSession::AddConnectionToSelf(const Byte& connIndex, const std::string& connPortService ) {

	static const std::string selfConnName = "self";

	NetAddresses netAddressesToConnect;
	std::string localHostName = AllocLocalHostName();
	AllocAddressesForHost(netAddressesToConnect, localHostName, connPortService );

	std::string addConnDebugToConsole = "Adding Connection to Self";

	AddConnection(netAddressesToConnect[0], connIndex, selfConnName);

	m_netConnNameRegistry[connIndex] = "self";

	addConnDebugToConsole += "\nAdded Connection to Self:" + netAddressesToConnect[0].ToString();

	OUTPUT_STRING_TO_CONSOLE(addConnDebugToConsole, 1000);
	ConsolePrintString(addConnDebugToConsole);

	
	return  m_netConnectionMap[selfConnName];


}
bool
ProgrammableOpAttributes::SetupPipeline(const JSONNode& atts, stringVector& args, const std::string& parent)
{
    if(atts.GetType() != JSONNode::JSONARRAY)
        return false;

    const JSONNode::JSONArray& array = atts.GetArray();

    for(int i = 0; i < array.size(); ++i)
    {
        /// need key, value pair
        /// this can be in the form of a dictionary, "a = b", pair tuple (a,b), or a pair array [a,b]
        JSONNode node = array[i];
        JSONNode key,value;
        if(node.GetType() == JSONNode::JSONARRAY)
        {
            if(node.GetArray().size() != 2) continue;

            key = node.GetArray()[0];
            value = node.GetArray()[1];
        }
        else if(node.GetType() == JSONNode::JSONOBJECT)
        {
            /// parse through dictionary and compute arguments from names..
            const JSONNode::JSONObject& obj = node.GetJsonObject();
            if(obj.size() != 1) continue;

            const JSONNode::JSONObject::const_iterator itr = obj.begin();
            key = itr->first;
            value = itr->second;
        }
        else if(node.GetType() == JSONNode::JSONSTRING)
        {
            std::string pair = node.GetString();
            int index = pair.find("=");
            if(index == std::string::npos) continue;
            key = pair.substr(0,index);

            value = trim(pair.substr(index+1));
         }

        if(key.GetType() != JSONNode::JSONSTRING) continue;

        std::string keystr = trim(key.GetString());

        std::ostringstream str;
        str << "import json\n";
        if(value.GetType() == JSONNode::JSONSTRING)
        {
            std::string v = trim(value.GetString());

            ///character at 0 and has :
            if(v.find(":") != std::string::npos && v.find(":") == 0)
            {
                /// optionally handle whether it can be as_vtkarray, as_ndarray, or as_rarray

                size_t index = v.find(":as_ndarray");

                if(index == std::string::npos)
                    index = v.find(":as_rarray");

                if(index != std::string::npos)
                {
                    std::string newName = getNextName();
                    v = v.substr(0,index);
                    AddNode(newName, "as_ndarray");
                    AddConnection(v, newName, "in");
                    AddConnection(newName,parent,keystr);
                }
                else
                {
                    index = v.find(":as_vtkarray");
                    if(index != std::string::npos)
                        v = v.substr(0,index);
                    AddConnection(v,parent,keystr);
                }
            }
            else
            {
                std::string escapedCode = trim(value.GetString());
                replace(escapedCode,"\n","\\\n");
                replace(escapedCode,"'","\"");
                escapedCode = "'" + escapedCode + "'";

                str << "try:\n"
                    << " a = json.loads(" << escapedCode << ")\n"
                    << "except:\n"
                    << " a = " << escapedCode << "\n"
                    << "setout(a)\n";

                AddPythonScript(keystr,stringVector(),str.str());
                AddNode(keystr,keystr);
                AddConnection(keystr,parent,keystr);
            }
        }
        else
        {
            str << "setout(json.loads('" << trim(value.ToString()) << "'))\n";

            AddPythonScript(keystr,stringVector(),str.str());
            AddNode(keystr,keystr);
            AddConnection(keystr,parent,keystr);
        }
        args.push_back(keystr);
    }
    return true;
}
Example #19
0
int main() {
	WSAStartup(MAKEWORD(2, 2), &wsa);
	s = socket(AF_INET, SOCK_DGRAM, 0);

	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons(PORT);

	bind(s, (struct sockaddr *)&server, sizeof(server));

	GenerateMap();

	while (isRunning) {
		incrementIndex = -1;

		memset(buf, '\0', BUFLEN);
		recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *)&tempClient.address, &tempClient.addrLength);

		for (int x = 0; x < clientList.size(); x++) {
			if (tempClient.address.sin_port == clientList[x].address.sin_port) incrementIndex = x;
		}

		std::string tempMessage = "";

		switch (ProcessCommand(buf)) {
			case 0 :
				tempClient.uniqueID = incrementID;
				incrementID += 1;

				if (AddConnection(tempClient)) SendMessage("connect", tempClient);

				std::cout << GetConnectionCount() << "/" << maxConnections << std::endl;
				break;
			case 1:
				SendMap(clientList[incrementIndex]);
				break;
			case 2:
				InitializePlayer(clientList[incrementIndex]);

				tempMessage += "advert<position>" + std::to_string((int)clientList[incrementIndex].uniqueID) + ":";
				tempMessage += std::to_string((int)clientList[incrementIndex].player.position.x) + "," + std::to_string((int)clientList[incrementIndex].player.position.y);

				char tempMessageChar[BUFLEN];
				strcpy(tempMessageChar, tempMessage.c_str());
				SendMessage(tempMessageChar, clientList[incrementIndex], clientList);

				break;
			case 3:
				RequestPlayer(clientList[incrementIndex]);
				break;
			case 4:
				UpdatePosition(clientList[incrementIndex], buf);
				break;
		}

		std::cout << buf << std::endl;
	}

	closesocket(s);
	WSACleanup();

	return 0;
}
	boost::signals::connection ConnectToSignal(const std::string& name, boost::function<Sig_Tp> slot){
		return AddConnection(name, signalbroker.ConnectToSignal(name, slot));
	}
Example #21
0
void ReadSocket(HWND hWnd,LPARAM lParam,serverStruct *server,clientStruct **clients)
{
	int wmEvent=WSAGETSELECTEVENT(lParam);
	int wmError=WSAGETSELECTERROR(lParam);
	clientStruct  *clientCopy=*clients;

	TCHAR incomingMSG[BUFFER_SIZE*sizeof(TCHAR)];
	int bufferSize=BUFFER_SIZE*sizeof(TCHAR);

	_tcscpy(incomingMSG,_T(""));

	switch(wmEvent)
	{
	case FD_ACCEPT:
		{
			if(wmError!=NULL)
				DisplayError(NULL,TEXT("Connection Error"),wmError,ALL,ERRORFOUND);
			else
			{
				server->noConnections=AddConnection(&clientCopy,server->inSocket,server->noConnections);	// Add new connection
				if(hWnd!=NULL)												// Don't display message if window not open
				{
					StringCbPrintf(incomingMSG, bufferSize,TEXT("[No %d/%d] connection(s) from IP: %s"),server->noConnections,server->maxConnections,(*clients)->ipAddress);
					SendMessage(hWnd,LB_ADDSTRING,0,(LPARAM)incomingMSG);
				}
			}
		}
		break;
	case FD_READ:
		{
			int szRead=0;
			int sender=0;
			int structSize=sizeof(clientStruct)*sizeof(TCHAR);
			clientStruct newData={'\0'};

			while((clients!=NULL) && (szRead==0))
			{	// Loop through all the known sockets
				// If data is waiting to be read recv returns size of data read
				// If it returns 0 the connection is closed
				sender=clientCopy->inSocket;
				szRead=recv(sender,(char*)&newData,structSize,0);
				if(0>szRead)
					clientCopy=clientCopy->next;
				else
				{
					_tcscpy(clientCopy->nickName,newData.nickName);
					_tcscpy(clientCopy->sendMSG,newData.sendMSG);
					_tcscpy(clientCopy->sendTo,newData.sendTo);
				}
			}
			if(sender>0)
				RelayMSG(hWnd,clientCopy,sender);                          // Send message to relevant clients
		}
		break;
	case FD_CLOSE:
		{
			SOCKET closedSocket=GetClosedSocket((*clients));                  // Find out which socket closed
			if((closesocket(closedSocket)==0) && (IsWindowVisible(hWnd)))// Socket found, only display info if hWnd open
			{
				StringCbPrintf(incomingMSG,100,TEXT("Disconnected : %s"),DeleteClient(clients,closedSocket));  // Display msg IP of client and data & time
				SendMessage(hWnd,LB_ADDSTRING,0, (LPARAM)incomingMSG);
			}
		}
		break;
	}
	*clients=clientCopy;
}
Example #22
0
void MainFrame::OnAddConnection(wxCommandEvent &evt)
{
    AddConnection();
}
Example #23
0
void set_connection(char *sp, char *dh, char *dp, enum event_types type)
{

  int cx;

  /* A connection is identified by the host/port 3-tuple (the source IP
     address is not needed because only one client is handled at a time).
     The connection's status depends on the type of the event that caused
     the update.  The following event type are defined with their effect
     on the connection's status:
           SYN, ACT-REQ, - The connection has begun (is an "active"
           ACT-RSP         connection.  Add it to the table as idle
                           (activity == 0) if a SYN or with request/
                           response activity (activity == 1) for ACT-REQ
                           or ACT-RSP.
           REQ           - Find the connection in the table and mark it with
                           an outstanding request (activity == 1).
           RSP           - Find the connection in the table and mark it with
                           a completed request (activity == 0).
           END           - The connection has ended (is no longer an "active"
                           connection).  Remove it from the table.
  */

  switch (type)
     {   
      case SYN:
      case ACT_REQ:
      case ACT_RSP:
	 {
          cx = AddConnection(sp, dh, dp);
          if (cx < 0)  /* already there */
	     {
              error_state("Add for existing connection");
              return;
             }            
          if (cx > MAX_CONNECTIONS)  /* table overflow */
	     {
              error_state("Active connections exceeds maximum");
              exit (-1);
             } 
          connections[cx].state = type;
          if (type == SYN)
             connections[cx].activity = 0;
          else
             connections[cx].activity = 1;
          break;
	 }    

      case REQ:
	 {
          cx = FindConnection(sp, dh, dp);
          if (cx < 0)  /* not there */
	     {
              error_state("REQ for non-existent connection");
              return;
             }
          if ((connections[cx].state == RSP) ||
              (connections[cx].state == ACT_REQ) ||
              (connections[cx].state == SYN))
	     {
              connections[cx].activity = 1; 
              connections[cx].state = REQ;
             }       
          else
              error_state("REQ in invalid connection state");

          break;
         }

      case RSP:
	 {
          cx = FindConnection(sp, dh, dp);
          if (cx < 0)  /* not there */
	     {
              error_state("RSP for non-existent connection");
              return;
             }
          if ((connections[cx].state == REQ) ||
              (connections[cx].state == ACT_RSP) ||
              (connections[cx].state == SYN))
	     {
              connections[cx].activity = 0; 
              connections[cx].state = RSP;
             }      
          else
              error_state("RSP in invalid connection state");

          break;
         }

      case END:
	 {
          cx = FindConnection(sp, dh, dp);
          if (cx < 0)  /* not there */
	     {
              error_state("End for non-existent connection");
              return;
             }
          connections[cx].activity = 0; 
          connections[cx].state = END;
          cx = RemoveConnection(sp, dh, dp);
          break;
	 }
      default:
      break;

     }
}
Example #24
0
uint32_t handle_PATCH( int fd, phttp_request phr )
{
    uint32_t retval = 0;
    uint32_t length = 0;
    uint8_t *file = NULL;
    uint32_t urllen = 0;
    pstr of = NULL;
    uint8_t *out = NULL;
    pstr response = NULL;
    pstr outdata = NULL;
    uint32_t start = 0;

    if ( phr == NULL ) {
        goto end;
    }

    if ( phr->root == NULL ) {
        DEBUG_PRINT("[ERROR] No root directory.\n");
        goto end;
    }

    if ( phr->url == NULL ) {
        goto end;
    }

    if ( phr->content_data == NULL ) {
        goto end;
    }

    if ( phr->content_length == NULL ) {
        goto end;
    }

    outdata = malloc( sizeof(str) );

    if ( outdata == NULL ) {
        goto end;
    }

    if ( phr->url[0] == '/' && ( phr->url[1] == ' ' || phr->url[1] == '\x00') ) {
        phr->url = (uint8_t*)"/index.html";
    }

    while ( phr->root[length] != 0 ) {
        length++;
    }

    while ( phr->url[urllen] != 0x00 ) {
        urllen++;
    }

    // The + two is for the possibility of adding a '/'
    //      plus the final null byte
    file = (uint8_t*)malloc( length + urllen + 2 );

    if ( file == NULL ) {
        goto end;
    }

    memset( file, 0x00, length + urllen + 2);

    if ( memcmp( phr->url, "/index.html", urllen ) != 0 
#ifndef VONE
            && memcmp( phr->url, "/index.ydg", urllen ) != 0 
#endif
       ) {
        send_error( fd, 415);
        goto end;
    }

    // Copy the root directory
    memcpy( file, phr->root, length );

    // check for starting '/'
    if (phr->url[0] != '/' ) {
        file[length] = '/';
        length++;
    }

    memcpy( file + length, phr->url, urllen );

    of = read_file( file );

    if ( of == NULL ) {
        send_error( fd, 404 );
        goto end;
    }

    start = 0;

    if ( phr->xoffset != NULL ) {
        start = catoi( phr->xoffset );
    }

    urllen = catoi( phr->content_length );
    if ( start + urllen > of->max ) {
        urllen += start;
    } else {
        urllen = of->max;
    }

    out = alloca( urllen );

    outdata = init_str( outdata, out, urllen );

    if ( outdata == NULL ) {
        goto end;
    }

    // Write the initial data
    if ( overwrite_data( outdata, of->str, 0, of->max ) == 0 ) {
        goto end;
    }

    if ( overwrite_data( outdata, phr->content_data, start, catoi(phr->content_length)) == 0 ) {
        send_error( fd, 400 );
        goto end;
    }

    if ( write_file( outdata, file ) == 0 ) {
        send_error( fd, 400 );
        goto end;
    }

    response = create_str( (uint8_t*)"HTTP/1.1 200 OK\r\n" );

    if ( response == NULL ) {
        DEBUG_PRINT("[ERROR] Failed to initialize response string\n");
        goto end;
    }

    AddConnection( response, 0 );
    AddServer( response );
    AddSetCookie( response );

    if ( append_str( response, (uint8_t*)"\r\n" ) == 0 ) {
        DEBUG_PRINT("[ERROR] Failed to append crlf crlf\n");
        goto end;
    }

    send( fd, response->str, response->max, 0 );

    retval = 1;
end:
    if ( outdata ) {
        free(outdata);
    }

    if ( file ) {
        free( file );
        file = NULL;
    }

    if ( of ) {
        free_str( of );
    }

    if ( response ) {
        free_str( response );
    }

    return retval;
}
Example #25
0
int ChatLoop()
{
    int i, j;
    FD_ZERO(&status);

    FD_SET(tsocket, &status);
    FD_SET(0, &status);

    while(1)
    {
        current = status;
        if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)
        {
            perror("Select");
            return 0;
        }
        for (i = 0; i < FD_SETSIZE; ++i)
        {
            if (FD_ISSET(i, &current))
            {
                if (i == tsocket)
                {
                    struct sockaddr_in cliinfo;
                    socklen_t addrlen = sizeof(cliinfo);
                    int handle;
                    handle = accept(tsocket, &cliinfo, &addrlen);
                    if (handle == -1)
                    {
                        perror ("Couldn't accept connection");
                    } else if (handle > FD_SETSIZE)
                    {
                        printf ("Unable to accept new connection.\n");
                        close(handle);
                    }
                    else
                    {
                        if (write(handle, "Enter name: ", 12) >= 0)
                        {
                            printf("-- New connection %d from %s:%hu\n",
                                handle,
                                inet_ntoa (cliinfo.sin_addr),
                                ntohs(cliinfo.sin_port));
                            FD_SET(handle, &status);

                            AddConnection(handle);
                        }
                    }
                } /* Read data, relay to others. */
                else
                {
                    char buf[512];
                    int b;

                    b = read(i, buf, 500);
                    if (b <= 0)
                    {
                        CloseConnection(i);
                    }
                    else
                    {
                        ClientText(i, buf, b);
                    }
                }
            }
        }
    } /* While 1 */
}
Connection *SocTransport::AsyncConnect(NetAddress *pnad)
{
	MpTrace("AsyncConnect(%s)", pnad != NULL ? inet_ntoa(((sockaddr_in *)pnad)->sin_addr) : "loopback");

	Connection *pcon;

	// A NULL pnad means this device is the server and is now trying to
	// connect to itself as a client. Use the LoopbackConnection to satisfy
	// this.

	if (pnad == NULL) {
		pcon = new LoopbackConnection(this);
		Assert(pcon != NULL, "out of memory!");
		if (pcon == NULL)
			return NULL;
		m_fAsyncConnectLoopback = true;

	} else {
		// Create the socket for connecting to the server

		SOCKET soc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if (soc == INVALID_SOCKET) {
#ifdef DEBUG
			HostMessageBox(TEXT("socket err: 0x%lx"), PszFromSocError());
#endif
			return NULL;
		}

		// Disable nagle algorithm

		int nTrue = 1;
		setsockopt(soc, IPPROTO_TCP, TCP_NODELAY, (NetBuff)&nTrue, sizeof(int));
                
		// Disable excessive 'lingering' (particularly a problem on PalmOS <=5 which has only 16 sockets)

		linger lngr;
		lngr.l_onoff = 1;
		lngr.l_linger = 0;
		setsockopt(soc, SOL_SOCKET, SO_LINGER, (NetBuff)&lngr, sizeof(lngr));

		// Connect to the server
		// UNDONE: On PalmOS <=5 this occasionally times out after 2 secs. Longer would be better

		if (connect(soc, (const sockaddr *)pnad, sizeof(sockaddr_in)) != 0) {
			switch (WSAGetLastError()) {
			case WSAEHOSTUNREACH:
				HtMessageBox(kfMbWhiteBorder, "Comm Problem", "Host unreachable.");
				break;

			case WSAECONNREFUSED:
				HtMessageBox(kfMbWhiteBorder, "Comm Problem", "Connection refused.");
				break;

			case WSAETIMEDOUT:
				HtMessageBox(kfMbWhiteBorder, "Comm Problem", "Timed out trying to connect to host.");
				break;

			default:
				HtMessageBox(kfMbWhiteBorder, "Comm Problem", "Unable to connect. Error %d", WSAGetLastError());
				break;
			}
			closesocket(soc);
			return NULL;
		}

		pcon = NewConnection(soc);
		if (pcon == NULL) {
			closesocket(soc);
			return NULL;
		}
		m_fAsyncConnectLoopback = false;
	}

	AddConnection(pcon);

	Assert(m_pconAsyncConnect == NULL, "Can only have one pending AsyncConnect at a time");
	m_pconAsyncConnect = pcon;

	return pcon;
}
Example #27
0
void EQWHTTPServer::CreateNewConnection(uint32 ID, SOCKET in_socket, uint32 irIP, uint16 irPort) {
	EQWHTTPHandler *conn = new EQWHTTPHandler(ID, in_socket, irIP, irPort);
	AddConnection(conn);
}
Example #28
0
CAsyncSocketEx * CListenSocket::OnAcceptEx(int /*nErrorCode*/)
{
	/*	m_nPendingConnections++;
	if (m_nPendingConnections < 1){
	ASSERT(0);
	m_nPendingConnections = 1;
	}

	if (TooManySockets(true) && !CGlobalVariable::serverconnect->IsConnecting()){
	StopListening();
	return NULL;
	}
	else if (!bListening)
	ReStartListening(); //If the client is still at maxconnections, this will allow it to go above it.. But if you don't, you will get a lowID on all servers.
	*/
	//uint32 nFataErrors = 0;
	//while (m_nPendingConnections > 0)
	//{
	if(m_nPendingConnections>0) m_nPendingConnections--;

	CClientReqSocket* newclient;
	//SOCKADDR_IN SockAddr = {0};
	//int iSockAddrLen = sizeof SockAddr;
	if (thePrefs.GetConditionalTCPAccept() && !thePrefs.GetProxySettings().UseProxy)
	{
		_iAcceptConnectionCondRejected = 0;
		//SOCKET sNew = 100;
		/*SOCKET sNew = WSAAccept(m_SocketData.hSocket, (SOCKADDR*)&SockAddr, &iSockAddrLen, AcceptConnectionCond, 0);
		if (sNew == INVALID_SOCKET)
		{
		DWORD nError = GetLastError();
		if (nError == WSAEWOULDBLOCK)
		{
		DebugLogError(LOG_STATUSBAR, _T("%hs: Backlogcounter says %u connections waiting, Accept() says WSAEWOULDBLOCK - setting counter to zero!"), __FUNCTION__, m_nPendingConnections);
		m_nPendingConnections = 0;
		break;
		}
		else{
		if (nError != WSAECONNREFUSED || _iAcceptConnectionCondRejected == 0){
		DebugLogError(LOG_STATUSBAR, _T("%hs: Backlogcounter says %u connections waiting, Accept() says %s - setting counter to zero!"), __FUNCTION__, m_nPendingConnections, GetErrorMessage(nError, 1));
		nFataErrors++;
		}
		else if (_iAcceptConnectionCondRejected == 1)
		theStats.filteredclients++;
		}
		if (nFataErrors > 10){
		// the question is what todo on a error. We cant just ignore it because then the backlog will fill up
		// and lock everything. We can also just endlos try to repeat it because this will lock up eMule
		// this should basically never happen anyway
		// however if we are in such a position, try to reinitalize the socket.
		DebugLogError(LOG_STATUSBAR, _T("%hs: Accept() Error Loop, recreating socket"), __FUNCTION__);
		Close();
		StartListening();
		m_nPendingConnections = 0;
		break;
		}
		continue;
		}*/
		newclient = new CClientReqSocket;
		newclient->m_bUseNat = true;

		VERIFY( newclient->InitAsyncSocketExInstance() );
		//newclient->m_SocketData.hSocket = sNew;
		//newclient->AttachHandle(sNew);

		AddConnection();
	}
	else
	{
		newclient = new CClientReqSocket;
		newclient->m_bUseNat = true;

		//SOCKET sNew = 100;
		//newclient->m_SocketData.hSocket = sNew;

		/*if (!Accept(*newclient, (SOCKADDR*)&SockAddr, &iSockAddrLen))
		{
		newclient->Safe_Delete();
		DWORD nError = GetLastError();
		if (nError == WSAEWOULDBLOCK){
		DebugLogError(LOG_STATUSBAR, _T("%hs: Backlogcounter says %u connections waiting, Accept() says WSAEWOULDBLOCK - setting counter to zero!"), __FUNCTION__, m_nPendingConnections);
		m_nPendingConnections = 0;
		break;
		}
		else{
		DebugLogError(LOG_STATUSBAR, _T("%hs: Backlogcounter says %u connections waiting, Accept() says %s - setting counter to zero!"), __FUNCTION__, m_nPendingConnections, GetErrorMessage(nError, 1));
		nFataErrors++;
		}
		if (nFataErrors > 10){
		// the question is what todo on a error. We cant just ignore it because then the backlog will fill up
		// and lock everything. We can also just endlos try to repeat it because this will lock up eMule
		// this should basically never happen anyway
		// however if we are in such a position, try to reinitalize the socket.
		DebugLogError(LOG_STATUSBAR, _T("%hs: Accept() Error Loop, recreating socket"), __FUNCTION__);
		Close();
		StartListening();
		m_nPendingConnections = 0;
		break;
		}
		continue;
		}

		AddConnection();

		if (SockAddr.sin_addr.S_un.S_addr == 0) // for safety..
		{
		iSockAddrLen = sizeof SockAddr;
		newclient->GetPeerName((SOCKADDR*)&SockAddr, &iSockAddrLen);
		DebugLogWarning(_T("SockAddr.sin_addr.S_un.S_addr == 0;  GetPeerName returned %s"), ipstr(SockAddr.sin_addr.S_un.S_addr));
		}

		ASSERT( SockAddr.sin_addr.S_un.S_addr != 0 && SockAddr.sin_addr.S_un.S_addr != INADDR_NONE );

		if (CGlobalVariable::ipfilter->IsFiltered(SockAddr.sin_addr.S_un.S_addr)){
		if (thePrefs.GetLogFilteredIPs())
		AddDebugLogLine(false, _T("Rejecting connection attempt (IP=%s) - IP filter (%s)"), ipstr(SockAddr.sin_addr.S_un.S_addr), CGlobalVariable::ipfilter->GetLastHit());
		newclient->Safe_Delete();
		theStats.filteredclients++;
		continue;
		}

		if (CGlobalVariable::clientlist->IsBannedClient(SockAddr.sin_addr.S_un.S_addr)){
		if (thePrefs.GetLogBannedClients()){
		CUpDownClient* pClient = CGlobalVariable::clientlist->FindClientByIP(SockAddr.sin_addr.S_un.S_addr);
		AddDebugLogLine(false, _T("Rejecting connection attempt of banned client %s %s"), ipstr(SockAddr.sin_addr.S_un.S_addr), pClient->DbgGetClientInfo());
		}
		newclient->Safe_Delete();
		continue;
		}*/
	}
	
	// newclient->AsyncSelect(FD_WRITE | FD_READ | FD_CLOSE);

	return newclient;
	//}

	//ASSERT( m_nPendingConnections >= 0 );
}
Example #29
0
void EmuTCPServer::CreateNewConnection(uint32 ID, SOCKET in_socket, uint32 irIP, uint16 irPort)
{
	EmuTCPConnection *conn = new EmuTCPConnection(ID, this, in_socket, irIP, irPort, pOldFormat);
	AddConnection(conn);
}
Example #30
0
int main( int argc, char *argv[] )
{
    Alignments alignments ;
    Genome genome ;
    std::vector<int> rascafFileId ;

    char line[2048] ;
    char prefix[512] = "rascaf_scaffold" ;
    int rawAssemblyInd = 1 ;
    FILE *rascafFile ;
    bool contigLevel = false ;
    int i ;
    FILE *outputFile ;
    FILE *infoFile ;

    breakN = 1 ;

    if ( argc < 2 )
    {
        fprintf( stderr, "%s", usage ) ;
        exit( 1 ) ;
    }
    for ( i = 1 ; i < argc ; ++i )
    {
        if ( !strcmp( "-o", argv[i] ) )
        {
            strcpy( prefix, argv[i + 1 ] ) ;
            ++i ;
        }
        else if ( !strcmp( "-ms", argv[i] ) )
        {
            minSupport = atoi( argv[i + 1] ) ;
            ++i ;
        }
        else if ( !strcmp( "-ignoreGap", argv[i] ) )
        {
            ignoreGap = true ;
        }
        else if ( !strcmp( "-r", argv[i] ) )
        {
            rascafFileId.push_back( i + 1 ) ;
            ++i ;
        }
        else
        {
            fprintf( stderr, "Unknown option: %s\n", argv[i] ) ;
            exit( EXIT_FAILURE ) ;
        }

    }

    if ( rascafFileId.size() == 0 )
    {
        fprintf( stderr, "Must use -r to specify rascaf output file.\n" ) ;
        exit( EXIT_FAILURE ) ;
    }

    MAX_NEIGHBOR = 1 + rascafFileId.size() ;

    // Get the bam file.
    rascafFile = fopen( argv[ rascafFileId[0] ], "r" ) ;
    while ( fgets( line, sizeof( line ), rascafFile ) != NULL )
    {
        if ( strstr( line, "command line:" ) )
        {
            char *p ;
            char buffer[512] ;

            p = strstr( line, "-breakN" ) ;
            if ( p != NULL )
            {
                p += 7 ;
                while ( *p == ' ' )
                    ++p ;
                for ( i = 0 ; *p && *p != ' ' ; ++p, ++i )
                    buffer[i] = *p ;
                buffer[i] = '\0' ;
                breakN = atoi( buffer ) ;
            }

            p = strstr( line, "-b" ) ;
            if ( p == NULL )
            {
                fprintf( stderr, "Could not find the bam file specified by -b in Rascaf.\n" ) ;
                exit( 1 ) ;
            }
            p += 2 ;
            while ( *p == ' ' )
                ++p ;
            for ( i = 0 ; *p && *p != ' ' ; ++p, ++i )
                buffer[i] = *p ;
            buffer[i] = '\0' ;
            alignments.Open( buffer ) ;

            p = strstr( line, "-f") ;
            if ( p == NULL )
            {
                fprintf( stderr, "Could not find the raw assembly file specified by -f in Rascaf.\n" ) ;
                exit( 1 ) ;
            }
            p += 2 ;
            while ( *p == ' ' )
                ++p ;
            for ( i = 0 ; *p && *p != ' ' && *p != '\n' ; ++p, ++i )
                buffer[i] = *p ;
            buffer[i] = '\0' ;
            fprintf( stderr, "Found raw assembly file: %s\n", buffer ) ;
            genome.Open( alignments, buffer ) ;

            break ;
        }
    }
    fclose( rascafFile ) ;
    // Parse the input.
    for ( unsigned int fid = 0 ; fid < rascafFileId.size() ; ++fid )
    {
        rascafFile = fopen( argv[ rascafFileId[fid] ], "r" ) ;
        bool start = false ;
        int tag ;
        while ( fgets( line, sizeof( line ), rascafFile ) != NULL )
        {
            if ( strstr( line, "command line:" ) )
            {
                start = true ;
                if ( strstr( line, "-f" ) )
                {
                    contigLevel = true ;
                }

                continue ;
            }

            if ( !start )
                continue ;

            if ( !strcmp( line, "WARNINGS:\n" ) )
                break ;

            std::vector<struct _part> nparts  ;
            if ( line[0] >= '0' && line[0] <= '9' )
            {
                AddConnection( line, alignments, nparts ) ;
                connects.push_back( nparts ) ;
                tag = 0 ;
            }
            else if ( line[0] == '\t' || line[0] == ' ' )
            {
                // Break the nparts if the support is too low.
                int num = 0 ;
                for ( i = 0 ; line[i] < '0' || line[i] > '9' ; ++i )
                    ;
                for ( ; line[i] >= '0' && line[i] <= '9' ; ++i )
                    num = num * 10 + line[i] - '0' ;
                ++tag ;
                if ( num < minSupport )
                {
                    nparts = connects.back() ;
                    connects.pop_back() ;
                    int size = nparts.size() ;

                    std::vector<struct _part> newNParts ;
                    for ( i = 0 ; i < tag ; ++i )
                        newNParts.push_back( nparts[i] ) ;
                    if ( newNParts.size() > 1 )
                        connects.push_back( newNParts ) ;

                    newNParts.clear() ;
                    for ( ; i < size ; ++i  )
                        newNParts.push_back( nparts[i] ) ;
                    if ( newNParts.size() > 1 )
                        connects.push_back( newNParts ) ;

                    tag = 0 ;
                }
            }
        }
        fclose( rascafFile ) ;
    }
    if ( contigLevel == false )
    {
        genome.SetIsOpen( contigLevel ) ;
    }

    // Build the graph
    int contigCnt = genome.GetContigCount() ;
    int edgeCnt = 0 ;
    int csize = connects.size() ;

    for ( i = 0 ; i < csize ; ++i )
        edgeCnt += connects[i].size() ;

    ContigGraph contigGraph( contigCnt, contigCnt + edgeCnt ) ;
    for ( i = 0 ; i < contigCnt - 1 ; ++i )
    {
        if ( genome.GetChrIdFromContigId( i ) == genome.GetChrIdFromContigId( i + 1 ) )
        {
            contigGraph.AddEdge( i, 1, i + 1, 0 ) ;
        }
    }
    for ( i = 0 ; i < csize ; ++i )
    {
        std::vector<struct _part> &parts = connects[i] ;
        int size = parts.size() ;
        for ( int j = 0 ; j < size - 1 ; ++j )
        {
            struct _part &a = parts[j] ;
            struct _part &b = parts[j + 1] ;

            // Two dummy nodes for each contig. Left is 0, right is 1
            int dummyU = 0 ;
            int dummyV = 0 ;
            if ( a.strand == '+' )
                dummyU = 1 ;
            if ( b.strand == '-' )
                dummyV = 1 ;
            contigGraph.AddEdge( a.contigId, dummyU, b.contigId, dummyV, true ) ;
        }
    }

    // Check the cycles in the contig graph. This may introduces when combining different rascaf outputs.
    int *visitTime = new int[contigCnt] ;
    struct _pair *neighbors = new struct _pair[ MAX_NEIGHBOR ] ;

    bool *isInCycle = new bool[contigCnt] ;
    std::vector<int> cycleNodes ;
    memset( visitTime, -1, sizeof( int ) * contigCnt ) ;
    memset( isInCycle, false, sizeof( bool ) * contigCnt ) ;
    for ( i = 0 ; i < contigCnt ; ++i )
    {
        if ( isInCycle[i] )
            continue ;
        if ( contigGraph.IsInCycle( i, cycleNodes, visitTime ) )
        {
            int cnt = cycleNodes.size() ;
            //printf( "===\n") ;
            for ( int j = 0 ; j < cnt ; ++j )
            {
                //printf( "In cycle %d\n", cycleNodes[j] ) ;
                isInCycle[ cycleNodes[j] ] = true ;
            }
        }
    }
    //exit( 1 ) ;
    // Remove the connected edges involving the nodes in the cycle
    for ( i = 0 ; i < contigCnt ; ++i )
    {
        if ( isInCycle[i] )
        {
            for ( int dummy = 0 ; dummy <= 1 ; ++dummy )
            {
                int ncnt = contigGraph.GetNeighbors( i, dummy, neighbors, MAX_NEIGHBOR ) ;
                for ( int j = 0 ; j < ncnt ; ++j )
                {
                    if ( neighbors[j].a == i + 2 * dummy - 1 && neighbors[j].b != dummy
                            && genome.GetChrIdFromContigId( i ) == genome.GetChrIdFromContigId( neighbors[j].a ) )
                        continue ; // the connection created by the raw assembly
                    else
                        contigGraph.RemoveEdge( i, dummy, neighbors[j].a, neighbors[j].b ) ;
                }
            }
        }
    }
    //delete[] isInCycle ;
    //printf( "hi: %d %d\n", __LINE__, contigCnt ) ;
    //printf( "%d %d\n", contigGraph.GetNeighbors( 0, 0, neighbors, MAX_NEIGHBOR ), contigGraph.GetNeighbors( 0, 1, neighbors, MAX_NEIGHBOR ) ) ;
    // Sort the scaffolds from fasta file, so that longer scaffold come first
    int scafCnt = genome.GetChrCount() ;
    struct _pair *scafInfo = new struct _pair[scafCnt] ;
    memset( scafInfo, -1, sizeof( struct _pair) * scafCnt ) ;
    for ( i = 0 ; i < contigCnt ; ++i )
    {
        int chrId = genome.GetChrIdFromContigId( i ) ;
        if ( scafInfo[chrId].a == -1 )
        {
            scafInfo[ chrId ].a = i ;
            scafInfo[ chrId ].b = genome.GetChrLength( chrId ) ;
        }
    }
    qsort( scafInfo, scafCnt, sizeof( struct _pair ), CompScaffold ) ;

    // Merge the branches and build the scaffold
    ContigGraph scaffold( contigCnt, 2 * contigCnt ) ;

    // Use a method similar to topological sort
    bool *used = new bool[contigCnt] ;
    int *degree = new int[2 *contigCnt] ;
    int *danglingVisitTime = new int[contigCnt] ;
    int *counter = new int[contigCnt] ;
    int *visitDummy = new int[ contigCnt ] ;
    int *buffer = new int[contigCnt] ;
    int *buffer2 = new int[contigCnt] ;
    bool *isInQueue = new bool[ contigCnt ] ;
    int *chosen = new int[contigCnt] ;
    int chosenCnt ;

    memset( isInCycle, false, sizeof( bool ) * contigCnt ) ;
    memset( visitTime, -1, sizeof( int ) * contigCnt ) ;
    memset( visitDummy, -1, sizeof( int ) * contigCnt ) ;
    memset( counter, -1, sizeof( int ) * contigCnt ) ;

    // Use those memory to remove triangular cycles
    for ( i = 0 ; i < scafCnt ; ++i )
    {
        int from, to ;
        if ( scafInfo[i].a == -1 )
            continue ;
        genome.GetChrContigRange( genome.GetChrIdFromContigId( scafInfo[i].a ), from, to ) ;
        ForwardSearch( from, 0, i, visitTime, counter, visitDummy, contigGraph ) ;
        chosenCnt = 0 ;
        BackwardSearchForTriangularCycle( to, 1, i, visitTime, counter, visitDummy, contigGraph, chosen, chosenCnt ) ;

        for ( int j = 0 ; j < chosenCnt ; ++j )
        {
            //printf( "%d\n", chosen[j] ) ;
            isInCycle[ chosen[j] ] = true ;
        }
    }

    for ( i = 0 ; i < contigCnt ; ++i )
    {
        if ( isInCycle[i] )
        {
            for ( int dummy = 0 ; dummy <= 1 ; ++dummy )
            {
                int ncnt = contigGraph.GetNeighbors( i, dummy, neighbors, MAX_NEIGHBOR ) ;
                for ( int j = 0 ; j < ncnt ; ++j )
                {
                    if ( neighbors[j].a == i + 2 * dummy - 1 && neighbors[j].b != dummy
                            && genome.GetChrIdFromContigId( i ) == genome.GetChrIdFromContigId( neighbors[j].a ) )
                        continue ; // the connection created by the raw assembly
                    else
                        contigGraph.RemoveEdge( i, dummy, neighbors[j].a, neighbors[j].b ) ;
                }
            }
        }
    }


    memset( used, false, sizeof( bool ) * contigCnt ) ;
    memset( visitTime, -1, sizeof( int ) * contigCnt ) ;
    memset( visitDummy, -1, sizeof( int ) * contigCnt ) ;
    memset( danglingVisitTime, -1, sizeof( int ) * contigCnt ) ;
    memset( counter, -1, sizeof( int ) * contigCnt ) ;
    memset( isInQueue, false, sizeof( bool ) * contigCnt ) ;
    ContigGraph newGraph( contigCnt, edgeCnt ) ;

    // Compute the gap size
    int *gapSize = new int[contigCnt] ;
    for ( i = 0 ; i < contigCnt - 1 ; ++i )
    {
        if ( genome.GetChrIdFromContigId( i ) == genome.GetChrIdFromContigId( i + 1 ) )
        {
            struct _contig c1 = genome.GetContigInfo( i ) ;
            struct _contig c2 = genome.GetContigInfo( i + 1 ) ;
            gapSize[i] = c2.start - c1.end - 1 ;
        }
        else
            gapSize[i] = -1 ;
    }

    // Start search
    int ncnt ;
    struct _pair *queue = new struct _pair[ contigCnt ] ;
    int head = 0, tail ;
    int danglingTime = 0 ;

    // Pre-allocate the subgraph.
    ContigGraph subgraph( contigCnt, 3 * contigCnt ) ;
    for ( i = 0 ; i < scafCnt ; ++i )
    {
        //if ( used[144281] == true )
        //	printf( "changed %d %d\n", i, scafInfo[i - 1].a ) ;
        if ( scafInfo[i].a == -1 )
            continue ;
        int from, to ;
        genome.GetChrContigRange( genome.GetChrIdFromContigId( scafInfo[i].a ), from, to ) ;
        //printf( "%d: %d %d %d\n", i, scafInfo[i].b, from, to ) ;
        ForwardSearch( from, 0, i, visitTime, counter, visitDummy, contigGraph ) ;
        chosenCnt = 0 ;
        BackwardSearch( to, 1, i, visitTime, counter, contigGraph, chosen, chosenCnt ) ;

        /*printf( "%s %d (%d %d) %d\n", alignments.GetChromName( genome.GetChrIdFromContigId( scafInfo[i].a ) ), i, from, to, chosenCnt ) ;
        if ( chosenCnt > 1 )
        {
        	printf( "=== " ) ;
        	for ( int j = 0 ; j < chosenCnt ; ++j )
        		printf( "%d ", chosen[j] ) ;
        	printf( "\n" ) ;
        }*/

        for ( int j = 0 ; j < chosenCnt ; ++j )
        {
            ncnt = contigGraph.GetNeighbors( chosen[j], 0, neighbors, MAX_NEIGHBOR ) ;
            //printf( "%d %d %d: %d %d %d\n", j, chosen[j], ncnt, neighbors[0].a, visitTime[ neighbors[0].a ],
            //	counter[neighbors[0].a ] ) ;
            for ( int k = 0 ; k < ncnt ; ++k )
            {
                //if ( i == 639 )
                //	printf( "Neighbor from 0 %d: %d %d\n", k, neighbors[k].a, neighbors[k].b ) ;
                if ( visitTime[ neighbors[k].a ] == 2 * i + 1 && counter[neighbors[k].a ] == 2 )
                {
                    subgraph.AddEdge( chosen[j], 0, neighbors[k].a, neighbors[k].b, true ) ;
                    //printf( "subgraph: (%d %d)=>(%d %d)\n", chosen[j], 0, neighbors[k].a, neighbors[k].b ) ;
                }
            }

            ncnt = contigGraph.GetNeighbors( chosen[j], 1, neighbors, MAX_NEIGHBOR ) ;
            for ( int k = 0 ; k < ncnt ; ++k )
            {
                //if ( i == 639 )
                //	printf( "Neighbor from 1 %d: %d %d\n", k, neighbors[k].a, neighbors[k].b ) ;
                if ( visitTime[ neighbors[k].a ] == 2 * i + 1 && counter[neighbors[k].a ] == 2 )
                {
                    subgraph.AddEdge( chosen[j], 1, neighbors[k].a, neighbors[k].b, true ) ;
                    //printf( "subgraph: (%d %d)=>(%d %d)\n", chosen[j], 1, neighbors[k].a, neighbors[k].b ) ;
                }
            }
        }

        // Initialize the degree counter
        for ( int j = 0 ; j < chosenCnt ; ++j )
        {
            for ( int l = 0 ; l < 2 ; ++l )
            {
                /*if ( i == 6145 )
                {
                	std::vector<struct _pair> neighbors ;
                	ncnt = subgraph.GetNeighbors( chosen[j], l, neighbors ) ;
                	printf( "%d ncnt=%d\n", l, ncnt ) ;
                }*/

                ncnt = subgraph.GetNeighbors( chosen[j], l, neighbors, MAX_NEIGHBOR ) ;
                degree[ 2 * chosen[j] + l ] = ncnt ;
            }
        }

        // "topological" sort
        head = 0 ;
        isInQueue[from] = true ;
        queue[0].a = from ;
        queue[0].b = 0 ;
        tail = 1 ;
        int prevTag = -1 ;
        int *prevAdd = buffer ; // reuse counter to save some memory.
        int *nextAdd = buffer2 ;
        int firstAdd = -1 ;

        while ( head < tail )
        {
            int tailTag = tail ;
            for ( int j = head ; j < tailTag ; ++j )
            {
                nextAdd[j] = -1 ;
                if ( !used[ queue[j].a ] )
                {
                    used[ queue[j].a ] = true ;
                    if ( prevTag != -1 )
                    {
                        scaffold.AddEdge( queue[ prevTag].a, 1 - queue[prevTag].b, queue[j].a, queue[j].b ) ;
                        nextAdd[ prevTag ] = j ;

                        /*if ( i == 639 )
                        	printf( "(%lld %lld)=>(%lld %lld)\n", queue[ prevTag].a, 1 - queue[prevTag].b, queue[j].a, queue[j].b ) ;*/
                    }
                    else
                        firstAdd = j ;

                    prevTag = j ;
                }
                prevAdd[j] = prevTag ; // the most recent(<=) queue id when added to scaffold.

                ncnt = subgraph.GetNeighbors( queue[j].a, 1 - queue[j].b, neighbors, MAX_NEIGHBOR ) ;
                for ( int k = 0 ; k < ncnt ; ++k )
                {
                    --degree[ 2 * neighbors[k].a + neighbors[k].b ] ;
                    if ( degree[ 2 * neighbors[k].a + neighbors[k].b ] == 0 && !isInQueue[neighbors[k].a] )
                    {
                        isInQueue[ neighbors[k].a ] = true ;
                        queue[ tail ] = neighbors[k] ; // Interesting assignment, I think.
                        ++tail ;
                        /*if ( i == 639 )
                        	printf( "pushed in queue: %d\n", neighbors[k].a ) ;*/
                        // Put the consecutive contigs together.
                        struct _pair testNeighbors[ MAX_NEIGHBOR ] ;
                        struct _pair tag ;
                        tag = neighbors[k] ;
                        while ( 1 )
                        {
                            if ( contigGraph.GetNeighbors( tag.a, 1 - tag.b, testNeighbors, MAX_NEIGHBOR ) != 1 )
                                break ;
                            int n = subgraph.GetNeighbors( tag.a, 1 - tag.b, testNeighbors, MAX_NEIGHBOR ) ;
                            if ( n != 1 )
                                break ;
                            //printf( "%d %d\n", n, testNeighbors[0].a ) ;

                            struct _pair backNeighbors[ MAX_NEIGHBOR ] ;
                            if ( contigGraph.GetNeighbors( testNeighbors[0].a, testNeighbors[0].b, backNeighbors, MAX_NEIGHBOR ) != 1 )
                                break ;
                            n = subgraph.GetNeighbors( testNeighbors[0].a, testNeighbors[0].b, backNeighbors, MAX_NEIGHBOR ) ;
                            if ( n != 1 )
                                break ;
                            isInQueue[ testNeighbors[0].a ] = true ;
                            queue[tail] = testNeighbors[0] ;
                            ++tail ;
                            /*if ( i == 639 )
                            	printf( "pushed in queue: %d\n", testNeighbors[0].a ) ;*/
                            tag = testNeighbors[0] ;
                        }
                    }
                }
            }

            head = tailTag ;
        }
        // Remove the effect on the subgraph.
        /*if ( tail != chosenCnt )
        {
        	printf( "WARNING: not matched\n" ) ;
        	exit( 1 ) ;
        }*/
        for ( int j = 0 ; j < tail ; ++j )
        {
            visitDummy[ queue[j].a ] = -1 ;
            counter[ queue[j].a ] = -1 ;
            subgraph.RemoveAdjacentEdges( queue[j].a ) ;
            isInQueue[ queue[j].a ] = false ;
        }
        subgraph.ResetEdgeUsed() ;

        // no point is picked
        if ( prevTag == -1 )
        {
            continue ;
        }

        // Update the gap size
        prevTag = -1 ;
        for ( int j = 0 ; j < tail - 1 ; ++j )
        {
            if ( genome.GetChrIdFromContigId( queue[j].a ) == genome.GetChrIdFromContigId( from ) )
                prevTag = queue[j].a ;
            else if ( prevTag != -1 )
            {
                struct _contig c = genome.GetContigInfo( queue[j].a ) ;
                gapSize[prevTag] -= ( c.end - c.start + 1) ;
            }
        }
        // Add the dangling contigs. Use the fact that the queue holding the contigs in the same order as in the scaffold.
        // 5'->3' dangling
        int *chosenDummy = degree ;
        for ( int j = tail - 1 ; j >= 0 ; --j )
        {
            //if ( j < tail - 1 )
            //	continue ;
            chosenCnt = 0 ;
            //if ( queue[j].a == 0 )
            //	printf( "Dummy: %d %d %d\n", j, queue[j].b, 1 - queue[j].b ) ;
            SearchDangling( queue[j].a, queue[j].b, used, danglingTime, danglingVisitTime, contigGraph, false, chosen, chosenDummy, chosenCnt, genome ) ;
            ++danglingTime ;
            int prevTag = prevAdd[j] ;
            /*if ( queue[j].a == 0 )
            {
            	struct _pair neighbors[5] ;
            	int ncnt = contigGraph.GetNeighbors( queue[j].a, 1 - queue[j].b, neighbors, 5 ) ;
            	printf( "%d %d %d %d: %d %d\n", queue[j].b, chosenCnt, prevTag, ncnt, neighbors[0].a, used[ neighbors[0].a ] ) ;
            }*/
            if ( prevTag == -1 )
                break ;

            // Trim the dangling list
            int k = chosenCnt - 1 ;
            if ( j > 0 && j < tail - 1 )
            {
                for ( k = chosenCnt - 1 ; k >= 1 ; --k )
                    if ( genome.GetChrIdFromContigId( chosen[k] ) != genome.GetChrIdFromContigId( chosen[k - 1] ) )
                        break ;
            }

            // Test the gap size
            int len = 0 ;
            for ( int l = 0 ; l <= k ; ++l )
            {
                struct _contig c = genome.GetContigInfo( chosen[k] ) ;
                len += c.end - c.start + 1 ;
            }

            if ( j < tail - 1 )
            {
                int l ;
                for ( l = j ; l >= 0 ; --l )
                    if ( genome.GetChrIdFromContigId( queue[l].a ) == genome.GetChrIdFromContigId( from ) )
                        break ;

                if ( !ignoreGap && len >= gapSize[ queue[l].a ] + 100 )
                    continue ;
                else
                    gapSize[ queue[l].a ] -= len ;
            }


            for ( ; k >= 0 ; --k )
            {
                used[ chosen[k] ] = true ;
                //printf( "Dangling 1: %d=>%d\n", queue[prevTag].a, chosen[k] ) ;
                scaffold.InsertNode( queue[ prevTag ].a, 1 - queue[ prevTag ].b, chosen[k], chosenDummy[k] ) ;
            }
        }

        // 3'->5' dangling
        for ( int j = 0 ; j < tail ; ++j )
        {
            //if ( j > 0 )
            //	continue ;
            chosenCnt = 0 ;
            SearchDangling( queue[j].a, 1 - queue[j].b, used, danglingTime, danglingVisitTime, contigGraph, false, chosen, chosenDummy, chosenCnt, genome ) ;
            ++danglingTime ;

            int prevTag = prevAdd[j] ;
            int nextTag ;
            if ( prevTag == -1 || j <= firstAdd )
                nextTag = firstAdd ;
            else if ( j == prevTag )
                nextTag = j ;
            else
                nextTag = nextAdd[ prevTag ] ;
            if ( nextTag == -1 )
                break ;
            /*if ( queue[j].a == 37549 )
            {
            	struct _pair neighbors[5] ;
            	int ncnt = contigGraph.GetNeighbors( queue[j].a, queue[j].b, neighbors, 5 ) ;
            	fprintf( stderr, "%d %d %d: %d %d %d: %d %d %d\n", j, queue[j].a, queue[j].b, chosenCnt, nextTag, ncnt, chosen[0], chosenDummy[0], used[ chosen[0] ] ) ;
            }*/

            // trim the danling list
            int k = chosenCnt - 1 ;
            if ( j < tail - 1 && j > 0 )
            {
                for ( k = chosenCnt - 1 ; k >= 1 ; --k )
                    if ( genome.GetChrIdFromContigId( chosen[k] ) != genome.GetChrIdFromContigId( chosen[k - 1] ) )
                        break ;
            }

            // Test the gap size
            int len = 0 ;
            for ( int l = 0 ; l <= k ; ++l )
            {
                struct _contig c = genome.GetContigInfo( chosen[k] ) ;
                len += c.end - c.start + 1 ;
            }

            if ( j > 0 )
            {
                int l ;
                for ( l = j - 1 ; l >= 0 ; --l ) // Notice the j-1 here, because we want the gap strictly before current contig
                    if ( genome.GetChrIdFromContigId( queue[l].a ) == genome.GetChrIdFromContigId( from ) )
                        break ;

                if ( !ignoreGap && len >= gapSize[ queue[l].a ] + 100 )
                    continue ;
                else
                    gapSize[ queue[l].a ] -= len ;
            }

            for ( ; k >= 0 ; --k )
            {
                used[ chosen[k] ] = true ;
                scaffold.InsertNode( queue[nextTag].a, queue[nextTag].b, chosen[k], chosenDummy[k] ) ;
                //printf( "Dangling 2: %d<=%d\n", queue[nextTag].a, chosen[k] ) ;
                //if ( chosen[k] == 10246 )
                //	printf( "hi %d %d %d %d\n", j, queue[j].a, k, chosen[k] ) ;
            }
        }
    }
    //return 0 ;

    // Output the scaffold
    int id = 0 ;
    char infoFileName[512] ;
    char outputFileName[512] ;
    sprintf( infoFileName, "%s.info", prefix ) ;
    sprintf( outputFileName, "%s.fa", prefix ) ;

    outputFile = fopen( outputFileName, "w" ) ;
    infoFile = fopen( infoFileName, "w") ;

    memset( used, false, sizeof( bool ) * contigCnt ) ;
    for ( i = 0 ; i < contigCnt ; ++i )
    {
        //printf( "%d (%s)\n", i, alignments.GetChromName( genome.GetChrIdFromContigId( i ) )  ) ; fflush( stdout ) ;
        /*if ( i == 10246 )
        {
        	std::vector<struct _pair> neighbors ;
        	scaffold.GetNeighbors( i, 0, neighbors ) ;
        	printf( "%u\n", neighbors.size() ) ;
        }*/
        if ( used[i] )
            continue ;
        int ncnt1 = scaffold.GetNeighbors( i, 0, neighbors, MAX_NEIGHBOR ) ;
        int ncnt2 = scaffold.GetNeighbors( i, 1, neighbors, MAX_NEIGHBOR ) ;
        if ( ncnt1 == 0 || ncnt2 == 0 ) // The end of a scaffold
        {
            fprintf( outputFile, ">scaffold_%d\n", id) ;
            fprintf( infoFile, ">scaffold_%d", id ) ;
            ++id ;
            int p = i ;
            int dummyP = 1 ;
            if ( ncnt1 == 0 )
                dummyP = 0 ;

            used[i] = true ;
            genome.PrintContig( outputFile, i, dummyP ) ;
            fprintf( infoFile, " (%s %d %c)", alignments.GetChromName( genome.GetChrIdFromContigId( p ) ), p, dummyP == 0 ? '+' : '-' ) ;
            while ( 1 )
            {
                ncnt = scaffold.GetNeighbors( p, 1 - dummyP, neighbors, MAX_NEIGHBOR ) ;
                if ( ncnt == 0 )
                    break ;
                // ncnt must be 1
                int insertN = 17 ;

                if ( genome.GetChrIdFromContigId( p ) == genome.GetChrIdFromContigId( neighbors[0].a ) )
                {
                    struct _contig cp, cna ;
                    cp = genome.GetContigInfo( p ) ;
                    cna = genome.GetContigInfo( neighbors[0].a ) ;
                    if ( p < neighbors[0].a )
                        insertN = cna.start - cp.end - 1 ;
                    else if ( p > neighbors[0].a )
                        insertN = cp.start - cna.end - 1 ;

                }

                p = neighbors[0].a ;
                dummyP = neighbors[0].b ;
                for ( int j = 0 ; j < insertN ; ++j )
                    fprintf( outputFile, "N" ) ;
                used[p] = true ;
                genome.PrintContig( outputFile, p, dummyP ) ;

                fprintf( infoFile, " (%s %d %c)", alignments.GetChromName( genome.GetChrIdFromContigId( p ) ), p, dummyP == 0 ? '+' : '-' ) ;
            }
            fprintf( outputFile, "\n" ) ;
            fprintf( infoFile, "\n" ) ;
        }
    }

    for ( i = 0 ; i < contigCnt ; ++i )
        if ( !used[i] )
        {
            fprintf( stderr, "Unreported contig %d.\n", i ) ;
        }
    fclose( outputFile ) ;
    fclose( infoFile ) ;

    delete[] buffer ;
    delete[] buffer2 ;
    delete[] chosen ;
    delete[] queue ;
    delete[] counter ;
    delete[] visitTime ;
    delete[] used ;
    delete[] scafInfo ;
    delete[] isInQueue ;
    delete[] gapSize ;

    //fclose( rascafFile ) ;
    return 0 ;
}