Example #1
0
Genesis::Genesis(QObject *parent)
    : QLocalServer(parent), _blockSize(0)
{
    if (!listen(QLatin1String("sform"))) {
        qDebug() << "Unable to start the sform genesis:"
                 << errorString();
        exit(1);
    }

    signal(SIGINT,  crashHandler);    /* 2:   interrupt */
    signal(SIGILL,  crashHandler);    /* 4:   illegal instruction (not reset when caught) */
    signal(SIGTRAP, crashHandler);    /* 5:   trace trap (not reset when caught) */
    signal(SIGFPE,  crashHandler);    /* 8:   floating point exception */
    signal(SIGKILL, crashHandler);    /* 9:   kill */
    signal(SIGBUS,  crashHandler);    /* 10:  bus error */
    signal(SIGSEGV, crashHandler);    /* 11:  segmentation violation */
    signal(SIGSYS,  crashHandler);    /* 12:  bad argument to system call */
    signal(SIGPIPE, crashHandler);    /* 13:  write on a pipe with no reader */
    signal(SIGTERM, crashHandler);    /* 15:  terminate */
    signal(SIGXCPU, crashHandler);    /* 24:  exceeded CPU time limit */
    signal(SIGXFSZ, crashHandler);    /* 25:  exceeded file size limit */

    connect(this, SIGNAL(newConnection()),
            this, SLOT(establishConnection()));

    _stdinNotifier = new QSocketNotifier(0, QSocketNotifier::Read, this);
    connect(_stdinNotifier, SIGNAL(activated(int)),
            this, SLOT(readStdin(int)));

    compileSeed();
}
Example #2
0
bool NameResolution::waitForData(ims::name::NameResolutionSourceType sourceType) {
	// prepare the command
	cmdLen = 3;
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = -3; // function, waitForData
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	
	do {
		if (socket_read(conn_fd, buf, 1, sockTimeout) != 1) {
			// error
			return false;
		}
	} while (buf[0] == 0);

	return true;
}
Example #3
0
int sendToBackup(int *portGlobal, pthread_mutex_t *mut, char request[MAX_REQUEST_SIZE]){
	//message is sent from primary to a backup, and acknowledged by the backup
	int otherPort;
	struct sockaddr_in other;
	otherPort = (*portGlobal);
	//printf("What port? %i\n", otherPort);
	if(otherPort != -1){
		//If port is alive (could be invalidated if dead) then get sockets
		int sock = createSockets(&other, otherPort);
		int conn = establishConnection(sock, &other);
		if(conn == -1){
			//puts("establishConnection failed");
			pthread_mutex_lock(mut);
			(*portGlobal) = -1;
			pthread_mutex_unlock(mut);
			return -1;
			//Server is dead
		}
		else{
			//Send request to backup server
			//printf("Sock before send %i\n", sock);
			if(send(sock, request, MAX_REQUEST_SIZE, 0) == -1){
				puts("send failed");
				pthread_mutex_lock(mut);
				(*portGlobal) = -1;
				pthread_mutex_unlock(mut);
				return -1;
			}
			return sock;
		}
	}
	return -1;
}
Example #4
0
// receive and process agent/server notifications
DWORD rxClientThread(LPVOID arg) {  
   char buffer[1024], msg[2048], * delim;
   int nBytes;
   struct socketDescriptor * sd = (struct socketDescriptor *) arg;
   SOCKET socket=sd->socket;
   msg[0]='\0';
   
   addSocketDescriptorToClientList(sd);
   
   while(!sd->exit) {
      if (!sd->connected) {
         if (establishConnection(sd))
            socket=sd->socket;
         else 
            Sleep(10000);
      } else {  
      
         nBytes=recv(sd->socket, buffer, sizeof(buffer-1), 0);
         
         if (nBytes==0) {
            // graceful close
            shutdownConnection(sd);
         }   
         else if(nBytes==SOCKET_ERROR) {
            // forceful close
            if (WSAGetLastError()!=WSAECONNABORTED) {
               // an aborted connection error is normal on a half closed connection
               printErrorMsg("rxClientThread");
            }   
            shutdownConnection(sd);
         } 
         else {
            // concatenate packets into a single carriage return terminated message
            // or process multiple carriage return terminated messages individually

            if (strlen(msg) + nBytes > sizeof(msg)) {
               // prevent an overrun
               msg[0]='\0';
            }

            buffer[nBytes]='\0';
            strcat(msg, buffer);

            while (delim=strstr(msg, "\r")) {
               *delim='\0';
               processServerMsg(msg, sd);
               strcpy(msg, delim+1);
            }   
         }
      }
   }
   
   CloseHandle(sd->hThread);
   sd->hThread=NULL;
   printq("rxClientThread exit host %s socket %d\n", sd->host, socket);
   ExitThread(0);
   
}
Example #5
0
//==============================================================================
// Drag and Drop
void QEPeriodic::setDrop( QVariant drop )
{
    QStringList PVs = drop.toString().split( ' ' );
    for( int i = 0; i < PVs.size() && i < QEPERIODIC_NUM_VARIABLES; i++ )
    {
        setVariableName( PVs[i], i );
        establishConnection( i );
    }
}
Example #6
0
CanServer::CanServer(QObject *parent) : QObject(parent)
{
    mServer = std::make_shared<QLocalServer>(nullptr);
    mServer->setMaxPendingConnections(1);

    QLocalServer::removeServer("can-messenger");
    qDebug() << mServer->listen("can-messenger");

    connect(mServer.get(), SIGNAL(newConnection()), this, SLOT(establishConnection()));
    connect(this, SIGNAL(received(QVariant)), this, SLOT(receive(QVariant)));
}
Example #7
0
int init_wifi(int bot_port,char* bot_address)
{
	int bot_sockfd = establishConnection(bot_address,bot_port);
	char *bot_buffer = (char *)malloc(BUFFER_SIZE*sizeof(char));
		  
	/* Initialization per bot */     
	do	
	{
		tcpRead(bot_sockfd,bot_buffer);
		printf("got: %s \n",bot_buffer); 
	}while(bot_buffer[0]!='M');
	printf("Bot ready\n");

	return bot_sockfd;
}
Example #8
0
bool NameResolution::getMappings(ims::name::NameIPMap &mappings, ims::name::NameResolutionSourceType sourceType) {
	// prepare the command
	cmdLen = 3;
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = 4; // function, getMappings
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}
	
	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	// at this point, all is well, and command has been issued
	// read back the # of mappings
	uint32_t count32;
	if (socket_read(conn_fd, (char *) &count32, sizeof(uint32_t), sockTimeout) != sizeof(uint32_t)) {
		// error
		return false;
	}
	count32 = ntohl(count32);
	// FIXME fill a buffer instead of reading one at a time
	for (uint32_t i = 0; i < count32; ++i) {
		if (socket_read(conn_fd, (char *) &nameLen, 1, sockTimeout) != 1) {
			return false;
		}
		if (socket_read(conn_fd, buf, nameLen, sockTimeout) != nameLen) {
			return false;
		}
		tmpName.assign(buf, nameLen);
		if (socket_read(conn_fd, (char *) &ip, sizeof(uint32_t), sockTimeout) != sizeof(uint32_t)) {
			return false;
		}
		mappings.insert(std::make_pair(tmpName, ntohl(ip)));
	}
	return true;
}
Example #9
0
bool NameResolution::getIPsFromName(ims::name::IPSet &ips, const std::string &name, ims::name::NameResolutionSourceType sourceType) {
	if (name.length() > 0xff) {
		// error...
		return false;
	}

	// prepare the command
	cmdLen = name.length() + 4;
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = 0; // function, getIPsFromName
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}
	buf[5] = (unsigned char) name.length();
	memcpy(buf + 6, name.c_str(), name.length());

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	// at this point, all is well, and command has been issued
	// read back the # of ips
	if (socket_read(conn_fd, (char *) &cmdLen, sizeof(uint16_t), sockTimeout) != sizeof(uint16_t)) {
		// error
		return false;
	}
	cmdLen = ntohs(cmdLen);
	// FIXME fill a buffer instead of reading one at a time
	for (uint16_t i = 0; i < cmdLen; ++i) {
		if (socket_read(conn_fd, (char *) &ip, sizeof(uint32_t), sockTimeout) != sizeof(uint32_t)) {
			return false;
		}
		ips.insert(ntohl(ip));
	}
	return true;
}
Example #10
0
bool NameResolution::getNamesFromIP(ims::name::NameSet &names, const uint32_t &ip, ims::name::NameResolutionSourceType sourceType) {
	// prepare the command
	cmdLen = 7;
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = 1; // function, getNamesFromIP
	this -> ip = htonl(ip);
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}
	memcpy(buf + 5, &(this -> ip), sizeof(uint32_t)); // arg (ip)

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	// at this point, all is well, and command has been issued
	// read back the # of names
	if (socket_read(conn_fd, (char *) &cmdLen, sizeof(uint16_t), sockTimeout) != sizeof(uint16_t)) {
		// error
		return false;
	}
	cmdLen = ntohs(cmdLen);
	// FIXME fill a buffer instead of reading one at a time
	for (uint16_t i = 0; i < cmdLen; ++i) {
		if (socket_read(conn_fd, (char *) &nameLen, 1, sockTimeout) != 1) {
			return false;
		}
		if (socket_read(conn_fd, buf, nameLen, sockTimeout) != nameLen) {
			return false;
		}
		tmpName.assign(buf, nameLen);
		names.insert(tmpName);
	}
	return true;
}
Example #11
0
GlobalScoresWindow::GlobalScoresWindow(QWidget *parent)
    : QDialog(parent){
    // Creates the 3 buttons that will be used in the dialog window
    searchButton = new QPushButton(tr("Search"));
    stopButton = new QPushButton(tr("Stop"));
    quitButton = new QPushButton(tr("Quit"));
    stopButton->setEnabled(false);

    connect(searchButton, SIGNAL(clicked()), this, SLOT(establishConnection()));
    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));

    // Sets up a table widget for the global scoreboard
    table = new QTableWidget(this);
    table->setColumnCount(3);
    tableHeader << "Rank" << "Name" << "Score";
    table->setHorizontalHeaderLabels(tableHeader);
    table->verticalHeader()->setVisible(false);
    table->setFixedHeight(342);

    // Creates the layout for the Global Scores window
    QVBoxLayout *buttonLayout = new QVBoxLayout;
    buttonLayout->addSpacing(6);
    buttonLayout->addWidget(searchButton);
    buttonLayout->addWidget(stopButton);
    buttonLayout->addWidget(quitButton);
    buttonLayout->addSpacing(250);

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addSpacing(20);
    mainLayout->addWidget(table, 0, Qt::AlignVCenter);
    mainLayout->addSpacing(6);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addSpacing(20);
    setLayout(mainLayout);

    connect(&tcpSocket, SIGNAL(connected()), this, SLOT(sendRequest()));
    connect(&tcpSocket, SIGNAL(readyRead()), this, SLOT(updateScoreTable()));
    connect(&tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(connectionError()));

    // Sets the title and size of the window
    setWindowTitle("Global High Scores");
    setFixedSize(450, 400);
}
Example #12
0
bool NameResolution::getLastResolutionTime(TimeStamp &ret, const uint32_t &host, const uint32_t &resolvedIP, const TimeStamp &t, ims::name::NameResolutionSourceType sourceType) {
	// prepare the command
	cmdLen = 19; //
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = 7; // function, getLastResolutionTime
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}
	this -> ip = htonl(host);
	memcpy(buf + 5, &(this -> ip), sizeof(uint32_t)); // arg (host)
	this -> ip = htonl(resolvedIP);
	memcpy(buf + 9, &(this -> ip), sizeof(uint32_t)); // arg (resolvedIP)
	this -> ip = htonl(t.seconds());
	memcpy(buf + 13, &(this -> ip), sizeof(uint32_t)); // arg (seconds)
	this -> ip = htonl(t.microseconds());
	memcpy(buf + 17, &(this -> ip), sizeof(uint32_t)); // arg (microseconds)

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	// at this point, all is well, and command has been issued
	// read back the answer
	if (socket_read(conn_fd, (char *) &ret, sizeof(ret), sockTimeout) != sizeof(ret)) {
		// error
		return false;
	}
	ret.set(ntohl(ret.seconds()), ntohl(ret.microseconds()));

	return true;
}
Example #13
0
/*!
  Start listening for incoming connections for the game.
*/
void TicTacServer::startServer()
{
    qDebug() << "TicTacServer::startServer()";

    if (mTcpServer && mTcpServer->isListening()) {
        qDebug() << "TicTacServer::startServer(): Will stop server.";
        stopServer();
    }

    if (mConnectionManager->state() == ConnectionManager::Connected) {
        // Server for listening to incoming game clients.
        mTcpServer = new QTcpServer(this);

        if (!mTcpServer->isListening()) {
            if (mTcpServer->listen(QHostAddress::Any, SERVER_PORT)) {
                connect(mTcpServer, SIGNAL(newConnection()),
                        this, SLOT(establishConnection()),
                        Qt::UniqueConnection);

                qDebug() << "TicTacServer::startServer(): Server listening on port"
                         << mTcpServer->serverPort();

                // Start broadcasting server IP periodically to invite clients
                if (!mBroadcastSocket) {
                    mBroadcastSocket = new QUdpSocket(this);
                }

                broadcastServerInfo();
                setState(Broadcasting);
            }
            else {
                qDebug() << "TicTacServer::startServer(): Server could not be started!";
            }
        }
    }
    else {
        qDebug() << "TicTacServer::startServer(): Pending start...";
        mConnectionManager->connectToWlan();
        setState(Starting);
    }
}
Example #14
0
bool NameResolution::hasMapping(bool &ret, const std::string &name, ims::name::NameResolutionSourceType sourceType) {
	if (name.length() > 0xff) {
		// error...
		return false;
	}

	// prepare the command
	cmdLen = name.length() + 4;
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = 2; // function, hasMappingName
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}
	buf[5] = (unsigned char) name.length();
	memcpy(buf + 6, name.c_str(), name.length());

	//std::cerr << "// issue the command\n";
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		//std::cerr << "// something went wrong...reconnect, try one more time, then fail\n";
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	// at this point, all is well, and command has been issued
	// read back the answer
	if (socket_read(conn_fd, buf, 1, sockTimeout) != 1) {
		// error
		return false;
	}
	ret = (buf[0] == 1)?true:false;

	return true;
}
Example #15
0
bool NameResolution::load(const TimeStamp &begin, const TimeStamp &end, ims::name::NameResolutionSourceType sourceType) {
	// prepare the command
	cmdLen = 19; //
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = -2; // function, load
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}
	this -> ip = htonl(begin.seconds());
	memcpy(buf + 5, &(this -> ip), sizeof(uint32_t)); // arg (t)
	this -> ip = htonl(begin.microseconds());
	memcpy(buf + 9, &(this -> ip), sizeof(uint32_t)); // arg (t)
	this -> ip = htonl(end.seconds());
	memcpy(buf + 13, &(this -> ip), sizeof(uint32_t)); // arg (t)
	this -> ip = htonl(end.microseconds());
	memcpy(buf + 17, &(this -> ip), sizeof(uint32_t)); // arg (t)

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}

	if (socket_read(conn_fd, buf, 1, sockTimeout) != 1) {
		// error
		return false;
	}

	return true;
}
Example #16
0
// generic routine to create a thread that maintains a connection 
// for receiving server messages
void initClientThread(struct socketDescriptor * sd) {
   int connected;
   
   if ((connected=establishConnection(sd)) || !sd->exit) {
      // start rx thread if connected or if thread should retry (not exit)
      sd->exit=FALSE;   
      sd->hThread = CreateThread(
         NULL,      // default security
         0,         // default stack size
         (LPTHREAD_START_ROUTINE)&rxClientThread,
         sd,        // thread parameter
         0,         // run thread immediately
         NULL);  // ignore thread id
   }      
       
   if ((!connected && sd->exit) || !sd->hThread) {
      const char * init = "initClientThread ";
      if (!sd->description) sd->description = sd->host;
      char * description = (char *) malloc(strlen(init) + strlen(sd->description)+1);
      printErrorAndExit((const char *)strcat(strcpy(description,init),sd->description));
   }
} 
int main(int argc , char *argv[])
{
	char *buff="";
	struct cipher ciph;
	char str2[1];
	char str3[40];
	unsigned char digest1[40];
	sock=establishConnection();
	while (recv(sock, response , 15000 , 0)<0){};
	location="test1.txt";
	if (strcmp(response,"GET /file2send.txt")==0){
			buff=readData(sock,location);
			//puts(buff);
			
			 //puts(ciph.value);
			strcpy(digest1, findHmac(buff));  

			
			strcat(str2,"$Message:$");
			strcat(str2,buff);
			strcat(str2,"$HMAC:$");
			strcat(str2,digest1);
			ciph=encryptAES(str2);
			sprintf(str3,"$Incominglength=$%d$EncryptedMessage:$",ciph.length);	
			strcat(str3,ciph.value);
			strcat(str3,"$");	
			//puts("Sending Encrypted (msg + HMAC)");
			//puts(str3);
			sendMsg(sock,str3);
			printf("Sent Successfully:length of data=%d ",(int)strlen(str3));
			puts(str3);
	
	}
	return 0;

}
Example #18
0
bool NameResolution::hasMapping(bool &ret, const uint32_t &ip, ims::name::NameResolutionSourceType sourceType) {
	// prepare the command
	cmdLen = 7; //
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = 3; // function, hasMappingIP
	if (sourceType == ims::name::NameResolutionSourceType::ANY) {
		buf[4] = 0;
	} else if (sourceType == ims::name::NameResolutionSourceType::DNS) {
		buf[4] = 1;
	}
	this -> ip = htonl(ip);
	memcpy(buf + 5, &(this -> ip), sizeof(uint32_t)); // arg (ip)

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	// at this point, all is well, and command has been issued
	// read back the answer
	if (socket_read(conn_fd, buf, 1, sockTimeout) != 1) {
		// error
		return false;
	}
	ret = (buf[0] == 1)?true:false;

	return true;
}
Example #19
0
// Access functions for variableName and variableNameSubstitutions
// variable substitutions Example: SECTOR=01 will result in any occurance of $SECTOR in variable name being replaced with 01.
void QCaLineEdit::setVariableNameAndSubstitutions( QString variableNameIn, QString variableNameSubstitutionsIn, unsigned int variableIndex )
{
    setVariableNameSubstitutions( variableNameSubstitutionsIn );
    setVariableName( variableNameIn, variableIndex );
    establishConnection( variableIndex );
}
Example #20
0
/** 
 * main()
 * 
 * This program comprises two processes.  First, the "brain" which
 * communicates with a supervisor-client.  The brain receives
 * high-level control commands from the supervisor-client and then
 * conveys any resulting sensor data back.  The second process is the
 * "nerves"; this process translates high-level commands into
 * low-level iRobot SCI commands, executes them on the iRobot, and
 * then obtains any resulting sensor data.
 * 
 */
