Exemplo n.º 1
0
void Server::run ()
{
    if (m_server == INVALID_SOCKET)
    {
        return;
    }

    struct sockaddr_in clientAddr;
    int length = sizeof(clientAddr);

    SOCKET sockAccept = accept(m_server, (struct sockaddr *)&clientAddr, (socklen_t *)(&length));

    if (sockAccept == INVALID_SOCKET)
    {
        perror("Accept failed");

        #ifdef WIN32
            printf("%i", WSAGetLastError());
        #endif
    }
    else
    {
        std::string result = nullToEmpty(recvMessage(sockAccept));
        std::string ip = inet_ntoa(clientAddr.sin_addr);
        printf("Resultado: %s\tClient: %s\tPort: %i\n", result.c_str(), ip.c_str(), clientAddr.sin_port);

        closesocket(sockAccept);
    }
}
Exemplo n.º 2
0
void CMessageQueue::threadWork()
{
	while (true){
		string str;
		if (!recvMessage(str))
			break;
		__NotificationCenter::getInstance()->postNotification(str.substr(0,4), __String::create(str.substr(4)));
	}
}
Exemplo n.º 3
0
void MessageType::onChatMessage(netlib::connectionPtr conn,ChatMessagePtr message)
{
    //获得完整消息,并将其填充成新message
    std::string recvMessage(getCompleteMessage(conn->ConnectionName_,message));
    ChatMessagePtr newMessage(new ChatMessage);
    newMessage->set_chat_message(recvMessage);
    //将消息发给每一个在线用户
    distributeMessage(newMessage,rooms_,codec_,conn->rooName_);
}
Exemplo n.º 4
0
/* The main game loop */
GAMECODE gameLoop()
{
	static uint32_t lastFlushTime = 0;

	static int renderBudget = 0;  // Scaled time spent rendering minus scaled time spent updating.
	static bool previousUpdateWasRender = false;
	const Rational renderFraction(2, 5);  // Minimum fraction of time spent rendering.
	const Rational updateFraction = Rational(1) - renderFraction;

	countUpdate(false); // kick off with correct counts

	while (true)
	{
		// Receive NET_BLAH messages.
		// Receive GAME_BLAH messages, and if it's time, process exactly as many GAME_BLAH messages as required to be able to tick the gameTime.
		recvMessage();

		// Update gameTime and graphicsTime, and corresponding deltas. Note that gameTime and graphicsTime pause, if we aren't getting our GAME_GAME_TIME messages.
		gameTimeUpdate(renderBudget > 0 || previousUpdateWasRender);

		if (deltaGameTime == 0)
		{
			break;  // Not doing a game state update.
		}

		ASSERT(!paused && !gameUpdatePaused(), "Nonsensical pause values.");

		unsigned before = wzGetTicks();
		syncDebug("Begin game state update, gameTime = %d", gameTime);
		gameStateUpdate();
		syncDebug("End game state update, gameTime = %d", gameTime);
		unsigned after = wzGetTicks();

		renderBudget -= (after - before) * renderFraction.n;
		renderBudget = std::max(renderBudget, (-updateFraction * 500).floor());
		previousUpdateWasRender = false;

		ASSERT(deltaGraphicsTime == 0, "Shouldn't update graphics and game state at once.");
	}

	if (realTime - lastFlushTime >= 400u)
	{
		lastFlushTime = realTime;
		NETflush();  // Make sure that we aren't waiting too long to send data.
	}

	unsigned before = wzGetTicks();
	GAMECODE renderReturn = renderLoop();
	unsigned after = wzGetTicks();

	renderBudget += (after - before) * updateFraction.n;
	renderBudget = std::min(renderBudget, (renderFraction * 500).floor());
	previousUpdateWasRender = true;

	return renderReturn;
}
Exemplo n.º 5
0
UdpSocketThread::UdpSocketThread(QObject *parent) :
    QThread(parent)
{
    bStop = false;
    boolPing = true;
    m_pInstacne = this;
    m_zipfileName = "";
    m_qUdpSocket.bind(serverPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
    connect(&m_qUdpSocket, SIGNAL(readyRead()), this, SLOT(recvMessage()));
    //connect(SaveDataThread::GetInstance(), SIGNAL(imageReady()), this , SLOT(recvImageName()), Qt::DirectConnection);
}
Exemplo n.º 6
0
static void sendDataMsgInternal(MSG_PTR msg, DATA_MSG_PTR dataMsg, 
				void *classData,
				DISPATCH_PTR parentDispatch, 
				RESP_PROC_FN resProc,
				void *resData)
{
  DISPATCH_PTR dispatch;
  
  dispatch = buildDispatchInternal(msg, dataMsg, classData, parentDispatch, 
				   resProc, resData);
  recvMessage(dispatch, dispatch->msg_class, classData);
}
Exemplo n.º 7
0
int antLoop(ipc_t ipc, grid_t grid) {

    char stop;
    handler_f* handlers;
    ant_t ant;
    cmd_t cmd;
    message_t message, ret;

    srand(getpid());

    ant = antNew();
    ant->ahr = ant->r = grid->anthillRow;
    ant->ahc = ant->c = grid->anthillCol;
    LOGPID("Starting ant %d logic loop.\n", ipc->id);

    handlers = buildHandlerArray();
    antFillHandlerArray(handlers);

    sendMessage(ipc, message = mnew(ipc->id, 1, sizeof(struct cmd_start_t),
                                    (char*) (cmd = newStart())));

    mdel(message);
    free(cmd);
    
    stop = 0;

    while(!stop) {

        if (message = recvMessage(ipc)) {
            LOGPID("Ant %d received cmd type %d.\n", ipc->id, ((cmd_t) mdata(message))->type);
            if (cmd = dispatchCmd((void*) ant, (cmd_t) mdata(message), handlers)) {
                mdel(message);

                sendMessage(ipc, message = mnew(ipc->id, 1, cmdsize(cmd),
                                               (char*) cmd));
                    
                LOGPID("Ant %d sent cmd type %d.\n", ipc->id, ((cmd_t) mdata(message))->type);
                mdel(message);   
                free(cmd);                   
            }
        }
        
        stop = (ant->state == ANT_STATE_FINAL);
    
    }
    
    ipc->stop = 1;
    return 0;
}
Exemplo n.º 8
0
/**
@brief 连接可读事件,返回-1,close()会被调用
@return -1:处理失败,会调用close(); 0:处理成功
*/
int CwxMqInnerDispHandler::onInput() {
  ///接受消息
  int ret = CwxMqInnerDispHandler::recvPackage(getHandle(), m_uiRecvHeadLen,
    m_uiRecvDataLen, m_szHeadBuf, m_header, m_recvMsgData);
  ///如果没有接受完毕(0)或失败(-1),则返回
  if (1 != ret) return ret;
  ///接收到一个完整的数据包,消息处理
  ret = recvMessage();
  ///如果没有释放接收的数据包,释放
  if (m_recvMsgData) CwxMsgBlockAlloc::free(m_recvMsgData);
  this->m_recvMsgData = NULL;
  this->m_uiRecvHeadLen = 0;
  this->m_uiRecvDataLen = 0;
  return ret;
}
Exemplo n.º 9
0
/* Registers a function with a fatbin handle received with
 * cudaRegisterFatBinary(). This function has something to
 * do with the way kernels are called from host code, and how
 * a kernel is identified.
 *
 * So far, two ways to call a kernel function has been registered.
 * The normal, user - mode method (if not using the 
 * kernname<<<launch_config>>>(kern_params) call, is to use cudaLaunch()
 * with the kernel name as input. The second is to use the address of a
 * user mode function with the same name as the kernel. Both the name
 * and the pointer are registered below, and probably used to identify
 * some kernel function in the fatbin image. */
void __cudaRegisterFunction(
        void **fatCubinHandle,      // fatbin image containing the GPU code
        const char *hostFun,        // The same-name-as-kernel host function pointer
        char *deviceFun,             
        const char *deviceName,     
        int thread_limit, 
        uint3 *tid,
        uint3 *bid, 
        dim3 *bDim,
        dim3 *gDim,
        int *wSize){

    struct cudaRegisterFunctionStruct *var = 
        (struct cudaRegisterFunctionStruct*) memptr;

    var->guest_pid = getpid();
    var->callhead.head.cmdType = normCall;
    var->callhead.callID = facu__cudaRegisterFunction;

    var->fatCubinHandle = fatCubinHandle;
    var->hostFun = (char*)hostFun;

    /* We REALLY should assert the size of the deviceFun
     * string. If > 1000.. crash 
     *
     * It's not necessarily required to pass the string
     * anyway. The ECS only handles the hostFun pointer. */


    strcpy(var->deviceFun,  deviceFun);
 //   strcpy(var->deviceName, deviceName);

    var->thread_limit = thread_limit;
    var->tid = tid;
    var->bid = bid;
    var->bDim = bDim;
    var->gDim = gDim;
    var->wSize = wSize;

    if(sendMessage((void*) var, sizeof(struct cudaRegisterFunctionStruct)) == FACUDA_ERROR)
        fprintf(stderr, "Unhandled error in __cudaRegisterFunction!\n");

    if(recvMessage((void**)&var) == FACUDA_ERROR)
        fprintf(stderr, "Unhandled error in __cudaRegisterFunction!\n");


}
Exemplo n.º 10
0
//{{{ waitForHellorep
int waitForHellorep(int waitingPeriod) {
	struct sockaddr_in netParamsNeighbour;
	time_t timeStart, timeCur;
	timeStart = time(&timeStart);
	timeCur = time(&timeCur);

	msg_t msg;

	int flags = fcntl(this_site.sdRecv, F_GETFL);
	int flags2 = flags | O_NONBLOCK;
	fcntl(this_site.sdRecv, F_SETFL, flags2);

	fprintf (stdout, "Expecting HELLOREP for network discover.\n");

	//while((this_site.nbNeighbours < 2) || (timeCur - timeStart < waitingPeriod))
	while(timeCur - timeStart < waitingPeriod) {
		timeCur = time(&timeCur);
		memset (&msg, 0, SIZE);

		if(recvMessage(&msg, &netParamsNeighbour) == -1) 
			continue;

		switch (type(msg)) {
			case HELLO:
				handleHello(msg);
				break;

			case HELLOREP:
				handleHelloRep(msg, &netParamsNeighbour);
				break;

			case RESOURCE:
				handleResource(msg);
				break;

			default:
				fprintf(stderr, "======> Unknown message type <======\n");
				break;
		}
	}

	fcntl(this_site.sdRecv, F_SETFL, flags);

	printf("End of network discovery : %ld sites found.\n", (long int)this_site.nbNeighbours);

	return 0;
}
Exemplo n.º 11
0
string nextToken() {
    string word;
    stringstream stream(recvMessage(true));
    stream >> word;
 
    int size = word.length() + 1;

    if (word != "") {
        char* buf = new char[size];
        if (recv(portfd, buf, size, 0) == -1)
            if (errno != EWOULDBLOCK) {
                cout << "Error in recv()" << endl;
            } // else cout << "No bytes in the socket" << endl;
    }
    
    return word;
}
Exemplo n.º 12
0
search::search(QWidget* p,MainWindow * m)
    : QDialog(p)
{
    parent = m;
    lineEdit = new QLineEdit(parent);
    lineEdit->show();
    lineEdit->setGeometry(100,45,160,25);
    
    button = new QPushButton(parent);
    button->show();
    button->setGeometry(275,45,25,25);
    button->setIcon(QIcon(":/images/search_black.png"));
    connect(button,SIGNAL(clicked(bool)),this,SLOT(searchWord()));
    textEdit = new QTextEdit(parent);
    textEdit->show();
    textEdit->setGeometry(80,80,240,210);
    connect(parent->socket,SIGNAL(readyRead()),this,SLOT(recvMessage()));
}
Exemplo n.º 13
0
X_IPC_RETURN_VALUE_TYPE centralReply(DISPATCH_PTR dispatch, const void *data)
{
  CONST_FORMAT_PTR format=NULL;

  if (data != NULL) 
    format = dispatch->msg->msgData->resFormat;

  dispatch->resData = x_ipc_dataMsgCreate(0, 0, 0, 0, 0,
				    format, data,
				    (FORMAT_PTR)NULL, (char *)NULL);
  
  if (dispatch->resData == NULL) return Failure;
  /* 20-Nov-90: fedor: to be consistent with recvMesgBuild */
  dispatch->msg_class = ReplyClass;
  recvMessage(dispatch, ReplyClass, dispatch->classData);

  return Success;
}
Exemplo n.º 14
0
void * handleConnection(void * arg) {
    char buffer[1024];
    int cd = *((int *)arg);

    // Detach the thread. The main thread doesn't need to wait for this thread
    // to finish or for the return value.
    pthread_detach(pthread_self());

    ssize_t rc = sendGreeting(cd);
    if (rc == -1) {
        close(cd);
        return NULL;
    }

    ///////
    // Receive USER command from client. TODO: move to function
    int buff_len = recvMessage(cd, buffer);

    if (buff_len == -1) {
        close(cd);
        return NULL;
    }

    // TODO: Make sure it's a USER command.

    // TODO: 5 Should be constant.
    int username_len = buff_len - 5;
    char username[username_len + 1];

    memcpy(username, buffer + 5, username_len);
    username[username_len] = '\0';

    printf("User %s logged in\n", username);
    ///////

    rc = sendValidLoginConfirmation(cd);
    if (rc == -1) {
        close(cd);
        return NULL;
    }

    close(cd);
    return NULL;
}
Exemplo n.º 15
0
void MulticastServer::run(void) {
	socketMsg *socketMessage;
	int returnCode;

#ifdef DEBUGOUTPUT
	systemLog->sysLog(DEBUG, "Multicast server is running and waiting for packets");
#endif
	for (;;) {
		socketMessage = recvMessage(sd);
#ifdef DEBUGOUTPUT
		systemLog->sysLog(DEBUG, "multicast packet size is %d", socketMessage->brecv);
#endif
		if (socketMessage) {
			returnCode = decodePacket(socketMessage->recvmsg);
			free(socketMessage);
			socketMessage = NULL;
		}
	}
}
Exemplo n.º 16
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //ui->chatTextBox->setEnabled(false);
    ui->sendTextBox->setEnabled(false);
    ui->sendPushButton->setEnabled(false);

    ui->chatTextBox->setReadOnly(true);

    connect(ui->joinPushButton, SIGNAL(clicked()), this, SLOT(joinChat()));
    connect(ui->sendPushButton, SIGNAL(clicked()), this, SLOT(sendMessage()));
    connect(&timer, SIGNAL(timeout()), this, SLOT(recvMessage()));

    /*Fill in remote sockaddr_in */
    bzero(&remoteAddress, sizeof(remoteAddress));
    remoteAddress.sin_family = PF_INET;
    remoteAddress.sin_port = htons(PORT);
    remoteAddress.sin_addr.s_addr = htonl(INADDR_BROADCAST);//inet_addr("192.168.0.255");

    /*Fill in server's sockaddr_in */
    bzero(&serverAddress, sizeof(serverAddress));
    serverAddress.sin_family = PF_INET;
    serverAddress.sin_port = htons(PORT);
    serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);


    sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sockfd == -1)
        QMessageBox::information(this, "Error: socket", strerror(errno), QMessageBox::Ok);

    int broadcastOn = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcastOn, 4) == -1)
        QMessageBox::information(this, "Error: setsockopt", strerror(errno), QMessageBox::Ok);

    if (bind(sockfd, (struct sockaddr* ) &serverAddress, sizeof(serverAddress)) == -1)
        QMessageBox::information(this, "Error: bind", strerror(errno), QMessageBox::Ok);

    this->setFixedSize(this->size());
}
Exemplo n.º 17
0
int initiateSync(int sfd, int numfiles) {
    SyncInit syncinit = SYNC_INIT__INIT;
    SyncInitResponse *response;
    char syncid[SYNCID_MAX];
    char idpath[PATH_MAX];

    snprintf(idpath, PATH_MAX, "%s/%s.id", config.logdir, config.resource);
    if (readSyncId(syncid, idpath, SYNCID_MAX) == -1) {
        errMsg(LOG_ERR, "Could not read sync-id %s.");
        return -1;
    }

    syncinit.number_files = numfiles;
    syncinit.sync_id = syncid;
    syncinit.resource = config.resource;

    if (sendMessage(sfd, SyncInitType, &syncinit) != 0) {
        return -1;
    }

    response = (SyncInitResponse *)
            recvMessage(sfd, SyncInitResponseType, NULL);
    if (response == NULL) {
        errMsg(LOG_ERR, "Could not read initialization response from server.");
        return -1;
    }

    if (response->continue_ == 0) {
        if (response->has_already_synced && response->already_synced) {
            return -2; // special case, which has to be handled in transfer()
        } else {
            if (strlen(response->error_message) > 0) {

                errMsg(LOG_ERR, "Could not initiate sync. "
                        "Response from server: %s", response->error_message);
            }
            return -1;
        }
    }

    return 0;
}
Exemplo n.º 18
0
void IPCManager::recvMessage(const char* buff, uint32 size)
{
	uint32 processed = 0;

	while (processed < size)
	{
		uint32 left = size-processed;

		if (left < 4)
		{
			Warning("Failed to read 4 bytes from pipe.\n");
			return;
		}

		uint32 messageSize = buffToUint32(buff+processed);
		recvMessage((IPCMessage*)(buff+processed));

		processed += messageSize;
	}
}
Exemplo n.º 19
0
int transfer(char *host, char *port) {
    int sfd; // server socket
    fileop_t *f; // contains all operations for a file

    sfd = inetConnect(host, port, SOCK_STREAM);
    if (sfd == -1) {
        errnoMsg(LOG_ERR, "Unable to connect to the server.");
        return -1;
    }

    // initiate sync (sync-id, resource, number of files)
    errMsg(LOG_INFO, "Number of files: %d", HASH_COUNT(files));
    switch (initiateSync(sfd, HASH_COUNT(files))) {
        case -1: // error
            return -1;
        case -2: // there's nothing to synchronize
            return 0;
        default:
            break;
    }

    // iterate over files in correct order
    HASH_SORT(files, sortByOrder);
    for (f = files; f != NULL; f = (fileop_t*) (f->hh.next)) {
        if (transferFile(sfd, f) == -1) {
            errMsg(LOG_ERR, "Transfer of file %s has failed.",
                    f->relpath);
            return -1;
        }
    }

    // wait for ACK
    SyncFinish *conf;
    conf = (SyncFinish *) recvMessage(sfd, SyncFinishType, NULL);
    if (conf == NULL) {
        errMsg(LOG_ERR, "Could not get transfer confirmation.");

        return -1;
    }
    return 0;
}
Exemplo n.º 20
0
void __cudaUnregisterFatBinary(void **fatCubinHandle){
    
    struct cudaUnRegisterFatBinaryStruct *var = 
        (struct cudaUnRegisterFatBinaryStruct*) memptr;

    var->guest_pid = getpid();
    var->callhead.head.cmdType = normCall;
    var->callhead.callID = facu__cudaUnregisterFatBinary;

    var->hostDblPtr = fatCubinHandle;

    if(sendMessage((void*) var, sizeof(struct cudaUnRegisterFatBinaryStruct)) == FACUDA_ERROR)
        fprintf(stderr, "Unhandled error in __cudaUnRegisterFatBinary!\n");

    if(recvMessage((void**)&var) == FACUDA_ERROR)
        fprintf(stderr, "Unhandled error in __cudaUnRegisterFatBinary!\n");

    //free((void*) var);


}
Exemplo n.º 21
0
SimilarWord::SimilarWord(MainWindow* m)
{
    parent = m;
    this->myRecv = new Recv(parent->getSocket());
    connect(this->myRecv,SIGNAL(similarSignal(QString,QVector<Word>)),this,SLOT(recvMessage(QString,QVector<Word>)));

    lineEdit = new myQLineEdit(parent);
    lineEdit->show();
    lineEdit->setGeometry(100,60,270,40);

    connect(lineEdit,SIGNAL(pressEnterSignal()),this,SLOT(searchWord()));

    button = new QPushButton(parent);
    button->show();
    button->setGeometry(380,60,120,40);
    button->setText("查询亲戚单词");
    connect(button,SIGNAL(clicked(bool)),this,SLOT(searchWord()));


    textEdit = new QTextEdit(parent);
    textEdit->show();
    textEdit->setGeometry(100,110,400,280);
}
Exemplo n.º 22
0
/* The main game loop */
GAMECODE gameLoop(void)
{
	static uint32_t lastFlushTime = 0;

	bool didTick = false;
	while (true)
	{
		// Receive NET_BLAH messages.
		// Receive GAME_BLAH messages, and if it's time, process exactly as many GAME_BLAH messages as required to be able to tick the gameTime.
		recvMessage();

		// Update gameTime and graphicsTime, and corresponding deltas. Note that gameTime and graphicsTime pause, if we aren't getting our GAME_GAME_TIME messages.
		gameTimeUpdate();

		if (deltaGameTime == 0)
		{
			break;  // Not doing a game state update.
		}
		didTick = true;

		ASSERT(!paused && !gameUpdatePaused() && !editPaused(), "Nonsensical pause values.");

		syncDebug("Begin game state update, gameTime = %d", gameTime);
		gameStateUpdate();
		syncDebug("End game state update, gameTime = %d", gameTime);

		ASSERT(deltaGraphicsTime == 0, "Shouldn't update graphics and game state at once.");
	}

	if (didTick || realTime - lastFlushTime < 400u)
	{
		lastFlushTime = realTime;
		NETflush();  // Make sure the game time tick message is really sent over the network, and that we aren't waiting too long to send data.
	}

	return renderLoop();
}
Exemplo n.º 23
0
struct CE* IoInterface::makeCeStruct(char deviceType, QHostAddress addr, quint16 port)
{
    struct CE *CeBuff = new CE();
    CeBuff->addr = 0;
    CeBuff->socket = NULL;

