Пример #1
0
//Continues to cgc_read into a buffer until '\n' is cgc_read in
// this is the problem
//inline should make this easier if needed since then we will remove
// a function boundary
//Question is whether the compiler will rearrange certain variables
// It looks okay when I inlined it in my test - but that does not
// necessarily mean that it is indeed good.
ssize_t readLine(int fd, char* buf, size_t len)
{
  char c = '\0';
  int ret = 0;
  size_t i = 0;
  size_t numRead;
  fd_set fdsToWait;
  size_t temp = len;
  struct timeval timeToWait;

  if (buf == NULL)
  {
    return (-EINVAL);
  }

  //wait in 1 second intervals
  timeToWait.tv_sec = 1;
  timeToWait.tv_usec = 0;

  //FD_ZERO is in libcgc.h, but just to make sure its not optimized, we will implement our own loop 
  for (i = 0; i < FD_SETSIZE / _NFDBITS; i++)
  {
    fdsToWait._fd_bits[i] = 0;  
  }

  //reset i to 0
  i = 0;

  //loop until the character is cgc_read
  do
  {
    FD_SET(fd, &fdsToWait);

    //wait forever to see if there is another character available
    ret = fdwait(1, &fdsToWait, NULL, &timeToWait, NULL);

    //check to see if there is an error
    if (ret != 0)
    {
      //according to the documentation we can have 4 errors, EBADF (which is what we are looking for)
      // EINVAL, EFAULT should not be possible since they have to do with incorrect parameters
      // and ENOMEM which is possible. At any rate, if this happens, we will just return errno
      return (-ret);
    }

    ret = receive(fd, &c, sizeof(char), &numRead);
    if ( (ret != 0) )
    {
      //since receive also returns errno, we can just pass it back
      return (-ret); 
    }
    if ( numRead == 0 ) //if EOF
    {
      return (-EPIPE);
    }

    if (numRead != sizeof(char)) 
    {
      //try again
      continue;
    }

    buf[i] = c; 
    i++;
    if (i >= temp)
    {
      i = temp - 1;
    }
  } while ( c != '\n');
 
  buf[i] = '\0';

  return (i);
}
Пример #2
0
Файл: main.c Проект: TolikT/pa3
int main(int argc, char *argv[]){
	
	// create an IO structure
	IO *inout = (IO*)malloc(sizeof(IO));
	
	// number of child processes from command line to numOfChildren variable
	int opt;	
	while ( (opt = getopt(argc,argv,"p:")) != -1){
		switch (opt){
		case 'p': 
			inout -> numOfChildren = atoi(optarg);
			break;
		default:
			free(inout); 
			return -1;		
        	}
	}

	inout -> id = PARENT_ID;
	
	// create or open logs for writing
	FILE *pipesLog = fopen(pipes_log, "w+");
	FILE *eventsLog = fopen(events_log, "w+");
	
	// create pipes and fill the inout.pipes  
	for (int i = 0; i < inout -> numOfChildren + 1; i++){
		for (int j = 0; j < inout -> numOfChildren + 1; j++){
			if  (i != j){
				Pipe *pipeMem = (Pipe*)malloc(sizeof(Pipe));
				int pipefd[2];
				pipe(pipefd);
				fcntl(pipefd[0], F_SETFL, O_NONBLOCK);
				fcntl(pipefd[1], F_SETFL, O_NONBLOCK);
				pipeMem -> in = pipefd[0];
				pipeMem -> out = pipefd[1];
				inout -> pipes[i][j] = pipeMem;
				fprintf(pipesLog, log_opened_fmt, pipefd[0], pipefd[1]);
				fflush(pipesLog);
				printf(log_opened_fmt, pipefd[0], pipefd[1]);
			}
		}	
	}	
	
	Message *msgReceive = (Message*)malloc(sizeof(Message));
	BalanceHistory *balanceHistory = (BalanceHistory*)malloc(sizeof(BalanceHistory));
	AllHistory *allHistory = (AllHistory*)malloc(sizeof(AllHistory));

	// create children
	for (int id = 1; id < inout -> numOfChildren + 1; id++){
		switch(fork()){
			case -1:
				perror("fork");
				exit(EXIT_FAILURE);
			case 0:
				lamport_process_init();
				fprintf(eventsLog, log_started_fmt, get_lamport_time(), id, getpid(), getppid(), atoi(argv[optind+id-1]));
				fflush(eventsLog);
				printf(log_started_fmt, get_lamport_time(), id, getpid(), getppid(), atoi(argv[optind+id-1]));
				timestamp_t after;
				balanceHistory -> s_id = id;
				balanceHistory -> s_history_len = 1;
				balanceHistory -> s_history[0].s_balance = atoi(argv[optind+id-1]);
				balanceHistory -> s_history[0].s_time = get_lamport_time();
				balanceHistory -> s_history[0].s_balance_pending_in = 0;
				
				inout -> id = id;
				
				// close unused pipes
				for (int i = 0; i < inout -> numOfChildren + 1; i++){
					for (int j = 0; j < inout -> numOfChildren + 1; j++){					
						if (i != j){
							if (i != inout -> id && j != inout -> id){
								close(inout -> pipes[i][j] -> in);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								close(inout -> pipes[i][j] -> out);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
							}
							if (i == inout -> id){
								close(inout -> pipes[i][j] -> in);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
							}
							if (j == inout -> id){
								close(inout -> pipes[i][j] -> out);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
							}
							
						}
					
					}
				}
				
				// update localTime 
				lamport_before_send();

				// fill the STARTED message								
				Message *msg = (Message*)malloc(sizeof(Message));
				sprintf(msg -> s_payload, log_started_fmt, get_lamport_time(), id, getpid(), getppid(), balanceHistory -> s_history[balanceHistory -> s_history_len].s_balance);
				msg -> s_header.s_magic = MESSAGE_MAGIC;
				msg -> s_header.s_payload_len = strlen(msg -> s_payload)+1;
				msg -> s_header.s_type = STARTED;
				msg -> s_header.s_local_time = get_lamport_time();

				// send STARTED message to other processes
				send_multicast(inout, msg);

				// receive STARTED message from other processes
				for (int i = 1; i < inout -> numOfChildren + 1; i++){
					if (i != inout -> id){					
						do{
							while (receive(inout, i, msgReceive) == -1)
								usleep(1000);
							// update localTime
							lamport_after_receive(&msgReceive -> s_header);
						} while (msgReceive -> s_header.s_type != STARTED);
					}
				}

				// logs
				fprintf(eventsLog, log_received_all_started_fmt, get_lamport_time(), inout -> id);
				fflush(eventsLog);
				printf(log_received_all_started_fmt, get_lamport_time(), inout -> id);
				
				// useful work
				while(1){
					int src = receive_any(inout, msgReceive);

					// update localTime
					lamport_after_receive(&msgReceive -> s_header);

					if (msgReceive -> s_header.s_type==STOP) break;
					printf("%d RECEIVE FROM %d TYPE %d\n", inout ->id, src, msgReceive -> s_header.s_type);
					TransferOrder *transferOrder;
					switch(msgReceive -> s_header.s_type){
						case TRANSFER:
							transferOrder =  (TransferOrder*)msgReceive -> s_payload;
							if (src == 0){
								after = get_lamport_time()+1;
								for (int i = balanceHistory -> s_history_len; i <= after; i++){
									balanceHistory -> s_history[i] = balanceHistory -> s_history[i-1];
									balanceHistory -> s_history[i].s_time = balanceHistory -> s_history[i-1].s_time+1;								
									balanceHistory -> s_history[i].s_balance_pending_in = 0;	
									balanceHistory -> s_history_len ++;
								}								
								balanceHistory -> s_history[after].s_balance -= transferOrder -> s_amount;							
								balanceHistory -> s_history[after].s_balance_pending_in = transferOrder -> s_amount;							
								
								// update localTime 
								lamport_before_send();
								msgReceive -> s_header.s_local_time = get_lamport_time();
								send(inout, transferOrder -> s_dst, msgReceive);
								fprintf(eventsLog, log_transfer_out_fmt, get_lamport_time(), inout -> id, transferOrder -> s_amount, transferOrder -> s_dst);
								fflush(eventsLog);
								printf(log_transfer_out_fmt, get_lamport_time(), inout -> id, transferOrder -> s_amount, transferOrder -> s_dst);								
							}
							if (src > 0){
								after = get_lamport_time();
								for (int i = balanceHistory -> s_history_len; i<=after; i++){
									balanceHistory -> s_history[i] = balanceHistory -> s_history[i-1];
									balanceHistory -> s_history[i].s_time=balanceHistory -> s_history[i-1].s_time+1;								
									balanceHistory -> s_history[i].s_balance_pending_in = 0;
									balanceHistory -> s_history_len ++;	
								}								
								balanceHistory -> s_history[after].s_balance += transferOrder -> s_amount;
								balanceHistory -> s_history[after].s_balance_pending_in = 0;

								// update localTime 
								lamport_before_send();

								msg -> s_header.s_magic = MESSAGE_MAGIC;
								msg -> s_header.s_payload_len = 0;
								msg -> s_header.s_type = ACK;
								msg -> s_header.s_local_time = get_lamport_time();
								send(inout, PARENT_ID, msg);
								fprintf(eventsLog, log_transfer_in_fmt, get_lamport_time(), inout -> id, transferOrder -> s_amount, transferOrder -> s_dst);
								fflush(eventsLog);
								printf(log_transfer_in_fmt, get_lamport_time(), inout -> id, transferOrder -> s_amount, transferOrder -> s_src);								
							}						
					}
				}

				// update localTime 
				lamport_before_send();

				// fill the DONE message
				sprintf(msg -> s_payload, log_done_fmt, get_lamport_time(), inout -> id, balanceHistory -> s_history[balanceHistory -> s_history_len-1].s_balance);
				msg -> s_header.s_magic = MESSAGE_MAGIC;
				msg -> s_header.s_payload_len = strlen(msg -> s_payload)+1;
				msg -> s_header.s_type = DONE;
				msg -> s_header.s_local_time = get_lamport_time();

				// send DONE message to other processes
				send_multicast(inout, msg);

				// receive DONE message from other processes
				for (int i = 1; i < inout -> numOfChildren + 1; i++){
					if (i != inout -> id){					
						do{
							while (receive(inout, i, msgReceive) == -1)
								usleep(1000);
							// update localTime
							lamport_after_receive(&msgReceive -> s_header);
						} while (msgReceive -> s_header.s_type != DONE);
					}
				}				

				// logs
				fprintf(eventsLog, log_received_all_done_fmt, get_lamport_time(), inout -> id);
				fflush(eventsLog);
				printf(log_received_all_done_fmt, get_lamport_time(), inout -> id);

				// update localTime 
				lamport_before_send();
				
				// fill the BALANCE_HISTORY message
				msg -> s_header.s_magic = MESSAGE_MAGIC;
				msg -> s_header.s_payload_len = sizeof(BalanceHistory);
				msg -> s_header.s_type = BALANCE_HISTORY;
				msg -> s_header.s_local_time = get_lamport_time();

							
				if (msg -> s_header.s_local_time > after){
					for (int i = balanceHistory -> s_history_len; i<=msg -> s_header.s_local_time; i++){
						balanceHistory -> s_history[i] = balanceHistory -> s_history[i-1];
						balanceHistory -> s_history[i].s_time=balanceHistory -> s_history[i-1].s_time+1;
						balanceHistory -> s_history[i].s_balance_pending_in = 0;
						balanceHistory -> s_history_len ++;
					}
				}

				memcpy(msg -> s_payload, balanceHistory, msg -> s_header.s_payload_len);
			

				// send the BALANCE_HISTORY to each child	
				send(inout, PARENT_ID, msg);
				
				// close all other pipes 
				for (int i = 0; i < inout -> numOfChildren + 1; i++){
					for (int j = 0; j < inout -> numOfChildren + 1; j++){					
						if (i != j){
							if (i == inout -> id){
 								close(inout -> pipes[i][j] -> out);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
							}
							if (j == inout -> id){
 								close(inout -> pipes[i][j] -> in);
								fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								fflush(pipesLog);
								printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
								
							}
						}
					}
				}
				
				for (int i = 0; i < inout -> numOfChildren + 1; i++){
					for (int j = 0; j < inout -> numOfChildren + 1; j++){					
						if (i != j) free(inout -> pipes[i][j]);
 					}						
				}
				free(msg);

				fprintf(eventsLog, log_done_fmt, get_lamport_time(), inout -> id, balanceHistory -> s_history[balanceHistory -> s_history_len-1].s_balance);
				fflush(eventsLog);
				printf(log_done_fmt, get_lamport_time(), inout -> id, balanceHistory ->s_history[balanceHistory -> s_history_len-1].s_balance);
				return 0;
			default:
				break;				
		}
	}
	
	for (int i = 0; i < inout -> numOfChildren + 1; i++){
		for (int j = 0; j < inout -> numOfChildren + 1; j++){					
			if (i != j){
				if (i != PARENT_ID && j != PARENT_ID){
 					close(inout -> pipes[i][j] -> in);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
					close(inout -> pipes[i][j] -> out);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
				}
				if (i == PARENT_ID){
					close(inout -> pipes[i][j] -> in);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
				}
				if (j == PARENT_ID){
					close(inout -> pipes[i][j] -> out);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
				}
			}
		}
	}

	for (int i = 1; i < inout -> numOfChildren + 1; i++){
		if (i != inout -> id){		
			do{
				while (receive(inout, i, msgReceive) == -1)
					usleep(1000);
				// update localTime
				lamport_after_receive(&msgReceive -> s_header);
				
			} while (msgReceive -> s_header.s_type != STARTED);
		}
	}

	fprintf(eventsLog, log_received_all_started_fmt, get_lamport_time(), inout -> id);
	fflush(eventsLog);
	printf(log_received_all_started_fmt, get_lamport_time(), inout -> id);
	
	// for pa2
	bank_robbery(inout, inout -> numOfChildren);
	
	Message *msg = (Message*)malloc(sizeof(Message));
	
	// update localTime 
	lamport_before_send();

	// fill the STOP message
	msg -> s_header.s_magic = MESSAGE_MAGIC;
	msg -> s_header.s_payload_len = 0;
	msg -> s_header.s_type = STOP;
	msg -> s_header.s_local_time = get_lamport_time();

	// send the STOP to each child	
	send_multicast(inout, msg);
	
	// receive all DONE messages
	for (int i = 1; i < inout -> numOfChildren + 1; i++){
		do{
			while (receive(inout, i, msgReceive) == -1)
				usleep(1000);
			// update localTime
			lamport_after_receive(&msgReceive -> s_header);

		} while (msgReceive -> s_header.s_type != DONE);
	}

	//logs
	fprintf(eventsLog, log_received_all_done_fmt, get_lamport_time(), inout -> id);
	fflush(eventsLog);
	printf(log_received_all_done_fmt, get_lamport_time(), inout -> id);
	
	// receive all BALANCE_HISTORY messages and fill AllHistory
	allHistory -> s_history_len = inout -> numOfChildren;
	for (int i = 1; i < inout -> numOfChildren + 1; i++){
		do{
			while (receive(inout, i, msgReceive) == -1)
				usleep(1000);
			// update localTime
			lamport_after_receive(&msgReceive -> s_header);
		} while (msgReceive -> s_header.s_type != BALANCE_HISTORY);		
		
		memcpy(&allHistory -> s_history[i-1], msgReceive -> s_payload, sizeof(BalanceHistory));
	}
	
	for (int i = 0; i < inout -> numOfChildren + 1; i++){
		for (int j = 0; j < inout -> numOfChildren + 1; j++){					
			if (i != j){
				if (i == PARENT_ID){
 					close(inout -> pipes[i][j] -> out);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> out, inout -> id);
				}
				if (j == PARENT_ID){
 					close(inout -> pipes[i][j] -> in);
					fprintf(pipesLog, log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
					fflush(pipesLog);
					printf(log_closed_fmt, inout -> pipes[i][j] -> in, inout -> id);
				}
			}
		}
	}
	for (int i = 0; i < inout -> numOfChildren; i++)
		wait(NULL);
	for (int i = 0; i< inout -> numOfChildren; i++){
		for (int j = 0; j<=allHistory -> s_history[i].s_history_len; j++){
			printf("N: %d process: %d balance: %d time: %d\n", j, allHistory -> s_history[i].s_id, allHistory -> s_history[i].s_history[j].s_balance, allHistory -> s_history[i].s_history[j].s_time);		
		}
	}
	print_history(allHistory);
	free(inout);
	free(msg);
	free(msgReceive);
	free(balanceHistory);
	free(allHistory);
	fclose(pipesLog);
	fclose(eventsLog);	
	return 0;
}
Пример #3
0
/*!
 \brief

 \fn CProtocolCDT::ProcessResponse
 \param response_
*/
void CProtocolCDT::ProcessResponse(CCDTResponse &response_)
{
    QByteArray receive((char *)response_.GetBuffer(0),response_.GetInfoSize());
//    receive.toHex().toUpper().count();
    QString frame = receive.toHex().toUpper();
    int nCount = frame.count();
    for (int i=0,j=0; i < nCount; i+=12,++j)
    {
        frame.insert(i+j,' ');
    }
    ShowMessage(SHOWMESSAGE_TYPE_RECEIVE,frame);
    if(response_.GetBit(6,7))
    {
        ProcessFrameExtend(response_);//处理扩展帧
        return ;
    }
    BYTE nInfoWord=response_.GetWordOfInfo();

    BYTE nSrcStationAddress = response_.GetUIntValue(9,1);
    CBaseFrame  frameInfoWord;//一个信息字
    for(int i=0;i<nInfoWord;i++)
    {
        frameInfoWord.RefBuffer(response_.GetBuffer(12+i*6),6);
        BYTE nFunctionCode=frameInfoWord[0];//功能码
        BYTE nLittle = 0x0;
        BYTE nBig    = 0x7f;
//        if ( (((BYTE)0x0) <= nFunctionCode) && (nFunctionCode <= ((BYTE)0x7f)) )//遥测信息字
//            ProcessRMInfoWord(frameInfoWord,nSrcStationAddress);
        if ( (nLittle <= nFunctionCode) && (nFunctionCode <= nBig) )//遥测信息字
        ProcessRMInfoWord(frameInfoWord,nSrcStationAddress);

        if ((0x86 <=nFunctionCode)&&(nFunctionCode <=0x89))//总加遥测
            ProcessTMInfoWord(frameInfoWord,nSrcStationAddress);

        nLittle = 0xf0;
        nBig    = 0xff;
//        if ( (0xf0 <=nFunctionCode) && (nFunctionCode <=0xff) )//遥信信息字
//            ProcessRSInfoWord(frameInfoWord,nSrcStationAddress);
        if ( (nLittle <=nFunctionCode) && (nFunctionCode <=nBig) )//遥信信息字
            ProcessRSInfoWord(frameInfoWord,nSrcStationAddress);


        if ((0xa0 <=nFunctionCode)&&(nFunctionCode <=0xdf))//电能脉冲计数值
            ProcessRPInfoWord(frameInfoWord,nSrcStationAddress);


        if  ((0x8d <= nFunctionCode)&&(nFunctionCode <=0x92))//水位信息
            ProcessWLInfoWord(frameInfoWord,nSrcStationAddress);


        if  (nFunctionCode == 0x8a)//频率信息
            ProcessFrequencyInfoWord(frameInfoWord,nSrcStationAddress);


        if (nFunctionCode ==  0x80 )//事件顺序记录信息//&& frameInfoWord[6]==  0x81
        {
            frameInfoWord.SetData(response_.GetBuffer(12+i*6),12);
            Q_ASSERT(frameInfoWord[6] == 0x81);
            i++;//soe为双信息字
            ProcessSoeInfoWord(frameInfoWord,nSrcStationAddress);
        }

        if(nFunctionCode == 0x84)//时钟怊唤返回//&& frameInfoWord[6]==  0x85
        {
            frameInfoWord.SetData(response_.GetBuffer(12+i*6),12);
            Q_ASSERT(frameInfoWord[6] == 0x85);
            i++;//时钟返回为双信息字
            ProcessTimeBackInfoWord(frameInfoWord,nSrcStationAddress);
        }

        if (nFunctionCode ==  0xec)//子站工作状态信息字
            ProcessSTInfoWord(frameInfoWord,nSrcStationAddress);

        if(nFunctionCode ==  0xe1 || nFunctionCode == 0xe5)//遥控、遥调返校
            ProcessRRInfoWord(frameInfoWord,nSrcStationAddress);
    }
}
Пример #4
0
  TEST(Routing, callbacks)
  {
    zmq::context_t context(1);
    zmq::socket_t alphaSocket(context, ZMQ_PAIR);
    zmq::socket_t betaSocket(context, ZMQ_PAIR);
    std::unique_ptr<zmq::socket_t> alphaSocketRouter(new zmq::socket_t(context, ZMQ_PAIR));
    std::unique_ptr<zmq::socket_t> betaSocketRouter(new zmq::socket_t(context, ZMQ_PAIR));
    alphaSocket.bind("tcp://*:5555");
    betaSocket.bind("tcp://*:5556");
    alphaSocketRouter->connect("tcp://localhost:5555");
    betaSocketRouter->connect("tcp://localhost:5556");

    SocketRouter router;

    router.add_socket(SocketID::ALPHA, alphaSocketRouter);
    router.add_socket(SocketID::BETA, betaSocketRouter);

    Message hello(HELLO);
    Message heartbeat(HEARTBEAT);
    Message problemspec(PROBLEMSPEC);
    Message jobrequest(JOBREQUEST);
    Message job(JOB);
    Message jobswap(JOBSWAP);
    Message alldone(ALLDONE);
    Message goodbye(GOODBYE);

    auto fwdToBeta = [&] (const Message&m)
    { router.send(SocketID::BETA, m);};
    // Bind functionality to the router
    router(SocketID::ALPHA).onRcvHELLO.connect(fwdToBeta);
    router(SocketID::ALPHA).onRcvHEARTBEAT.connect(fwdToBeta);
    router(SocketID::ALPHA).onRcvPROBLEMSPEC.connect(fwdToBeta);
    router(SocketID::ALPHA).onRcvJOBREQUEST.connect(fwdToBeta);
    router(SocketID::ALPHA).onRcvJOB.connect(fwdToBeta);
    router(SocketID::ALPHA).onRcvJOBSWAP.connect(fwdToBeta);
    router(SocketID::ALPHA).onRcvALLDONE.connect(fwdToBeta);
    router(SocketID::ALPHA).onRcvGOODBYE.connect(fwdToBeta);

    router.start(10);//ms per poll
    send(alphaSocket, hello);
    Message rhello = receive(betaSocket);
    send(alphaSocket, heartbeat);
    Message rheartbeat = receive(betaSocket);
    send(alphaSocket, problemspec);
    Message rproblemspec = receive(betaSocket);
    send(alphaSocket, jobrequest);
    Message rjobrequest = receive(betaSocket);
    send(alphaSocket, job);
    Message rjob = receive(betaSocket);
    send(alphaSocket, jobswap);
    Message rjobswap = receive(betaSocket);
    send(alphaSocket, alldone);
    Message ralldone = receive(betaSocket);
    send(alphaSocket, goodbye);
    Message rgoodbye = receive(betaSocket);

    router.stop();
    ASSERT_EQ(hello, rhello);
    ASSERT_EQ(heartbeat, rheartbeat);
    ASSERT_EQ(problemspec, rproblemspec);
    ASSERT_EQ(jobrequest, rjobrequest);
    ASSERT_EQ(job, rjob);
    ASSERT_EQ(jobswap, rjobswap);
    ASSERT_EQ(alldone, ralldone);
    ASSERT_EQ(goodbye, rgoodbye);
  }
