Example #1
0
void ipc3_shutdown( int sock, int how ) {
    shutdown( sock, how );
}
Example #2
0
/*
 * State Machine Procedure
 */
void sm_run(void) {

    /* 
     * STANDBY STATE 
     * The system starts by this state and wait command to Turn on (b_On = 1)
     */
    if (us_State == 1U) 
    {
        /* If system is ON */
        if (b_On == 1U) 
        {
            /* Change State to IBIT */
            us_State = 2U;
        }
        /* If emergency active */
        if (b_Emergency == 1U) 
        {
            /* Show Emergency Alert */
            /* (" --EMERGENCY ACTIVATED-- ") */
        }
    }
        /* 
         * The system check the state
         */
    else 
    {
        /* 
         * OPERATIONAL STATE
         */
        if (us_State == 7U) 
        {
            /* If operational ON */
            if (b_Operational == 1U) 
            {
                /* Call OPERATIONAL state */
                operational(b_Fail);
            } 
            else 
            {
                /* Call to Close Panel */
                shutdown(b_Fail);

                /* If fail is active */
                if (b_Fail == 1U) 
                {
                    /* Return to Fail state */
                    us_State = 3U;
                } 
                else 
                {
                    /* Return to READY state */
                    us_State = 4U;
                }
            }

            /* Call Health Monitoring
             * return: state if changed */
            us_State = powerMonitoring(us_State);
        }
            /*
             * BIT STATE 
             */
        else if (us_State == 2U) 
        {
            /* Call Built-in Test */
            us_State = bit();

            /* Call Health Monitoring
             * return: state if changed */
            us_State = powerMonitoring(us_State);
        }
            /*
             * FAIL STATE 
             */
        else if (us_State == 3U) 
        {
            /* Alert system to FAIL */
            b_Fail = 1U;

            /* If system is ON */
            if (b_On == 0U) 
            {
                /*Change State to STANDBY*/
                us_State = 1U;
            }

            if (b_Operational == 1U) 
            {
                /* Change State to OPERATIONAL REDUCED */
                us_State = 7U;

                /* Initialize operational variables */
                operational_init();
            }

            /* Call Health Monitoring
             * return: state if changed */
            us_State = powerMonitoring(us_State);
        }
            /*
             * READY STATE 
             */
        else if (us_State == 4U) 
        {
            /* If system is ON */
            if (b_On == 0U) 
            {
                /*Change State to STANDBY*/
                us_State = 1U;
            }

            if (b_Maintenance == 1U) 
            {
                /*Change State to MAINTENANCE*/
                us_State = 6U;
            }

            if (b_Operational == 1U) 
            {
                /*Change State to Operational*/
                us_State = 7U;

                /* Initialize operational variables */
                operational_init();
            }

            /* Call Health Monitoring
             * return: state if changed */
            us_State = powerMonitoring(us_State);
        }
            /*
             * MAINTENANCE STATE 
             */
        else if (us_State == 6U) 
        {
            /* If maintenance active */
            if (b_Maintenance == 0U) 
            {
                /* Call to Close Panel */
                shutdown(b_Fail);

                /* Change State to READY */
                us_State = 4U;
            } 
            else {
                /* State MAINTENANCE */
                maintenance();
            }

            /* Call Health Monitoring
             * return: state if changed */
            us_State = powerMonitoring(us_State);
        } else 
        {
            /*
             * EMERGENCY STATE 
             */
            if (us_State == 9U) 
            {
                /* System Turn OFF */
                b_On = 0U;

                /* Set FAIL Alert to OFF */
                b_Fail = 0U;

                /* Change state to STANDBY */
                us_State = 1U;

                /* Emergency Active */
                b_Emergency = 1U;

                /* Operational OFF */
                b_Operational = 0U;

                /* Shutdown System Safely */
                shutdown(b_Fail);
            }
        }
    }
}
Example #3
0
/**
 * Send an IOQueue.
 * This attempts to send as much of the IOQueue data as possible. The IOQueue
 * may be non-empty when this completes if the descriptor buffer is full.
 * @returns the number of bytes sent.
 */
ssize_t ConnectedDescriptor::Send(IOQueue *ioqueue) {
  if (!ValidWriteDescriptor())
    return 0;

  int iocnt;
  const struct IOVec *iov = ioqueue->AsIOVec(&iocnt);

  ssize_t bytes_sent = 0;

#ifdef _WIN32
  /* There is no scatter/gather functionality for generic descriptors on
   * Windows, so this is implemented as a write loop. Derived classes should
   * re-implement Send() using scatter/gather I/O where available.
   */
  int bytes_written = 0;
  for (int io = 0; io < iocnt; ++io) {
    bytes_written = write(WriteDescriptor().m_handle.m_fd, iov[io].iov_base,
                          iov[io].iov_len);
    if (bytes_written == -1) {
      OLA_INFO << "Failed to send on " << WriteDescriptor() << ": " <<
        strerror(errno);
      break;
    }
    bytes_sent += bytes_written;
  }
#else
#if HAVE_DECL_MSG_NOSIGNAL
  if (IsSocket()) {
    struct msghdr message;
    memset(&message, 0, sizeof(message));
    message.msg_name = NULL;
    message.msg_namelen = 0;
    message.msg_iov = reinterpret_cast<iovec*>(const_cast<IOVec*>(iov));
    message.msg_iovlen = iocnt;
    bytes_sent = sendmsg(WriteDescriptor(), &message, MSG_NOSIGNAL);
  } else {
#else
  {
#endif
    bytes_sent = writev(WriteDescriptor(),
                        reinterpret_cast<const struct iovec*>(iov), iocnt);
  }
#endif

  ioqueue->FreeIOVec(iov);
  if (bytes_sent < 0) {
    OLA_INFO << "Failed to send on " << WriteDescriptor() << ": " <<
      strerror(errno);
  } else {
    ioqueue->Pop(bytes_sent);
  }
  return bytes_sent;
}


/*
 * Read data from this descriptor.
 * @param buffer a pointer to the buffer to store new data in
 * @param size the size of the buffer
 * @param data_read a value result argument which returns the amount of data
 * copied into the buffer
 * @returns -1 on error, 0 on success.
 */
int ConnectedDescriptor::Receive(uint8_t *buffer,
                                 unsigned int size,
                                 unsigned int &data_read) { // NOLINT
  int ret;
  uint8_t *data = buffer;
  data_read = 0;
  if (!ValidReadDescriptor())
    return -1;

  while (data_read < size) {
#ifdef _WIN32
    if ((ret = read(ReadDescriptor().m_handle.m_fd, data, size - data_read))
        < 0) {
#else
    if ((ret = read(ReadDescriptor(), data, size - data_read)) < 0) {
#endif
      if (errno == EAGAIN)
        return 0;
      if (errno != EINTR) {
        OLA_WARN << "read failed, " << strerror(errno);
        return -1;
      }
    } else if (ret == 0) {
      return 0;
    }
    data_read += ret;
    data += data_read;
  }
  return 0;
}


/*
 * Check if the remote end has closed the connection.
 * @return true if the socket is closed, false otherwise
 */
bool ConnectedDescriptor::IsClosed() const {
  return DataRemaining() == 0;
}

// LoopbackDescriptor
// ------------------------------------------------


/*
 * Setup this loopback socket
 */
bool LoopbackDescriptor::Init() {
  if (m_handle_pair[0] != INVALID_DESCRIPTOR ||
      m_handle_pair[1] != INVALID_DESCRIPTOR)
    return false;

  if (!CreatePipe(m_handle_pair))
    return false;

  SetReadNonBlocking();
  SetNoSigPipe(WriteDescriptor());
  return true;
}


/*
 * Close the loopback socket
 * @return true if close succeeded, false otherwise
 */
bool LoopbackDescriptor::Close() {
  if (m_handle_pair[0] != INVALID_DESCRIPTOR) {
#ifdef _WIN32
    CloseHandle(m_handle_pair[0].m_handle.m_handle);
#else
    close(m_handle_pair[0]);
#endif
  }

  if (m_handle_pair[1] != INVALID_DESCRIPTOR) {
#ifdef _WIN32
    CloseHandle(m_handle_pair[1].m_handle.m_handle);
#else
    close(m_handle_pair[1]);
#endif
  }

  m_handle_pair[0] = INVALID_DESCRIPTOR;
  m_handle_pair[1] = INVALID_DESCRIPTOR;
  return true;
}


/*
 * Close the write portion of the loopback socket
 * @return true if close succeeded, false otherwise
 */
bool LoopbackDescriptor::CloseClient() {
  if (m_handle_pair[1] != INVALID_DESCRIPTOR) {
#ifdef _WIN32
    CloseHandle(m_handle_pair[1].m_handle.m_handle);
#else
    close(m_handle_pair[1]);
#endif
  }

  m_handle_pair[1] = INVALID_DESCRIPTOR;
  return true;
}



// PipeDescriptor
// ------------------------------------------------

/*
 * Create a new pipe socket
 */
bool PipeDescriptor::Init() {
  if (m_in_pair[0] != INVALID_DESCRIPTOR ||
      m_out_pair[1] != INVALID_DESCRIPTOR)
    return false;

  if (!CreatePipe(m_in_pair))
    return false;

  if (!CreatePipe(m_out_pair)) {
#ifdef _WIN32
    CloseHandle(m_in_pair[0].m_handle.m_handle);
    CloseHandle(m_in_pair[1].m_handle.m_handle);
#else
    close(m_in_pair[0]);
    close(m_in_pair[1]);
#endif
    m_in_pair[0] = m_in_pair[1] = INVALID_DESCRIPTOR;
    return false;
  }

  SetReadNonBlocking();
  SetNoSigPipe(WriteDescriptor());
  return true;
}


/*
 * Fetch the other end of the pipe socket. The caller now owns the new
 * PipeDescriptor.
 * @returns NULL if the socket wasn't initialized correctly.
 */
PipeDescriptor *PipeDescriptor::OppositeEnd() {
  if (m_in_pair[0] == INVALID_DESCRIPTOR ||
      m_out_pair[1] == INVALID_DESCRIPTOR)
    return NULL;

  if (!m_other_end) {
    m_other_end = new PipeDescriptor(m_out_pair, m_in_pair, this);
    m_other_end->SetReadNonBlocking();
  }
  return m_other_end;
}


/*
 * Close this PipeDescriptor
 */
bool PipeDescriptor::Close() {
  if (m_in_pair[0] != INVALID_DESCRIPTOR) {
#ifdef _WIN32
    CloseHandle(m_in_pair[0].m_handle.m_handle);
#else
    close(m_in_pair[0]);
#endif
  }

  if (m_out_pair[1] != INVALID_DESCRIPTOR) {
#ifdef _WIN32
    CloseHandle(m_out_pair[1].m_handle.m_handle);
#else
    close(m_out_pair[1]);
#endif
  }

  m_in_pair[0] = INVALID_DESCRIPTOR;
  m_out_pair[1] = INVALID_DESCRIPTOR;
  return true;
}


/*
 * Close the write portion of this PipeDescriptor
 */
bool PipeDescriptor::CloseClient() {
  if (m_out_pair[1] != INVALID_DESCRIPTOR) {
#ifdef _WIN32
    CloseHandle(m_out_pair[1].m_handle.m_handle);
#else
    close(m_out_pair[1]);
#endif
  }

  m_out_pair[1] = INVALID_DESCRIPTOR;
  return true;
}


// UnixSocket
// ------------------------------------------------

/*
 * Create a new unix socket
 */
bool UnixSocket::Init() {
#ifdef _WIN32
  return false;
#else
  int pair[2];
  if ((m_handle != INVALID_DESCRIPTOR) || m_other_end)
    return false;

  if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair)) {
    OLA_WARN << "socketpair() failed, " << strerror(errno);
    return false;
  }

  m_handle = pair[0];
  SetReadNonBlocking();
  SetNoSigPipe(WriteDescriptor());
  m_other_end = new UnixSocket(pair[1], this);
  m_other_end->SetReadNonBlocking();
  return true;
#endif
}


/*
 * Fetch the other end of the unix socket. The caller now owns the new
 * UnixSocket.
 * @returns NULL if the socket wasn't initialized correctly.
 */
UnixSocket *UnixSocket::OppositeEnd() {
  return m_other_end;
}


/*
 * Close this UnixSocket
 */
bool UnixSocket::Close() {
#ifdef _WIN32
  return true;
#else
  if (m_handle != INVALID_DESCRIPTOR) {
    close(m_handle);
  }

  m_handle = INVALID_DESCRIPTOR;
  return true;
#endif
}


/*
 * Close the write portion of this UnixSocket
 */
bool UnixSocket::CloseClient() {
#ifndef _WIN32
  if (m_handle != INVALID_DESCRIPTOR)
    shutdown(m_handle, SHUT_WR);
#endif

  m_handle = INVALID_DESCRIPTOR;
  return true;
}