    CeBuff->type = 0x00;
    CeBuff->firstAttr = 0x00;
    CeBuff->secondAttr = 0x00;
    CeBuff->thirdAttr = 0xFF;
    //CeBuff->ui = new QMainWindow();



    CeBuff->type = deviceType;
    QUdpSocket *sock = new QUdpSocket();
    quint16 _port = 0;

    if(ipSocketHashmap.size() == 0)
    {
        qDebug() << "hashMapSize zero";
        sock = new QUdpSocket();

        connect(sock, SIGNAL(readyRead()), this, SLOT(recvMessage()));
        ipSocketHashmap.insert(addr, sock);

        if(sock->bind(_port)) {
            qDebug() << "makeCEStruct bind success";
        } else {
            qDebug() << "makeCEStruct bind fail";
        };
    } else {

        if(ipSocketHashmap.contains(addr)) {
            sock = ipSocketHashmap.value(addr);
            qDebug() << "already exist IP";
        } else {
            qDebug() << "not exist";
            sock = new QUdpSocket();
            connect(sock, SIGNAL(readyRead()), this, SLOT(recvMessage()));
            ipSocketHashmap.insert(addr, sock);

            if(sock->bind(_port)) {
                qDebug() << "makeCEStruct bind success";
            } else {
                qDebug() << "makeCEStruct bind fail";
            };
        }
    }