Пример #5
0
void CUnixSocket::threadFunc()
{
   LOG4CPLUS_TRACE(logger, "CUnixSocket::threadFunc() this = "
                          + convertIntegerToString((intptr_t)this));
   UInt32 size = 0;

   assert(mpSubscriber);

   if (mIncomingListen)
   {
      assert(mSock != -1);

      while (!getStopFlag())
      {
         int newSock = accept(mSock, NULL, NULL);
         assert(newSock != -1);
         LOG4CPLUS_INFO(logger, "CUnixSocket::threadFunc() new socket accepted this = "
                               + convertIntegerToString((intptr_t)this));
         mpSubscriber->onIncomingConnection(this, new CUnixSocket(false, mpSubscriber, newSock, mAskForReadiness));
         /*
         fd_set readfds;
         FD_ZERO(&readfds);
         FD_SET(mSock, &readfds);

         int ret = select(0, &readfds, NULL, NULL, &tv);
         if (ret > 0)
         {
            if (FD_ISSET(mSock, &readfds))
            {
               int newSock = accept(mSock, NULL, NULL);
               assert(newSock != -1);
               Log("CUnixSocket::threadFunc() new socket accepted this = %p", this);
               mpSubscriber->onIncomingConnection(this, new CUnixSocket(false, mpSubscriber, newSock));
            }
         }
         */
      }
   }
   else
   {
      ERROR_CODE err;
      bool canRecv = true;
      while (!getStopFlag())
      {
         if (mAskForReadiness)
         {
            err = receive(size, true);

            if (err == ERR_CONNECTION_LOST)
            {
               mpSubscriber->onConnectionLost(this);
               break;
            }
            else
            {
               mReceiveMutex.lock();

               if (size > 0)
               {
                  canRecv = mpSubscriber->isReadyToReceiveData(this, size);
                  if (!canRecv)
                     CThread::sleep(100);
               }
               else
                  canRecv = false;

               mReceiveMutex.unlock();
            }
         }

         if (canRecv)
         {
            if (receive(size) == ERR_CONNECTION_LOST)
            {
               mpSubscriber->onConnectionLost(this);
               break;
            }
            else if (!mDestroyed)
            {
               mReceiveMutex.lock();

               if (size > 0)
                  mpSubscriber->onReceive(this, mBuffer, size);

               mReceiveMutex.unlock();
            }
         }

      }
   }
}
Пример #6
0
process	shell (
    did32	dev		/* ID of tty device from which	*/
)				/*   to accept commands		*/
{
    char	buf[SHELL_BUFLEN];	/* Input line (large enough for	*/
    /*   one line from a tty device	*/
    int32	len;			/* Length of line read		*/
    char	tokbuf[SHELL_BUFLEN +	/* Buffer to hold a set of	*/
                   SHELL_MAXTOK];  /* Contiguous null-terminated	*/
    /* Strings of tokens		*/
    int32	tlen;			/* Current length of all data	*/
    /*   in array tokbuf		*/
    int32	tok[SHELL_MAXTOK];	/* Index of each token in	*/
    /*   array tokbuf		*/
    int32	toktyp[SHELL_MAXTOK];	/* Type of each token in tokbuf	*/
    int32	ntok;			/* Number of tokens on line	*/
    pid32	child;			/* Process ID of spawned child	*/
    bool8	backgnd;		/* Run command in background?	*/
    char	*outname, *inname;	/* Pointers to strings for file	*/
    /*   names that follow > and <	*/
    did32	stdinput, stdoutput;	/* Descriptors for redirected	*/
    /*   input and output		*/
    int32	i;			/* Index into array of tokens	*/
    int32	j;			/* Index into array of commands	*/
    int32	msg;			/* Message from receive() for	*/
    /*   child termination		*/
    int32	tmparg;			/* Address of this var is used	*/
    /*   when first creating child	*/
    /*   process, but is replaced	*/
    char	*src, *cmp;		/* Pointers used during name	*/
    /*   comparison			*/
    bool8	diff;			/* Was difference found during	*/
    /*   comparison			*/
    char	*args[SHELL_MAXTOK];	/* Argument vector passed to	*/
    /*   builtin commands		*/

    /* Print shell banner and startup message */

    fprintf(dev, "\n\n%s%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
            SHELL_BAN0,SHELL_BAN1,SHELL_BAN2,SHELL_BAN3,SHELL_BAN4,
            SHELL_BAN5,SHELL_BAN6,SHELL_BAN7,SHELL_BAN8,SHELL_BAN9);

    fprintf(dev, "%s\n\n", SHELL_STRTMSG);
    fprintf(dev, "%s\n\n", SHELL_AUTHOR);
    /* Continually prompt the user, read input, and execute command	*/

    while (TRUE) {

        /* Display prompt */

        fprintf(dev, SHELL_PROMPT);

        /* Read a command */

        len = read(dev, buf, sizeof(buf));

        /* Exit gracefully on end-of-file */

        if (len == EOF) {
            break;
        }

        /* If line contains only NEWLINE, go to next line */

        if (len <= 1) {
            continue;
        }

        buf[len] = SH_NEWLINE;	/* terminate line */

        /* Parse input line and divide into tokens */

        ntok = lexan(buf, len, tokbuf, &tlen, tok, toktyp);

        /* Handle parsing error */

        if (ntok == SYSERR) {
            fprintf(dev,"%s\n", SHELL_SYNERRMSG);
            continue;
        }

        /* If line is empty, go to next input line */

        if (ntok == 0) {
            fprintf(dev, "\n");
            continue;
        }

        /* If last token is '&', set background */

        if (toktyp[ntok-1] == SH_TOK_AMPER) {
            ntok-- ;
            tlen-= 2;
            backgnd = TRUE;
        } else {
            backgnd = FALSE;
        }


        /* Check for input/output redirection (default is none) */

        outname = inname = NULL;
        if ( (ntok >=3) && ( (toktyp[ntok-2] == SH_TOK_LESS)
                             ||(toktyp[ntok-2] == SH_TOK_GREATER))) {
            if (toktyp[ntok-1] != SH_TOK_OTHER) {
                fprintf(dev,"%s\n", SHELL_SYNERRMSG);
                continue;
            }
            if (toktyp[ntok-2] == SH_TOK_LESS) {
                inname =  &tokbuf[tok[ntok-1]];
            } else {
                outname = &tokbuf[tok[ntok-1]];
            }
            ntok -= 2;
            tlen = tok[ntok];
        }


        if ( (ntok >=3) && ( (toktyp[ntok-2] == SH_TOK_LESS)
                             ||(toktyp[ntok-2] == SH_TOK_GREATER))) {
            if (toktyp[ntok-1] != SH_TOK_OTHER) {
                fprintf(dev,"%s\n", SHELL_SYNERRMSG);
                continue;
            }
            if (toktyp[ntok-2] == SH_TOK_LESS) {
                if (inname != NULL) {
                    fprintf(dev,"%s\n", SHELL_SYNERRMSG);
                    continue;
                }
                inname = &tokbuf[tok[ntok-1]];
            } else {
                if (outname != NULL) {
                    fprintf(dev,"%s\n", SHELL_SYNERRMSG);
                    continue;
                }
                outname = &tokbuf[tok[ntok-1]];
            }
            ntok -= 2;
            tlen = tok[ntok];
        }

        /* Verify remaining tokens are type "other" */

        for (i=0; i<ntok; i++) {
            if (toktyp[i] != SH_TOK_OTHER) {
                break;
            }
        }
        if ((ntok == 0) || (i < ntok)) {
            fprintf(dev, SHELL_SYNERRMSG);
            continue;
        }

        stdinput = stdoutput = dev;

        /* Lookup first token in the command table */

        for (j = 0; j < ncmd; j++) {
            src = cmdtab[j].cname;
            cmp = tokbuf;
            diff = FALSE;
            while (*src != NULLCH) {
                if (*cmp != *src) {
                    diff = TRUE;
                    break;
                }
                src++;
                cmp++;
            }
            if (diff || (*cmp != NULLCH)) {
                continue;
            } else {
                break;
            }
        }

        /* Handle command not found */

        if (j >= ncmd) {
            fprintf(dev, "command %s not found\n", tokbuf);
            continue;
        }

        /* Handle built-in command */

        if (cmdtab[j].cbuiltin) { /* No background or redirect. */
            if (inname != NULL || outname != NULL || backgnd) {
                fprintf(dev, SHELL_BGERRMSG);
                continue;
            } else {
                /* Set up arg vector for call */

                for (i=0; i<ntok; i++) {
                    args[i] = &tokbuf[tok[i]];
                }

                /* Call builtin shell function */

                if ((*cmdtab[j].cfunc)(ntok, args)
                        == SHELL_EXIT) {
                    break;
                }
            }
            continue;
        }

        /* Open files and redirect I/O if specified */

        if (inname != NULL) {
            stdinput = open(NAMESPACE,inname,"ro");
            if (stdinput == SYSERR) {
                fprintf(dev, SHELL_INERRMSG, inname);
                continue;
            }
        }
        if (outname != NULL) {
            stdoutput = open(NAMESPACE,outname,"w");
            if (stdoutput == SYSERR) {
                fprintf(dev, SHELL_OUTERRMSG, outname);
                continue;
            } else {
                control(stdoutput, F_CTL_TRUNC, 0, 0);
            }
        }

        /* Spawn child thread for non-built-in commands */

        child = create(cmdtab[j].cfunc,
                       SHELL_CMDSTK, SHELL_CMDPRIO,
                       cmdtab[j].cname, 2, ntok, &tmparg);

        /* If creation or argument copy fails, report error */

        if ((child == SYSERR) ||
                (addargs(child, ntok, tok, tlen, tokbuf, &tmparg)
                 == SYSERR) ) {
            fprintf(dev, SHELL_CREATMSG);
            continue;
        }

        /* Set stdinput and stdoutput in child to redirect I/O */

        proctab[child].prdesc[0] = stdinput;
        proctab[child].prdesc[1] = stdoutput;

        msg = recvclr();
        resume(child);
        if (! backgnd) {
            msg = receive();
            while (msg != child) {
                msg = receive();
            }
        }
    }

    /* Terminate the shell process by returning from the top level */

    fprintf(dev,SHELL_EXITMSG);
    return OK;
}
Пример #7
0
void* Job::WorkThread(void* connect_fd){
	cout << "connect..." << endl;
	int conn_fd = *(int*) connect_fd;
	char buff[4096],utf8buff[4096];
	int n = recv(conn_fd, buff, 4096, 0);
	buff[n] = '\0';
	printf("recv msg from client: %s\n", buff);
	Utils util;
	util.gb2312toutf8(buff, n, utf8buff, 4096);
	printf("recv msg from client: %s\n", utf8buff);
	string receive(utf8buff);
	Json::Reader reader;
	Json::Value value;

	int object;
	if (reader.parse(receive, value)) {
		object = value["m_object"].asInt();
		cout<<"object="<<object<<endl;
	}

	switch(object)
	{
		case 0:{
			Facility fac;
			FacilityService fs;
			fac=fs.GetParasFRomJson(receive);
			if(fac.getOp()=="selectFacility"){
				string res=fs.SelectAll();
				send(conn_fd, res.c_str(), (unsigned int) strlen(res.c_str()), 0);
				cout<<"the selectFacility res is :"<<res<<endl;
			}else if(fac.getOp()=="selectSFacility"){
				string res=fs.SelectSignle(fac.getFacilityId());
				send(conn_fd, res.c_str(), (unsigned int) strlen(res.c_str()), 0);
					cout<<"the  selectSFacility res is :"<<res<<endl;
			}else if(fac.getOp()=="addFacility"){
				int res=fs.Add(fac);
				char buff[20];
				memset(buff,0,20);
				sprintf(buff,"%d",res);
				send(conn_fd, buff, 26, 0);
				cout<<"the  addFacility res is :"<<res<<endl;
			}else if(fac.getOp()=="deleteFacility"){
				int res=fs.DeleteSignle(fac.getFacilityId());
			}
		}
		break;
		case 1:
		{
			User user;
			UserService us;
			user=us.GetParasFRomJson(receive);
			if(user.getOp()==SELECT_ALL_USER){
				string res=us.SelectAll();
	cout<<"i'm in the Job res="<<res<<endl;
				send(conn_fd, res.c_str(), (unsigned int) strlen(res.c_str()), 0);
			}else if(user.getOp()==SELECT_SINGLE_USER){
				string res=us.SelectSignle(user.getId());
				send(conn_fd, res.c_str(), (unsigned int) strlen(res.c_str()), 0);
			}else if(user.getOp()==UPDATE_USER){
				if(us.Update(user)==0){
					send(conn_fd, "300", 26, 0);
				}else{
					send(conn_fd, "301", 26, 0);
				}
			}else if(user.getOp()==DELETE_USER){
				int res=us.DeleteSignle(user.getId());
				char buff[20];
				memset(buff,0,20);
				sprintf(buff,"%d",res);
				send(conn_fd, buff, 26, 0);
			}else if(user.getOp()==ADD_USER){
				int res=us.Add(user);
				char buff[20];
				memset(buff,0,20);
				sprintf(buff,"%d",res);
				send(conn_fd, buff, 26, 0);
			}
		}
			break;
        /*
         * 超级管理员:权限为1
         *
         */
		case 2:
		{
			AdminService as;
			Admin admin;
			string loginId;
			admin=as.GetParasFRomJson(receive);
			loginId =admin.getLoginId();  //拿到目前登录状态的管理员的id
			string info= "对不起,您不是超级管理员,没有权限!";

			if(admin.getOp()==LOGIN){
cout<<"i'm in the login, admin_id = "<<admin.getOp()<<endl;
				   char buff[20];
				   memset(buff,0,20);
				   int res = as.LoginSys(admin.getId(),admin.getPsd());
				   sprintf(buff,"%d",res);
				   send(conn_fd, buff,strlen(buff), 0);//重复
			}else if(admin.getOp()==ADD_ADMIN){
				if(loginId=="0001"){            //检查是否是超级管理员
					char buff[20];
					memset(buff,0,20);
					int res = as.addAdmin(admin);
					sprintf(buff,"%d",res);
					send(conn_fd,buff,strlen(buff), 0);
				}else{
					send(conn_fd,info.c_str(),strlen(info.c_str()),0);
				}

			}else if(admin.getOp()==DELETE_SINGLE_ADMIN){
				if(loginId=="0001"){            //检查是否是超级管理员
					char buff[20];
					memset(buff,0,20);
					int res = as.deleteSingleAdmin(admin.getId());
					sprintf(buff,"%d",res);
					send(conn_fd,buff,strlen(buff), 0);
				}else{
					send(conn_fd,info.c_str(),strlen(info.c_str()),0);
				}

			}else if(admin.getOp()==DELETE_ALL_ADMIN){
				if(loginId=="0001"){            //检查是否是超级管理员
					char buff[20];
					memset(buff,0,20);
					int res = as.deleteAllAdmin();
					sprintf(buff,"%d",res);
					send(conn_fd,buff,strlen(buff), 0);
				}else{
					send(conn_fd,info.c_str(),strlen(info.c_str()),0);
				}
			}else if(admin.getOp()==UPDATE_ADMIN){
				if(loginId=="0001"){            //检查是否是超级管理员
				char buff[20];
				memset(buff,0,20);
				int res = as.updateAdmin(admin);
				sprintf(buff,"%d",res);
				send(conn_fd,buff,strlen(buff), 0);
				}else{
					send(conn_fd,info.c_str(),strlen(info.c_str()),0);
				}

			}else if(admin.getOp()==SELECT_ALL_ADMIN){
				if(loginId=="0001"){            //检查是否是超级管理员
					string res = as.selectAllAdmin();
	cout<<"i'm in the Job admin ,res="<<res<<endl;
					send(conn_fd,res.c_str(),(unsigned int)strlen(res.c_str()),0);
				}else{
					send(conn_fd,info.c_str(),strlen(info.c_str()),0);
				}
			}else if(admin.getOp()==SELECT_SINGLE_ADMIN){
				if(loginId=="0001"){            //检查是否是超级管理员
					string res = as.selectSingleAdmin(admin.getId());
					send(conn_fd,res.c_str(),(unsigned int)strlen(res.c_str()),0);
				}else{
					send(conn_fd,info.c_str(),strlen(info.c_str()),0);
				}
			}
		}
		break;
	}
}
 // Retrieves the count of positive numbers that the agent received.
 size_t positives()
 {
    return receive(_positives);
 }