// DeviceDescriptor
// ------------------------------------------------
DeviceDescriptor::DeviceDescriptor(int fd) {
#ifdef _WIN32
  m_handle.m_handle.m_fd = fd;
  m_handle.m_type = GENERIC_DESCRIPTOR;
  m_handle.m_event_handle = 0;
#else
  m_handle = fd;
#endif
}
Example #4
0
int
main(int argc, char *argv[])
{
	u_int readers, writers;
	int ch, cnt, runs;
	char *config_open;

	if ((progname = strrchr(argv[0], '/')) == NULL)
		progname = argv[0];
	else
		++progname;

	config_open = NULL;
	ftype = ROW;
	nkeys = 1000;
	nops = 10000;
	readers = 10;
	runs = 1;
	session_per_op = 0;
	writers = 10;

	while ((ch = getopt(argc, argv, "C:k:l:n:R:r:St:W:")) != EOF)
		switch (ch) {
		case 'C':			/* wiredtiger_open config */
			config_open = optarg;
			break;
		case 'k':			/* rows */
			nkeys = (u_int)atoi(optarg);
			break;
		case 'l':			/* log */
			if ((logfp = fopen(optarg, "w")) == NULL) {
				fprintf(stderr,
				    "%s: %s\n", optarg, strerror(errno));
				return (EXIT_FAILURE);
			}
			break;
		case 'n':			/* operations */
			nops = (u_int)atoi(optarg);
			break;
		case 'R':
			readers = (u_int)atoi(optarg);
			break;
		case 'r':			/* runs */
			runs = atoi(optarg);
			break;
		case 'S':			/* new session per operation */
			session_per_op = 1;
			break;
		case 't':
			switch (optarg[0]) {
			case 'f':
				ftype = FIX;
				break;
			case 'r':
				ftype = ROW;
				break;
			case 'v':
				ftype = VAR;
				break;
			default:
				return (usage());
			}
			break;
		case 'W':
			writers = (u_int)atoi(optarg);
			break;
		default:
			return (usage());
		}

	argc -= optind;
	argv += optind;
	if (argc != 0)
		return (usage());

	/* Clean up on signal. */
	(void)signal(SIGINT, onint);

	printf("%s: process %" PRIu64 "\n", progname, (uint64_t)getpid());
	for (cnt = 1; runs == 0 || cnt <= runs; ++cnt) {
		printf(
		    "    %d: %u readers, %u writers\n", cnt, readers, writers);

		shutdown();			/* Clean up previous runs */

		wt_connect(config_open);	/* WiredTiger connection */

		load();				/* Load initial records */
						/* Loop operations */
		if (rw_start(readers, writers))
			return (EXIT_FAILURE);

		stats();			/* Statistics */

		wt_shutdown();			/* WiredTiger shut down */
	}
	return (0);
}
Example #5
0
void Socket::ShutDown(int how)
{
	assert(m_s != INVALID_SOCKET);
	int result = shutdown(m_s, how);
	CheckAndHandleError_int("shutdown", result);
}
Example #6
0
int main(int argc, char *argv[]){
    int fd;
    char buffer[BUFFER_SIZE];
    int num;
     char command[BUFFER_SIZE];
    /*
     *int Humidity=0;
     *int Temperature=0;
     */

    if(argc < 3){
        //fprintf(stderr, "Usage: %s <hostname> <port>\n", argv[0]);
        fprintf(stderr, "Usage: %s <hostname> <port>\n", argv[0]);
        fprintf(stderr, "eg: ./socket api.thingspeak.com 80\n");
        exit(1); 
    }

/*GET /1/classes/TestObject?include=game HTTP/1.1*/
/*Host: api.parse.com*/
/*User-Agent: curl/7.43.0*/
/*Accept: *[>*/
/*X-Parse-Application-Id: pXOUZN6OVN5aAuLCMm0WvX3yRLJBInn0cmBWA6kj*/
/*X-Parse-REST-API-Key: aMzETnz9UKWIJRoBX8sytC2wxdItM7Rt6YrnlAuH*/


    while(1){

        fd = socket_connect(argv[1], atoi(argv[2])); 
        srand(time(NULL));
        /*
         *Humidity=rand()%100;
         *Temperature=rand()%20+20;
         */
        //write(fd, "GET /update?key=WFVT9X78TAM164OX&field1=125.0&field2=80\r\n", strlen("GET /update?key=WFVT9X78TAM164OX&field1=125.0&field2=80\r\n")); // write(fd, char[]*, len);  
        //write(fd, "GET /channels/46080/feed.json?key=WFVT9X78TAM164OX\r\n", strlen("GET /channels/46080/feed.json?key=WFVT9X78TAM164OX\r\n")); // write(fd, char[]*, len);  
        /*
         *sprintf(command, "GET /update?key=WFVT9X78TAM164OX&field1=%d&field2=%d\r\n", Humidity, Temperature);
         *printf("inserting command:\n%s", command);
         *write(fd, command, strlen(command)); // write(fd, char[]*, len);  
         */
        sprintf(command,"GET /1/classes/TestObject?include=game HTTP/1.1\n");
        num=write(fd, "command", strlen("command")); // write(fd, char[]*, len);  
        if (num==-1) { perror("write"); return -1; }else{printf("%s",command);}

        sprintf(command,"Host: api.parse.com\n");
        num=write(fd, "command", strlen("command")); // write(fd, char[]*, len);  
        if (num==-1) { perror("write"); return -1; }else{printf("%s",command);}

        sprintf(command,"User-Agent: curl/7.43.0\n");
        num=write(fd, "command", strlen("command")); // write(fd, char[]*, len);  
        if (num==-1) { perror("write"); return -1; }else{printf("%s",command);}

        sprintf(command,"Accept: */*\n");
        num=write(fd, "command", strlen("command")); // write(fd, char[]*, len);  
        if (num==-1) { perror("write"); return -1; }else{printf("%s",command);}

        sprintf(command,"X-Parse-Application-Id: pXOUZN6OVN5aAuLCMm0WvX3yRLJBInn0cmBWA6kj\n");
        num=write(fd, "command", strlen("command")); // write(fd, char[]*, len);  
        if (num==-1) { perror("write"); return -1; }else{printf("%s",command);}

        sprintf(command,"X-Parse-REST-API-Key: aMzETnz9UKWIJRoBX8sytC2wxdItM7Rt6YrnlAuH\n\n");
        num=write(fd, "command", strlen("command")); // write(fd, char[]*, len);  
        if (num==-1) { perror("write"); return -1; }else{printf("%s",command);}


        bzero(buffer, BUFFER_SIZE);

        while(read(fd, buffer, BUFFER_SIZE - 1) != 0){
            fprintf(stderr, "Server response:%s\n", buffer);
            bzero(buffer, BUFFER_SIZE);
        }
        sleep(RATE_LIMIT);

        shutdown(fd, SHUT_RDWR); 
        close(fd); 

    }


    return 0;
}
 ///Shutdown the socket.
 UDPSocket::~UDPSocket( void )
 {
   shutdown(socket, SD_BOTH);
 }
void TcpServer::listen() {
	serverSocket = socket(AF_INET, SOCK_STREAM, 0);
	if (serverSocket == -1) {
		logError("Could not create socket");
		return;
	}

	if (bind(serverSocket, (struct sockaddr *) &serverAddress,
			sizeof(serverAddress)) < 0) {
		logError("Could not bind socket");
		return;
	}
	::listen(serverSocket, 1);
	logDebug("Waiting for incoming connections...");
	serverInstance = this;
	int clientSocket;
	struct sockaddr_in client;
	int c = sizeof(client);
	while ((clientSocket = accept(serverSocket, (struct sockaddr *) &client,
			(socklen_t*) &c))) {
		const char* message = MessageConversion::getHandshakeInitiation();
		bool connectionRefused = false;
		StatusResponse response(false, nullptr);
		if (numCurrentConnections < maxConnections
				&& sendMessage(clientSocket, message)) {
			char* receivedMessage = receiveMessage(clientSocket);
			if (receivedMessage != nullptr) {
				if (MessageConversion::isHandshakeCorrect(receivedMessage)) {
					logDebug("Connection accepted");
					response.setSuccess(true);
					message = MessageConversion::convertResponseToJson(
							&response);
					if (sendMessage(clientSocket, message)) {
						TcpConnection* connection = new TcpConnection(
								clientSocket, this, spotifyRunner);
						connection->start();
						this->currentConnections.push_back(connection);
						numCurrentConnections++;
					}
					delete[] message;
				} else {
					response.setMessage("Handshake incorrect.");
					message = MessageConversion::convertResponseToJson(
							&response);
					sendMessage(clientSocket, message);
					delete[] message;
					connectionRefused = true;
				}
				delete[] receivedMessage;
			} else {
				response.setMessage("Error during receiving of message");
				message = MessageConversion::convertResponseToJson(&response);
				sendMessage(clientSocket, message);
				delete[] message;
				connectionRefused = true;
			}
		} else {
			response.setMessage("Too many connections");
			message = MessageConversion::convertResponseToJson(&response);
			sendMessage(clientSocket, message);
			delete[] message;
			connectionRefused = true;
		}

		if (connectionRefused) {
			logDebug("Connection refused");
			shutdown(clientSocket, SHUT_RDWR);
		}
	}

	shutdown(serverSocket, SHUT_RDWR);
}
Example #9
0
/*
 * main function of the simple client
 */