    CeBuff->socket = sock;
    CeBuff->addr = addr;

    // 임시
    CeBuff->firstAttr = 0x01;
    QString t;
    t.sprintf("first Attr : %x", CeBuff->firstAttr);
    //qDebug() << t;

    //connect(CeBuff->socket, SIGNAL(readyRead()), this, SLOT(recvMessage()));

 // writeDiagram 참고 코드
    //00421000  set 2번Attr 16
    // 마지막 1바이트가 사실상 필요가 없음.
    QByteArray message;
    message.resize(4);
    message.clear();

    // 0x00 <TV> 3개
    // 0x01 <Refrigerator> 2개
    // 0x02 <Light> 2개
    // 0x03 <Heater> 3개
    // 0x04 <Cooler> 3개
//this->CeBuffer = CeBuff;
    switch(deviceType)
    {
        case 0x00:
        this->sendGetMessageEachAttribute(CeBuff, 3);
        break;
        case 0x01:
        this->sendGetMessageEachAttribute(CeBuff, 2);
        break;
        case 0x02:
        this->sendGetMessageEachAttribute(CeBuff, 2);
        break;
        case 0x03:
        this->sendGetMessageEachAttribute(CeBuff, 3);
        break;
        case 0x04:
        this->sendGetMessageEachAttribute(CeBuff, 3);
        break;
        default:
        break;
    }