Пример #9
0
 void receive_loop(Args&&... args) {
     receive(std::forward<Args>(args)...);
 }
Пример #10
0
int
main(int argc, char **argv)
{
	struct sockaddr *sock;
	struct sockaddr_un ifsun;
	int fd, len, verbose, save_errno;
	unsigned TimeoutVal;
	struct sigaction act, oact;
	char *sockname = HONEYD_SOCK;
#ifdef HAVE_LIBEDIT
	EditLine *edit;
	History *hist;
	HistEvent hev = { 0, "" };
#endif
	const char *l;
	int ch;

	verbose = 0;
	TimeoutVal = 2;

	while ((ch = getopt(argc, argv, "t:v")) != -1) {
		switch (ch) {
		case 't':
			TimeoutVal = (unsigned)atoi(optarg);
			break;
    
		case 'v':
			verbose = REC_VERBOSE;
			break;
		default:
			usage();
		}
	}

        argc -= optind;
        argv += optind;

	if (argc > 0)
		sockname = argv[0];

	sock = (struct sockaddr *)&ifsun;
	
	memset(&ifsun, '\0', sizeof (ifsun));
#ifdef HAVE_SUN_LEN
	ifsun.sun_len = strlen(sockname);
	if (ifsun.sun_len > sizeof (ifsun.sun_path) - 1)
		errx(1, "%s: path too long", sockname);
#endif /* HAVE_SUN_LEN */

	ifsun.sun_family = AF_UNIX;
	strlcpy(ifsun.sun_path, sockname, sizeof(ifsun.sun_path));

	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
		errx(2, "cannot create local domain socket");

	TimedOut = 0;
	if (TimeoutVal) {
		act.sa_handler = Timeout;
		sigemptyset(&act.sa_mask);
		act.sa_flags = 0;
		sigaction(SIGALRM, &act, &oact);
		alarm(TimeoutVal);
	}

	if (connect(fd, sock, sizeof (ifsun)) == -1) {
		if (TimeoutVal) {
			save_errno = errno;
			alarm(0);
			sigaction(SIGALRM, &oact, 0);
			errno = save_errno;
		}
		if (TimedOut)
			warnx("timeout: cannot connect to socket %s",
			    sockname);
		else
			warn("cannot connect to socket %s", sockname);
		close(fd);
		return 3;
	}

	if (TimeoutVal) {
		alarm(0);
		sigaction(SIGALRM, &oact, 0);
	}

	/* Get Prompt ? */
	receive(fd, REC_SHOW);

#ifdef HAVE_LIBEDIT
	hist = history_init();
#  ifdef H_SETSIZE
	history(hist, &hev, H_SETSIZE, 20);
	edit = el_init("honeydctl", stdin, stdout, stderr);
#  else /* !H_SETSIZE */
	history(hist, H_EVENT, 20);
	edit = el_init("honeydctl", stdin, stdout);
#  endif

	el_source(edit, NULL);
	el_set(edit, EL_PROMPT, getprompt);
	el_set(edit, EL_EDITOR, "emacs");
	el_set(edit, EL_SIGNAL, 1);
	el_set(edit, EL_HIST, history, (const char *)hist);
#endif
	
#ifdef HAVE_LIBEDIT
	while ((l = smartgets(edit, &len, fd))) {
		if (len > 1)
#	ifdef H_SETSIZE
			history(hist, &hev, H_ENTER, l);
#	else
			history(hist, H_ENTER, l);
#	endif /* H_SETSIZE */
#else /* !HAVE_LIBEDIT */
	while ((l = smartgets(&len, fd))) {
		char line[128];
		if (len > 0) {
			add_history((char *)l);
			snprintf(line, sizeof(line), "%s\n", l);
			l = line;
			len++;
		}
#endif
		write(fd, l, len);
		if (receive(fd, REC_SHOW) != 0)
			break;
	}
	fprintf(stderr, "Connection closed\n");
#ifdef HAVE_LIBEDIT
	el_end(edit);
	history_end(hist);
#endif
	close(fd);
    
	return 0;
}
 // Retrieves the count of negative numbers that the agent received.
 size_t negatives() 
 {
    return receive(_negatives);
 }
Пример #12
0
void
QPythonPriv::receiveObject(PyObject *o)
{
    emit receive(convertPyObjectToQVariant(o));
}
Пример #13
0
int main(int argc, char** argv)
{
  pwr_tStatus sts;
  qcom_sGet get;
  net_sNotify* notify;
  net_sMessage* mp;
  gdb_sNode* np;
  qcom_sQid qid = qcom_cNQid;

  errh_Init("pwr_nacp", errh_eAnix_neth_acp);
  errh_SetStatus(PWR__SRVSTARTUP);

  init(&qid);
  errh_SetStatus(PWR__SRUN);

  for (;;) {
    mp = receive(&qid, &get);

    np = node(mp);
    if (np == NULL) {
      errh_Error("sender %u.%u, type %u.%u, size %u, reply %u.%u",
          get.sender.nid, get.sender.aix, get.type.b, get.type.s, get.size,
          get.reply.nid, get.reply.qix);
      continue;
    }

    switch ((int)get.type.s) {
    case net_eMsg_nodeUp:
      nodeUp((net_sNodeUp*)mp);
      break;
    case net_eMsg_createObject:
      gdb_ScopeLock
      {
        subc_ActivateList(&gdbroot->no_node->subc_lh, pwr_cNObjid);
      }
      gdb_ScopeUnlock;
      break;

    case net_eMsg_deleteObject:
      notify = (net_sNotify*)mp;
      gdb_ScopeLock
      {
        subc_ActivateList(&np->subc_lh, notify->oid);
      }
      gdb_ScopeUnlock;
      break;

    case net_eMsg_moveObject:
    case net_eMsg_renameObject:
      gdb_ScopeLock
      {
        subc_ActivateList(&np->subc_lh, pwr_cNObjid);
        subc_ActivateList(&gdbroot->no_node->subc_lh, pwr_cNObjid);
      }
      gdb_ScopeUnlock;
      break;

    default:
      errh_Error("Unexpected subtype %d received from %d.%d %X", get.type.s,
          get.reply.qix, get.reply.nid, get.pid);
    }

    qcom_Free(&sts, mp);
  }
}
Пример #14
0
	INSERT_ITERATOR receive(uint64_t len, INSERT_ITERATOR back) const {
		auto data = receive(len);

		return std::copy(std::begin(data), std::end(data), back);
	}
Пример #15
0
Client::Client()
{
    connect(&socket, SIGNAL(readyRead()), this, SLOT(receive()));
}
Пример #16
0
 void receive_while(Args&&... args) {
     receive(std::forward<Args>(args)...);
 }
Пример #17
0
int UDPReceive::receive( char *buffer, int len, double *ptime ) {
	return receive( buffer, len, "", ptime );
}
Пример #18
0
 void do_receive(Args&&... args) {
     receive(std::forward<Args>(args)...);
 }
Пример #19
0
int XC::DistributedBandGenLinSOE::recvSelf(const CommParameters &cp)
  {
    const int retval= receive(cp);
    return retval;
  }
Пример #20
0
static void trains_server(void) {
	register_as("trains");
	struct trainsrv_state state;

	trainsrv_state_init(&state);

	train_alert_start(switch_historical_get_current(&state.switch_history), true);

	// TODO: we should block the creating task from continuing until init is done

	for (;;) {
		int tid = -1;
		struct trains_request req;
		receive(&tid, &req, sizeof(req));

		/* printf("Trains server got message! %d"EOL, req.type); */
		switch (req.type) {
		case QUERY_ACTIVE: {
			int active_trains[MAX_ACTIVE_TRAINS];
			int num_active_trains = handle_query_active(&state, active_trains);
			reply(tid, &active_trains, num_active_trains * sizeof(active_trains[0]));
			break;
		}
		case QUERY_SPATIALS: {
			struct train_state ts = handle_query_spatials(&state, req.train_number);
			reply(tid, &ts, sizeof(ts));
			break;
		}
		case QUERY_ARRIVAL: {
			int ticks = handle_query_arrival(&state, req.train_number, req.distance);
			reply(tid, &ticks, sizeof(ticks));
			break;
		}
		case QUERY_ERROR: {
			int error = handle_query_error(&state, req.train_number);
			reply(tid, &error, sizeof(error));
			break;
		}
		case SEND_SENSORS:
			handle_sensors(&state, req.sensors);
			reply(tid, NULL, 0);
			break;
		case SET_SPEED:
			handle_set_speed(&state, req.train_number, req.speed);
			reply(tid, NULL, 0);
			break;
		case REVERSE:
			handle_reverse(&state, req.train_number);
			reply(tid, NULL, 0);
			break;
		case REVERSE_UNSAFE:
			handle_reverse_unsafe(&state, req.train_number);
			reply(tid, NULL, 0);
			break;
		case SWITCH_SWITCH:
			handle_switch(&state, req.switch_number, req.direction);
			reply(tid, NULL, 0);
			break;
		case SWITCH_GET: {
			struct switch_state switches = switch_historical_get_current(&state.switch_history);
			reply(tid, &switches, sizeof(switches));
			break;
		}
		case GET_STOPPING_DISTANCE: {
			struct internal_train_state *ts = get_train_state(&state, req.train_number);
			int distance = ts->est_stopping_distances[train_speed_index(ts, 1)];
			reply(tid, &distance, sizeof(distance));
			break;
		}
		case SET_STOPPING_DISTANCE: {
			struct internal_train_state *ts = get_train_state(&state, req.train_number);
			ts->est_stopping_distances[train_speed_index(ts, 1)] = req.stopping_distance;
			reply(tid, NULL, 0);
			break;
		}
		case GET_LAST_KNOWN_SENSOR: {
			struct internal_train_state *ts = get_train_state(&state, req.train_number);
			int last_sensor_hit = sensor_historical_get_current(&ts->sensor_history);
			reply(tid, &last_sensor_hit, sizeof(last_sensor_hit));
			break;
		}
		default:
			nameserver_dump_names();
			WTF("UNKNOWN TRAINS REQ %d FROM %d"EOL, req.type, tid);
			break;
		}
	}
}
int main(void) 
{
	
	Simple_Clk_Init();
	Power_Clk_Init();
	PortInit();
	UartInit();
	
	write("Hello World\r\n"); // Test the serial connection on startup
	
	//char array[i]; // declare a char array
	//char array[4] = {'1','8','9','7'}; 
	//write (array);
	
	Port *ports = PORT_INSTS; // Use port registers
	
	PortGroup *portAs = &(ports->Group[0]); //introduce port groups A
	PortGroup *portBs = &(ports->Group[1]); //introduce port groups B
	
	//set a direction; SET = output, CLR = input
	portAs ->DIRCLR.reg = PORT_PA16|PORT_PA17|PORT_PA18|PORT_PA19;	 // inputs
	portAs ->DIRSET.reg = PORT_PA04|PORT_PA05|PORT_PA06|PORT_PA07;   // outputs
	
	portBs->DIRSET.reg = PORT_PB00|PORT_PB01|PORT_PB02|PORT_PB03|PORT_PB04|PORT_PB05|PORT_PB06|PORT_PB07; //outputs
	
	//setting pull up and pull down resistors
	portAs ->PINCFG[16].reg = PORT_PINCFG_INEN|PORT_PINCFG_PULLEN;
	portAs ->PINCFG[17].reg = PORT_PINCFG_INEN|PORT_PINCFG_PULLEN;
	portAs ->PINCFG[18].reg = PORT_PINCFG_INEN|PORT_PINCFG_PULLEN;
	portAs ->PINCFG[19].reg = PORT_PINCFG_INEN|PORT_PINCFG_PULLEN;

	

	while(1)
	{
		    receive();
		
			portAs -> OUTSET.reg = PORT_PA04|PORT_PA05| PORT_PA06|PORT_PA07;
			switch (v)
			{
				case 0:
				ledDisplay(array[v]);
				portAs -> OUTCLR.reg = PORT_PA07;
				if (portAs ->IN.reg & PORT_PA19)
				{
					//character 1
					array[i] = '1';
					i++;
					while (portAs ->IN.reg & PORT_PA19);		
				}
				else if (portAs ->IN.reg & PORT_PA18)
				{
					array[i] = '2';
					i++;

					while (portAs ->IN.reg & PORT_PA18);
				}
				else if (portAs ->IN.reg & PORT_PA17)
				{
					array[i] = '3';
					i++;
					while (portAs ->IN.reg & PORT_PA17);
				}
				
				break;
				
				
				case 1:
				ledDisplay(array[v]);
				portAs -> OUTCLR.reg = PORT_PA06;
				if (portAs ->IN.reg & PORT_PA19)
				{
					// character 4
					array[i] = '4';
					i++;
					while (portAs ->IN.reg & PORT_PA19);

				}
				else if (portAs ->IN.reg & PORT_PA18)
				{
					array[i] = '5';
					i++;
					while (portAs ->IN.reg & PORT_PA18);
				}
				else if (portAs ->IN.reg & PORT_PA17)
				{
					array[i] = '6';
					i++;
					while (portAs ->IN.reg & PORT_PA17);
				}
				
				break;
				
				
				case 2:
				ledDisplay(array[v]);
				portAs -> OUTCLR.reg = PORT_PA05;
				if (portAs ->IN.reg & PORT_PA19)
				{
					// Number 7
					array[i] = '7';
					i++;
					while (portAs ->IN.reg & PORT_PA19);

				}
				else if (portAs ->IN.reg & PORT_PA18)
				{
					array[i] = '8';
					i++;
					
					while (portAs ->IN.reg & PORT_PA18);
					
				}
				else if (portAs ->IN.reg & PORT_PA17)
				{
					array[i] = '9';
					i++;
					while (portAs ->IN.reg & PORT_PA17);
				}
			
				break;
				
				
				
				case 3:
				ledDisplay(array[v]);
				portAs -> OUTCLR.reg = PORT_PA04;
				if (portAs ->IN.reg & PORT_PA18)
				{
					array[i] = '0';
					i++;
					while (portAs ->IN.reg & PORT_PA18);
				}
				else if (portAs ->IN.reg & PORT_PA16)
				{
					//D
					write(array);
					i = 0;
					while (portAs ->IN.reg & PORT_PA16);
				}
				
				break;
				
			}

			v++;	
			
			if (v == 4)
			{
				v = 0;
			}			
		
			if (i == 4)
			{ i = 0;}	
	}
	
}
Пример #22
0
int main(int argc, char ** argv){
    system("title SERWER");

    if(enet_initialize()!=0){
        fprintf (stderr, "An error occurred while initializing ENet.\n");
        return EXIT_FAILURE;
    }

    /***variables***/
    int serviceResult = 1;
    int ID=1;

    string name, password;
    string packet_name, packet_password;
    bool busy_account=false;
    char* gh;
    fstream file;

    ENetAddress address;

    string mapa;

    file.open("map.txt", ios::in);
    if(!file.good())
        cout << "\nI can't find map!";
    else {
        getline(file, mapa);
    }
    file.close();

    /***over variables***/

    address.host = ENET_HOST_ANY;
    address.port = PORT;
    server=enet_host_create(&address, MAX_CLIENTS, 2, 0, 0);
    if(server==NULL){
        fprintf(stderr, "\nAn error occurred while trying to create an ENet server host.\n");
        exit(EXIT_FAILURE);
    }
    printf("::SERVER START!\n\nEVENTS:\n");

   // while(1){
        //serviceResult=1;

        //while(serviceResult>0){
        while(1){
            serviceResult = enet_host_service(server, &event, 1); //1000 milisekund
            switch (event.type){
                case ENET_EVENT_TYPE_CONNECT:{
                    printf ("- A new client connected from %x:%u.\n", event.peer -> address.host, event.peer -> address.port);
                    event.peer -> data = (void*)"Client information";
                    //event.peer->data = (void*)ID;
                }
                break;

                case ENET_EVENT_TYPE_RECEIVE:{
                    //printf ("\nDOSTANO: '%s', client [%s], kanal [%u].", //event.packet -> dataLength,
                    //        event.packet -> data, event.peer -> data, event.channelID);

                    //cout << "\n$$$ OTRZYMANO OD [" << event.peer->address.host << "] dane: '" << event.packet->data << "'";

                    if(receive(event.packet->data, "register")) {
                        packet_name=getPacket(event.packet->data);
                        packet_password=getPacket(event.packet->data);
                        packet_name.erase( 0, 8 );
                        packet_password.erase( 0, 8 );
                        size_t znalezionaPozycja = packet_name.find( ":" );
                        packet_name.erase( znalezionaPozycja, 20 );
                        packet_password.erase( 0, znalezionaPozycja+1 );
                        busy_account = true;

                        file.open("nick.txt", ios::in);
                        if(file.good())
                        {
                            while(!file.eof())
                            {
                                file >> name >> password;
                                if(packet_name != name)
                                    busy_account = false;
                                else
                                    busy_account = true;

                                if(busy_account){ cout << "\nERROR!\n" << endl; break; }
                            }
                            file.close();
                        }
                        else {
                            cout << "\nERROR: I can't open nick.txt\n";
                            busy_account=true;
                        }

                        if(!busy_account)
                        {
                            file.open("nick.txt", ios::out | ios::app);
                            file << packet_name << " " << packet_password << "\n";
                            file.close();

                            string path = "users/"+packet_name+".txt";
                            file.open(path.c_str(), ios::out);
                            file << "1 1 1 1 1 0 0"; // hair, head, body, leg, boots, posX, posY
                            file.close();

                            char message[] = "GOOD";
                            ENetPacket *p = enet_packet_create(message, strlen(message)+1, ENET_PACKET_FLAG_RELIABLE);
                            //enet_host_broadcast(server, 0, p);
                            enet_peer_send(event.peer, 0, p);
                            cout << "- Zarejestrowano nowego uzytkownika!\n";
                        }
                        else
                        {
                            char message[] = "FAIL";
                            ENetPacket *p = enet_packet_create(message, strlen(message)+1, ENET_PACKET_FLAG_RELIABLE);
                            //enet_host_broadcast(server, 0, p);
                            enet_peer_send(event.peer, 0, p);
                        }
                        file.close();

                        continue;
                    }
                    else if(receive(event.packet->data, "login")) {
                        bool isLogin = false;

                        packet_name=getPacket(event.packet->data);
                        packet_password=getPacket(event.packet->data);
                        packet_name.erase( 0, 5 );
                        packet_password.erase( 0, 5 );
                        size_t znalezionaPozycja = packet_name.find( ":" );
                        packet_name.erase( znalezionaPozycja, 20 );
                        packet_password.erase( 0, znalezionaPozycja+1 );

                        file.open("nick.txt", ios::in);
                        if(file.good())
                        {
                            while(!file.eof())
                            {
                                file >> name >> password;
                                if(packet_name == name && packet_password == password) {
                                    isLogin = true;
                                    break;
                                }
                            }
                            file.close();
                        }
                        else {
Пример #23
0
/*===========================================================================*
 *				dpeth_task				     *
 *===========================================================================*/
int main(int argc, char *argv[])
{
	message m;
	int i, irq, r;
	dpeth_t *dep;
	long v;

	env_setargs(argc, argv);

	for (i= 0, dep= de_table; i<DE_PORT_NR; i++, dep++)
	{
		strcpy(dep->de_name, "dp8390#0");
		dep->de_name[7] += i;
	}

	v= 0;
	(void) env_parse("ETH_IGN_PROTO", "x", 0, &v, 0x0000L, 0xFFFFL);
	eth_ign_proto= htons((u16_t) v);

	while (TRUE)
	{
		if ((r= receive(ANY, &m)) != OK)
			panic("", "dp8390: receive failed", r);

		switch (m.m_type)
		{
		case DL_WRITE:	do_vwrite(&m, FALSE, FALSE);	break;
		case DL_WRITEV:	do_vwrite(&m, FALSE, TRUE);	break;
		case DL_READ:	do_vread(&m, FALSE);		break;
		case DL_READV:	do_vread(&m, TRUE);		break;
		case DL_INIT:	do_init(&m);			break;
		case DL_GETSTAT: do_getstat(&m);		break;
		case DL_STOP:	do_stop(&m);			break;
		case HARD_INT:
			for (i= 0, dep= &de_table[0]; i<DE_PORT_NR; i++, dep++)
			{
				if (dep->de_mode != DEM_ENABLED)
					continue;
				assert(dep->de_flags & DEF_ENABLED);
				irq= dep->de_irq;
				assert(irq >= 0 && irq < NR_IRQ_VECTORS);
				if (dep->de_int_pending || 1)
				{
					dep->de_int_pending= 0;
					dp_check_ints(dep);
					do_int(dep);
					r= sys_irqenable(&dep->de_hook);
					if (r != OK)
					{
						panic("DP8390", 
						"unable enable interrupts", r);
					}
				}
			}
			break;
		case SYS_SIG:	{
			sigset_t sigset = m.NOTIFY_ARG;
			if (sigismember(&sigset, SIGKSTOP)) dp8390_stop();
			break;
		}
		case SYN_ALARM:
			printf("dp8390: strange, got SYN_ALARM\n");
			break;
		default:
			panic("", "dp8390: illegal message", m.m_type);
		}
	}
}
Пример #24
0
// wait if blocking for input, return false for error
bool Socket::wait()
{
    byte b;
    return receive(&b, 1, MSG_PEEK) != static_cast<uint>(-1);
}
Пример #25
0
int main()
{
	WSADATA wsaData;
	struct addrinfo *result = NULL, *ptr = NULL, hints;
	int recvbuflen = DEFAULT_BUFLEN;
	int iResult;

	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); // Initialize Winsock.
	if(iResult != 0)
	{
		printf("WSAStartup failed with error: %d\n", iResult);
		return 1;
	}

	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); // Resolve the server address and port
	if(iResult != 0)
	{
		printf("getaddrinfo failed with error: %d\n", iResult);
		WSACleanup();
		return 1;
	}

	for(ptr = result; ptr != NULL; ptr = ptr->ai_next) // Attempt to connect to an address until one succeeds.
	{
		ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); // Create a SOCKET for connecting to server.
		if(ConnectSocket == INVALID_SOCKET)
		{
			printf("socket failed with error: %ld\n", WSAGetLastError());
			WSACleanup();
			return 1;
		}

		iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen); // Connect to server.
		if(iResult == SOCKET_ERROR)
		{
			closesocket(ConnectSocket);
			ConnectSocket = INVALID_SOCKET;
			continue;
		}
		break;
	}

	freeaddrinfo(result);

	if(ConnectSocket == INVALID_SOCKET)
	{
		printf("Unable to connect to server!\n");
		WSACleanup();
		return 1;
	}
	else
		std::cout << "Server connection established." << std::endl;

	std::cout << "Sending confirmation message to server." << std::endl;

	char sendbuf[] = "CONFIRM CONNECTION!";
	iResult = send(ConnectSocket, sendbuf, strlen(sendbuf), 0); // Send an initial buffer.

	if(iResult == SOCKET_ERROR)
	{
		printf("SEND failed with error: %d\n", WSAGetLastError());
		closesocket(ConnectSocket);
		WSACleanup();
		return 1;
	}
	else
		std::cout << "Confirmation message was successfull." << std::endl;

	std::thread receive(ReceiveMessages, ConnectSocket); // Start thread for receiving messages.
	receive.detach();

	while(WriteMessage() == true && receiving); // Send messages to server.

	shutdown(ConnectSocket, SD_SEND); 
	closesocket(ConnectSocket);
	WSACleanup();

	std::cout << "--- CLOSING GAME ---" << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(5));

	return 0;
}
Пример #26
0
std::streamsize Socket::showmanyc() {
	#ifdef WIN32
	unsigned long result = -1;
	if(ioctlsocket(handle, FIONREAD, &result)) {
	#else
	int result = -1;
	if(ioctl(handle, FIONREAD, &result)) {
	#endif
        disconnect();
		throw Exception(Exception::ERROR_IOCTL);
    }else
        return result;
}

std::streamsize Socket::advanceInputBuffer() {
    if(inputIntermediateSize == 0) //No input buffer
        return 0;

    std::streamsize inAvail;
    if(type == UDP_PEER)
        inAvail = 0;
    else{
        inAvail = egptr()-gptr();
        memmove(eback(), gptr(), inAvail);
    }

    try {
        inAvail += receive(eback()+inAvail, inputIntermediateSize-inAvail);
    } catch(Exception err) {

    }

    setg(eback(), eback(), eback()+inAvail);
    return inAvail;
}

std::streamsize Socket::receive(char_type* buffer, std::streamsize size) {
    size = std::min(size, showmanyc());
    if(size == 0) return 0;
    
    switch(type) {
        case UDP_PEER: {
            struct sockaddr_storage remoteAddr;
			#ifdef WIN32
			int addrSize = sizeof(remoteAddr);
			#else
			unsigned int addrSize = sizeof(remoteAddr);
			#endif
            int result = recvfrom(handle, (char*)buffer, size, 0, reinterpret_cast<struct sockaddr*>(&remoteAddr), &addrSize);
            
            if(result == -1) {
                portRemote = 0;
                hostRemote = "";
                throw Exception(Exception::ERROR_READ);
            }else
                readSockaddr(&remoteAddr, hostRemote, portRemote);
            
            return result;
        }
        case TCP_CLIENT:
        case TCP_SERVERS_CLIENT: {
            int result = recv(handle, (char*)buffer, size, 0);
            
            if(result == -1)
                throw Exception(Exception::ERROR_READ);
            
            return result;
        }
		default:
        case NONE:
        case TCP_SERVER:
            throw Exception(Exception::BAD_TYPE);
    }
}
Пример #27
0
static respData_t* p61_dev_receiveData_internal(struct file *filp)
{
	short rPcb = 0;
	short rLen = 0;
	respData_t *header=NULL;
	respData_t *respData=NULL;
	unsigned char *wtx=NULL;
	unsigned char *data=NULL;
	//unsigned char *data1=NULL;
	int len=0;
	int len1=0;
	int stat_timer;
Start:
	NFC_DBG_MSG(KERN_INFO  "receiveData -Enter\n");

	// receive the T=1 header
	header = (respData_t*)receiveHeader(filp);
	if(header == NULL)
	{
		NFC_ERR_MSG(KERN_ALERT "ERROR:Failed to receive header data\n");
		return NULL;
	}
	rPcb = header->data[0];
	rLen = (short) (header->data[1] & 0xFF);
	NFC_DBG_MSG(KERN_ALERT "receive header data rPcb = 0x%x , rLen = %d\n", rPcb, rLen);

#if 1

	//check the header if wtx is requested
	if ((rPcb & PH_SCAL_T1_S_BLOCK) == PH_SCAL_T1_S_BLOCK)
	{
		NFC_DBG_MSG(KERN_ALERT "receiveDatav - WTX requested\n");
		data = gRecvBuff;
		len = 1;
		NFC_DBG_MSG(KERN_ALERT "receiveDatav - WTX1 requested\n");
		receive(filp,&data,len, C_TRANSMIT_NO_STOP_CONDITION | C_TRANSMIT_NO_START_CONDITION);
		NFC_DBG_MSG(KERN_ALERT "receiveDatav - WTX2 requested\n");
		receiveAndCheckChecksum(filp,rPcb, rLen, data,len);
		NFC_DBG_MSG(KERN_ALERT "receiveDatav - WTX3 requested\n");
		NFC_DBG_MSG(KERN_ALERT "value is %x %x",data[0],data[1]);
                memset(gRecvBuff,0,300);
		wtx = gRecvBuff;
		wtx[0] = 0x00; wtx[1] = 0xE3; wtx[2] = 0x01; wtx[3] = 0x01; wtx[4] = 0xE3;
		len1 = 5;
		udelay(1000);
		send(filp,&wtx, C_TRANSMIT_NORMAL_SPI_OPERATION,len1);
		udelay(1000);

                //gStRecvData->len = 5;
                //memcpy(gStRecvData->data, wtx, 5);;
#ifdef TIMER_ENABLE
                stat_timer = start_timer();
#endif
                //return gStRecvData;
		goto Start;
	}

	//check the header if retransmit is requested
	if ((rPcb & PH_SCAL_T1_R_BLOCK) == PH_SCAL_T1_R_BLOCK)
	{
		memset(data1,0,1);
		len1=1;
		receiveAndCheckChecksum(filp,rPcb, rLen, data1,len1);
		udelay(1000);
		send(filp,&lastFrame, C_TRANSMIT_NORMAL_SPI_OPERATION,lastFrameLen);
		udelay(1000);
		goto Start;
//		return (ssize_t)p61_dev_receiveData_internal(filp);
	}

	//check the PCB byte and receive the rest of the frame
	if ((rPcb & PH_SCAL_T1_CHAINING) == PH_SCAL_T1_CHAINING)
	{
		NFC_DBG_MSG(KERN_ALERT "Chained Frame Requested\n");

		return receiveChainedFrame(filp,rPcb, rLen);

	}
	else
	{
		NFC_DBG_MSG(KERN_ALERT "receiveFrame Requested\n");
		respData = receiveFrame(filp,rPcb, rLen);
		NFC_DBG_MSG(KERN_ALERT "***************** 0x%x \n",respData->data[0]);
		return respData;
	}
#endif
	return NULL;
}
Пример #28
0
void do_tests() {
    ASSERT(!receive(""));
    ASSERT(!receive("recieve_test"));
}
Пример #29
0
PUBLIC void eth_init0()
{
	int result;
	eth_port_t *eth_port;
	static message mess, repl_mess;

	eth_port= &eth_port_table[0];

	eth_port->etp_osdep.etp_port= 0;
	eth_port->etp_osdep.etp_task= DL_ETH;
	eth_port->etp_osdep.etp_minor= ETH_DEV;

#if XXX
	mess.m_type= DL_STOP;
	mess.DL_PORT= eth_port->etp_osdep.etp_port;
#if DEBUG & 256
 { where(); printf("sending DL_STOP\n"); }
#endif
assert (eth_port->etp_osdep.etp_task != MM_PROC_NR);
	result= send(eth_port->etp_osdep.etp_task, &mess);
	if (result < 0)
	{
		printf("send failed with error %d\n",result);
		printf("eth_init0: unable to stop ethernet task\n");
		return;
	}
#endif

#if DEBUG & 256
 { where(); printf("sending DL_INIT\n"); }
#endif
	mess.m_type= DL_INIT;
	mess.DL_PORT= eth_port->etp_osdep.etp_port;
	mess.DL_PROC= THIS_PROC;
	mess.DL_MODE= DL_NOMODE;
assert (eth_port->etp_osdep.etp_task != MM_PROC_NR);
	result= send(eth_port->etp_osdep.etp_task, &mess);
	if (result<0)
	{
		printf(
		"eth_init0: unable to send to ethernet task, error= %d\n",
			result);
		return;
	}

	if (receive(eth_port->etp_osdep.etp_task, &mess)<0)
		ip_panic(("unable to receive"));

	if (mess.m3_i1 != eth_port->etp_osdep.etp_port)
	{
		printf("eth_init0: got reply for wrong port\n");
		return;
	}

	eth_port->etp_ethaddr= *(ether_addr_t *)mess.m3_ca1;

	if (sr_add_minor (eth_port->etp_osdep.etp_minor, 
		eth_port- eth_port_table, eth_open, eth_close, eth_read, 
		eth_write, eth_ioctl, eth_cancel)<0)
		ip_panic(("can't sr_init"));

	eth_port->etp_flags |= EPF_ENABLED;
	eth_port->etp_wr_pack= 0;
	eth_port->etp_rd_pack= 0;
	setup_read (eth_port);
}
Пример #30
0
bool ARTSPConnection::receiveRTSPReponse() {
    AString statusLine;

    if (!receiveLine(&statusLine)) {
        return false;
    }

    if (statusLine == "$") {
        sp<ABuffer> buffer = receiveBinaryData();

        if (buffer == NULL) {
            return false;
        }

        if (mObserveBinaryMessage != NULL) {
            sp<AMessage> notify = mObserveBinaryMessage->dup();
            notify->setObject("buffer", buffer);
            notify->post();
        } else {
            LOGW("received binary data, but no one cares.");
        }

        return true;
    }

    sp<ARTSPResponse> response = new ARTSPResponse;
    response->mStatusLine = statusLine;

    LOGI("status: %s", response->mStatusLine.c_str());

    ssize_t space1 = response->mStatusLine.find(" ");
    if (space1 < 0) {
        return false;
    }
    ssize_t space2 = response->mStatusLine.find(" ", space1 + 1);
    if (space2 < 0) {
        return false;
    }

    bool isRequest = false;

    if (!IsRTSPVersion(AString(response->mStatusLine, 0, space1))) {
        CHECK(IsRTSPVersion(
                    AString(
                        response->mStatusLine,
                        space2 + 1,
                        response->mStatusLine.size() - space2 - 1)));

        isRequest = true;

        response->mStatusCode = 0;
    } else {
        AString statusCodeStr(
                response->mStatusLine, space1 + 1, space2 - space1 - 1);

        if (!ParseSingleUnsignedLong(
                    statusCodeStr.c_str(), &response->mStatusCode)
                || response->mStatusCode < 100 || response->mStatusCode > 999) {
            return false;
        }
    }

    AString line;
    ssize_t lastDictIndex = -1;
    for (;;) {
        if (!receiveLine(&line)) {
            break;
        }

        if (line.empty()) {
            break;
        }

        LOGV("line: '%s'", line.c_str());

        if (line.c_str()[0] == ' ' || line.c_str()[0] == '\t') {
            // Support for folded header values.

            if (lastDictIndex < 0) {
                // First line cannot be a continuation of the previous one.
                return false;
            }

            AString &value = response->mHeaders.editValueAt(lastDictIndex);
            value.append(line);

            continue;
        }

        ssize_t colonPos = line.find(":");
        if (colonPos < 0) {
            // Malformed header line.
            return false;
        }

        AString key(line, 0, colonPos);
        key.trim();
        key.tolower();

        line.erase(0, colonPos + 1);

        lastDictIndex = response->mHeaders.add(key, line);
    }

    for (size_t i = 0; i < response->mHeaders.size(); ++i) {
        response->mHeaders.editValueAt(i).trim();
    }

    unsigned long contentLength = 0;

    ssize_t i = response->mHeaders.indexOfKey("content-length");

    if (i >= 0) {
        AString value = response->mHeaders.valueAt(i);
        if (!ParseSingleUnsignedLong(value.c_str(), &contentLength)) {
            return false;
        }
    }

    if (contentLength > 0) {
        response->mContent = new ABuffer(contentLength);

        if (receive(response->mContent->data(), contentLength) != OK) {
            return false;
        }
    }

    if (response->mStatusCode == 401) {
        if (mAuthType == NONE && mUser.size() > 0
                && parseAuthMethod(response)) {
            ssize_t i;
            CHECK_EQ((status_t)OK, findPendingRequest(response, &i));
            CHECK_GE(i, 0);

            sp<AMessage> reply = mPendingRequests.valueAt(i);
            mPendingRequests.removeItemsAt(i);

            AString request;
            CHECK(reply->findString("original-request", &request));

            sp<AMessage> msg = new AMessage(kWhatSendRequest, id());
            msg->setMessage("reply", reply);
            msg->setString("request", request.c_str(), request.size());

            LOGI("re-sending request with authentication headers...");
            onSendRequest(msg);

            return true;
        }
    }

    return isRequest
        ? handleServerRequest(response)
        : notifyResponseListener(response);
}