int main(int argc, char *argv[])
{
	char  sendbuf[MAX_MSG_LEN+1], recvbuf[MAX_MSG_LEN+1];
	int   server_sock, max_fd, ready, byte_read;
	int   stdineof = 0;
	char  *end;
	fd_set read_fds;

	/* display usage information */
	if (argc > 1){
		if ((strcmp(argv[1], "--help") == 0) || 
		    (strcmp(argv[1], "-h") == 0)){
			usage(argv[0]);
			return -1;
		}

		if (argc == 2){
			/* parse options if there are */
			if (strchr(argv[1], '.')){
				/* consider it to be an IP with ".", 
				   buggy with no further checking though */
				strcpy(server_ip, argv[1]);
			}else{
				server_port = atoi(argv[1]);
			}
		}else{
			strcpy(server_ip, argv[1]);
			server_port = atoi(argv[2]);
		}
	}

	printf("Connecting to server %s at port %d ...\n", server_ip, server_port);

	// connect to the server
	server_sock = socket_connect();

	printf("Connected, ready for commands:\n");

	// init read_fds
	FD_ZERO(&read_fds);

	while (1){

		// check which is ready, stdin or server_sock
		FD_SET(server_sock, &read_fds);
		FD_SET(fileno(stdin), &read_fds);
		max_fd = MAX(server_sock, fileno(stdin)) + 1;
		ready = Select(max_fd, &read_fds, 0, 0, 0);
		if (ready == 0)
			continue;

		// display server message first 
		if (FD_ISSET(server_sock, &read_fds)){
			do {
				bzero(recvbuf, MAX_MSG_LEN+1);
				byte_read = read(server_sock, recvbuf, MAX_MSG_LEN);
				if (byte_read > 0){
					recvbuf[byte_read] = '\0';
					printf("%s", recvbuf);

				}else if (byte_read == 0){

					// server send EOF
					if (stdineof == 1)
						return 0;
					printf("Server EOF, exit\n");
					exit(0);
				}else{
					if ((errno == EAGAIN) || (errno == EINTR))
						break;

					// error read
					printf("Error read, exit\n");
					close(server_sock);
					exit(0);
				}
			}while (byte_read > 0);
		}
	    
		// get a line from screen
		if (FD_ISSET(fileno(stdin), &read_fds)){
			if (!fgets(sendbuf, MAX_MSG_LEN, stdin)){
				// stdin EOF
				stdineof = 1;
				shutdown(server_sock, SHUT_WR);
				FD_CLR(fileno(stdin), &read_fds);
				continue;
			}

			// add \r\n if not
			if (!(end = strstr(sendbuf, "\r\n"))){
				end = strchr(sendbuf, '\n');
			}
			if (!end){
				printf("Error finding \\n\n");
				close(server_sock);
				exit(1);
			}
			strcpy(end, "\r\n");
			
			// send the line to the server
			Rio_writen(server_sock, sendbuf, strlen(sendbuf));
		}
	}

	close(server_sock);
	return 0;
}
Example #10
0
File: tcp.c Project: 337240552/node
void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) {
  int status;
  int sys_error;
  unsigned int i;
  uv_tcp_accept_t* req;

  if (handle->flags & UV_HANDLE_CONNECTION &&
      handle->flags & UV_HANDLE_SHUTTING &&
      !(handle->flags & UV_HANDLE_SHUT) &&
      handle->write_reqs_pending == 0) {

    if (shutdown(handle->socket, SD_SEND) != SOCKET_ERROR) {
      status = 0;
      handle->flags |= UV_HANDLE_SHUT;
    } else {
      status = -1;
      sys_error = WSAGetLastError();
    }
    if (handle->shutdown_req->cb) {
      if (status == -1) {
        uv__set_sys_error(loop, sys_error);
      }
      handle->shutdown_req->cb(handle->shutdown_req, status);
    }

    DECREASE_PENDING_REQ_COUNT(handle);
    return;
  }

  if (handle->flags & UV_HANDLE_CLOSING &&
      handle->reqs_pending == 0) {
    assert(!(handle->flags & UV_HANDLE_CLOSED));
    handle->flags |= UV_HANDLE_CLOSED;

    if (!(handle->flags & UV_HANDLE_CONNECTION) && handle->accept_reqs) {
      if (handle->flags & UV_HANDLE_EMULATE_IOCP) {
        for (i = 0; i < uv_simultaneous_server_accepts; i++) {
          req = &handle->accept_reqs[i];
          if (req->wait_handle != INVALID_HANDLE_VALUE) {
            UnregisterWait(req->wait_handle);
            req->wait_handle = INVALID_HANDLE_VALUE;
          }
          if (req->event_handle) {
            CloseHandle(req->event_handle);
            req->event_handle = NULL;
          }
        }
      }

      free(handle->accept_reqs);
      handle->accept_reqs = NULL;
    }

    if (handle->close_cb) {
      handle->close_cb((uv_handle_t*)handle);
    }

    loop->active_tcp_streams--;

    uv_unref(loop);
  }
}
Example #11
0
static int
ssl_connect(struct stream *stream)
{
    struct ssl_stream *sslv = ssl_stream_cast(stream);
    int retval;

    switch (sslv->state) {
    case STATE_TCP_CONNECTING:
        retval = check_connection_completion(sslv->fd);
        if (retval) {
            return retval;
        }
        sslv->state = STATE_SSL_CONNECTING;
        setsockopt_tcp_nodelay(sslv->fd);
        /* Fall through. */

    case STATE_SSL_CONNECTING:
        /* Capture the first few bytes of received data so that we can guess
         * what kind of funny data we've been sent if SSL negotiation fails. */
        if (sslv->n_head <= 0) {
            sslv->n_head = recv(sslv->fd, sslv->head, sizeof sslv->head,
                                MSG_PEEK);
        }

        retval = (sslv->type == CLIENT
                   ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
        if (retval != 1) {
            int error = SSL_get_error(sslv->ssl, retval);
            if (retval < 0 && ssl_wants_io(error)) {
                return EAGAIN;
            } else {
                int unused;

                interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
                                     : "SSL_accept"), retval, error, &unused);
                shutdown(sslv->fd, SHUT_RDWR);
                stream_report_content(sslv->head, sslv->n_head, STREAM_SSL,
                                      THIS_MODULE, stream_get_name(stream));
                return EPROTO;
            }
        } else if (bootstrap_ca_cert) {
            return do_ca_cert_bootstrap(stream);
        } else if (verify_peer_cert
                   && ((SSL_get_verify_mode(sslv->ssl)
                       & (SSL_VERIFY_NONE | SSL_VERIFY_PEER))
                       != SSL_VERIFY_PEER)) {
            /* Two or more SSL connections completed at the same time while we
             * were in bootstrap mode.  Only one of these can finish the
             * bootstrap successfully.  The other one(s) must be rejected
             * because they were not verified against the bootstrapped CA
             * certificate.  (Alternatively we could verify them against the CA
             * certificate, but that's more trouble than it's worth.  These
             * connections will succeed the next time they retry, assuming that
             * they have a certificate against the correct CA.) */
            VLOG_INFO("rejecting SSL connection during bootstrap race window");
            return EPROTO;
        } else {
            return 0;
        }
    }

    OVS_NOT_REACHED();
}
Example #12
0
int
main(int argc, char **argv)
{
  char inpstr[2000], authstr[2000];
  char buffer[1000], *miasma;
  char *next, *current;
  int len, i, ret;
  int host_socket;
  fd_set readmask;
  pid_t ident_pid;

  printf("*** ArIdent Daemon Version 2.0.2\n*** Forking...\n");

  /* not even think in turning this into a switch. Been there, done that. */
  ret = (int) fork();
  if (ret == -1) { exit(1);  }
  if (ret !=  0) { _exit(0); }

  setsid();
  if (argc) {
    /* make it look pwetty */
    sprintf(argv[0], "[ArIdent Daemon for %s]", TALKERNAME);
  }
  host_socket = socket_connect(SERVER, HOSTPORT);
  if (host_socket < 0) {
    printf("Error in socket_connect() to %s:%s.\n", SERVER, HOSTPORT);
    exit(0);
  }
  authenticate_host(host_socket);
  ident_pid = getpid();
  printf("*** Booted successfully with PID %d ***\n", ident_pid);
  for (;;) {
    FD_ZERO(&readmask);
    FD_SET(host_socket, &readmask);
    len = select(1 + host_socket, &readmask, NULL, NULL, NULL);
    if (len == -1) {
      continue;
    }
    len = recv(host_socket, inpstr, (sizeof inpstr) - 3, 0);
    if (!len) {
#ifdef DEBUG
      printf("Disconnected from host.\n");
#endif
      shutdown(host_socket, SHUT_WR);
      close(host_socket);
      host_socket = -1;
      do {
        sleep(5);
        host_socket = socket_connect(SERVER, HOSTPORT);
      } while (host_socket < 0);
      authenticate_host(host_socket);
      continue;
    }
    inpstr[len] = '\0';
    inpstr[len + 1] = 127;
#ifdef DEBUG
    printf("RECEIVED: %s\n", inpstr);
#endif
    next = inpstr - 1;
    while (*(++next) != 127) {
      current = next;
      while (*next && *next != '\n') {
        ++next;
      }
      *next = '\0';
      if (!strncmp(current, "EXIT", 4)) {
        shutdown(host_socket, SHUT_WR);
        close(host_socket);
        exit(0);
      }
      switch (double_fork()) {
      case -1:
        exit(1);                /* fork failure */
      case 0:
        break;                  /* child continues */
      default:
        continue;               /* parent carries on the fine family tradition */
      }
      if (argc) {
        sprintf(argv[0], "[ArIdent Child for %s]", TALKERNAME);
      }
      if (!strncmp(current, "PID", 3)) {
        sprintf(buffer, "PRETURN: %u\n", ident_pid);
#ifdef DEBUG
        printf("[PID] %s\n", buffer);
#endif
        send(host_socket, buffer, strlen(buffer), 0);
        _exit(0);
      }
      if (!strncmp(current, "SITE:", 5)) {
        /* They want a site. So call the site function and send a message back. */
        miasma = current + 6;
        sprintf(buffer, "RETURN: %s %s\n", miasma, get_proc(miasma));
#ifdef DEBUG
        printf("[SITE] %s\n", buffer);
#endif
        send(host_socket, buffer, strlen(buffer), 0);
        _exit(0);
      }
      if (!strncmp(current, "AUTH:", 5)) {
        char word[MAX_WORDS + 1][WORD_LEN + 1];
        struct timeval t_struct;
        int auth_socket;

        /* They want a username. So setup nice sockets stuff. */
        miasma = current + 6;
        wordfind(miasma, word);
        miasma = strchr(word[3], '!');
        if (miasma) {
          *miasma = '\0';
        }
        auth_socket = socket_connect(word[3], "113");
        if (auth_socket < 0) {
          _exit(0);
        }
        sprintf(buffer, "%s, %s\n", word[1], word[2]);
        send(auth_socket, buffer, strlen(buffer), 0);
        for (;;) {
          FD_ZERO(&readmask);
          FD_SET(auth_socket, &readmask);
          t_struct.tv_sec = 10;
          t_struct.tv_usec = 0;
          len = select(1 + auth_socket, &readmask, NULL, NULL, &t_struct);
          if (len == -1) {
            continue;
          }
          if (!len) {
            shutdown(auth_socket, SHUT_WR);
            close(auth_socket);
            _exit(0);
          }
          len = recv(auth_socket, authstr, (sizeof authstr) - 3, 0);
          if (!len) {
            shutdown(auth_socket, SHUT_WR);
            close(auth_socket);
            _exit(0);
          }
          if (len > 255 || len < 5) {
            shutdown(auth_socket, SHUT_WR);
            close(auth_socket);
            _exit(0);
          }
          authstr[len] = '\0';  /* Find the last "word" in inpstr. */
          if (strstr(authstr, "ERROR")) {
            shutdown(auth_socket, SHUT_WR);
            close(auth_socket);
            _exit(0);
          }
          for (i = len - 1; i > 2; --i) {
            if (authstr[i] == ' ' || authstr[i] == ':') {
              miasma = authstr + i + 1;
              sprintf(buffer, "ARETURN: %s %s %s\n", word[1],
                      word[0], miasma);
#ifdef DEBUG
              printf("[AUTH] %s\n", buffer);
#endif
              send(host_socket, buffer, strlen(buffer), 0);
              shutdown(auth_socket, SHUT_WR);
              close(auth_socket);
              _exit(0);
            }
          }
          shutdown(auth_socket, SHUT_WR);
          close(auth_socket);
          _exit(0);
        }
      }
      _exit(0);
    }
  }
  return 0;
}
Example #13
0
int main(int argc, const char * argv[]) {

    const char *server;
    const char *port;
    const char *user;
    const char *image_url;
    const char *message;

    programName = argv[0];

    smc_parsecommandline(argc, argv, showUsage, &server, &port, &user, &message, &image_url, &verbose);

    INFO("main()", "Using the following options: server=\"%s\", port=\"%s\", user=\"%s\", img_url=\"%s\", message=\"%s\"", server, port, user, image_url, message);

    INFO("main()", "connecting to server=\"%s\", port=\"%s\"", server, port);
    int sfd = 0;
    if (connectToServer(server, port, &sfd) != SUCCESS) {
        fprintf(stderr, "%s: connectToServer() failed for server %s and port %s: %s\n", programName, server, port, strerror(errno));
        exit(errno);
    }

    INFO("main()", "open file descriptor for writing %s", "");
    errno = SUCCESS;
    FILE *toServer = fdopen(sfd, "w");
    if (toServer == NULL) {
        fprintf(stderr, "%s: fdOpen() to write to server failed: %s\n", programName, strerror(errno));
        close(sfd);
        exit(errno);
    }

    INFO("main()", "sending data to server %s", server);
    if (sendData(toServer, "user="******"%s: sendData() for param user=<user> failed: %s\n", programName, strerror(errno));
        shutdown(sfd, SHUT_RDWR);
        fclose(toServer);
        exit(errno);
    }

    if (image_url != NULL) {
        INFO("main()", "found image, sending to server %s", server);
        if (sendData(toServer, "img=", image_url) == ERROR) {
            fprintf(stderr, "%s: sendData() for param img=<image_url> failed: %s\n", programName, strerror(errno));
            shutdown(sfd, SHUT_RDWR);
            fclose(toServer);
            exit(errno);
        }
    }

    INFO("main()", "send message to server %s", server);
    if (sendData(toServer, "", message) == ERROR) {
        fprintf(stderr, "%s: sendData() for message failed: %s\n", programName, strerror(errno));
        shutdown(sfd, SHUT_RDWR);
        fclose(toServer);
        exit(errno);
    }

    /* fclose schließt auch sfd, daher vorher ein dup */
    INFO("main()", "creating backup of file descriptor %s", "");
    int backupOfSfd = dup(sfd);

    INFO("main()", "closing connection to server %s", server);
    if (shutdown(sfd, SHUT_WR) != SUCCESS) {
        fprintf(stderr, "%s: shutDown() SHUT_WR for server connection failed: %s\n", programName, strerror(errno));
        fclose(toServer);
        exit(EXIT_FAILURE);
    }

    INFO("main()", "closing file descriptor %s", "");
    fclose(toServer);
    INFO("main()", "closed writing channel to server %s", server);

    INFO("main()", "open stream from server %s", server);
    FILE *fromServer = fdopen(backupOfSfd, "r");
    if (fromServer == NULL) {
        fprintf(stderr, "%s: fdOpen() to read from server failed: %s\n", programName, strerror(errno));
        close(backupOfSfd);
        exit(errno);
    }
    INFO("main()", "opened reading channel from server %s", server);
    /* read line for status=... */
    /* if status returned from server != 0 then exit using the status */
    int status = ERROR;

    INFO("main()", "start checking server response %s", "");
    if (checkServerResponseStatus(fromServer, &status) != SUCCESS || status != SUCCESS) {
        fprintf(stderr, "%s: reading server response failed with error %d\n", programName, status);
        fclose(fromServer);
        close(backupOfSfd);
        exit(status);
    }
    INFO("main()", "server returned status %d", status);

    INFO("main()", "start receiving files from server %s", server);
    int canTransferFile = SUCCESS;
    while (canTransferFile != DONE) {
        canTransferFile = transferFile(fromServer);
        if (canTransferFile == ERROR) {
            fprintf(stderr, "%s: transferFile() failed: %s\n", programName, strerror(errno));
            fclose(fromServer);
            close(backupOfSfd);
            exit(EXIT_FAILURE);
        }
    }

    INFO("main()", "received all data, closing connection to server %s", server);
    fclose(fromServer);
    close(backupOfSfd);
    INFO("main()", "closed connection to server %s", server);
    INFO("main()", "bye %s!", user);
    exit(status);
}
Example #14
0
File: main.c Project: olebole/iraf
/* CLSHUTDOWN -- Public entry for shutdown.
 */