    return CeBuff;
}
Exemplo n.º 24
0
/**
 * Daemon entry point.
 */
int main(int argc, char** argv) {
	int sock; // Listening UDP socket

	// Options
	char bDaemon=0,bOutputToNull=1;
	
	bVerbose=0; // Set global verbosity option to false

	// Program name (i.e. argv[0])
	char* progName;

	// Port to listen to (set to default)
	unsigned short port = SSD_DEFAULT_PORT;
	
	progName = argv[0]; // Note our program name
	argc--; argv++; // ...and get rid of it

	// Get all cmdline args
	while (argc >= 1 && argv[0][0]=='-') {
		switch (argv[0][1]) {
			case 'v': bVerbose=1; break;
			case 'O': bOutputToNull=0; break;
			case 'd': bDaemon=1; break;
			default: usage(progName); // Invalid argument, give the help message and exit
		}
		
		argc--; argv++; // Shift cmdline arguments to get rid of this option we just processed
	}

	// Check for port number on command line
	if (argc == 1) {
		port = atoi(argv[0]);
		if (port == 0) {
			fprintf(stderr,"Invalid port number '%s'!\n",argv[0]);
			return EXIT_FAILURE;
		}
	} else if (argc > 1) {
		usage(progName);
	}

	// Emit banner with options listing
	printf(
			TITLE "\n"
			"\n"
			"Options:\n"
			"  Verbose?      : %s\n"
			"  Daemon?       : %s\n"
			"  OutputToNull? : %s  (daemon mode only)\n"
			"\n",
	tf(bVerbose),
	tf(bDaemon),
	tf(bOutputToNull));

	// Read the gears file
	if (readGears() != 0) {
		fprintf(stderr,"Unable to read frequencies list from '%s'.\n",FILE_FREQ_LIST);
		return EXIT_FAILURE;
	}

	// Emit the detected gears
	printf("Gears:\n");
	int i;
	for (i=0; i<numGears; i++) {
		printf("  [%d] %d MHz\n",i,gearSpeeds[i]/1000);
	}
	printf("\n");

	// Become a daemon if we should
	if (bDaemon) {
		printf("Forking daemon...\n");
		daemonize(bOutputToNull);
	}

	// Create UDP socket for listening
	sock = makeUDPSocket(port);

	printf("Up and running!\n");
	while (1) { // Server loop
		struct sockaddr_in addrOther;
		SSDMessage msgIn,msgOut;
		int result;

		// Get next request
		result = recvMessage(sock, &msgIn, &addrOther);
		if (result != 0) {
			printf("Error receiving message...\n");
			continue;
		}

		if (bVerbose) printf("Got message %s.\n",msgToString(&msgIn));

		// Handle it
		char bValid;
		switch (msgIn.type) {
			case SSD_SET_SPEED:
				// Determine if this is a valid gear
				bValid = (msgIn.gear >= 0 && msgIn.gear < numGears);

				// Prepare response
				if (bValid) {
					msgOut.type = SSD_ACK;
					msgOut.gear = msgIn.gear;
					msgOut.freqKHz = gearSpeeds[msgIn.gear];
				} else {
					msgOut.type = SSD_NAK;
					msgOut.gear = -1;
					msgOut.freqKHz = -1;
				}

				// Send response
				if (bVerbose) printf("Sending response %s.\n",msgToString(&msgOut));
				sendMessage(sock, &msgOut, &addrOther);

				// Actually set gear
				if (bValid) setSpeed(msgIn.gear);
				break;

			case SSD_GET_SPEED:
				// Prepare response & check for validity
				msgOut.gear = getSpeed();
				
				bValid = (msgOut.gear >= 0 && msgOut.gear < numGears);
				
				if (bValid) {
					msgOut.type = SSD_ACK;
					msgOut.freqKHz = gearSpeeds[msgOut.gear];
				} else { // Error, send NAK
					msgOut.type = SSD_NAK;
					msgOut.gear = -1;
					msgOut.freqKHz = -1;
				}

				// Send response
				if (bVerbose) printf("Sending response %s.\n",msgToString(&msgOut));
				sendMessage(sock, &msgOut, &addrOther);
				break;

			case SSD_ACK:
			case SSD_NAK:
				printf("Daemon got an ACK/NAK?!?\n");

				break;
			default:
				printf("Daemon got message with invalid type %s.\n",msgToString(&msgIn));

		}
		
	}

	// We never get here, but who cares
	return EXIT_SUCCESS;
}
Exemplo n.º 25
0
int main(int argc, char** argv) {

    pid_t cpid, spid, pid;
    message_t temp;
    ipcdata_t ipcdata, ipcdata2;
    ipc_t sipc, cipc;
    
    char stop = 0;
    LOG("Creating IPCData for server... "); // Macro defined in tools.h
    
    if ((ipcdata = IPCF_IPCDATA(IPCF_IPCDATA_ARGS)) != NULL)
        LOG("ok.\n");
    else {
        LOG("failed!\n");
        exit(1);
    }
    
    LOG("Attempting to serve... ");
    
    sipc = IPCF_SERVE(ipcdata, 10);
    
    while(sipc->status == IPCSTAT_PREPARING);
        
    LOG("status %d (errno %d) ", sipc->status, sipc->errn);
    
    if (sipc->status == IPCSTAT_SERVING)
        LOG("ok! Listening on port %d.\n", ipcdata->sdata.addr.sin_port);
        
    else {
        LOG("failed!\n");
        exit(1);
    }
    
    if (pid = fork()) {
        LOG("Server: pid %d.\n", spid = getpid());
        
        while(!stop) {
        
            fflush(stdout);
            if (temp = recvMessage(sipc)) {
                LOG("(%d) Server received: ", spid);
                mprintln(temp);
                
                /* Swap from and to, so that the message is routed: */
                
                temp->header.to = temp->header.from;
                temp->header.from = 0;

                sendMessage(sipc, temp);
                LOG("(%d) Server sent: ", spid);
                mprintln(temp);

                mdel(temp);    
            }
        }
        
    } else {
    
	    LOG("Creating IPCData for client... "); // Macro defined in tools.h
	    
    	if ((ipcdata2 = IPCF_IPCDATA(IPCF_IPCDATA_ARGS)) != NULL)
		    LOG("ok.\n");
		else {
		    LOG("failed!\n");
		    exit(1);
		}
    
        LOG("Client: pid %d.\n", cpid = getpid());
        LOG("Attempting to connect... ");

        cipc = IPCF_CONNECT(ipcdata2, 1);

        while (cipc->status == IPCSTAT_CONNECTING);
        
        LOG("status %d (errno %d) ", cipc->status, cipc->errn);

        if (cipc->status == IPCSTAT_CONNECTED)
            LOG("ok!\n");
            
        else {
            LOG("failed!\n");
            exit(1);
        }

        sendMessage(cipc, temp = mnew(1, 0, 5, "ping!"));
        mdel(temp);
        
        while(!stop) {
        
            if (temp = recvMessage(cipc)) {

                LOG("(%d) Client received: ", spid);
                mprintln(temp);
                
                /* Bounce the message! */
                temp->header.to = temp->header.from;
                temp->header.from = 1;
                
                LOG("(%d) Client sent: ", spid);
                mprintln(temp);
                sendMessage(cipc, temp);
                mdel(temp);
                
            }
            
        }
    }
}
Exemplo n.º 26
0
int handleClient(int cfd, struct sockaddr *claddr, socklen_t *addrlen) {
    long long tbytes = 0; // total number of transfered bytes
    char addrstr[IS_ADDR_STR_LEN];

    errMsg(LOG_INFO, "Connection from %s", inetAddressStr(claddr, *addrlen,
            addrstr, IS_ADDR_STR_LEN));

    // sync-init, return value is number of files
    int32_t nfiles;
    nfiles = syncInit(cfd, &tbytes);
    if (nfiles == -1)
        return -1;
    
    errMsg(LOG_INFO, "Number of files to synchronize: %d", nfiles);
    // outer loop: files, inner loop: chunks
    for (int i = 0; i < nfiles; i++) {
        FileChunk *chunk;
        int fd = -1;

        // we are guaranteed to get at least one chunk for each file
        chunk = (FileChunk *) recvMessage(cfd, FileChunkType, &tbytes);
        if (chunk == NULL) {
            errMsg(LOG_ERR, "Could not read message from client.");
            return -1;
        }

        for (;;) {
            for (int k = 0; k < chunk->n_ops; k++) {
                // TODO
                // in case of a failure inform client to do an rsync based sync
                handleGenericOperation(&fd, chunk->relative_path, chunk->ops[k]);
            }

            if (chunk->last_chunk == 1) {
                file_chunk__free_unpacked(chunk, NULL);
                break;
            } else {
                file_chunk__free_unpacked(chunk, NULL);
                chunk = (FileChunk *) recvMessage(cfd, FileChunkType, &tbytes);
                if (chunk == NULL) {
                    errMsg(LOG_ERR, "Could not read message from client.");
                    return -1;
                }
            }
        }

        if (fd != -1) {
            if (close(fd) == -1)
                errMsg(LOG_WARNING, "Could not close file.");
        }

    }

    errMsg(LOG_INFO, "Received bytes: %lld", tbytes);

    // transfer was successful, we can delete snapshot (created in syncInit())
    if (deleteSnapshot(config.snapshot) == -1) {
        errMsg(LOG_ERR, "Could not delete snapshot %s", config.snapshot);
        close(cfd);
        return -1;
    }

    // rename resource.syncid to resource.syncid.last
    char lastsyncidpath[PATH_MAX];
    char syncidpath[PATH_MAX];
    snprintf(lastsyncidpath, PATH_MAX, "%s/%s.syncid.last", config.logdir,
            config.resource);
    snprintf(syncidpath, PATH_MAX, "%s/%s.syncid", config.logdir,
            config.resource);

    if (rename(syncidpath, lastsyncidpath) == -1) {
        errnoMsg(LOG_CRIT, "Could not rename sync-id file to sync-id.last.");
        close(cfd);
        return -1;
    }

    // and finally send confirmation to client
    SyncFinish conf = SYNC_FINISH__INIT;
    conf.has_transferred_bytes = 1;
    conf.transferred_bytes = (uint64_t) tbytes;
    if (sendMessage(cfd, SyncFinishType, &conf) != 0) {
        close(cfd);
        return -1;
    }

    if (close(cfd) == -1)
        errMsg(LOG_WARNING, "Could not close socket.");
    
    return 0;
}
Exemplo n.º 27
0
int syncInit(int cfd, long long *tbytes) {
    char errmsg[ERRMSG_MAX] = {0};
    SyncInit *syncinit;
    SyncInitResponse response = SYNC_INIT_RESPONSE__INIT;

    syncinit = (SyncInit *) recvMessage(cfd, SyncInitType, tbytes);
    if (syncinit == NULL) {
        errMsg(LOG_ERR, "Could not read initialization message from client.");
        return -1;
    }

    // initial checks
    // check resource (must match)
    if (strcmp(syncinit->resource, config.resource) != 0) {
        snprintf(errmsg, ERRMSG_MAX, "Received resource %s does not match."
                "local resource %s", syncinit->resource, config.resource);
        response.continue_ = 0;
        response.error_message = errmsg;
        sendMessage(cfd, SyncInitResponseType, &response);
        return -1;
    }

    // check sync-id
    char lastsyncid[SYNCID_MAX];
    char lastsyncidpath[PATH_MAX];
    char syncid[SYNCID_MAX];
    char syncidpath[PATH_MAX];

    // if we receive syncid, we already marked as successfully done
    // only sending confirmation has failed last time
    snprintf(lastsyncidpath, PATH_MAX, "%s/%s.syncid.last", config.logdir,
            config.resource);
    if (fileExists(lastsyncidpath) &&
            (readSyncId(lastsyncid, lastsyncidpath, SYNCID_MAX) == 0)) {
        if (lastsyncid == syncinit->sync_id) {
            // send the confirmation, don't sync
            response.continue_ = 0;
            response.has_already_synced = 1;
            response.already_synced = 1;
            sendMessage(cfd, SyncInitResponseType, &response);
            return 0; // no files to be synchronized
        }
    }

    int errflag = 0;
    // if we can read syncid file, last sync did not finish properly
    // revert snapshot
    snprintf(syncidpath, PATH_MAX, "%s/%s.syncid", config.logdir,
            config.resource);
    if (fileExists(syncidpath) &&
            (readSyncId(syncid, syncidpath, SYNCID_MAX) == 0)) {
        if (syncid == syncinit->sync_id) {
            // TODO: here we should support resume
        }

        // revert last snapshot, check for its existence is necessary, but
        // is done nevertheless
        if (fileExists(config.snapshot) == 1) {
            // do as one block, this should not fail, if yes, we are in trouble
            errMsg(LOG_INFO, "Reverting snapshot.");
            int ret = 0;

            ret = deleteSnapshot(config.rootdir);
            ret |= createSnapshot(config.snapshot, config.rootdir, 0);
            ret |= deleteSnapshot(config.snapshot);

            if (ret != 0) {
                errflag = 1;
                snprintf(errmsg, ERRMSG_MAX, "Reverting to last snapshot"
                        "has failed.");
            }
        }
    }

    // create snapshot
    // snapshot might exists (if last time program crash before sync-id was
    // written or before it was deleted), but in this case we don't need to
    // revert it
    if (!errflag && fileExists(config.snapshot)) {
        errMsg(LOG_INFO, "Snapshot %s unexpectedly exists, deleting.",
                config.snapshot);
        if (deleteSnapshot(config.snapshot) == -1) {
            errMsg(LOG_ERR, "Could not delete snapshot %s", config.snapshot);
            errflag = 1;
        }
    }
    if (!errflag &&
            (createSnapshot(config.rootdir, config.snapshot, 1) != 0)) {
        errMsg(LOG_ERR, "Could not create snapshot %s", config.snapshot);
        errflag = 1;
    }

    // write syncid
    if (!errflag && (writeSyncId(syncinit->sync_id, syncidpath) != 0)) {
        errMsg(LOG_ERR, "Could not write sync-id. Stopping.");
        errflag = 1;
    }

    // send response
    int ret;
    if (errflag) {
        response.continue_ = 0;
        snprintf(errmsg, ERRMSG_MAX, "Error in snapshot operation.");
        response.error_message = errmsg;
        ret = -1;
    } else {
        response.continue_ = 1;
        ret = syncinit->number_files;
    }
    sync_init__free_unpacked(syncinit, NULL);

    if (sendMessage(cfd, SyncInitResponseType, &response) == 0)
        return ret;
    else
        return -1;
}
Exemplo n.º 28
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //ui->chatTextBox->setEnabled(false);
    ui->sendTextBox->setEnabled(false);
    ui->sendPushButton->setEnabled(false);

    ui->chatTextBox->setReadOnly(true);

    connect(ui->joinPushButton, SIGNAL(clicked()), this, SLOT(joinChat()));
    connect(ui->sendPushButton, SIGNAL(clicked()), this, SLOT(sendMessage()));
    connect(&timer, SIGNAL(timeout()), this, SLOT(recvMessage()));

    /*Fill in remote sockaddr_in */
    bzero(&remoteAddress, sizeof(remoteAddress));
    remoteAddress.sin_family = PF_INET;
    remoteAddress.sin_port = htons(PORT);
    remoteAddress.sin_addr.s_addr = inet_addr("226.0.0.1");

    /*Fill in server's sockaddr_in */
    bzero(&serverAddress, sizeof(serverAddress));
    serverAddress.sin_family = PF_INET;
    serverAddress.sin_port = htons(PORT);
    serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);


    bzero(&iaddr, sizeof(iaddr));
    iaddr.s_addr = INADDR_ANY; // use DEFAULT interface

    /* for multicast */
    imreq.imr_multiaddr.s_addr = inet_addr("226.0.0.1");
    imreq.imr_interface.s_addr = INADDR_ANY; // use DEFAULT interface

    sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sockfd == -1)
        QMessageBox::information(this, "Error: socket", strerror(errno), QMessageBox::Ok);

    int broadcastOn = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcastOn, 4) == -1)
        QMessageBox::information(this, "Error: setsockopt", strerror(errno), QMessageBox::Ok);

    if (bind(sockfd, (struct sockaddr* ) &serverAddress, sizeof(serverAddress)) == -1)
        QMessageBox::information(this, "Error: bind", strerror(errno), QMessageBox::Ok);

    /* Join multicast group */
    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&imreq, sizeof(struct ip_mreq)))
        QMessageBox::information(this, "Error: setsockopt", strerror(errno), QMessageBox::Ok);

    /* Set the outgoing interface to default interface */
    if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_IF, &iaddr, sizeof(struct in_addr)))
        QMessageBox::information(this, "Error: setsockopt", strerror(errno), QMessageBox::Ok);

    unsigned char ttl = 3;
    /* Set multicast packet TTL to 3; default TTL is 1 */
    if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(unsigned char)))
        QMessageBox::information(this, "Error: setsockopt", strerror(errno), QMessageBox::Ok);

    unsigned char one = 1;
    /* send multicast traffic to myself too */
    if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_LOOP, &one, sizeof(unsigned char)))
        QMessageBox::information(this, "Error: setsockopt", strerror(errno), QMessageBox::Ok);

    this->setFixedSize(this->size());
}
Exemplo n.º 29
0
void centralFailure(DISPATCH_PTR dispatch)
{
  dispatch->msg_class = FailureClass;
  recvMessage(dispatch, FailureClass, dispatch->classData);
}
Exemplo n.º 30
0
void centralSuccess(DISPATCH_PTR dispatch)
{
  dispatch->msg_class = SuccessClass;
  recvMessage(dispatch, SuccessClass, dispatch->classData);
}