int main(int argc, char* argv[])
{

  /* Create a message queue using O_CREAT so that if the queue doesn't
   * already exist, it will be created.  When using mq_open with
   * O_CREAT, one must supply four arguments.  The first "name"
   * argument must begin with a slash.  The third "mode" argument is
   * derived from the symbolic constants is <sys/stat.h>.
   */
   mqd_t mqd_cmd = mq_open("/q_cmd", 
		    O_RDWR | O_CREAT , 
		    S_IRWXU | S_IRWXG | S_IRWXO, 
		    NULL);

   mqd_t mqd_sns = mq_open("/q_sns", 
		    O_RDWR | O_CREAT, 
		    S_IRWXU | S_IRWXG | S_IRWXO, 
		    NULL);
 
  printf("The message queue id is: %d\n", mqd_cmd);

  /* Determine the size of messages for this message queue
   */
  struct mq_attr a;
  mq_getattr(mqd_cmd,&a);  

  printf("The default message size is: %d\n", a.mq_msgsize);
   
   if( mqd_cmd == -1)
    {
      perror("mq_open():");
      return -1;
    }


   if( mqd_sns == -1)
    {
      perror("mq_open():");
      return -1;
    }

  

  int check = 0;
  char addresses[3][13];
  if ((check = checkArgName(argc, argv, addresses)) == -1)
    {
      printf("Not correct name entered. Exiting.\n");
      exit(0);
    }
  int i, counter, serverID, clientSock, numBytes;
  pid_t pid, pid2;

  // Arrays to hold most recent command sent by the
  // supervisor-client and the most recent command sent to the iRobot.
  char commandFromSupervisor[MAXDATASIZE] = {'\0'};
  char commandToRobot[MAXDATASIZE] = {'\0'};

  // An array to hold sensor data sent to the supervisor-client and
  // obtained from the iRobot.
  char sensDataToSupervisor[MAXDATASIZE] = {'\0'};
  char sensDataFromRobot[MAXDATASIZE] = {'\0'};
  char emptyDataToSupervisor[MAXDATASIZE] = "0000000000 ";
  char rawTimeString[12] = {'\0'};

  // An array to hold the timestamp.
  char currTime[100];


  // Create pipe to communicate between parent and child
  int fd[2];
  if(pipe(fd) < 0)
    perror("pipe error");

  //------------------------------------------------------------------------
  // Added Code to implement client
  //------------------------------------------------------------------------
  int sockfd, numbytes;  
  //buffer to store sensor information
  char sensorBuf[MAXDATASIZE];
  char msgBuf[MAXDATASIZE];
  struct addrinfo hints, *servinfo, *p;
  int rv;
  char s[INET6_ADDRSTRLEN];
  //array to hold the command sent
  char cmd[1];
  //initialize the input to NULL char
  char input = '\0';
  //------------------------------------------------------------------------
  // End of added section
  //------------------------------------------------------------------------ 

  // Create a socket-based server
  if((serverID = createServer()) == -1)
    {
      perror("createServer()");
      return -1;
    }

  printf("brainstem: waiting for connections...\n");


  // Establish a client-connection for the socket-based server
  if((clientSock = establishConnection(serverID)) == -1)
    {
      perror("establishConnection(serverID)");
      return -1;
    }
  

  // Set up signal-based communication between the child 
  // (brain) and parent (nervous system) to avoid possible
  // race conditions.
  TELL_WAIT();



  // Fork a child process.  This process will handle the "brain"
  // activities: communicating sensor data to the client
  // and receiving control commands from the client.
  if(( pid = fork()) < 0)
    {
      perror("fork error");

    }



  //------------------------------------------------------------------------
  // Code for parent (nerves)
  //------------------------------------------------------------------------
  else if (pid > 0)
    {

      // Close the client socket since this parent won't be using it.
      close(clientSock);

      //TELL_CHILD(pid);

      // Open the serial port to the robot.  If this is unsuccessful,
      // there is no point in continuing.
      if(openPort() == 0)
	{
	  printf("Port failed to open \n");
	  exit(-1);
	}

      // Initialize the robot, prepare it to receive commands.  Wait
      // for a second to give this some time to take effect.
      initialize();
      sleep(1);


#ifdef TARGET_WEBBY
      // Initialize the compass device.
      initializeCompass();

      // This is temporary until turn() works.
      // Turn Left 10 degrees
      turn(TURN_LEFT, 10);
#endif 


      // Turn on the LED to indicate the robot is ready and listening.
      // It's a nice sanity check.
      setLED(RED, PLAY_ON, ADVANCE_ON);

      //------------------------------------------------------------------------
      // Added Code to implement client
      //------------------------------------------------------------------------
      if(check == 1)
	{
#ifdef DEBUG
	  printf("%s %d \n", __FILE__, __LINE__);
#endif
      
	  memset(&hints, 0, sizeof hints);
	  hints.ai_family = AF_UNSPEC;
	  hints.ai_socktype = SOCK_STREAM;
    
	  if ((rv = getaddrinfo(addresses[1], PORT, &hints, &servinfo)) != 0) 
	    {
	      fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
	      return 1;
	    }
    
	  // loop through all the results and connect to the first we can
	  for(p = servinfo; p != NULL; p = p->ai_next) 
	    {
	      if ((sockfd = socket(p->ai_family, p->ai_socktype,
				   p->ai_protocol)) == -1) {
		perror("client: socket");
		continue;
	      }
      
	      if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
		close(sockfd);
		perror("client: connect");
		continue;
	      }
      
	      break;
	    }
    
	  if (p == NULL) 
	    {
	      fprintf(stderr, "client: failed to connect\n");
	      return 2;
	    }
    
	  inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
		    s, sizeof s);
	  printf("client: connecting to %s\n", s);
    
	  freeaddrinfo(servinfo); // all done with this structure
    
	  //if the client does not recieve anything from server then exit
	  if ((numbytes = recv(sockfd, msgBuf, MAXDATASIZE-1, 0)) == -1) 
	    {
	      perror("recv");
	      exit(1);
	    }
	}

      //------------------------------------------------------------------------
      // End of added section
      //------------------------------------------------------------------------

      while(commandToRobot[0] != ssQuit)
	{
	  commandToRobot[0] = 'z';
	  // Wait until a valid command is received.
	  while(commandToRobot[0] == 'z')
	    {
          commandToRobot[0] = readFromMessageQueueAndExecute(mqd_cmd);
	      
	    }

	  printf("commandToRobot: %d\n", commandToRobot[0]);
	  //------------------------------------------------------------------------
	  // Added Code to implement client
	  //------------------------------------------------------------------------
	  if(check == 1)
	    {
	      if(send(sockfd, &commandToRobot[0], 1, 0) == -1)
		perror("send");
	      printf("      the command code sent was: %d\n", commandToRobot[0]);
	    }
	  //------------------------------------------------------------------------
	  // End of added section
	  //------------------------------------------------------------------------

	  receiveGroupOneSensorData(sensDataFromRobot);

	  // check if any of the sensor data indicates a 
	  // sensor has been activated.  If so, react be
	  // driving backwards briefly and then stopping.
	  
	  int sensData = 0;

	  // Check sensor data first to stop ramming into wall.
	  sensData = checkSensorData(sensDataFromRobot);

#ifdef DEBUG
	  printf("%s %d \n", __FILE__, __LINE__);
#endif
	  // Wait until child has sent previous sensor data.
	  //WAIT_CHILD();

#ifdef DEBUG

	  printf("%s %d \n", __FILE__, __LINE__);
	  printf("%d \n", sensData);
#endif

	  if(sensData)
	    {
#ifdef DEBUG
	      printf("%s %d \n", __FILE__, __LINE__);	     	      
#endif
	      // Drive backwards and then stop.
	      driveBackwardsUntil(EIGHTH_SECOND, MED);
	      STOP_MACRO;	      

	      // Convey sensorData back to the child.
	      writeSensorDataToMessageQueue(sensDataFromRobot, mqd_sns, getTime(), getRawTime());

	    }  
	  // Done writing sensor data, tell child to proceed reading sensor data.
	  TELL_CHILD(pid);
	  
	  // Reset the array; fill it again in the next loop.
	  for(i = 0; i <= 6; i++)
	    {
	      sensDataFromRobot[i]= FALSE;
	    }
	}


      if (closePort() == -1)
	{
	  perror("Port failed to close \n");
	  exit(-1);
	}
      send(sockfd, &input, 1, 0);
      close(sockfd);
      kill(0, SIGTERM);
      mq_close(mqd_cmd);

      exit(0);
    }

  //------------------------------------------------------------------------
  // Code for child (brain)
  //------------------------------------------------------------------------
  else
    {
      // Child process doesn't need the listener.
      close(serverID);

      // Initially tell the parent to proceed and write sensor data.
      //TELL_PARENT(getppid());

      // Send the client the initial connection message.
      if(send(clientSock, MSG, sizeof(MSG), 0) == -1)
	perror("send");

      // At the request of the supervisor implementation team, The
      // brain follows a strict alternation of 'receive control
      // command' then 'send sensor data'.  If the control command
      // sent by the supervisor-client is 'turn left' and the iRobot
      // happens to bump into something, then the subsequent message
      // to the supervisor-client will indicate which bumper was activated.  
      // Similarly, if the control command sent by the supervisor is
      // 'turn left' and the iRobot experiences no sensory input, the
      // subsequent message to the supervisor will indicate that no sensors
      // were activated.

      // As long as the quit command 'q' has not been sent by the
      // supervisor-client, receive a control command and send the
      // subsequent sensor data.
      while(commandFromSupervisor[0] != ssQuit)
	{
	  // Wait to receive command from supervisor-client; read the command
	  // into cmdBuf.
	  if ((numBytes = recv(clientSock, commandFromSupervisor, MAXDATASIZE-1, 0)) == -1)
	    {
	      perror("recv");
	      return -1;
	    }
	  // Write the read command into shared memory so that the
	  // parent (nerves) may read and execute it.
	  //writeCommandToSharedMemory(commandFromSupervisor, cmdArea,mqd_cmd);
      writeCommandToMessageQueue(commandFromSupervisor,mqd_cmd);

	  // Wait until parent has written sensor data.
	  WAIT_PARENT();

#ifdef DEBUG
	  printf("%s %d \n", __FILE__, __LINE__);
#endif

	  // If there is sensor data available, send it to the
	  // supervisor-client.
	  if(readSensorDataFromMessageQueue(sensDataToSupervisor, mqd_sns))
	    {
	      printf("\nsensDataToSupervisor: %s \n", sensDataToSupervisor);
	      if(send(clientSock, sensDataToSupervisor, strlen(sensDataToSupervisor)-1 , 0) == -1)
		perror("send");
	    }
	  
	  // Otherwise, assume no sensor was activated.  Send an empty
	  // sensor message to the supervisor-client.
	  else
	    {
	      itoa(getRawTime(), rawTimeString);
	      
	      // Construct an empty sensor data message and send it to
	      // the supervisor-client.
	      strncat(emptyDataToSupervisor, rawTimeString, MAXDATASIZE-SIZE_OF_EMPTY_DATA);
	      strncat(emptyDataToSupervisor, " ", 1);
	      strncat(emptyDataToSupervisor, getTime(), MAXDATASIZE-SIZE_OF_EMPTY_DATA);
	      printf("\nemptySensDataToSupervisor: %s \n", emptyDataToSupervisor);
	      if(send(clientSock, emptyDataToSupervisor, MAXDATASIZE-1, 0) == -1)
		perror("send");

	      emptyDataToSupervisor[SIZE_OF_EMPTY_DATA] = '\0';
	    }

	  // Done reading sensor data, allow parent to write more sensor data.
	  TELL_PARENT(getppid());
	}
	

      // All done.  Clean up the toys and go home.
      printf("Closing socket and terminating processes.\nHave a nice day!\n");
      kill(pid, SIGTERM);
      close(clientSock);
      mq_close(mqd_cmd);

      exit(0);
    }
  // Added following code to implement communication between roomba's
 
  
	  
}
Boolean TPZCrossbarFlowCTMux :: dispatchEvent(const TPZEvent& event)
{        
   if( ( event.type() == _CrossbarRequest_ ) ||
       ( event.type() == _CrossbarPass_ ) )
   {
      TPZCrossbar& crossbar = (TPZCrossbar&)(getComponent());
      unsigned iPort =   event.source();
      unsigned oPort =   getOutputForInput(iPort).left();
      unsigned channel = getOutputForInput(iPort).right();
      
      if(event.type() == _CrossbarRequest_)
      {
        oPort=event.destiny();
        channel=event.channel();  
      } 
      TPZMessage *msg;
      m_MessageReceivedTable->valueAt(iPort,&msg);
      
      if(!msg) return true;
      
      if(!channel)
      {
         if(_CrossbarRequest_)
         {
           EXIT_PROGRAM("Channel set to 0 in request Not allowed");
         }
         else
         {
           EXIT_PROGRAM("Channel set to 0 in data Not allowed");
         }
      }  
      else if( ! iPort )
      {
         TPZString err;
         err.sprintf( ERR_TPZCFLOC_001, 
                      (char*)getComponent().asString(),
                      (char*)msg->asString() );
         EXIT_PROGRAM(err);
      }
      else if(!oPort)
      {
         TPZString err;
         err.sprintf( ERR_TPZCFLOC_002, 
                      (char*)getComponent().asString(),
                      (char*)msg->asString() );
         EXIT_PROGRAM(err);
      }
      
      //Here's the difference with the normal version
      if( event.type() == _CrossbarRequest_)
      {
         for(int i=1; i<=crossbar.numberOfInputs(); i++)
         {
            uPAIR temp;
            m_PortAsignamentTable->valueAt(i,temp);
            if(i!=iPort && (temp.left()==oPort) )
            {
                inputInterfaz(iPort)->sendStop();
                uTIME delayTime = getOwnerRouter().getCurrentTime() + 1;
                getEventQueue().enqueue(event,delayTime); 

   #ifndef NO_TRAZA 
                TPZString time = getOwnerRouter().getCurrentTime();       
                TPZString texto = getComponent().asString() + " CONTENTION  STOP TIME = ";
                texto += time + msg->asString() + " i=" + TPZString(iPort) +
                    ", o=" + TPZString(oPort) + ", OPORT used by i=" + TPZString(i);
                TPZWRITE2LOG( texto );
   #endif
                return true;
            }
         }
      
         if( (outputInterfaz(oPort)->isStopActive(channel)))
         {
            inputInterfaz(iPort)->sendStop();
            uTIME delayTime = getOwnerRouter().getCurrentTime() + 1;
            getEventQueue().enqueue(event,delayTime);

   #ifndef NO_TRAZA 
      TPZString time = getOwnerRouter().getCurrentTime();       
      TPZString texto = getComponent().asString() + " QUEUES  STOP TIME = ";
      texto += time + msg->asString() + " i=" + TPZString(iPort) +
               ", o=" + TPZString(oPort);
             
      TPZWRITE2LOG( texto );
   #endif
               return true;
         }
               establishConnection(iPort,oPort,channel);

      setStateForInput(iPort,Connect);   
      }

   
    
      inputInterfaz(iPort)->clearStopRightNow();
     
      outputInterfaz(oPort)->sendData(msg,channel);
      ((TPZNetwork*)(getOwnerRouter().getOwner()))->incrEventCount( TPZNetwork::SWTraversal);
      if (msg->getRoutingPort()!=_LocalNode_) 
      ((TPZNetwork*)(getOwnerRouter().getOwner()))->incrEventCount( TPZNetwork::LinkTraversal);
           
   #ifndef NO_TRAZA 
      TPZString time = getOwnerRouter().getCurrentTime();       
      TPZString texto = getComponent().asString() + " Flit Tx. TIME = ";
      texto += time + msg->asString() + " i=" + TPZString(iPort) +
               ", o=" + TPZString(oPort);
            
      TPZWRITE2LOG( texto );
   #endif
   
      if( msg->isTail() )
      {
         clearConnection(iPort);
         uPAIR temp;
         temp = getConnectionRequestForWith(oPort);
         iPort=temp.left();
         channel=temp.right();
         if( iPort != 0 )
         {
            establishConnection(iPort,oPort,channel);
            TPZEvent requestEvent(_CrossbarRequest_,iPort,oPort,channel);
            uTIME delayTime = getOwnerRouter().getCurrentTime() +
                              MAXIMO(1,getHeaderDelay());
            
            if( ((TPZCrossbar&)getComponent()).isLocalNodeOutput(oPort) )
            {
               if( getHeaderDelay() > 1 )
                  delayTime -= 1;
            }
            
            getEventQueue().enqueue(requestEvent,delayTime);
         }
      }
   }  
   return true;
}
Example #22
0
//==============================================================================
// Drag drop
void QESpinBox::setDrop( QVariant drop )
{
    setVariableName( drop.toString(), 0 );
    establishConnection( 0 );
}
Example #23
0
void QESpinBox::paste (QVariant s)
{
    setVariableName( s.toString(), 0 );
    establishConnection( 0 );
}
Example #24
0
int main(){

	// printf("Testing RSA functions with EVP_DigestSign and EVP_DigestVerify\n");
	char response[1000];

	OpenSSL_add_all_algorithms();

	/* Sign and Verify HMAC keys */
	EVP_PKEY *skey = NULL, *vkey = NULL;
	
	int rc = make_keys(&skey, &vkey);
	assert(rc == 0);
	if(rc != 0)
	exit(1);

	assert(skey != NULL);
	if(skey == NULL)
	exit(1);

	assert(vkey != NULL);
	if(vkey == NULL)
	exit(1);
	DH *privkey=createPubkey();
	//char *dh_param_pub=BN_bn2dec(privkey->pub_key); 
	const byte *msg = BN_bn2dec(privkey->pub_key);//msg contains dh_param_pub
	printf("DH public key Generated:%s \n",msg);
	byte* sig = NULL;
	size_t slen = 0;

	
	
	sock=establishConnection();
	int i=0;
	//int count = split(data1, "$", tokens);
	sendMsg(sock,msg);
	
	 if( recv(sock, response , 6000 , 0) < 0)
	{
	puts("recv failed");
	}
	printf("Recieved Successfully:length of data=%d \n",(int)strlen(response));
	printf("DH public key Recieved:%s \n",response);
	//printf("Sent Successfully: length of data=%d\n",sumSend);
	char *pubkey=response;
	struct sec s=performDH(pubkey,privkey);
	printf("Shared key is:%s\n ",s.value);
	puts("The DH Key is");
	BIO_dump_fp(stdout, s.value, s.length);
	//free(msg);
	verifySignature(sock,msg);
	if(sig)
	OPENSSL_free(sig);

	if(skey)
	EVP_PKEY_free(skey);

	if(vkey)
	EVP_PKEY_free(vkey);
	
	return 0;
}
Example #25
0
bool NameResolution::getConfiguration(ims::QueryManagerConfiguration &queryManConfig) {
	// prepare the command
	cmdLen = 3;
	uint16_t tmpCmdLen = htons(cmdLen);
	memcpy(buf, &tmpCmdLen, sizeof(uint16_t));
	buf[2] = 0; // type, NameResolution
	buf[3] = -4; // function, getConfiguration
	buf[4] = 0;

	// issue the command
	if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
		// something went wrong...reconnect, try one more time, then fail
		close(conn_fd);
		if (!establishConnection()) {
			return false;
		}
		if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) {
			return false;
		}
	}
	
	uint32_t count32, tmp32;
	std::string tmpStr;
	// read all dbHomes...
	// number of dbHomes...
	if (socket_read(conn_fd, (char *) &count32, sizeof(count32), sockTimeout) != sizeof(count32)) {
		// error
		return false;
	}
	tmp32 = ntohl(count32);

	for (uint32_t i = 0; i < tmp32; ++i) {
		// dbHome.size()
		if (socket_read(conn_fd, (char *) &count32, sizeof(count32), sockTimeout) != sizeof(count32)) {
			// error
			return false;
		}
		count32 = ntohl(count32);

		// dbHome
		if (count32 <= 0xffff) {
			if (socket_read(conn_fd, buf, count32, sockTimeout) != count32) {
				return false;
			}
			tmpStr.assign(buf, count32);
		} else {
			if (socket_read(conn_fd, buf, 0xffff, sockTimeout) != 0xffff) {
				return false;
			}
			tmpStr.assign(buf, 0xffff);
			
			count32 -= 0xffff;
			if (socket_read(conn_fd, buf, count32, sockTimeout) != count32) {
				return false;
			}
			tmpStr.append(buf, count32);
		}
		queryManConfig.dbHomes.push_back(tmpStr);
	}

	// sockPath.size()
	if (socket_read(conn_fd, (char *) &count32, sizeof(count32), sockTimeout) != sizeof(count32)) {
		// error
		return false;
	}
	count32 = ntohl(count32);

	// sockPath
	if (count32 <= 0xffff) {
		if (socket_read(conn_fd, buf, count32, sockTimeout) != count32) {
			return false;
		}
		queryManConfig.sockPath.assign(buf, count32);
	} else {
		if (socket_read(conn_fd, buf, 0xffff, sockTimeout) != 0xffff) {
			return false;
		}
		queryManConfig.sockPath.assign(buf, 0xffff);
		
		count32 -= 0xffff;
		if (socket_read(conn_fd, buf, count32, sockTimeout) != count32) {
			return false;
		}
		queryManConfig.sockPath.append(buf, count32);
	}

	// sockTimeout
	if (socket_read(conn_fd, (char *) &count32, sizeof(count32), sockTimeout) != sizeof(count32)) {
		// error
		return false;
	}
	queryManConfig.sockTimeout = ntohl(count32);

	return true;
}
Example #26
0
//==============================================================================
// Drag drop
//
void QEGenericEdit::setDrop( QVariant drop )
{
    setVariableName( drop.toString(), 0 );
    establishConnection( 0 );
}