void
clshutdown (void)
{
	shutdown();
}
Example #15
0
bool CRTSPClient::OpenStream(char* url)
{
  LogDebug("CRTSPClient::OpenStream()");
  m_session=NULL;
	
  strcpy(m_url,url);
  // Open the URL, to get a SDP description: 
  char* sdpDescription= getSDPDescriptionFromURL(m_ourClient, url, ""/*username*/, ""/*password*/,""/*proxyServerName*/, 0/*proxyServerPortNum*/,1234/*desiredPortNum*/);
  if (sdpDescription == NULL) 
  {
    LogDebug("Failed to get a SDP description from URL %s %s",url ,m_env->getResultMsg() );
    shutdown();
    return false;
  }
  //LogDebug("Opened URL %s %s",url,sdpDescription);

  char* range=strstr(sdpDescription,"a=range:npt=");
  if (range!=NULL)
  {
    char *pStart = range+strlen("a=range:npt=");
    char *pEnd = strstr(range,"-") ;
    if (pEnd!=NULL)
    {
      pEnd++ ;
      double Start=atof(pStart) ;
      double End=atof(pEnd) ;

      LogDebug("rangestart:%f rangeend:%f", Start,End);
      m_duration=((End-Start)*1000.0);
    }
  }
  // Create a media session object from this SDP description:
  m_session = MediaSession::createNew(*m_env, sdpDescription);
  delete[] sdpDescription;
  if (m_session == NULL) 
  {
    LogDebug("Failed to create a MediaSession object from the SDP description:%s ",m_env->getResultMsg());
    shutdown();
    return false;
  } 
  else if (!m_session->hasSubsessions()) 
  {
    LogDebug("This session has no media subsessions");
    shutdown();
    return false;
  }

  // Then, setup the "RTPSource"s for the session:
  MediaSubsessionIterator iter(*m_session);
  MediaSubsession *subsession;
  Boolean madeProgress = False;
  char const* singleMediumToTest = singleMedium;
  while ((subsession = iter.next()) != NULL) 
  {
    // If we've asked to receive only a single medium, then check this now:
    if (singleMediumToTest != NULL) 
    {
      if (strcmp(subsession->mediumName(), singleMediumToTest) != 0) 
      {
        LogDebug("Ignoring %s %s %s" , subsession->mediumName(),subsession->codecName(),singleMedium);
        continue;
      } 
      else 
      {
        // Receive this subsession only
        singleMediumToTest = "xxxxx";
        // this hack ensures that we get only 1 subsession of this type
      }
    }
    if (desiredPortNum != 0) 
    {
      subsession->setClientPortNum(desiredPortNum);
      desiredPortNum += 2;
    }

    if (createReceivers) 
    {
      if (!subsession->initiate(simpleRTPoffsetArg)) 
      {
        LogDebug("Unable to create receiver for %s %s %s" ,subsession->mediumName(),subsession->codecName(),m_env->getResultMsg());
      } 
      else 
      {
        LogDebug("Created receiver for %s %s %d %d " ,subsession->mediumName(),subsession->codecName(),subsession->clientPortNum(),subsession->clientPortNum()+1 );
        madeProgress = True;

        if (subsession->rtpSource() != NULL) 
        {
          // Because we're saving the incoming data, rather than playing
          // it in real time, allow an especially large time threshold
          // (1 second) for reordering misordered incoming packets:
          
          int socketNum= subsession->rtpSource()->RTPgs()->socketNum();
          LogDebug("rtsp:increaseReceiveBufferTo to 2000000 for s:%d",socketNum);
          increaseReceiveBufferTo( *m_env, socketNum, 2000000 );

          unsigned const thresh = 1000000; // 1 second 
          subsession->rtpSource()->setPacketReorderingThresholdTime(thresh);

          if (socketInputBufferSize > 0) 
          {
            // Set the RTP source's input buffer size as specified:
            int socketNum= subsession->rtpSource()->RTPgs()->socketNum();
            unsigned curBufferSize= getReceiveBufferSize(*m_env, socketNum);
            unsigned newBufferSize= setReceiveBufferTo(*m_env, socketNum, socketInputBufferSize);
            LogDebug( "Changed socket receive buffer size for the %s %s %d %d",
            subsession->mediumName(),subsession->codecName(),curBufferSize,newBufferSize);
          }
        }
      }
    } 
    else 
    {
      if (subsession->clientPortNum() == 0) 
      {
        LogDebug("No client port was specified for the %s %s",subsession->mediumName(),subsession->codecName());
      } 
      else 
      {	
        madeProgress = True;
      }
    }
  }
  if (!madeProgress) 
  {
    shutdown();
    return false;
  }
	
  // Perform additional 'setup' on each subsession, before playing them:
  if (!setupStreams())
  {
    return false;
  }

  // Create output files:
  // Create and start "FileSink"s for each subsession:
  madeProgress = False;
  iter.reset();
  while ((subsession = iter.next()) != NULL) 
  {
    if (subsession->readSource() == NULL) continue; // was not initiated
		
    CMemorySink* fileSink= CMemorySink::createNew(*m_env,m_buffer,fileSinkBufferSize);
    subsession->sink = fileSink;
    if (subsession->sink == NULL) 
    {
      LogDebug("Failed to create FileSink %s",m_env->getResultMsg());
      shutdown();
      return false;
    } 
    LogDebug("Created output sink:");;
    subsession->sink->startPlaying(*(subsession->readSource()),subsessionAfterPlaying,subsession);
				  
    // Also set a handler to be called if a RTCP "BYE" arrives
    // for this subsession:
    if (subsession->rtcpInstance() != NULL) 
    {
      subsession->rtcpInstance()->setByeHandler(subsessionByeHandler,subsession);
    }
    madeProgress = True;
  }

  return true;
}
Example #16
0
static void
manage_client_event (struct item_s *it, uint32_t evt)
{
    ssize_t rc;

    if (evt & EPOLLIN) {
        rc = splice (it->fd, NULL, it->pfd[1], NULL, PIPE_SIZE,
            SPLICE_F_MOVE | SPLICE_F_MORE | SPLICE_F_NONBLOCK);
        if (rc > 0) {
            it->loaded += rc;
            evt |= EPOLLOUT;
        }
        else if (rc == 0)
            evt |= EPOLLHUP;
        else {
            if (errno != EINTR && errno != EAGAIN)
                evt |= EPOLLERR;
        }
    }
    if (evt & EPOLLOUT) {
        if (it->loaded > 0) {
            rc = splice (it->pfd[0], NULL, it->fd, NULL, it->loaded,
                SPLICE_F_MOVE | SPLICE_F_MORE | SPLICE_F_NONBLOCK);
            if (rc > 0)
                it->loaded -= rc;
            else if (rc < 0) {
                if (errno != EINTR && errno != EAGAIN)
                    evt |= EPOLLERR;
            }
        }
    }
    if ((evt & EPOLLHUP) && !(evt & EPOLLERR)) {
        shutdown (it->fd, SHUT_WR);
        it->shut = 1;
        evt |= EPOLLERR;
    }
    if (evt & EPOLLERR) {
retry_del:
        rc = epoll_ctl (fd_epoll, EPOLL_CTL_DEL, it->fd, NULL);
        if (rc < 0) {
            if (errno == EINTR)
                goto retry_del;
            if (errno != ENOENT) {
                ASSERT (rc == 0);
            }
        }

        return item_free (it);
    }
    else {
        uint32_t e = ((it->loaded > 0) ? EPOLLOUT : 0)
            | ((it->loaded < PIPE_SIZE) ? EPOLLIN : 0);

        if (e != it->events) {
            struct epoll_event epevt;

retry_mod:
            epevt.data.ptr = it;
            epevt.events = e;
            it->events = e;
            rc = epoll_ctl (fd_epoll, EPOLL_CTL_MOD, it->fd, &epevt);
            if (rc < 0) {
                if (errno == EINTR)
                    goto retry_mod;
                ASSERT (rc == 0);
            }
        }
    }
}
Example #17
0
/*
* Main loop used to continuously ask for user input
*/
int mainloop(){

	//Local variables
	int mode = 0;
	char op_code[100];
	uint16_t instAddr;
	uint16_t topAddr;
	uint16_t baseAddr;
	char fileName[100];
	char run = 1;
	char in[100];
	regA.data = 0;
	regSTAT.data = 0;
	nibble currentInst;
	int tempAddress = 0;
	int instrRun = 0;
	struct timespec gettime_now;
	struct timespec newTime = {0, 0};
	long totalFirstTime;
	long totalSecondTime;
	long firstTime;
	long secondTime;
	long period = 200000;
	char step = 0;




	while(run){

		if(mode == USERMODE)
			printf("Input: ");
		fgets(in, 99, stdin);
		sscanf(in, "%s %hu %hu", op_code, &instAddr, &topAddr);

		//Process input
		if(!strcmp(op_code, "~q")){
			printf("Halting\n");
			run = 0;
		}
		else if(!strcmp(op_code, "~pm")){
			printMem(instAddr, topAddr);
		}
		else if(!strcmp(op_code, "~pr")){
			printReg();
		}
		else if(!strcmp(op_code, "~in")){
			printf("Enter file name, followed by an address to load at: ");
        	        scanf("%s %hu", fileName, &baseAddr);
			puts("WARNING, make sure the base address is set correctly when assembling file");
			while(getchar()!= '\n');
			if(readBin(fileName, baseAddr) == -1){
                        	printf("Entering User Input Mode");
   				mode = USERMODE;
			}
		}
		else if(!strcmp(op_code, "~run")){
			regPC = instAddr;
			instrRun = 0;
			regSTAT.data &= 0xD;
			mode = FILEMODE;
			step = 0;
		}
		else if(!strcmp(op_code, "~step")){
			if(instAddr != NULL)
			{
				regPC = instAddr;
				regSTAT.data &= 0xD;
			}
			instrRun = 0;
			mode = FILEMODE;
			step = 1;
		}
		else if(!strcmp(op_code, "~cp")){
                        printf("Enter period: ");
                        scanf("%li", &period);
                        while(getchar()!= '\n');
		}
		else if(!strcmp(op_code, "~rm")){
			freeMem();
			initMem();
		}
		else {
			if(mode == USERMODE)
				decode(op_code, instAddr);
		}

		if(mode == FILEMODE){
			if(step == 0)
			{
				puts("Program started...");
			}
			else if (step == 1)
			{
				puts("Stepping forward...");
			}

			//Runs while HLT is off
			while(!(regSTAT.data & 0x2)){

				//Start of file code

				//EXECUTE FIRST 4 BITS
				currentInst = readMem(regPC);

                                clock_gettime(CLOCK_REALTIME, &gettime_now);
                                firstTime = gettime_now.tv_nsec;
                                waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_CLR = 1<<CLKPIN;
								#endif
				
				clock_gettime(CLOCK_REALTIME, &gettime_now);
                                firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_SET = 1<<CLKPIN;
								#endif
				
				//EXECUTE SECOND 4 BITS
				instAddr = 0;
				tempAddress = 0;
				tempAddress = readMem(++regPC).data;
				instAddr |= (tempAddress << 12);

                                clock_gettime(CLOCK_REALTIME, &gettime_now);
				firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2);
								#ifdef RPI
                                GPIO_CLR = 1 <<CLKPIN;
								#endif
								
				clock_gettime(CLOCK_REALTIME, &gettime_now);
                                firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_SET = 1<<CLKPIN;
								#endif

				//EXECUTE THIRD 4 BITS
	                        tempAddress = readMem(++regPC).data;
       		                instAddr |= (tempAddress << 8);


                                clock_gettime(CLOCK_REALTIME, &gettime_now);
				firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_CLR = 1<<CLKPIN;
								#endif
								
				clock_gettime(CLOCK_REALTIME, &gettime_now);
                                firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_SET = 1<<CLKPIN;
								#endif
				//EXECUTE FOURTH 4 BITS
                        	tempAddress = readMem(++regPC).data;
                        	instAddr |= (tempAddress << 4);

                                clock_gettime(CLOCK_REALTIME, &gettime_now);
				firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2 );
				#ifdef RPI
				GPIO_CLR = 1 <<CLKPIN;
				#endif

				clock_gettime(CLOCK_REALTIME, &gettime_now);
                                firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_SET = 1<<CLKPIN;
								#endif
								
				//EXECUTE FIFTH 4 BITS
                      		tempAddress = readMem(++regPC).data;
	                        instAddr |= (tempAddress);
				regPC++;

                                clock_gettime(CLOCK_REALTIME, &gettime_now);
                                firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_CLR = 1<<CLKPIN;
								#endif
								
				clock_gettime(CLOCK_REALTIME, &gettime_now);
                                firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_SET = 1<<CLKPIN;
								#endif	
								
	                        if(currentInst.data == HLT)
        	                        decode("HLT", instAddr);
                	        else if(currentInst.data == LOD)
                        	        decode("LOD", instAddr);
	                        else if(currentInst.data == STR)
        	                       	decode("STR", instAddr);
                	        else if(currentInst.data == ADD)
                        	        decode("ADD", instAddr);
	                        else if(currentInst.data == NOP)
        	                        decode("NOP", instAddr);
                	        else if(currentInst.data == NND)
                        	        decode("NND", instAddr);
	                        else if(currentInst.data == CXA)
        	                       	decode("CXA", instAddr);
                	        else if(currentInst.data == JMP)
                        	        decode("JMP", instAddr);
	                        else
									#ifndef __MINGW32__
        	                        shutdown(UNKNOWNINSTRUCTIONERROR);
									#endif
									#ifdef __MINGW32__
									shutdown_vm4(UNKNOWNINSTRUCTIONERROR);
									#endif

                                clock_gettime(CLOCK_REALTIME, &gettime_now);
                                firstTime = gettime_now.tv_nsec;
                                waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_CLR = 1 <<CLKPIN;
								#endif
								
				clock_gettime(CLOCK_REALTIME, &gettime_now);
                                firstTime = gettime_now.tv_nsec;
				waitForPeriod(firstTime,gettime_now,period/2 );
								#ifdef RPI
                                GPIO_SET = 1<<CLKPIN;
								#endif

				if(step == 1)
				{
					break;
				}

			}
		if((regSTAT.data & 0x2) && step)
		{
			puts("Computer halted");
		}
		mode = USERMODE;
		if(step == 0)
		{
			puts("Program finished");
			printf("Instructions run %d\n", instrRun);
			#ifdef RPI
			GPIO_CLR = 1 << CLKPIN;
			#endif
		}
		}

	}

	return 1;
}
Example #18
0
void Viewer::mainloop() {
    Timer timer;
    Timer total;

    if (m_print_perf)
        fmt::print("Rendering frame {}\n", m_frame);
    m_scene_changed = false;
    m_frame++;

    int current_time = SDL_GetTicks();
    double dt = (current_time - m_last_frame_time) / 1000.0;
    m_last_frame_time = current_time;
    auto fps = 1. / dt;

    // Input
    SDL_Event e;
    while (SDL_PollEvent(&e)) {
        if (e.type == SDL_QUIT) {
            shutdown();
        }

        if (e.type == SDL_KEYDOWN) {
            if (e.key.keysym.sym == SDLK_ESCAPE) {
                shutdown();
            }
            if (e.key.keysym.sym == SDLK_b) {
                m_debug = !m_debug;
            }
            if (e.key.keysym.sym == SDLK_n) {
                m_print_perf = !m_print_perf;
            }
            if (e.key.keysym.sym == SDLK_1) {
                m_stride_x = 1;
                m_stride_y = 1;
                m_scene_changed = true;
            }
            if (e.key.keysym.sym == SDLK_2) {
                m_stride_x = 2;
                m_stride_y = 2;
                m_scene_changed = true;
            }
            if (e.key.keysym.sym == SDLK_3) {
                m_stride_x = 4;
                m_stride_y = 4;
                m_scene_changed = true;
            }
        }

        if (e.type == SDL_MOUSEBUTTONDOWN) {
            if (e.button.button == SDL_BUTTON_RIGHT) {
                if (m_look_mode) {
                    m_look_mode = false;
                    SDL_SetRelativeMouseMode(SDL_FALSE);
                } else if (!m_look_mode) {
                    m_look_mode = true;
                    SDL_SetRelativeMouseMode(SDL_TRUE);
                }
            }
        }
    }

    float cam_speed = .8f * dt;

    // Left/right
    const uint8_t *keystates = SDL_GetKeyboardState(0);
    if (keystates[SDL_SCANCODE_A]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) - Camera::right(m_camera) * cam_speed);
    } else if (keystates[SDL_SCANCODE_D]) {
        Camera::set_pos(m_camera, Camera::pos(m_camera) + Camera::right(m_camera) * cam_speed);
        m_scene_changed = true;
    }

    // Up/down
    if (keystates[SDL_SCANCODE_SPACE]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) + glm::vec3{0, 1, 0} * cam_speed);
    } else if (keystates[SDL_SCANCODE_LCTRL]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) - glm::vec3{0, 1, 0} * cam_speed);
    }

    // Roll
    if (keystates[SDL_SCANCODE_Q]) {
        m_scene_changed = true;
        Camera::set_world_up(m_camera, glm::rotateZ(Camera::up(m_camera), 0.1f));
    } else if (keystates[SDL_SCANCODE_E]) {
        m_scene_changed = true;
        Camera::set_world_up(m_camera, glm::rotateZ(Camera::up(m_camera), -0.1f));
    }

    // Front/back
    if (keystates[SDL_SCANCODE_W]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) + Camera::dir(m_camera) * cam_speed);
    } else if (keystates[SDL_SCANCODE_S]) {
        m_scene_changed = true;
        Camera::set_pos(m_camera, Camera::pos(m_camera) - Camera::dir(m_camera) * cam_speed);
    }

    // Rendering here
    int width;
    int height;
    SDL_GetWindowSize(m_window, &width, &height);

    glm::ivec2 mouse_pos;
    if (m_look_mode) {
        // Yaw
        SDL_GetRelativeMouseState(&(mouse_pos.x), &(mouse_pos.y));
        if (mouse_pos.x != 0) {
            m_scene_changed = true;
            Camera::set_dir(m_camera, glm::rotateY(Camera::dir(m_camera), mouse_pos.x * 0.001f));
        }

        // Pitch
        if (mouse_pos.y != 0) {
            m_scene_changed = true;
            Camera::set_dir(m_camera,
                            glm::rotate(Camera::dir(m_camera), mouse_pos.y * 0.001f,
                                        glm::cross(Camera::up(m_camera), Camera::dir(m_camera))));
        }

    } else if (!m_look_mode) {
        SDL_GetMouseState(&(mouse_pos.x), &(mouse_pos.y));
    }

    if (m_scene_changed) {
        m_samples_accumulated = 0;
    }

    if (m_print_perf)
        fmt::print("    {:<15} {:>10.3f} ms\n", "Input handling", timer.elapsed());

    Scene::rebuild(m_scene);

    if (m_print_perf)
        fmt::print("    {:<15} {:=10.3f} ms\n", "Scene rebuild", timer.elapsed());

    const auto luminance = m_renderer->render(m_scene_changed, m_stride_x, m_stride_y);
    if (m_print_perf) {
        m_renderer->print_last_frame_timings();
    }

    m_samples_accumulated += 1;

    timer.reset();

// This striding is just for speeding up
// We're basically drawing really big pixels here
#pragma omp parallel for collapse(2) schedule(dynamic, 1024)
    for (auto x = 0; x < width; x += m_stride_x) {
        for (auto y = 0; y < height; y += m_stride_y) {
            glm::vec4 color = luminance[y * width + x] / static_cast<float>(m_samples_accumulated);
            for (auto u = 0; u < m_stride_x; u++) {
                for (auto v = 0; v < m_stride_y; v++) {
                    m_pixels[(y + v) * width + (x + u)] = trac0r::pack_color_argb(color);
                }
            }
        }
    }

    if (m_print_perf)
        fmt::print("    {:<15} {:>10.3f} ms\n", "Pixel transfer", timer.elapsed());

    // std::vector<uint32_t> m_pixels_filtered;
    // m_pixels_filtered.resize(m_screen_width * m_screen_height, 0);
    // trac0r::box_filter(m_pixels, width, height, m_pixels_filtered);
    // m_pixels = m_pixels_filtered;
    //
    // if (m_print_perf)
    //     fmt::print("    {:<15} {:>10.3f} ms\n", "Image filtering", timer.elapsed());

    SDL_RenderClear(m_render);
    SDL_UpdateTexture(m_render_tex, 0, m_pixels.data(), width * sizeof(uint32_t));
    SDL_RenderCopy(m_render, m_render_tex, 0, 0);

    if (m_debug) {
        // Lots of debug info
        glm::vec2 mouse_rel_pos =
            Camera::screenspace_to_camspace(m_camera, mouse_pos.x, mouse_pos.y);
        glm::vec3 mouse_canvas_pos = Camera::camspace_to_worldspace(m_camera, mouse_rel_pos);

        auto fps_debug_info = "FPS: " + std::to_string(int(fps));
        auto scene_changing_info = "Samples : " + std::to_string(m_samples_accumulated);
        scene_changing_info += " Scene Changing: " + std::to_string(m_scene_changed);
        auto cam_look_debug_info = "Cam Look Mode: " + std::to_string(m_look_mode);
        auto cam_pos_debug_info = "Cam Pos: " + glm::to_string(Camera::pos(m_camera));
        auto cam_dir_debug_info = "Cam Dir: " + glm::to_string(Camera::dir(m_camera));
        auto cam_up_debug_info = "Cam Up: " + glm::to_string(Camera::up(m_camera));
        auto cam_fov_debug_info =
            "Cam FOV (H/V): " +
            std::to_string(int(glm::degrees(Camera::horizontal_fov(m_camera)))) + "/";
        cam_fov_debug_info += std::to_string(int(glm::degrees(Camera::vertical_fov(m_camera))));
        auto cam_canvas_center_pos_info =
            "Cam Canvas Center: " + glm::to_string(Camera::canvas_center_pos(m_camera));
        auto mouse_pos_screen_info = "Mouse Pos Screen Space: " + glm::to_string(mouse_pos);
        auto mouse_pos_relative_info = "Mouse Pos Cam Space: " + glm::to_string(mouse_rel_pos);
        auto mouse_pos_canvas_info =
            "Mouse Pos Canvas World Space: " + glm::to_string(mouse_canvas_pos);

        auto fps_debug_tex =
            trac0r::make_text(m_render, m_font, fps_debug_info, {200, 100, 100, 200});
        auto scene_changing_tex =
            trac0r::make_text(m_render, m_font, scene_changing_info, {200, 100, 100, 200});
        auto cam_look_debug_tex =
            trac0r::make_text(m_render, m_font, cam_look_debug_info, {200, 100, 100, 200});
        auto cam_pos_debug_tex =
            trac0r::make_text(m_render, m_font, cam_pos_debug_info, {200, 100, 100, 200});
        auto cam_dir_debug_tex =
            trac0r::make_text(m_render, m_font, cam_dir_debug_info, {200, 100, 100, 200});
        auto cam_up_debug_tex =
            trac0r::make_text(m_render, m_font, cam_up_debug_info, {200, 100, 100, 200});
        auto cam_fov_debug_tex =
            trac0r::make_text(m_render, m_font, cam_fov_debug_info, {200, 100, 100, 200});
        auto cam_canvas_center_pos_tex =
            trac0r::make_text(m_render, m_font, cam_canvas_center_pos_info, {200, 100, 100, 200});
        auto mouse_pos_screen_tex =
            trac0r::make_text(m_render, m_font, mouse_pos_screen_info, {200, 100, 100, 200});
        auto mouse_pos_relative_tex =
            trac0r::make_text(m_render, m_font, mouse_pos_relative_info, {200, 100, 100, 200});
        auto mouse_pos_canvas_tex =
            trac0r::make_text(m_render, m_font, mouse_pos_canvas_info, {200, 100, 100, 200});

        trac0r::render_text(m_render, fps_debug_tex, 10, 10);
        trac0r::render_text(m_render, scene_changing_tex, 10, 25);
        trac0r::render_text(m_render, cam_look_debug_tex, 10, 40);
        trac0r::render_text(m_render, cam_pos_debug_tex, 10, 55);
        trac0r::render_text(m_render, cam_dir_debug_tex, 10, 70);
        trac0r::render_text(m_render, cam_up_debug_tex, 10, 85);
        trac0r::render_text(m_render, cam_fov_debug_tex, 10, 100);
        trac0r::render_text(m_render, cam_canvas_center_pos_tex, 10, 115);
        trac0r::render_text(m_render, mouse_pos_screen_tex, 10, 130);
        trac0r::render_text(m_render, mouse_pos_relative_tex, 10, 145);
        trac0r::render_text(m_render, mouse_pos_canvas_tex, 10, 160);

        // Let's draw some debug to the display (such as AABBs)
        if (m_debug) {
            auto &accel_struct = Scene::accel_struct(m_scene);
            for (auto &shape : FlatStructure::shapes(accel_struct)) {
                auto &aabb = Shape::aabb(shape);
                const auto &verts = AABB::vertices(aabb);
                std::array<glm::i8vec2, 12> pairs;
                pairs[0] = {0, 1};
                pairs[1] = {1, 3};
                pairs[2] = {2, 3};
                pairs[3] = {0, 2};
                pairs[4] = {4, 5};
                pairs[5] = {5, 7};
                pairs[6] = {6, 7};
                pairs[7] = {4, 6};
                pairs[8] = {0, 4};
                pairs[9] = {1, 5};
                pairs[10] = {2, 6};
                pairs[11] = {3, 7};
                for (auto pair : pairs) {
                    auto ws1 = Camera::worldpoint_to_worldspace(m_camera, verts[pair[0]]);
                    auto ss1 = glm::i32vec2(0);
                    if (ws1 != glm::vec3(0)) {
                        auto cs1 = Camera::worldspace_to_camspace(m_camera, ws1);
                        ss1 = Camera::camspace_to_screenspace(m_camera, cs1);
                    }
                    auto ws2 = Camera::worldpoint_to_worldspace(m_camera, verts[pair[1]]);
                    auto ss2 = glm::i32vec2(0);
                    if (ws2 != glm::vec3(0)) {
                        auto cs2 = Camera::worldspace_to_camspace(m_camera, ws2);
                        ss2 = Camera::camspace_to_screenspace(m_camera, cs2);
                    }
                    if (ss1 != glm::i32vec2(0) && ss2 != glm::i32vec2(0)) {
                        aalineRGBA(m_render, ss1.x, ss1.y, ss2.x, ss2.y, 255, 255, 0, 200);
                    }
                }
            }
        }

        SDL_DestroyTexture(fps_debug_tex);
        SDL_DestroyTexture(scene_changing_tex);
        SDL_DestroyTexture(cam_look_debug_tex);
        SDL_DestroyTexture(cam_pos_debug_tex);
        SDL_DestroyTexture(cam_dir_debug_tex);
        SDL_DestroyTexture(cam_up_debug_tex);
        SDL_DestroyTexture(cam_fov_debug_tex);
        SDL_DestroyTexture(cam_canvas_center_pos_tex);
        SDL_DestroyTexture(mouse_pos_screen_tex);
        SDL_DestroyTexture(mouse_pos_relative_tex);
        SDL_DestroyTexture(mouse_pos_canvas_tex);
    }

    SDL_RenderPresent(m_render);

    if (m_print_perf) {
        fmt::print("    {:<15} {:>10.3f} ms\n", "Rendering", timer.elapsed());
        fmt::print("    {:<15} {:>10.3f} ms\n", "=> Budget", 1000.f / 60.f - total.peek());
        fmt::print("    {:<15} {:>10.3f} ms\n\n", "=> Total", total.peek());
    }

    m_frame_total += total.elapsed();
    if (m_benchmark_mode < 0 && m_max_frames != 0 && m_frame > m_max_frames) {
        auto filename = std::string("trac0r-") + std::to_string(m_max_frames) + std::string(".bmp");
        SDL_Surface *sshot = SDL_CreateRGBSurface(0, m_screen_width, m_screen_height, 32,
                                                  0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
        SDL_RenderReadPixels(m_render, NULL, SDL_PIXELFORMAT_ARGB8888, sshot->pixels, sshot->pitch);
        SDL_SaveBMP(sshot, filename.c_str());
        SDL_FreeSurface(sshot);
        shutdown();
    } else if (m_benchmark_mode > 0 && m_max_frames != 0 && m_frame > m_max_frames) {
        fmt::print("Benchmark results:\n");
        fmt::print("    {:<15} {:>10}\n", "Frames rendered", m_max_frames);
        fmt::print("    {:<15} {:>10.3f} ms\n", "Total runtime", m_frame_total);
        fmt::print("    {:<15} {:>10.3f} ms\n", "Avg. frame", m_frame_total / m_max_frames);
        fmt::print("    {:<15} {:>10.3f} FPS\n", "Avg. FPS",
                   1.f / ((m_frame_total / 1000.f) / m_max_frames));
        shutdown();
    }
}
Example #19
0
bool runServer(const McrouterStandaloneOptions& standaloneOpts,
               const McrouterOptions& mcrouterOpts) {
  AsyncMcServer::Options opts;

  if (standaloneOpts.listen_sock_fd >= 0) {
    opts.existingSocketFd = standaloneOpts.listen_sock_fd;
  } else if (!standaloneOpts.unix_domain_sock.empty()) {
    opts.unixDomainSockPath = standaloneOpts.unix_domain_sock;
  } else {
    opts.ports = standaloneOpts.ports;
    opts.sslPorts = standaloneOpts.ssl_ports;
    opts.pemCertPath = mcrouterOpts.pem_cert_path;
    opts.pemKeyPath = mcrouterOpts.pem_key_path;
    opts.pemCaPath = mcrouterOpts.pem_ca_path;
  }

  opts.numThreads = mcrouterOpts.num_proxies;

  opts.setPerThreadMaxConns(standaloneOpts.max_conns, opts.numThreads);
  opts.worker.defaultVersionHandler = false;
  opts.worker.maxInFlight = standaloneOpts.max_client_outstanding_reqs;
  opts.worker.sendTimeout = std::chrono::milliseconds{
    standaloneOpts.client_timeout_ms};
  if (!mcrouterOpts.debug_fifo_root.empty()) {
    opts.worker.debugFifoPath = getServerDebugFifoFullPath(mcrouterOpts);
  }

  /* Default to one read per event to help latency-sensitive workloads.
     We can make this an option if this needs to be adjusted. */
  opts.worker.maxReadsPerEvent = 1;

  try {
    LOG(INFO) << "Spawning AsyncMcServer";

    AsyncMcServer server(opts);
    server.installShutdownHandler({SIGINT, SIGTERM});

    auto router = McrouterInstance::init(
      "standalone",
      mcrouterOpts,
      server.eventBases());

    if (router == nullptr) {
      LOG(ERROR) << "CRITICAL: Failed to initialize mcrouter!";
      return false;
    }

    router->addStartupOpts(standaloneOpts.toDict());

    if (standaloneOpts.postprocess_logging_route) {
      router->setPostprocessCallback(getLogPostprocessFunc<void>());
    }

    if (standaloneOpts.enable_server_compression &&
        !mcrouterOpts.enable_compression) {
      initCompression(*router);
    }

    server.spawn(
      [router, &standaloneOpts] (size_t threadId,
                                 folly::EventBase& evb,
                                 AsyncMcServerWorker& worker) {
        serverLoop(*router, threadId, evb, worker, standaloneOpts);
      },
      [router]() {
        router->shutdown();
      }
    );

    server.join();

    LOG(INFO) << "Shutting down";

    McrouterInstance::freeAllMcrouters();

    if (!opts.unixDomainSockPath.empty()) {
      std::remove(opts.unixDomainSockPath.c_str());
    }
  } catch (const std::exception& e) {
    LOG(ERROR) << e.what();
    return false;
  }
  return true;
}
Example #20
0
/*############################# pop3_quit() #############################*/
int
pop3_quit(void)
{
   int reply;

   if (pop3_fd != -1)
   {
      (void)command(pop3_fd, "QUIT");
      if (timeout_flag == OFF)
      {
         if ((reply = get_reply()) == INCORRECT)
         {
            (void)close(pop3_fd);
            return(INCORRECT);
         }

#ifdef _WITH_SHUTDOWN
         if (shutdown(pop3_fd, 1) < 0)
         {
            trans_log(DEBUG_SIGN, __FILE__, __LINE__, "pop3_quit", NULL,
                      _("shutdown() error : %s"), strerror(errno));
         }
         else
         {
            int    status;
            char   buffer[32];
            fd_set rset;

            /* Initialise descriptor set */
            FD_ZERO(&rset);
            FD_SET(pop3_fd, &rset);
            timeout.tv_usec = 0L;
            timeout.tv_sec = transfer_timeout;

            /* Wait for message x seconds and then continue. */
            status = select(pop3_fd + 1, &rset, NULL, NULL, &timeout);

            if (status > 0)
            {
               if (FD_ISSET(pop3_fd, &rset))
               {
                  if ((status = read(pop3_fd, buffer, 32)) < 0)
                  {
                     trans_log(ERROR_SIGN, __FILE__, __LINE__, "pop3_quit", NULL,
                               _("read() error (%d) : %s"),
                               status, strerror(errno));
                     reply = INCORRECT;
                  }
               }
            }
            else if (status == 0)
                 {
                    /* Timeout has arrived. */
                    timeout_flag = ON;
                    reply = INCORRECT;
                 }
                 else
                 {
                    trans_log(ERROR_SIGN, __FILE__, __LINE__, "pop3_quit", NULL,
                              _("select() error : %s"), strerror(errno));
                    reply = INCORRECT;
                 }
         }
#endif
      }
      else
      {
         reply = SUCCESS;
      }

#ifdef WITH_SSL
      if (ssl_con != NULL)
      {
         SSL_free(ssl_con);
         ssl_con = NULL;
      }
#endif
      if (close(pop3_fd) == -1)
      {
         trans_log(DEBUG_SIGN, __FILE__, __LINE__, "pop3_quit", NULL,
                   _("close() error : %s"), strerror(errno));
      }
      pop3_fd = -1;
   }
   else
   {
      reply = SUCCESS;
   }

   return(reply);
}
Example #21
0
void SecureSocketImpl::close()
{
	shutdown();
	_pSocket->close();
}
Example #22
0
/*
 *  stress_socket_client()
 *	client reader
 */
static void stress_socket_client(
	uint64_t *const counter,
	const uint32_t instance,
	const uint64_t max_ops,
	const char *name,
	const pid_t ppid)
{
	struct sockaddr *addr;

	setpgid(0, pgrp);
	stress_parent_died_alarm();

	do {
		char buf[SOCKET_BUF];
		int fd;
		int retries = 0;
		socklen_t addr_len = 0;
retry:
		if (!opt_do_run) {
			(void)kill(getppid(), SIGALRM);
			exit(EXIT_FAILURE);
		}
		if ((fd = socket(opt_socket_domain, SOCK_STREAM, 0)) < 0) {
			pr_fail_dbg(name, "socket");
			/* failed, kick parent to finish */
			(void)kill(getppid(), SIGALRM);
			exit(EXIT_FAILURE);
		}

		stress_set_sockaddr(name, instance, ppid,
			opt_socket_domain, opt_socket_port,
			&addr, &addr_len);
		if (connect(fd, addr, addr_len) < 0) {
			(void)close(fd);
			usleep(10000);
			retries++;
			if (retries > 100) {
				/* Give up.. */
				pr_fail_dbg(name, "connect");
				(void)kill(getppid(), SIGALRM);
				exit(EXIT_FAILURE);
			}
			goto retry;
		}

		do {
			ssize_t n = recv(fd, buf, sizeof(buf), 0);
			if (n == 0)
				break;
			if (n < 0) {
				if (errno != EINTR)
					pr_fail_dbg(name, "recv");
				break;
			}
		} while (opt_do_run && (!max_ops || *counter < max_ops));
		(void)shutdown(fd, SHUT_RDWR);
		(void)close(fd);
	} while (opt_do_run && (!max_ops || *counter < max_ops));

#ifdef AF_UNIX
	if (opt_socket_domain == AF_UNIX) {
		struct sockaddr_un *addr_un = (struct sockaddr_un *)addr;
		(void)unlink(addr_un->sun_path);
	}
#endif
	/* Inform parent we're all done */
	(void)kill(getppid(), SIGALRM);
}
Example #23
0
int
main(void)
{
	int num;

	num = 1;
	printf("1..18\n");
	fflush(stdout);

	/* Large write with close */
	setup();
	if (poll(&pfd0, 1, 0) == -1)
		err(1, "poll");
	report(num++, "initial 0", POLLOUT, pfd0.revents);
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "initial 1", POLLOUT, pfd1.revents);
	if (write(fd[0], largeblock, sizeof(largeblock)) == -1)
		err(1, "write");
	if (poll(&pfd0, 1, 0) == -1)
		err(1, "poll");
	report(num++, "after large write", 0, pfd0.revents);
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "other side after large write", POLLIN | POLLOUT, pfd1.revents);
	close(fd[0]);
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "other side after close", POLLIN | POLLHUP, pfd1.revents);
	if (read(fd[1], largeblock, sizeof(largeblock)) == -1)
		err(1, "read");
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "other side after reading input", POLLHUP, pfd1.revents);
	close(fd[1]);

	/* With shutdown(SHUT_WR) */
	setup();
	if (shutdown(fd[0], SHUT_WR) == -1)
		err(1, "shutdown");
	if (poll(&pfd0, 1, 0) == -1)
		err(1, "poll");
	report(num++, "after shutdown(SHUT_WR)", POLLOUT, pfd0.revents);
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "other side after shutdown(SHUT_WR)", POLLIN | POLLOUT, pfd1.revents);
	switch (read(fd[1], largeblock, sizeof(largeblock))) {
		case 0:
			break;
		case -1:
			err(1, "read after other side shutdown");
			break;
		default:
			errx(1, "kernel made up data that was never written");
	}
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "other side after reading EOF", POLLIN | POLLOUT, pfd1.revents);
	if (write(fd[1], largeblock, sizeof(largeblock)) == -1)
		err(1, "write");
	if (poll(&pfd0, 1, 0) == -1)
		err(1, "poll");
	report(num++, "after data from other side", POLLIN | POLLOUT, pfd0.revents);
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "after writing", POLLIN, pfd1.revents);
	if (shutdown(fd[1], SHUT_WR) == -1)
		err(1, "shutdown second");
	if (poll(&pfd0, 1, 0) == -1)
		err(1, "poll");
	report(num++, "after second shutdown", POLLIN | POLLHUP, pfd0.revents);
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "after second shutdown", POLLHUP, pfd1.revents);
	close(fd[0]);
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "after close", POLLHUP, pfd1.revents);
	close(fd[1]);

	/*
	 * With shutdown(SHUT_RD)
	 * Note that shutdown(SHUT_WR) is passed to the peer, but
	 * shutdown(SHUT_RD) is not.
	 */
	setup();
	if (shutdown(fd[0], SHUT_RD) == -1)
		err(1, "shutdown");
	if (poll(&pfd0, 1, 0) == -1)
		err(1, "poll");
	report(num++, "after shutdown(SHUT_RD)", POLLIN | POLLOUT, pfd0.revents);
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "other side after shutdown(SHUT_RD)", POLLOUT, pfd1.revents);
	if (shutdown(fd[0], SHUT_WR) == -1)
		err(1, "shutdown");
	if (poll(&pfd0, 1, 0) == -1)
		err(1, "poll");
	report(num++, "after shutdown(SHUT_WR)", POLLHUP, pfd0.revents);
	if (poll(&pfd1, 1, 0) == -1)
		err(1, "poll");
	report(num++, "other side after shutdown(SHUT_WR)", POLLIN | POLLOUT, pfd1.revents);
	close(fd[0]);
	close(fd[1]);

	return (0);
}
Example #24
0
int Application::run(Application* self)
{
	m_self = self;

	if (!framework::Utils::exists("data/gui"))
	{
		Logger::toLog("Error: could not find gui directory. Probably working directory has not been set correctly (especially if you are running from IDE).\n");
		return EXIT_FAILURE;
	}

	init();
	m_isRunning = true;

	glfwSetErrorCallback(&Application::errorCallback);

	if (!glfwInit())
	{
		Logger::toLog("Error: glfwInit failed");
		return EXIT_FAILURE;
	}

	glfwWindowHint(GLFW_VISIBLE, GL_TRUE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	glfwWindowHint(GLFW_RED_BITS, 8);
	glfwWindowHint(GLFW_GREEN_BITS, 8);
	glfwWindowHint(GLFW_BLUE_BITS, 8);
	glfwWindowHint(GLFW_ALPHA_BITS, 0);
	glfwWindowHint(GLFW_DEPTH_BITS, 32);
	glfwWindowHint(GLFW_STENCIL_BITS, 0);

	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, m_info.majorVersion);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, m_info.minorVersion);
	#ifdef _DEBUG
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
	#endif
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_SAMPLES, m_info.samples);
    glfwWindowHint(GLFW_STEREO, m_info.flags.stereo ? GL_TRUE : GL_FALSE);

	// create window
	m_window = glfwCreateWindow(m_info.windowWidth, m_info.windowHeight, 
								m_info.title.c_str(), 
								m_info.flags.fullscreen ? glfwGetPrimaryMonitor() : NULL, 
								NULL);
	if (!m_window)
    {
        glfwTerminate();
        return EXIT_FAILURE;
    }

	glfwSetWindowSizeCallback(m_window, &Application::_setWindowSize);
    glfwSetKeyCallback(m_window, &Application::_onKey);
	glfwSetCharCallback(m_window, &Application::_onChar);
    glfwSetMouseButtonCallback(m_window, &Application::_onMouse);
    glfwSetCursorPosCallback(m_window, &Application::_onCursor);
    glfwSetScrollCallback(m_window, &Application::_onScroll);
	glfwSetInputMode(m_window, GLFW_CURSOR, m_info.flags.cursor ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_HIDDEN);

	// center position
	GLFWmonitor* primary = glfwGetPrimaryMonitor();
	const GLFWvidmode* mode = glfwGetVideoMode(primary);
	int posx = (mode->width - m_info.windowWidth) >> 1;
	int posy = (mode->height - m_info.windowHeight) >> 1;
	glfwSetWindowPos(m_window, posx, posy);

	// set vsync
	glfwMakeContextCurrent(m_window);
	glfwSwapInterval((int)m_info.flags.vsync);

	// init GL3w
	gl3wInit();

	std::vector<int> multisamplingLevels;
	if (!checkOpenGLVersion() || !checkDeviceCapabilities(multisamplingLevels))
	{
		glfwDestroyWindow(m_window);
		glfwTerminate();
		return EXIT_FAILURE;
	}

	#ifdef _DEBUG
	Logger::toLogWithFormat("Video adapter: %s - %s, OpenGL: %s\n", (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER), (const char*)glGetString(GL_VERSION));
	#endif

    if (m_info.flags.debug)
    {
        if (gl3wIsSupported(4, 3))
        {
            glDebugMessageCallback(debugCallback, this);
            glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
        }
        else if (IsExtensionSupported("GL_ARB_debug_output"))
        {
            glDebugMessageCallbackARB(debugCallback, this);
            glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
        }
    }

	initGui();

	if (!StandardGpuPrograms::init())
	{
		glfwDestroyWindow(m_window);
		glfwTerminate();
		return EXIT_FAILURE;
	}
	initAxes();
	startup(m_rootWindow);

	do
    {
		glfwMakeContextCurrent(m_window);
		Texture::beginFrame();
		if (fabs(m_lastTime) < 1e-7)
		{
			render(0);
			Texture::endFrame();
			renderGui(0);

			m_lastTime = glfwGetTime();
		}
		else
		{
			double curTime = glfwGetTime();
			double delta = curTime - m_lastTime;
				
			// fps counter
			measureFps(delta);

			// rendering
			render(delta);
			Texture::endFrame();
			renderGui(delta);

			m_lastTime = curTime;
		}

        glfwSwapBuffers(m_window);

		glfwPollEvents();
			
		if (glfwWindowShouldClose(m_window))
		{
            m_isRunning = GL_FALSE;
		}
		m_isRunning &= (glfwGetKey(m_window, GLFW_KEY_ESCAPE) == GLFW_RELEASE);
    } 
	while(m_isRunning);

	shutdown();
	destroyAllDestroyable();
	destroyGui();

	glfwDestroyWindow(m_window);
	glfwTerminate();
	return EXIT_SUCCESS;
}
int connect_with_timeout(char *host, int port, int timeout_sec,
		int timeout_usec, char *account)
{
	  int res, valopt;
	  struct sockaddr_in addr;
	  long arg;
	  fd_set myset;
	  struct timeval tv;
	  socklen_t lon;
	  char buffer[181] = {0};

	  /* Base64 */
	  char sender[181] = {0};
	  char receiver[181] = {0};
	  int rc;

	  // Create socket
	  int soc = socket(AF_INET, SOCK_STREAM, 0);

	  // Set non-blocking
	  arg = fcntl(soc, F_GETFL, NULL);
	  arg |= O_NONBLOCK;
	  fcntl(soc, F_SETFL, arg);

	  // Trying to connect with timeout
	  addr.sin_family = AF_INET;
	  addr.sin_port = htons(port);
	  addr.sin_addr.s_addr = inet_addr(host);
	  res = connect(soc, (struct sockaddr *)&addr, sizeof(addr));

	  if (res < 0) {
	     if (errno == EINPROGRESS) {
	        tv.tv_sec = timeout_sec;
	        tv.tv_usec = timeout_usec;
	        FD_ZERO(&myset);
	        FD_SET(soc, &myset);
	        if (select(soc+1, NULL, &myset, NULL, &tv) > 0) {
	           lon = sizeof(int);
	           getsockopt(soc, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon);
	           if (valopt) {
	              return -2;
	           }
	        }
	        else {
	           return -3;
	        }
	     }
	     else {
	        return -4;
	     }
	  }

	  // Set to blocking mode again...
	  arg = fcntl(soc, F_GETFL, NULL);
	  arg &= (~O_NONBLOCK);
	  fcntl(soc, F_SETFL, arg);

	  rc = Base64Encode(account, sender, BUFFFERLEN);
	  send(soc,sender,181,NULL);
	  recv(soc, buffer, 181, NULL);
	  rc = Base64Decode(buffer, receiver, BUFFFERLEN);

	  printf ("Connect to server: account= %s, buffer = %s\n", account, buffer);
	  if (strcmp(buffer,"Failed"))
	  {
		  return soc;
	  }
	  else
	  {
		shutdown(soc,2);
		return -5;
	  }
}
Example #26
0
/**
 * @brief
 *      This function provides the port forwarding feature for forwarding the
 *      X data from mom to qsub and from qsub to the X server.
 *
 * @param socks[in] - Input structure which tracks the sockets that are active
 *                    and data read/written by peers.
 * @param connfunc[in] - Function pointer pointing to a function used for
 *                       either connecting the X server (if running in qsub) or
 *                       connecting qsub (if running in mom).
 * @param phost[in] - peer host that needs to be connected.
 * @param pport[in] - peer port number.
 * @param inter_read_sock[in] -  socket descriptor from where mom and qsub
 *                               readers read data.
 * @param readfunc[in] - function pointer pointing to the mom and qsub readers.
 * @param logfunc[in] - Function pointer for log function
 *
 * @return void
 */
void
port_forwarder(
	struct pfwdsock *socks,
	int (*connfunc)(char *, long),
	char *phost,
	int pport,
	int inter_read_sock,
	int (*readfunc)(int),
	void (*logfunc) (char *))
{
	fd_set rfdset, wfdset, efdset;
	int rc;
	struct sockaddr_in from;
	pbs_socklen_t fromlen;
	int n, n2, sock;
	fromlen = sizeof(from);
	char err_msg[LOG_BUF_SIZE];
	int readfunc_ret;
        /*
         * Make the sockets in the socks structure non blocking
         */
	for (n = 0; n < NUM_SOCKS; n++) {
		if (!(socks + n)->active || ((socks + n)->sock < 0))
			continue;
		if (set_nonblocking((socks + n)->sock) == -1) {
			close((socks + n)->sock);
			(socks + n)->active = 0;
			snprintf(err_msg, sizeof(err_msg),
				"set_nonblocking failed for socket=%d, errno=%d",
				(socks + n)->sock, errno);
			PF_LOGGER(logfunc, err_msg);
			continue;
		}
		if (set_nodelay((socks + n)->sock) == -1) {
			snprintf(err_msg, sizeof(err_msg),
				"set_nodelay failed for socket=%d, errno=%d",
				(socks + n)->sock, errno);
			PF_LOGGER(logfunc, err_msg);
		}
	}

	while (x11_reader_go) {
		int maxsock;

		FD_ZERO(&rfdset);
		FD_ZERO(&wfdset);
		FD_ZERO(&efdset);
		maxsock = inter_read_sock + 1;
		/*setting the sock fd in rfdset for qsub and mom readers to read data*/
		FD_SET(inter_read_sock, &rfdset);
		FD_SET(inter_read_sock, &efdset);
		for (n = 0; n < NUM_SOCKS; n++) {
			if (!(socks + n)->active || ((socks + n)->sock < 0))
				continue;

			if ((socks + n)->listening) {
				FD_SET((socks + n)->sock, &rfdset);
				maxsock = (socks + n)->sock > maxsock ?(socks + n)->sock : maxsock;
			} else{
				if ((socks + n)->bufavail < PF_BUF_SIZE) {
					FD_SET((socks + n)->sock, &rfdset);
					maxsock = (socks + n)->sock > maxsock ?(socks + n)->sock : maxsock;
				}
				if ((socks + ((socks + n)->peer))->bufavail -
					(socks + ((socks + n)->peer))->bufwritten > 0) {
					FD_SET((socks + n)->sock, &wfdset);
					maxsock = (socks + n)->sock > maxsock ?(socks + n)->sock : maxsock;
				}
			}

		}

		maxsock++;

		rc = select(maxsock, &rfdset, &wfdset, &efdset, NULL);
		if ((rc == -1) && (errno == EINTR))
			continue;
		if (rc < 0) {
			snprintf(err_msg, sizeof(err_msg),
				"port forwarding select() error");
			PF_LOGGER(logfunc, err_msg);
			return;
		}
		if (FD_ISSET(inter_read_sock, &efdset)) {
			snprintf(err_msg, sizeof(err_msg),
				"exception for socket=%d, errno=%d",
				inter_read_sock, errno);
			PF_LOGGER(logfunc, err_msg);
			close(inter_read_sock);
			return;
		}
		if (FD_ISSET(inter_read_sock, &rfdset)) {
			/*calling mom/qsub readers*/
			readfunc_ret = readfunc(inter_read_sock);
			if (readfunc_ret == -1) {
				snprintf(err_msg, sizeof(err_msg),
					"readfunc failed for socket:%d", inter_read_sock);
				PF_LOGGER(logfunc, err_msg);
			}
			if (readfunc_ret  < 0) {
				return;
			}
		}

		for (n = 0; n < NUM_SOCKS; n++) {
			if (!(socks + n)->active || ((socks + n)->sock < 0))
				continue;
			if (FD_ISSET((socks + n)->sock, &rfdset)) {
				if ((socks + n)->listening && (socks + n)->active) {
					int newsock = 0, peersock = 0;
					if ((sock = accept((socks + n)->sock, (struct sockaddr *)
						& from, &fromlen)) < 0) {
						if ((errno == EAGAIN) || (errno == EWOULDBLOCK)
							|| (errno == EINTR) || (errno == ECONNABORTED))
							continue;
						snprintf(err_msg, sizeof(err_msg),
							"closing the socket %d after accept call failure, errno=%d",
							(socks + n)->sock, errno);
						PF_LOGGER(logfunc, err_msg);
						close((socks + n)->sock);
						(socks + n)->active = 0;
						continue;
					}
                                        /*
                                         * Make the sock non blocking
                                         */
					if (set_nonblocking(sock) == -1) {
						snprintf(err_msg, sizeof(err_msg),
							"set_nonblocking failed for socket=%d, errno=%d",
							sock, errno);
						PF_LOGGER(logfunc, err_msg);
						close(sock);
						continue;
					}
					if (set_nodelay(sock) == -1) {
						snprintf(err_msg, sizeof(err_msg),
							"set_nodelay failed for socket=%d, errno=%d",
							sock, errno);
						PF_LOGGER(logfunc, err_msg);
					}

					newsock = peersock = 0;

					for (n2 = 0; n2 < NUM_SOCKS; n2++) {
						if ((socks + n2)->active || (((socks + n2)->peer != 0)
							&& (socks + ((socks + n2)->peer))->active))
							continue;
						if (newsock == 0)
							newsock = n2;
						else if (peersock == 0)
							peersock = n2;
						else
							break;
					}

					(socks + newsock)->sock = (socks + peersock)->remotesock
						= sock;
					(socks + newsock)->listening = (socks + peersock)->listening
						= 0;
					(socks + newsock)->active = (socks + peersock)->active = 1;
					(socks + peersock)->sock = connfunc(phost, pport);
                                        /*
                                         * Make sockets non-blocking
                                         */
					if (set_nonblocking((socks + peersock)->sock) == -1) {
						snprintf(err_msg, sizeof(err_msg),
							"set_nonblocking failed for socket=%d, errno=%d",
							(socks + peersock)->sock, errno);
						PF_LOGGER(logfunc, err_msg);
						close((socks + peersock)->sock);
						(socks + peersock)->active = 0;
						continue;
					}
					if (set_nodelay((socks + peersock)->sock) == -1) {
						snprintf(err_msg, sizeof(err_msg),
							"set_nodelay failed for socket=%d, errno=%d",
							(socks + peersock)->sock, errno);
						PF_LOGGER(logfunc, err_msg);
					}
					(socks + newsock)->bufwritten = (socks + peersock)->bufwritten = 0;
					(socks + newsock)->bufavail = (socks + peersock)->bufavail = 0;
					(socks + newsock)->buff[0] = (socks + peersock)->buff[0] = '\0';
					(socks + newsock)->peer = peersock;
					(socks + peersock)->peer = newsock;
				} else{
					/* non-listening socket to be read */
					rc = read(
						(socks + n)->sock,
						(socks + n)->buff + (socks + n)->bufavail,
						PF_BUF_SIZE - (socks + n)->bufavail);
					if (rc == -1) {
						if ((errno == EWOULDBLOCK) || (errno == EAGAIN) || (errno == EINTR) || (errno == EINPROGRESS)) {
							continue;
						}
						shutdown((socks + n)->sock, SHUT_RDWR);
						close((socks + n)->sock);
						(socks + n)->active = 0;
						snprintf(err_msg, sizeof(err_msg),
							"closing the socket %d after read failure, errno=%d",
							(socks + n)->sock, errno);
						PF_LOGGER(logfunc, err_msg);
					} else if (rc == 0) {
						shutdown((socks + n)->sock, SHUT_RDWR);
						close((socks + n)->sock);
						(socks + n)->active = 0;
					} else{
						(socks + n)->bufavail += rc;
					}
				}
			} /* END if rfdset */
			if (FD_ISSET((socks + n)->sock, &wfdset)) {
				int peer = (socks + n)->peer;

				rc = write(
					(socks + n)->sock,
					(socks + peer)->buff + (socks + peer)->bufwritten,
					(socks + peer)->bufavail - (socks + peer)->bufwritten);

				if (rc == -1) {
					if ((errno == EWOULDBLOCK) || (errno == EAGAIN) || (errno == EINTR) || (errno == EINPROGRESS)) {
						continue;
					}
					shutdown((socks + n)->sock, SHUT_RDWR);
					close((socks + n)->sock);
					(socks + n)->active = 0;
					snprintf(err_msg, sizeof(err_msg),
						"closing the socket %d after write failure, errno=%d",
						(socks + n)->sock, errno);
					PF_LOGGER(logfunc, err_msg);
				} else if (rc == 0) {
					shutdown((socks + n)->sock, SHUT_RDWR);
					close((socks + n)->sock);
					(socks + n)->active = 0;
				} else{
					(socks + peer)->bufwritten += rc;
				}
			} /* END if wfdset */
			if (!(socks + n)->listening) {
				int peer = (socks + n)->peer;
				if ((socks + peer)->bufavail == (socks + peer)->bufwritten) {
					(socks + peer)->bufavail = (socks + peer)->bufwritten = 0;
				}
				if (!(socks + peer)->active && ((socks + peer)->bufwritten
					== (socks + peer)->bufavail)) {
					shutdown((socks + n)->sock, SHUT_RDWR);
					close((socks + n)->sock);
					(socks + n)->active = 0;
				}
			}

		} /* END foreach fd */


	} /* END while(x11_reader_go) */
}  /* END port_forwarder() */
Example #27
0
int ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  int status = 0;

#ifdef OPENDDS_SAFETY_PROFILE
  TheServiceParticipant->configure_pool ();
#endif

  try
    {
      ACE_DEBUG((LM_INFO,"(%P|%t) %T subscriber main\n"));

      dpf = TheParticipantFactoryWithArgs(argc, argv);

      // let the Service_Participant (in above line) strip out -DCPSxxx parameters
      // and then get application specific parameters.
      parse_args (argc, argv);

      init_listener ();
      init_dcps_objects (0);
      init_dcps_objects (1);

      // Indicate that the subscriber is ready
      FILE* readers_ready = ACE_OS::fopen (sub_ready_filename.c_str (), ACE_TEXT("w"));
      if (readers_ready == 0)
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT("(%P|%t) ERROR: Unable to create subscriber completed file\n")));
        }

      // Wait for the publisher to be ready
      FILE* writers_ready = 0;
      do
        {
          ACE_Time_Value small_time(0,250000);
          ACE_OS::sleep (small_time);
          writers_ready = ACE_OS::fopen (pub_ready_filename.c_str (), ACE_TEXT("r"));
        } while (0 == writers_ready);

      ACE_OS::fclose(readers_ready);
      ACE_OS::fclose(writers_ready);

      int expected
        = num_datawriters * num_instances_per_writer * num_samples_per_instance;

      FILE* writers_completed = 0;
      int timeout_writes = 0;

      while ( num_reads < expected)
        {
          // Get the number of the timed out writes from publisher so we
          // can re-calculate the number of expected messages. Otherwise,
          // the blocking timeout test will never exit from this loop.
          if (writers_completed == 0)
            {
              writers_completed = ACE_OS::fopen (pub_finished_filename.c_str (), ACE_TEXT("r"));
              if (writers_completed != 0)
                {
                  //writers_completed = ACE_OS::fopen (pub_finished_filename.c_str (), ACE_TEXT("r"));
                  std::fscanf (writers_completed, "%d\n", &timeout_writes);
                  expected -= timeout_writes;
                  ACE_DEBUG((LM_DEBUG,
                             ACE_TEXT ("(%P|%t) timed out writes %d, we expect %d\n"),
                             timeout_writes, expected));
                }

            }
          ACE_OS::sleep (1);
        }

      // Indicate that the subscriber is done
      FILE* readers_completed = ACE_OS::fopen (sub_finished_filename.c_str (), ACE_TEXT("w"));
      if (readers_completed == 0)
        {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT("(%P|%t) ERROR: Unable to create subscriber completed file\n")));
        }

      // Wait for the publisher to finish
      while (writers_completed == 0)
        {
          ACE_Time_Value small_time(0,250000);
          ACE_OS::sleep (small_time);
          writers_completed = ACE_OS::fopen (pub_finished_filename.c_str (), ACE_TEXT("r"));
        }

      ACE_OS::fclose(readers_completed);
      ACE_OS::fclose(writers_completed);
    }
  catch (const TestException&)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT("(%P|%t) TestException caught in main (). ")));
      status = 1;
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught in main ():");
      status = 1;
    }

  try
    {
      for (int i = 0; i < 2; ++i)
      {
        if (! CORBA::is_nil (participant[i].in ()))
          {
            participant[i]->delete_contained_entities();
          }
        if (! CORBA::is_nil (dpf.in ()))
          {
            dpf->delete_participant(participant[i].in ());
          }
      }
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Exception caught in cleanup.");
      status = 1;
    }

  shutdown ();

  return status;
}
Example #28
0
static int sendtoxymond(char *recipient, char *message, FILE *respfd, char **respstr, int fullresponse, int timeout)
{
	struct in_addr addr;
	struct sockaddr_in saddr;
	int	sockfd;
	fd_set	readfds;
	fd_set	writefds;
	int	res, isconnected, wdone, rdone;
	struct timeval tmo;
	char *msgptr = message;
	char *p;
	char *rcptip = NULL;
	int rcptport = 0;
	int connretries = SENDRETRIES;
	char *httpmessage = NULL;
	char recvbuf[32768];
	int haveseenhttphdrs = 1;
	int respstrsz = 0;
	int respstrlen = 0;
	int result = XYMONSEND_OK;

	if (dontsendmessages && !respfd && !respstr) {
		printf("%s\n", message);
		return XYMONSEND_OK;
	}

	setup_transport(recipient);

	dbgprintf("Recipient listed as '%s'\n", recipient);

	if (strncmp(recipient, "http://", strlen("http://")) != 0) {
		/* Standard communications, directly to Xymon daemon */
		rcptip = strdup(recipient);
		rcptport = xymondportnumber;
		p = strchr(rcptip, ':');
		if (p) {
			*p = '\0'; p++; rcptport = atoi(p);
		}
		dbgprintf("Standard protocol on port %d\n", rcptport);
	}
	else {
		char *bufp;
		char *posturl = NULL;
		char *posthost = NULL;

		if (xymonproxyhost == NULL) {
			char *p;

			/*
			 * No proxy. "recipient" is "http://host[:port]/url/for/post"
			 * Strip off "http://", and point "posturl" to the part after the hostname.
			 * If a portnumber is present, strip it off and update rcptport.
			 */
			rcptip = strdup(recipient+strlen("http://"));
			rcptport = xymondportnumber;

			p = strchr(rcptip, '/');
			if (p) {
				posturl = strdup(p);
				*p = '\0';
			}

			p = strchr(rcptip, ':');
			if (p) {
				*p = '\0';
				p++;
				rcptport = atoi(p);
			}

			posthost = strdup(rcptip);

			dbgprintf("HTTP protocol directly to host %s\n", posthost);
		}
		else {
			char *p;

			/*
			 * With proxy. The full "recipient" must be in the POST request.
			 */
			rcptip = strdup(xymonproxyhost);
			rcptport = xymonproxyport;

			posturl = strdup(recipient);

			p = strchr(recipient + strlen("http://"), '/');
			if (p) {
				*p = '\0';
				posthost = strdup(recipient + strlen("http://"));
				*p = '/';

				p = strchr(posthost, ':');
				if (p) *p = '\0';
			}

			dbgprintf("HTTP protocol via proxy to host %s\n", posthost);
		}

		if ((posturl == NULL) || (posthost == NULL)) {
			sprintf(errordetails + strlen(errordetails), "Unable to parse HTTP recipient");
			if (posturl) xfree(posturl);
			if (posthost) xfree(posthost);
			if (rcptip) xfree(rcptip);
			return XYMONSEND_EBADURL;
		}

		bufp = msgptr = httpmessage = malloc(strlen(message)+1024);
		bufp += sprintf(httpmessage, "POST %s HTTP/1.0\n", posturl);
		bufp += sprintf(bufp, "MIME-version: 1.0\n");
		bufp += sprintf(bufp, "Content-Type: application/octet-stream\n");
		bufp += sprintf(bufp, "Content-Length: %d\n", strlen(message));
		bufp += sprintf(bufp, "Host: %s\n", posthost);
		bufp += sprintf(bufp, "\n%s", message);

		if (posturl) xfree(posturl);
		if (posthost) xfree(posthost);
		haveseenhttphdrs = 0;

		dbgprintf("HTTP message is:\n%s\n", httpmessage);
	}

	if (inet_aton(rcptip, &addr) == 0) {
		/* recipient is not an IP - do DNS lookup */

		struct hostent *hent;
		char hostip[IP_ADDR_STRLEN];

		hent = gethostbyname(rcptip);
		if (hent) {
			memcpy(&addr, *(hent->h_addr_list), sizeof(struct in_addr));
			strcpy(hostip, inet_ntoa(addr));

			if (inet_aton(hostip, &addr) == 0) {
				result = XYMONSEND_EBADIP;
				goto done;
			}
		}
		else {
			sprintf(errordetails+strlen(errordetails), "Cannot determine IP address of message recipient %s", rcptip);
			result = XYMONSEND_EIPUNKNOWN;
			goto done;
		}
	}

retry_connect:
	dbgprintf("Will connect to address %s port %d\n", rcptip, rcptport);

	memset(&saddr, 0, sizeof(saddr));
	saddr.sin_family = AF_INET;
	saddr.sin_addr.s_addr = addr.s_addr;
	saddr.sin_port = htons(rcptport);

	/* Get a non-blocking socket */
	sockfd = socket(PF_INET, SOCK_STREAM, 0);
	if (sockfd == -1) { result = XYMONSEND_ENOSOCKET; goto done; }
	res = fcntl(sockfd, F_SETFL, O_NONBLOCK);
	if (res != 0) { result = XYMONSEND_ECANNOTDONONBLOCK; goto done; }

	res = connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
	if ((res == -1) && (errno != EINPROGRESS)) {
		sprintf(errordetails+strlen(errordetails), "connect to Xymon daemon@%s:%d failed (%s)", rcptip, rcptport, strerror(errno));
		result = XYMONSEND_ECONNFAILED;
		goto done;
	}

	rdone = ((respfd == NULL) && (respstr == NULL));
	isconnected = wdone = 0;
	while (!wdone || !rdone) {
		FD_ZERO(&writefds);
		FD_ZERO(&readfds);
		if (!rdone) FD_SET(sockfd, &readfds);
		if (!wdone) FD_SET(sockfd, &writefds);
		tmo.tv_sec = timeout;  tmo.tv_usec = 0;
		res = select(sockfd+1, &readfds, &writefds, NULL, (timeout ? &tmo : NULL));
		if (res == -1) {
			sprintf(errordetails+strlen(errordetails), "Select failure while sending to Xymon daemon@%s:%d", rcptip, rcptport);
			result = XYMONSEND_ESELFAILED;
			goto done;
		}
		else if (res == 0) {
			/* Timeout! */
			shutdown(sockfd, SHUT_RDWR);
			close(sockfd);

			if (!isconnected && (connretries > 0)) {
				dbgprintf("Timeout while talking to Xymon daemon@%s:%d - retrying\n", rcptip, rcptport);
				connretries--;
				sleep(1);
				goto retry_connect;	/* Yuck! */
			}

			result = XYMONSEND_ETIMEOUT;
			goto done;
		}
		else {
			if (!isconnected) {
				/* Havent seen our connect() status yet - must be now */
				int connres;
				socklen_t connressize = sizeof(connres);

				res = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &connres, &connressize);
				dbgprintf("Connect status is %d\n", connres);
				isconnected = (connres == 0);
				if (!isconnected) {
					sprintf(errordetails+strlen(errordetails), "Could not connect to Xymon daemon@%s:%d (%s)", 
						  rcptip, rcptport, strerror(connres));
					result = XYMONSEND_ECONNFAILED;
					goto done;
				}
			}

			if (!rdone && FD_ISSET(sockfd, &readfds)) {
				char *outp;
				int n;

				n = recv(sockfd, recvbuf, sizeof(recvbuf)-1, 0);
				if (n > 0) {
					dbgprintf("Read %d bytes\n", n);
					recvbuf[n] = '\0';

					/*
					 * When running over a HTTP transport, we must strip
					 * off the HTTP headers we get back, so the response
					 * is consistent with what we get from the normal Xymon daemon
					 * transport.
					 * (Non-http transport sets "haveseenhttphdrs" to 1)
					 */
					if (!haveseenhttphdrs) {
						outp = strstr(recvbuf, "\r\n\r\n");
						if (outp) {
							outp += 4;
							n -= (outp - recvbuf);
							haveseenhttphdrs = 1;
						}
						else n = 0;
					}
					else outp = recvbuf;

					if (n > 0) {
						if (respfd) {
							fwrite(outp, n, 1, respfd);
						}
						else if (respstr) {
							char *respend;

							if (respstrsz == 0) {
								respstrsz = (n+sizeof(recvbuf));
								*respstr = (char *)malloc(respstrsz);
							}
							else if ((n+respstrlen) >= respstrsz) {
								respstrsz += (n+sizeof(recvbuf));
								*respstr = (char *)realloc(*respstr, respstrsz);
							}
							respend = (*respstr) + respstrlen;
							memcpy(respend, outp, n);
							*(respend + n) = '\0';
							respstrlen += n;
						}
						if (!fullresponse) {
							rdone = (strchr(outp, '\n') == NULL);
						}
					}
				}
				else rdone = 1;
				if (rdone) shutdown(sockfd, SHUT_RD);
			}

			if (!wdone && FD_ISSET(sockfd, &writefds)) {
				/* Send some data */
				res = write(sockfd, msgptr, strlen(msgptr));
				if (res == -1) {
					sprintf(errordetails+strlen(errordetails), "Write error while sending message to Xymon daemon@%s:%d", rcptip, rcptport);
					result = XYMONSEND_EWRITEERROR;
					goto done;
				}
				else {
					dbgprintf("Sent %d bytes\n", res);
					msgptr += res;
					wdone = (strlen(msgptr) == 0);
					if (wdone) shutdown(sockfd, SHUT_WR);
				}
			}
		}
	}

done:
	dbgprintf("Closing connection\n");
	shutdown(sockfd, SHUT_RDWR);
	close(sockfd);
	xfree(rcptip);
	if (httpmessage) xfree(httpmessage);
	return result;
}
Example #29
0
static int core_netio_shutdown_cb(pr_netio_stream_t *nstrm, int how) {
  return shutdown(nstrm->strm_fd, how);
}
Example #30
0
// shut down a monitor's filesystem-specific state 
// not much we can do if any shutdown step fails, so try them all
int udev_monitor_fs_shutdown( struct udev_monitor* monitor ) {
   
   int rc = 0;
   
   // stop tracking this monitor
   udev_monitor_unregister( monitor );
   
   if( monitor->sock >= 0 ) {
      rc = shutdown( monitor->sock, SHUT_RDWR );
      if( rc < 0 ) {
         rc = -errno;
         log_error("shutdown(socket %d) rc = %d", monitor->sock, rc );
      }
   }
      
   if( monitor->sock_fs >= 0 ) {
      rc = shutdown( monitor->sock_fs, SHUT_RDWR );
      if( rc < 0 ) {
         rc = -errno;
         log_error("shutdown(socket %d) rc = %d", monitor->sock_fs, rc );
      }
   }
   
   if( monitor->sock >= 0 ) {
      rc = close( monitor->sock );
      if( rc < 0 ) {
         rc = -errno;
         log_error("close(socket %d) rc = %d", monitor->sock, rc );
      }
      else {
         monitor->sock = -1;
      }
   }
    
   if( monitor->sock_fs >= 0 ) {
      rc = close( monitor->sock_fs );
      if( rc < 0 ) {
         rc = -errno;
         log_error("close(socket %d) rc = %d", monitor->sock_fs, rc );
      }
      else {
         monitor->sock_fs = -1;
      }
   }
   
   if( monitor->epoll_fd >= 0 ) {
      rc = close( monitor->epoll_fd );
      if( rc < 0 ) {
         rc = -errno;
         log_error("close(epoll_fd %d) rc = %d", monitor->epoll_fd, rc );
      }
      else {
         monitor->epoll_fd = -1;
      }
   }
  
   if( monitor->events_wd >= 0 ) {

      if( monitor->inotify_fd >= 0 ) {
         rc = inotify_rm_watch( monitor->inotify_fd, monitor->events_wd );
         if( rc < 0 ) {
            rc = -errno;
            log_error("close(events_wd %d) rc = %d", monitor->events_wd, rc );
         }
         else {
            monitor->events_wd = -1;
         }
      }
   } 
   if( monitor->inotify_fd >= 0 ) {
      rc = close( monitor->inotify_fd );
      if( rc < 0 ) {
         rc = -errno;
         log_error("close(inotify_fd %d) rc = %d", monitor->inotify_fd, rc );
      }
      else {
         monitor->inotify_fd = -1;
      }
   }
   
   return rc;
}