コード例 #1
0
void TCPClient::setClientStatus(unsigned status)
{
    if (status != STATUS_OFFLINE){
        if (getState() == Connected){
            setStatus(status);
            return;
        }
        m_logonStatus = status;
        if ((getState() != Connecting) || m_bWaitReconnect){
            setState(Connecting, NULL);
            m_reconnect = RECONNECT_TIME;
            m_bWaitReconnect = false;
            setState(Connecting);
            socketConnect();
        }
        return;
    }
    m_bWaitReconnect = false;
    m_timer->stop();
    m_loginTimer->stop();
    if (m_socket)
        setStatus(STATUS_OFFLINE);
    m_status = STATUS_OFFLINE;
    setState(Offline);
    disconnected();
    if (m_socket){
        m_socket->close();
        delete m_socket;
        m_socket = NULL;
    }
}
コード例 #2
0
ファイル: client.c プロジェクト: sumdog/assignments
//Return 0 on success
//       -1 on invalid nameserver hostname
//       -2 could not connect to server
//       -3 error during lookup
//       -4 invalid data from nameserver
//       -5 unknown service
short serviceLookup(cmd_t *cmd, ns_t *ns){

  //setup I/O buffers
  char sndbuf[BUFFER];
  char recbuf[BUFFER];
  sprintf(sndbuf,"L:%s\n",cmd->service);  
 
  //send/recieve information from service
  short c = socketConnect(ns->nshost,ns->nsport,&sndbuf[0],&recbuf[0],BUFFER);
  if(c != 0) { return c; } //error

  //parse response
  char *i = strtok(&recbuf[0],":\n"); //response type
  if(i == NULL) { return -4; }
  if(strcmp(i,"A") != 0) { return -5; }
  i = strtok(NULL,":\n"); //hostname
  if(i == NULL) { return -4; }
  cmd->host = malloc(sizeof(char)*strlen(i)+1);
  strcpy(cmd->host,i);
  i = strtok(NULL,":\n"); //port
  if(i == NULL) { return -4; }
  cmd->port = (unsigned short) atol(i);

  //cleanup
  return 0; 
}
コード例 #3
0
ファイル: client.c プロジェクト: sumdog/assignments
// 0  on failure
// 1  on success
// -1 on undefined response 
short runCommand(cmd_t *cmd, char *output, long bufsize){

  //setup our buffers
  char recvbuf[BUFFER];
  recvbuf[BUFFER-1] = '\0';
  char sendbuf[BUFFER];
  sendbuf[BUFFER-1] = '\0';

  //format our command to send to server
  sprintf(sendbuf,"I:%s",cmd->command);
  
  //connect and send that command
  short c = socketConnect(cmd->host,cmd->port,&sendbuf[0],&recvbuf[0],BUFFER);
  if(c != 0) { return c; } //error

  //output result to user
  switch(recvbuf[0]) {
  case 'E':
    printf("<<ERROR>> %s",&recvbuf[2]);
    return 0;
    break;
  case 'A':
    printf("Response: %s",&recvbuf[2]);
    return 1;
    break;
  default:
    printf("<<Unknown Response>> %s",&recvbuf[0]);
    return -1;
  }

}
コード例 #4
0
int main()
{
	char google[] = "173.194.79.103";
	char message[] = "GET / HTTP/1.1\r\n\r\n";
	char reply[2000];
	int port = 80;
	int ret, sd;
	
	sd = socketCreate();
	printf("Created socket wrapper with descriptor %d.\n", sd);

	ret = socketConnect(sd, google, port);
	printf("Socket wrapper connected to '%s' on port '%d' with return value %d.\n", google, port, ret);

	ret = socketSend(sd, message, -1);
	printf("Socket wrapper sent: \n\n'%s'\n\nto '%s' on port '%d' with return value %d.\n", message, google, port, ret);

	ret = socketReceive(sd, reply, 2000);
	printf("Socket wrapper received: \n\n'%s'\n\nfrom '%s' on port '%d' with return value %d.\n", reply, google, port, ret);

	ret = socketDisconnect(sd);
	printf("Socket wrapper disconnected from '%s' on port '%d' with return value %d.\n", google, port, ret);
	
	return 0;
}
コード例 #5
0
MStatus update_tags(MIntArray &nFV, MIntArray &F, VertexData &v, HalfedgeData &he)
{
    // export into TCCNodeData, send to MATLAB, read back results and store
    TCCNodeData nd;

    write_to_TCCNodeData(nFV, F, v, he, nd);

    char localhost[] = "localhost";
    int remote_socket = socketConnect(3003, localhost);
    cout<<"socket: "<<remote_socket<<endl;

    if (!send_KVCObject_to_Socket(&nd, remote_socket))
    {
        cout<<"sending failed!"<<endl;
        close(remote_socket);
        return MS::kUnknownParameter;
    }

    if (!init_KVCObject_from_Socket(&nd, remote_socket))
    {
        cout<<"receiving failed!"<<endl;
        close(remote_socket);
        return MS::kUnknownParameter;
    }
    close(remote_socket);

    read_from_TCCNodeData(nd, v, he);

    return MS::kSuccess;
}
コード例 #6
0
ファイル: Game.cpp プロジェクト: zombobilium/laig3
void Game::initializeSocket(int type){
	if(firstGame)
		socketConnect();
	char connectMsg[256];
	if(type == 1)
		sprintf(connectMsg, "initialize(%i, 1).\n", this->gameboard->size);
	else if (type == 2) //Man vs CPU
		sprintf(connectMsg, "initialize(%i, 2, %s).\n", this->gameboard->size, this->player2->cpudiff);
	else if(type == 3) //CPU vs Man
		sprintf(connectMsg, "initialize(%i, 3, %s).\n", this->gameboard->size, this->player1->cpudiff);
	else if(type == 4)
		sprintf(connectMsg, "initialize(%i, 4, %s, %s).\n", this->gameboard->size, this->player1->cpudiff, this->player2->cpudiff);
	printf("%s\n", connectMsg);
	envia(connectMsg, strlen(connectMsg));
	char ans[256];

	recebe(ans);

	//Guardar o tabuleiro PROLOG
	int i=3;
	while(true){
		if(ans[i] == ')')
			break;
		this->tabProlog[i-3] = ans[i];
		i++;
	}
	this->tabProlog[i-3] = '\0';

	char* buf = (char*)malloc(256*sizeof(char));
	strcpy(buf, this->tabProlog);
	gameboardsProlog.push(buf);
}
コード例 #7
0
ファイル: optirun.c プロジェクト: GarothLongint/Bumblebee
int main(int argc, char *argv[]) {
  int exitcode = EXIT_FAILURE;

  init_early_config(argc, argv, BB_RUN_APP);

  /* Setup signal handling before anything else */
  signal(SIGHUP, handle_signal);
  signal(SIGTERM, handle_signal);
  signal(SIGINT, handle_signal);
  signal(SIGQUIT, handle_signal);

  bb_init_log();

  /* Initializing configuration */
  init_config(argc, argv);
  bbconfig_parse_opts(argc, argv, PARSE_STAGE_PRECONF);
  GKeyFile *bbcfg = bbconfig_parse_conf();
  /* XXX load the driver (or even better, the ldpath) through the protocol */
  bbconfig_parse_opts(argc, argv, PARSE_STAGE_DRIVER);
  driver_detect();
  if (bbcfg) {
    bbconfig_parse_conf_driver(bbcfg, bb_config.driver);
    g_key_file_free(bbcfg);
  }
  bbconfig_parse_opts(argc, argv, PARSE_STAGE_OTHER);
  config_dump();

  bb_log(LOG_DEBUG, "%s version %s starting...\n", "optirun", GITVERSION);

  /* Connect to listening daemon */
  bb_status.bb_socket = socketConnect(bb_config.socket_path, SOCK_NOBLOCK);
  if (bb_status.bb_socket < 0) {
    bb_log(LOG_ERR, "Could not connect to bumblebee daemon - is it running?\n");
    run_fallback(argv + optind);
    bb_closelog();
    return exitcode;
  }

  /* Request status */
  if (bb_status.runmode == BB_RUN_STATUS) {
    exitcode = report_daemon_status();
  }

  /* Run given application */
  if (bb_status.runmode == BB_RUN_APP) {
    if (optind >= argc) {
      bb_log(LOG_ERR, "Missing argument: application to run\n");
      print_usage(EXIT_FAILURE);
    } else {
      exitcode = run_app(argc, argv);
    }
  }

  bb_closelog();
  bb_stop_all(); //stop any started processes that are left
  return exitcode;
}
コード例 #8
0
ファイル: tcpconnector.cpp プロジェクト: mocap-ca/mayaMocap
// called by the socket when connected
void TcpConnector::sConnect()
{
    for(QStringList::iterator i = messages.begin(); i != messages.end(); i++)
    {
        sendMessage((*i).toUtf8());
    }
    messages.clear();
    logMessage("connected");    
    emit socketConnect();
}
コード例 #9
0
ファイル: RedFly.cpp プロジェクト: CMon/arduinoWifiRemote
uint32_t REDFLY::gettime(uint8_t *server, uint16_t port)
{
  uint8_t buf[64]; //min. NTP_PACKETLEN
  uint32_t time=0UL, timeout;
  uint8_t hNTP, sock, buf_len, *ptr;
  uint16_t rd, len;
  
  if(port == 0)
  {
    port = NTP_PORT;
  }

  //open connection to server
  hNTP = socketConnect(PROTO_UDP, server, port, port);
  if(hNTP != INVALID_SOCKET)
  {
    //send NTP request
    memset(buf, 0, NTP_PACKETLEN);
    buf[NTP_FLAGOFFSET] = (0<<6)|(1<<3)|(3<<0); //NTP flags: LI=0 | VN=1 | Mode=3 -> Client
    if(socketSend(hNTP, buf, NTP_PACKETLEN) == 0)
    {
      //get data
      ptr     = buf;
      buf_len = 0;
      for(timeout=F_CPU/16UL; timeout!=0; timeout--) //about 3s
      {
        sock = hNTP;
        rd = socketRead(&sock, &len, ptr, sizeof(buf)-buf_len);
        if((rd != 0) && (rd != 0xFFFF)) //0xFFFF = connection closed
        {
          ptr     += rd;
          buf_len += rd;
        }
        if(buf_len && (len == 0)) //all data received?
        {
          break;
        }
      }
      //check data
      if((buf_len >= NTP_PACKETLEN) && ((buf[NTP_FLAGOFFSET]&0x07) == 4)) //NTP flags: Mode=4 -> Server
      {
        //time = (uint32_t)*((uint32_t*)&buf[NTP_TIMEOFFSET]);
        time = (((uint32_t)buf[NTP_TIMEOFFSET+0])<<24)|
               (((uint32_t)buf[NTP_TIMEOFFSET+1])<<16)|
               (((uint32_t)buf[NTP_TIMEOFFSET+2])<< 8)|
               (((uint32_t)buf[NTP_TIMEOFFSET+3])<< 0); //swap32
        time -= 2208988800UL; //sub seconds 1900-1970
      }
    }
    socketClose(hNTP);
  }

  return time;
}
コード例 #10
0
ファイル: RedFly.cpp プロジェクト: CMon/arduinoWifiRemote
uint8_t REDFLY::socketConnect(uint8_t proto, uint8_t *ip, uint16_t port)
{
  static uint16_t lport=1024;

  if(++lport > 2048)
  {
    lport = 1024;
  }

  return socketConnect(proto, ip, port, lport);
}
コード例 #11
0
void terminadoPlanDeNiveles(t_personaje *personaje) { 
  log_debug(logger, "Terminado plan de niveles.");

  t_mensaje *mensaje = mensaje_create(TERMINADO_NIVELES,"");

  int socket = socketCreate(handleConnectionError);
  socketConnect(socket, personaje->orquestador->ip, personaje->orquestador->puerto, handleConnectionError);
  socketSend(socket, mensaje, handleConnectionError);
  
  free(mensaje);
  socketClose(socket, NULL);
}
コード例 #12
0
void CBNLSClient::socketDisconnected()
{
	CONSOLE_Print( "[BNLSC: " + m_Server + ":" + QString::number( m_Port ) + ":C" + QString::number( m_WardenCookie ) + "] disconnected from BNLS server" );
	m_Socket->deleteLater();
	m_Socket = new QTcpSocket();

	if (m_Retries > 6)
	{
		CONSOLE_Print("[BNLSC: " + m_Server + ":" + QString::number( m_Port ) + ":C" + QString::number( m_WardenCookie ) + "] giving up after 5 failed retries." );
		deleteLater();
		return;
	}

	QTimer::singleShot(5000, this, SLOT(socketConnect()));

}
コード例 #13
0
ファイル: ProxySplice.cpp プロジェクト: vovaprog/learn
int proxySplice()
{
	int serverFd = socketListen(7000);
	int connectFd = socketConnect("127.0.0.1", 7001);

	struct sockaddr_in cli_addr;
	socklen_t clilen = sizeof(sockaddr_in);
	int clientFd = accept(serverFd, (struct sockaddr*) &cli_addr, &clilen);


	int pipefd[2];

	if(pipe(pipefd) != 0)
	{
		perror("pipe failed");
		return -1;
	}


	while(true)
	{
		int nr = splice(clientFd, NULL, pipefd[1], NULL, 100000, 0);
		if(nr <= 0)
		{
			perror("splice failed");
			break;
		}
		do
		{
			int ret = splice(pipefd[0], NULL, connectFd, NULL, nr, 0);
			if (ret <= 0)
			{
				perror("splice failed");
				break;
			}

			nr -= ret;
		} while (nr);
	}
	close(pipefd[0]);
	close(pipefd[1]);

	return 0;
}
コード例 #14
0
ファイル: tcpcomponent.cpp プロジェクト: heartsg/oceanbase
/*
 * ���ӵ�ָ���Ļ���
 *
 * @param  isServer: �Ƿ���ʼ��һ����������Connection
 * @return �Ƿ��ɹ�
 */
bool TCPComponent::init(bool isServer) {
    _socket->setSoBlocking(false);
    _socket->setSoLinger(false, 0);
    _socket->setReuseAddress(true);
    _socket->setIntOption(SO_KEEPALIVE, 1);
    _socket->setIntOption(SO_SNDBUF, 640000);
    _socket->setIntOption(SO_RCVBUF, 640000);
    // _socket->setTcpNoDelay(true);
    if (!isServer) {
        if (!socketConnect() && _autoReconn == false) {
            return false;
        }
    } else {
        _state = TBNET_CONNECTED;
    }
    _connection->setServer(isServer);
    _isServer = isServer;

    return true;
}
コード例 #15
0
int main(int argc, char** argv) {

	if(argc != 2){
		puts("No se ingreso la ruta del archivo de configuracion\n");
		return 0;
	}

	thread_socket= 3030;
	paginaEncontrada=TRUE;
	umclog=malloc(sizeof(t_log));
	memcpy(umclog,log_create("umc.log", "UMC", TRUE, LOG_LEVEL_TRACE), sizeof(t_log));

	leerArchivoDeConfiguracion(argv[1]);
	crearLogger(0);
	log_info(umclog, "Inicio UMC.");

	pthread_t hiloComandos;
	pthread_attr_t attrhiloComandos;

	memoriaReal = reservarMemoria(marcos, marco_Size); //Fabrico mi memoria real

	iniciarEstructurasUMC();

	socketSwap=socketCreateClient();

	socketConnect(socketSwap,ip_Swap,atoi(puerto_Swap));

	menuUMC(hiloComandos, attrhiloComandos);

	manageSocketConnections();


	liberarMemoria(memoriaReal); //Una vez terminado, libero toda mi memoria real
	log_destroy(logger);

	return EXIT_SUCCESS;

}
コード例 #16
0
ファイル: socket_linux.c プロジェクト: KHATEEBNSIT/AP
struct _Socket *osSockConnect
(
	char *mach_name
)
{
	struct _Socket *pOSSock;
	int res;
	char *cp;
    A_UINT32 err;
   HANDLE       hDevice;

        //uiPrintf("SNOOP:: osSockConnect called\n");
    pOSSock = (struct _Socket *) malloc(sizeof(*pOSSock));
    if (!pOSSock) {
       uiPrintf("ERROR::osSockConnect: malloc failed for pOSSock \n");
       return NULL;
    }


	while (*mach_name == '\\') {
		mach_name++;
	}
	
	for (cp = mach_name; (*cp != '\0') && (*cp != '\\'); cp++) {
	}
	*cp = '\0';

	q_uiPrintf("osSockConnect: starting mach_name = '%s'\n", mach_name);

	if (!strcmp(mach_name, ".")) {
			mach_name = "localhost";
     }

	  strcpy(pOSSock->hostname, mach_name);
	  pOSSock->port_num = -1;  // ???

    if (!strcasecmp(mach_name, "COM1")) {
	    q_uiPrintf("osSockConnect: Using serial communication port 1\n");
	    strcpy(pOSSock->hostname, COM1);
		pOSSock->port_num = COM1_PORT_NUM;
    }
    if (!strcasecmp(mach_name, "COM2")) {
	    q_uiPrintf("osSockConnect: Using serial communication port 2\n");
	    strcpy(pOSSock->hostname, COM2);
		pOSSock->port_num = COM2_PORT_NUM;
    }
	if (!strcasecmp(pOSSock->hostname, "SDIO")) {
       pOSSock->port_num = MBOX_PORT_NUM;
	}
	pOSSock->sockDisconnect = 0;
	pOSSock->sockClose = 0;

    switch(pOSSock->port_num) {
       case MBOX_PORT_NUM: 
            hDevice = open_device(SDIO_FUNCTION, 0, NULL);
		    pOSSock->sockfd = hDevice;
			break;
       case COM1_PORT_NUM:
       case COM2_PORT_NUM:
        if ((err=os_com_open(pOSSock)) != 0) {
            uiPrintf("ERROR::osSockConnect::Com port open failed with error = %x\n", err);
            exit(0);
        }
		break;
       case SOCK_PORT_NUM: {
			q_uiPrintf("osSockConnect: revised mach_name = '%s':%d\n", pOSSock->hostname, pOSSock->port_num);
	  		res = socketConnect(pOSSock->hostname, pOSSock->port_num, &pOSSock->ip_addr);
	  		if (res < 0) {
	          uiPrintf("ERROR::osSockConnect: pipe connect failed\n"); free(pOSSock);
	          return NULL;
	  		}
	  		q_uiPrintf("osSockConnect: Connected to pipe\n");

	  		q_uiPrintf("ip_addr = %d.%d.%d.%d\n",(pOSSock->ip_addr >> 24) & 0xff,
											(pOSSock->ip_addr >> 16) & 0xff,
											(pOSSock->ip_addr >> 8) & 0xff,
											(pOSSock->ip_addr >> 0) & 0xff);
	  		pOSSock->sockfd = res;

		} // end of else
	}

	return pOSSock;
}
コード例 #17
0
ファイル: bsd_socket.c プロジェクト: hyper123/CycloneTCP
int_t connect(int_t s, const sockaddr *addr, int_t addrlen)
{
   error_t error;
   uint16_t port;
   IpAddr ipAddr;
   Socket *socket;

   //Make sure the socket descriptor is valid
   if(s < 0 || s >= SOCKET_MAX_COUNT)
   {
      socketError(NULL, ERROR_INVALID_SOCKET);
      return SOCKET_ERROR;
   }

   //Point to the socket structure
   socket = &socketTable[s];

   //Check the length of the address
   if(addrlen < sizeof(sockaddr))
   {
      socketError(socket, ERROR_INVALID_PARAMETER);
      return SOCKET_ERROR;
   }

#if (IPV4_SUPPORT == ENABLED)
   //IPv4 address?
   if(addr->sa_family == AF_INET && addrlen >= sizeof(sockaddr_in))
   {
      //Point to the IPv4 address information
      sockaddr_in *sa = (sockaddr_in *) addr;
      //Get port number
      port = ntohs(sa->sin_port);

      //Copy IPv4 address
      if(sa->sin_addr.s_addr == INADDR_ANY)
      {
         ipAddr.length = 0;
         ipAddr.ipv4Addr = IPV4_UNSPECIFIED_ADDR;
      }
      else
      {
         ipAddr.length = sizeof(Ipv4Addr);
         ipAddr.ipv4Addr = sa->sin_addr.s_addr;
      }
   }
   else
#endif
#if (IPV6_SUPPORT == ENABLED)
   //IPv6 address?
   if(addr->sa_family == AF_INET6 && addrlen == sizeof(sockaddr_in6))
   {
      //Point to the IPv6 address information
      sockaddr_in6 *sa = (sockaddr_in6 *) addr;
      //Get port number
      port = ntohs(sa->sin6_port);

      //Copy IPv6 address
      if(ipv6CompAddr(sa->sin6_addr.s6_addr, &in6addr_any))
      {
         ipAddr.length = 0;
         ipAddr.ipv6Addr = IPV6_UNSPECIFIED_ADDR;
      }
      else
      {
         ipAddr.length = sizeof(Ipv6Addr);
         ipv6CopyAddr(&ipAddr.ipv6Addr, sa->sin6_addr.s6_addr);
      }
   }
   else
#endif
   //Invalid address?
   {
      //Report an error
      socketError(socket, ERROR_INVALID_PARAMETER);
      return SOCKET_ERROR;
   }

   //Establish connection
   error = socketConnect(socket, &ipAddr, port);

   //Any error to report?
   if(error)
   {
      socketError(socket, error);
      return SOCKET_ERROR;
   }

   //Successful processing
   return SOCKET_SUCCESS;
}
コード例 #18
0
int32 crlCb(psPool_t *pool, psX509Cert_t *CA, int append, char *url,
				uint32 urlLen)
{
	SOCKET			fd;
	struct hostent	*ip;
	struct in_addr	intaddr;
	char			*pageStart, *replyPtr, *ipAddr;
	char			hostAddr[HOST_ADDR_LEN], getReq[GET_REQ_LEN];
	char			crlBuf[CRL_BUF_SIZE];
	int				hostAddrLen, getReqLen, pageLen;
	int32			transferred;
	int32			err, httpUriLen, port, offset;
	uint32			crlBinLen;
	
	/* Is URI in expected URL form? */
	if (strstr(url, "http://") == NULL) {
		if (strstr(url, "https://") == NULL) {
			_psTraceStr("crlCb: Unsupported CRL URI: %s\n", url);
			return -1;
		}
		httpUriLen = 8;
		port = 80; /* No example yet of using SSL to fetch CRL */
	} else {
		httpUriLen = 7;
		port = 80;
	}
	
	/* Parsing host and page and setting up IP address and GET request */
	if ((pageStart = strchr(url + httpUriLen, '/')) == NULL) {
		_psTrace("crlCb: No host/page divider found\n");
		return -1;
	}
	if ((hostAddrLen = (int)(pageStart - url) - httpUriLen) > HOST_ADDR_LEN) {
		_psTrace("crlCb: HOST_ADDR_LEN needs to be increased\n");
		return -1; /* ipAddr too small to hold */
	}
	
	memset(hostAddr, 0, HOST_ADDR_LEN);
	memcpy(hostAddr, url + httpUriLen, hostAddrLen);
	if ((ip = gethostbyname(hostAddr)) == NULL) {
		_psTrace("crlCb: gethostbyname failed\n");
		return -1;
	}
	
	memcpy((char *) &intaddr, (char *) ip->h_addr_list[0],
        (size_t) ip->h_length);
	if ((ipAddr = inet_ntoa(intaddr)) == NULL) {
		_psTrace("crlCb: inet_ntoa failed\n");
		return -1;
	}
	
	pageLen = (urlLen - hostAddrLen - httpUriLen);
	getReqLen = pageLen + hostAddrLen + GET_OH_LEN + HTTP_OH_LEN +
		HOST_OH_LEN + ACCEPT_OH_LEN;
	if (getReqLen > GET_REQ_LEN) {
		_psTrace("crlCb: GET_REQ_LEN needs to be increased\n");
		return -1;
	}
	
	// Build the request:
	//
	//	GET /page.crl HTTP/1.0
	//	Host: www.host.com
	//	Accept: */*
	//	
	memset(getReq, 0, GET_REQ_LEN);
	memcpy(getReq, crl_getHdr, GET_OH_LEN);
	offset = GET_OH_LEN;
	memcpy(getReq + offset, pageStart, pageLen);
	offset += pageLen;
	memcpy(getReq + offset, crl_httpHdr, HTTP_OH_LEN);
	offset += HTTP_OH_LEN;
	memcpy(getReq + offset, crl_hostHdr, HOST_OH_LEN);
	offset += HOST_OH_LEN;
	memcpy(getReq + offset, hostAddr, hostAddrLen);
	offset += hostAddrLen;
	memcpy(getReq + offset, crl_acceptHdr, ACCEPT_OH_LEN);
	
	/* Connect and send */
	fd = socketConnect(ipAddr, port, &err);
	if (fd == INVALID_SOCKET || err != PS_SUCCESS) {
		_psTraceInt("crlCb: socketConnect failed: %d\n", err);
		return PS_PLATFORM_FAIL;
	}

	/* Send request and receive response */
	offset = 0;
	while (getReqLen) {
		if ((transferred = send(fd, getReq + offset, getReqLen, 0)) < 0) {
			_psTraceInt("crlCb: socket send failed: %d\n", errno);
			close(fd);
			return PS_PLATFORM_FAIL;
		}
		getReqLen -= transferred;
		offset += transferred;
	}
	
	/* Not a good full recv */
	if ((transferred = recv(fd, crlBuf, CRL_BUF_SIZE, 0)) <= 0) {
		_psTrace("crlCb: socket recv closed or failed\n");
		close(fd);
		return PS_PLATFORM_FAIL;
	} 
	if (transferred == CRL_BUF_SIZE) {
		/* CRL larger than max */
		_psTrace("crlCb: CRL_BUF_SIZE needs to be increased\n");
		close(fd);
		return -1;
	}
	close(fd);
	
	/* Did we get an OK response? */
	if (strstr(crlBuf, "200 OK") == NULL) {
		_psTrace("crlCb: server reply was not '200 OK'\n");
		return -1;
	}
	/* Length parse */
	if ((replyPtr = strstr(crlBuf, "Content-Length: ")) == NULL) {
		return -1;
	}
	crlBinLen = (int)atoi(replyPtr + 16);
	
	/* Data begins after CRLF CRLF */
	if ((replyPtr = strstr(crlBuf, "\r\n\r\n")) == NULL) {
		return -1;
	}
	/* A sanity test that the length matches the remainder */
	if ((transferred - (replyPtr - crlBuf) - 4) != crlBinLen) {
		return -1;
	}
	
	/* Lastly, pass the CRL to matrixSslLoadCRL to parse, perform signature
		validation, and cache the revoked certificates for this CA */
	return matrixSslLoadCRL(pool, CA, append, replyPtr + 4, crlBinLen);
}
コード例 #19
0
void notify(int socket, int id, char* message) {
	socketConnect(socket, conf.IP_Orquestador, conf.puertoOrquestador, errorConexionOrquestador);
	t_mensaje* msg = mensaje_create(id, message);
	socketSend(socket, msg, errorConexionOrquestador);
	free(msg);
}
コード例 #20
0
ファイル: dhcpv6_relay.c プロジェクト: rpc-fw/analyzer
error_t dhcpv6RelayStart(Dhcpv6RelayCtx *context, const Dhcpv6RelaySettings *settings)
{
   error_t error;
   uint_t i;
   OsTask *task;

   //Debug message
   TRACE_INFO("Starting DHCPv6 relay agent...\r\n");

   //Ensure the parameters are valid
   if(!context || !settings)
      return ERROR_INVALID_PARAMETER;
   //The pointer to the network-facing interface shall be valid
   if(!settings->serverInterface)
      return ERROR_INVALID_INTERFACE;
   //Check the number of client-facing interfaces
   if(!settings->clientInterfaceCount)
      return ERROR_INVALID_PARAMETER;
   if(settings->clientInterfaceCount >= DHCPV6_RELAY_MAX_CLIENT_IF)
      return ERROR_INVALID_PARAMETER;

   //Loop through the client-facing interfaces
   for(i = 0; i < settings->clientInterfaceCount; i++)
   {
      //A valid pointer is required for each interface
      if(!settings->clientInterface[i])
         return ERROR_INVALID_INTERFACE;
   }

   //Check the address to be used when forwarding messages to the server
   if(ipv6CompAddr(&settings->serverAddress, &IPV6_UNSPECIFIED_ADDR))
      return ERROR_INVALID_ADDRESS;

   //Clear the DHCPv6 relay agent context
   memset(context, 0, sizeof(Dhcpv6RelayCtx));

   //Save the network-facing interface
   context->serverInterface = settings->serverInterface;
   //Save the number of client-facing interfaces
   context->clientInterfaceCount = settings->clientInterfaceCount;
   //Save all the client-facing interfaces
   for(i = 0; i < context->clientInterfaceCount; i++)
      context->clientInterface[i] = settings->clientInterface[i];

   //Save the address to be used when relaying client messages to the server
   context->serverAddress = settings->serverAddress;

   //Join the All_DHCP_Relay_Agents_and_Servers multicast group
   //for each client-facing interface
   error = dhcpv6RelayJoinMulticastGroup(context);
   //Any error to report?
   if(error) return error;

   //Start of exception handling block
   do
   {
      //Open a UDP socket to handle the network-facing interface
      context->serverSocket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);
      //Failed to open socket?
      if(!context->serverSocket)
      {
         //Report an error
         error = ERROR_OPEN_FAILED;
         //Stop processing
         break;
      }

      //Explicitly associate the socket with the relevant interface
      error = socketBindToInterface(context->serverSocket, context->serverInterface);
      //Unable to bind the socket to the desired interface?
      if(error) break;

      //Relay agents listen for DHCPv6 messages on UDP port 547
      error = socketBind(context->serverSocket, &IP_ADDR_ANY, DHCPV6_SERVER_PORT);
      //Unable to bind the socket to the desired port?
      if(error) break;

      //Only accept datagrams with source port number 547
      error = socketConnect(context->serverSocket, &IP_ADDR_ANY, DHCPV6_SERVER_PORT);
      //Any error to report?
      if(error) break;

      //If the relay agent relays messages to the All_DHCP_Servers address
      //or other multicast addresses, it sets the Hop Limit field to 32

      //Loop through the client-facing interfaces
      for(i = 0; i < context->clientInterfaceCount; i++)
      {
         //Open a UDP socket to handle the current interface
         context->clientSocket[i] = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);
         //Failed to open socket?
         if(!context->clientSocket[i])
         {
            //Report an error
            error = ERROR_OPEN_FAILED;
            //Stop processing
            break;
         }

         //Explicitly associate the socket with the relevant interface
         error = socketBindToInterface(context->clientSocket[i], context->clientInterface[i]);
         //Unable to bind the socket to the desired interface?
         if(error) break;

         //Relay agents listen for DHCPv6 messages on UDP port 547
         error = socketBind(context->clientSocket[i], &IP_ADDR_ANY, DHCPV6_SERVER_PORT);
         //Unable to bind the socket to the desired port?
         if(error) break;

         //Only accept datagrams with source port number 546
         error = socketConnect(context->clientSocket[i], &IP_ADDR_ANY, DHCPV6_CLIENT_PORT);
         //Any error to report?
         if(error) break;
      }

      //Propagate exception if necessary...
      if(error) break;

      //Create event objects
      context->event = osEventCreate(FALSE);
      context->ackEvent = osEventCreate(FALSE);

      //Out of resources?
      if(context->event == OS_INVALID_HANDLE ||
         context->ackEvent == OS_INVALID_HANDLE)
      {
         //Report an error
         error = ERROR_OUT_OF_RESOURCES;
         //Stop processing
         break;
      }

      //The DHCPv6 relay agent is now running
      context->running = TRUE;

      //Start the DHCPv6 relay agent service
      task = osTaskCreate("DHCPv6 Relay", dhcpv6RelayTask,
         context, DHCPV6_RELAY_STACK_SIZE, DHCPV6_RELAY_PRIORITY);

      //Unable to create the task?
      if(task == OS_INVALID_HANDLE)
         error = ERROR_OUT_OF_RESOURCES;

      //End of exception handling block
   } while(0);

   //Did we encounter an error?
   if(error)
   {
      //Close the socket associated with the network-facing interface
      socketClose(context->serverSocket);

      //Close the socket associated with each client-facing interface
      for(i = 0; i < context->clientInterfaceCount; i++)
         socketClose(context->clientSocket[i]);

      //Leave the All_DHCP_Relay_Agents_and_Servers multicast group
      //for each client-facing interface
      dhcpv6RelayLeaveMulticastGroup(context);

      //Close event objects
      osEventClose(context->event);
      osEventClose(context->ackEvent);
   }

   //Return status code
   return error;
}
コード例 #21
0
ファイル: dns_client.c プロジェクト: FXRer/STM32F4_DISCOVERY
error_t dnsResolve(NetInterface *interface, const char_t *name, IpAddr *ipAddr)
{
   error_t error;
   uint_t i;
   size_t length;
   uint16_t identifier;
   IpAddr serverIpAddr;
   Socket *socket;
   DnsHeader *dnsMessage;

   //Debug message
   TRACE_INFO("Trying to resolve %s...\r\n", name);

   //Use default network interface?
   if(!interface)
      interface = tcpIpStackGetDefaultInterface();

   //Allocate a memory buffer to hold DNS messages
   dnsMessage = memPoolAlloc(DNS_MESSAGE_MAX_SIZE);
   //Failed to allocate memory?
   if(!dnsMessage)
      return ERROR_OUT_OF_MEMORY;

   //Open a UDP socket
   socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_PROTOCOL_UDP);

   //Failed to open socket?
   if(!socket)
   {
      //Free previously allocated memory
      osMemFree(dnsMessage);
      //Return status code
      return ERROR_OPEN_FAILED;
   }

#if (IPV4_SUPPORT == ENABLED)
   //IP address of the DNS server
   serverIpAddr.length = sizeof(Ipv4Addr);
   serverIpAddr.ipv4Addr = interface->ipv4Config.dnsServer[0];
#elif (IPV6_SUPPORT == ENABLED)
   //IP address of the DNS server
   serverIpAddr.length = sizeof(Ipv6Addr);
   serverIpAddr.ipv6Addr = interface->ipv6Config.dnsServer[0];
#endif

   //Associate the socket with the relevant interface
   error = socketBindToInterface(socket, interface);

   //Any error to report?
   if(error)
   {
      //Free previously allocated memory
      osMemFree(dnsMessage);
      //Close socket
      socketClose(socket);
      //Return status code
      return error;
   }

   //Connect the newly created socket to the primary DNS server
   error = socketConnect(socket, &serverIpAddr, DNS_PORT);

   //Failed to connect?
   if(error)
   {
      //Free previously allocated memory
      osMemFree(dnsMessage);
      //Close socket
      socketClose(socket);
      //Return status code
      return error;
   }

   //An identifier is used by the client to match replies
   //with corresponding requests
   identifier = rand();

   //Try to retransmit the DNS message if the previous query timed out
   for(i = 0; i < DNS_MAX_RETRIES; i++)
   {
      //Send DNS query message
      error = dnsSendQuery(socket, dnsMessage, identifier, name);
      //Failed to send message ?
      if(error) break;

      //Adjust receive timeout
      error = socketSetTimeout(socket, DNS_REQUEST_TIMEOUT);
      //Any error to report?
      if(error) break;

      //Wait for the server response
      error = socketReceive(socket, dnsMessage, DNS_MESSAGE_MAX_SIZE, &length, 0);

      //Any response from the specified DNS server?
      if(!error)
      {
         //Parse DNS response
         error = dnsParseResponse(dnsMessage, length, identifier, ipAddr);
         //DNS response successfully decoded?
         if(!error) break;
      }
   }

   //The maximum number of retransmissions has been reached?
   if(i >= DNS_MAX_RETRIES)
      error = ERROR_TIMEOUT;

   //Free previously allocated memory
   osMemFree(dnsMessage);
   //Close socket
   socketClose(socket);

   //Debug message
   if(!error)
   {
      //Name resolution succeeds
      TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL));
   }
   else
   {
      //Report an error
      TRACE_ERROR("DNS resolution failed!\r\n");
   }

   //Return status code
   return error;
}
コード例 #22
0
ファイル: indiclient.cpp プロジェクト: aaronevers/indi-fcgi
void IndiClient::reconnect()
{
    socketConnect(mHost);
}
コード例 #23
0
ファイル: pusher.c プロジェクト: jdee/dubsar
int
main(int argc, char** argv)
{
    signal(SIGINT, signalHandler);
    signal(SIGTERM, signalHandler);

    int s = -1;
    int success = 0;
    SSL* tls = NULL;

    /*
     * Parse and validate args
     */
    if (parseArgs(argc, argv))
    {
        usage(argv[0]);
        return 1;
    }

    // make logs a little easier to read/more useful
    setvbuf(stderr, NULL, _IOLBF, 0);

    if (broadcast)
    {
        timestamp_f(stderr);
        fprintf(stderr, "broadcast environment: %s\n", (production ? "prod" : "dev"));
    }
    else if (noSend == 0)
    {
        timestamp_f(stderr);
        fprintf(stderr, "device token: %s\n", deviceToken);
    }
    else
    {
        timestamp_f(stderr);
        fprintf(stderr, "build and report only; no send\n");
    }

    timestamp_f(stderr);
    fprintf(stderr, "cert. file: %s. passphrase loaded\n", certPath);
    timestamp_f(stderr);
    fprintf(stderr, "database path: %s\n", databasePath);
    timestamp_f(stderr);
    fprintf(stderr, "message: \"%s\"\n", message);
    timestamp_f(stderr);
    fprintf(stderr, "host: %s, port: %d\n", host, port);
    timestamp_f(stderr);
    fprintf(stderr, "url: %s\n", url);
    timestamp_f(stderr);
    fprintf(stderr, "wotd: %d\n", wotd);

    time_t expiration = time(NULL) + 43200;
    
    void* notificationPayload = NULL;
    size_t notificationPayloadSize = 0;
    if (buildNotificationPayload(wotd, broadcast, production, deviceToken,
        databasePath, message, url, wotdExpiration, expiration,
        &notificationPayload, &notificationPayloadSize))
    {
        timestamp_f(stderr);
        fprintf(stderr, "failed to build notification payload\n");
        return -1;
    }
    timestamp_f(stderr);
    fprintf(stderr, "notification length is %ld\n", notificationPayloadSize);

    if (noSend)
    {
        free(notificationPayload);
        return 0;
    }

    /*
     * Connect to server
     */

    int nb = 0;
    int b = 0;
    while (!success && !_shutdown && time(NULL) < expiration)
    {
        while (!_shutdown && time(NULL) < expiration && s < 0)
        {
            timestamp_f(stderr);
            fprintf(stderr, "attempting connection to %s:%d\n", host, port);
            s = socketConnect(host, port);
            if (s < 0)
            {
                timestamp_f(stderr);
                fprintf(stderr, "connection to %s:%d failed\n", host, port);
                b = backoff();

                if (_shutdown || time(NULL) + b >= expiration)
                {
                    free(notificationPayload);
                    return 1;
                }

                timestamp_f(stderr);
                fprintf(stderr, "will try again in %d s\n", b);
                sleep(b);
                continue;
            }
        
            timestamp_f(stderr);
            fprintf(stderr, "successfully connected to %s:%d\n", host, port);
        }
    
        if (_shutdown || time(NULL) >= expiration)
        {
            free(notificationPayload);
            if (s >= 0) close(s);
            return 1;
        }

        tls = makeTlsConnection(s, certPath, passphrase, cacertPath);
        if (!tls)
        {
            timestamp_f(stderr);
            fprintf(stderr, "TLS handshake failed\n");
            close(s);
            s = -1;
            b = backoff();

            if (_shutdown || time(NULL) + b >= expiration)
            {
                free(notificationPayload);
                return 1;
            }

            timestamp_f(stderr);
            fprintf(stderr, "will reconnect in %d s\n", b);
            sleep(b);
            continue;
        }

        if (_shutdown)
        {
            free(notificationPayload);
            stopTlsConnection(tls);
            return 1;
        }
    
        nb = SSL_write(tls, notificationPayload, notificationPayloadSize);
        if (nb != notificationPayloadSize)
        {
            timestamp_f(stderr);
            fprintf(stderr, "SSL_write: %s", ERR_error_string(nb, NULL));
            stopTlsConnection(tls);
            s = -1;
            tls = NULL;
            b = backoff();

            if (_shutdown || time(NULL) + b >= expiration)
            {
                free(notificationPayload);
                return 1;
            }

            timestamp_f(stderr);
            fprintf(stderr, "will reconnect in %d s\n", b);
            sleep(b);
            continue;
        }
    
        timestamp_f(stderr);
        fprintf(stderr, "successfully wrote %d bytes\n", nb);
        free(notificationPayload);
        success = 1;
    }

    if (_shutdown || time(NULL) >= expiration)
    {
        if (tls) stopTlsConnection(tls);
        else if (s >= 0) close(s);
        return 1;
    }

    /*
     * Check for error response packet(s)
     */
    timestamp_f(stderr);
    fprintf(stderr, "checking for error responses (10 s)\n");
    char errorResponse[6];
    
    int numErrors;
    for (numErrors=0;
        (nb=SSL_read(tls, errorResponse, sizeof(errorResponse))) == sizeof(errorResponse);
        ++numErrors)
    {
        uint32_t identifier;
        memcpy(&identifier, errorResponse+2, sizeof(identifier));

        timestamp_f(stderr);
        fprintf(stderr, "APNS error response: command %d, status %d, identifier %u (network order)\n", errorResponse[0], errorResponse[1], identifier);
    }

    if (nb == 0 || (nb == -1 && errno == EAGAIN))
    {
        if (numErrors == 0)
        {
            timestamp_f(stderr);
            fprintf(stderr, "APNS push successfully sent\n");
        }
    }
    else if (nb == -1)
    {
        timestamp_f(stderr);
        perror("SSL_read");
    }
    else {
        timestamp_f(stderr);
        fprintf(stderr, "SSL_read error %d: %s", nb, ERR_error_string(nb, NULL));
    }

    stopTlsConnection(tls);
    
    return 0;
}
コード例 #24
0
ファイル: optirun.c プロジェクト: seanbruno/fbsd-bumblebee
int main(int argc, char *argv[]) {
  int exitcode = EXIT_FAILURE;

  init_early_config(argc, argv, BB_RUN_APP);

  /* Setup signal handling before anything else */
  signal(SIGHUP, handle_signal);
  signal(SIGTERM, handle_signal);
  signal(SIGINT, handle_signal);
  signal(SIGQUIT, handle_signal);

  bb_init_log();

  /* Initializing configuration */
  init_config(argc, argv);
  bbconfig_parse_opts(argc, argv, PARSE_STAGE_PRECONF);
  __unused GKeyFile *bbcfg = bbconfig_parse_conf();


  /* Connect to listening daemon */
  bb_status.bb_socket = socketConnect(bb_config.socket_path, SOCK_BLOCK);
  if (bb_status.bb_socket < 0) {
    bb_log(LOG_ERR, "Could not connect to bumblebee daemon - is it running?\n");
    run_fallback(argv + optind);
    bb_closelog();
    return exitcode;
  }

  free_and_set_value(&bb_config.ld_path, malloc(BUFFER_SIZE));
  if (bbsocket_query("LibraryPath", bb_config.ld_path, BUFFER_SIZE)) {
    bb_log(LOG_ERR, "Failed to retrieve LibraryPath setting.\n");
    return EXIT_FAILURE;
  }
  free_and_set_value(&bb_config.x_display, malloc(BUFFER_SIZE));
  if (bbsocket_query("VirtualDisplay", bb_config.x_display, BUFFER_SIZE)) {
    bb_log(LOG_ERR, "Failed to retrieve VirtualDisplay setting.\n");
    return EXIT_FAILURE;
  }

  /* parse remaining common and optirun-specific options */
  bbconfig_parse_opts(argc, argv, PARSE_STAGE_OTHER);
  bb_log(LOG_DEBUG, "%s version %s starting...\n", "optirun", GITVERSION);
  config_dump();

  /* Request status */
  if (bb_status.runmode == BB_RUN_STATUS) {
    exitcode = report_daemon_status();
  }

  /* Run given application */
  if (bb_status.runmode == BB_RUN_APP) {
    if (optind >= argc) {
      bb_log(LOG_ERR, "Missing argument: application to run\n");
      print_usage(EXIT_FAILURE);
    } else {
      exitcode = run_app(argc, argv);
    }
  }

  bb_closelog();
  bb_stop_all(); //stop any started processes that are left
  return exitcode;
}
コード例 #25
0
void
proxyAccept(int srv_fd,	struct proxyConnection	*ncp)
{
	SOCKET			src_fd, dst_fd;
//	struct linger linger;
	int				status;
		int			res;
		struct timeval tv;
		int pc, sc;
		int			ccount=0;
		
	ILOG("Accepting new connection.");
	
	if ((src_fd = socketAccept(srv_fd, &status)) == INVALID_SOCKET) {
		WLOG("Error accepting connection: %d", status);
		return;
	}

	#ifdef USE_FORK
		// fork here
		fd_set	rs, ws, es;
		int fdmax;

		int pid=fork();
	  switch(pid) {
	  case -1:    /* error */
	      closesocket(ncp->plain);
	      closesocket(ncp->secure->fd);
	      break;

	  case  0:    /* child */
  #endif

	ncp->inuse=1;

	if (!isClient) {
		DLOG("Trying to accept ssl connection");
		if (sslAccept(&ncp->secure, src_fd, keys, cervalidator, 0)) {
			WLOG("Error could not establish ssl connection");
			socketShutdown(src_fd);
			/* Gemtek add +++ */
#ifdef USE_FORK
      quit=1;
#endif
      /* Gemtek add --- */
			return;
		}
	}

	setSocketNonblock(src_fd);
/*
	linger.l_onoff = 1;
	linger.l_linger = 1;
	setsockopt(src_fd, SOL_SOCKET, SO_LINGER, (char *) &linger,sizeof(linger));
*/
	/* try to connect to remote end of tunnel */
	DLOG("Trying to connect server %s:%d", dst_host, dst_port);
	if ((dst_fd = socketConnect(dst_host, dst_port, &status)) == INVALID_SOCKET) {
		WLOG("Error connecting to server %s:%d", dst_host, dst_port);
		socketShutdown(src_fd);
		/* Gemtek add +++ */
#ifdef USE_FORK
    quit=1;
#endif
    /* Gemtek add --- */
		return;
	}
	
	if (isClient) {
		DLOG("Trying to establish an ssl connection to server %s:%d", dst_host, dst_port);
		if ((sslConnect(&ncp->secure, dst_fd, keys, ncp->sessionId, ncp->cipherSuite, cervalidator)) == INVALID_SOCKET) {
			WLOG("Error connecting to ssl server %s:%d", dst_host, dst_port);
			socketShutdown(src_fd);
			return;
		}
	}
	setSocketNonblock(dst_fd);
/*
	linger.l_onoff = 1;
	linger.l_linger = 1;
	setsockopt(dst_fd, SOL_SOCKET, SO_LINGER, (char *) &linger,sizeof(linger));
*/
	ncp->plain = isClient ? src_fd : dst_fd;
	ncp->plain_up=1;
	ncp->secure_up=1;
	ILOG("Connection established. plain_fd:%d secure_fd:%d", ncp->plain, ncp->secure->fd);	
	
	// handle remaining bytes in buffer.
	/*
	res=proxyReadwrite(ncp,1);
	if(res<0) {
		ncp->error=1;
		closeProxyConnection(ncp);
	}
	*/
	// fork here
#ifdef USE_FORK
		
		closesocket(srv_fd);
		fdmax=ncp->plain > ncp->secure->fd ? ncp->plain : ncp->secure->fd;
		while (!quit) {
			FD_ZERO(&rs);
			FD_ZERO(&ws);
			FD_ZERO(&es);
			
				FD_SET(ncp->plain,&rs);
				FD_SET(ncp->plain,&ws);
				FD_SET(ncp->plain,&es);
				FD_SET(ncp->secure->fd,&rs);
				FD_SET(ncp->secure->fd,&ws);
				FD_SET(ncp->secure->fd,&es);
			
			
			tv.tv_sec=10;
			tv.tv_usec=0;

			DLOG("select on %d open connections. fdmax: %d", ccount, fdmax);
			res=select(fdmax+1,&rs,NULL,&es,&tv);
//			DLOG("select returned: %d", res);
			DLOG("proxyAccept->select returned: %d %s errno=%d", res , strerror(errno), errno );

			if(res<0) {
				perror("select");
				continue;
			}
/*
			if(res==0)
				continue;
*/
			if(FD_ISSET(ncp->secure->fd,&es) || FD_ISSET(ncp->plain,&es)) {
				ncp->error=1;
				break;
			}

			sc=proxyReadwrite(ncp,1);
			if(sc<0) break;
			pc=proxyReadwrite(ncp,0);
			if(pc<0) break;
			
			if(ncp->done) {
				quit=1;
				break;
			}
		}
		closeProxyConnection(ncp);
		DLOG("done. exiting...");
		exit(0);
		break;

	default:
      closesocket(src_fd);
							/* server */
		break;
	}
#endif
}
コード例 #26
0
 error_t sntpClientGetTimestamp(NetInterface *interface,
   const IpAddr *serverIpAddr, NtpTimestamp *timestamp)
{
   error_t error;
   uint_t i;
   systime_t timeout;
   SntpClientContext context;

   //Check parameters
   if(serverIpAddr == NULL || timestamp == NULL)
      return ERROR_INVALID_PARAMETER;

   //Use default network interface?
   if(!interface)
      interface = netGetDefaultInterface();

   //Open a UDP socket
   context.socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);
   //Failed to open socket?
   if(!context.socket)
      return ERROR_OPEN_FAILED;

   //Associate the socket with the relevant interface
   error = socketBindToInterface(context.socket, interface);
   //Any error to report?
   if(error)
   {
      //Close socket
      socketClose(context.socket);
      //Return status code
      return error;
   }

   //Only accept datagrams from the specified NTP server
   error = socketConnect(context.socket, serverIpAddr, NTP_PORT);
   //Any error to report?
   if(error)
   {
      //Close socket
      socketClose(context.socket);
      //Return status code
      return error;
   }

   //Initial timeout value
   timeout = SNTP_CLIENT_INIT_TIMEOUT;

   //Retransmission loop
   for(i = 0; i < SNTP_CLIENT_MAX_RETRIES; i++)
   {
      //Send NTP request message
      error = sntpSendRequest(&context);
      //Failed to send message ?
      if(error) break;

      //Wait for a valid NTP response message
      error = sntpWaitForResponse(&context, timeout);
      //Valid NTP response received?
      if(!error) break;

      //The timeout value is doubled for each subsequent retransmission
      timeout = MIN(timeout * 2, SNTP_CLIENT_MAX_TIMEOUT);
   }

   //Successful processing?
   if(!error)
   {
      //Save server timestamp
      timestamp->seconds = ntohl(context.message.transmitTimestamp.seconds);
      timestamp->fraction = ntohl(context.message.transmitTimestamp.fraction);
   }

   //Close socket
   socketClose(context.socket);
   //Return status code
   return error;
}
コード例 #27
0
ファイル: darnit_socket.c プロジェクト: 0502758187/libdarnit
void EXPORT_THIS *d_socket_connect(const char *host, int port, void (*callback)(int ret, void *data, void *socket), void *data) {
	return socketConnect(host, port, callback, data);
}
コード例 #28
0
ファイル: optirun.c プロジェクト: TheFrozenFire/bumblebeed
int main(int argc, char* argv[]) {

  /* Setup signal handling before anything else */
  signal(SIGHUP, handle_signal);
  signal(SIGTERM, handle_signal);
  signal(SIGINT, handle_signal);
  signal(SIGQUIT, handle_signal);

  /* Initializing configuration */
  init_config(argc, argv);
  
  /* set runmode depending on leftover arguments */
  if (optind >= argc) {
    bb_status.runmode = BB_RUN_STATUS;
  } else {
    bb_status.runmode = BB_RUN_APP;
  }

  bb_init_log();
  bb_log(LOG_DEBUG, "%s version %s starting...\n", bb_status.program_name, GITVERSION);

  /* Connect to listening daemon */
  bb_status.bb_socket = socketConnect(bb_config.socket_path, SOCK_NOBLOCK);
  if (bb_status.bb_socket < 0) {
    bb_log(LOG_ERR, "Could not connect to bumblebee daemon - is it running?\n");
    bb_closelog();
    return EXIT_FAILURE;
  }
  char buffer[BUFFER_SIZE];
  int r;

  /* Request status */
  if (bb_status.runmode == BB_RUN_STATUS) {
    r = snprintf(buffer, BUFFER_SIZE, "Status?");
    socketWrite(&bb_status.bb_socket, buffer, r);
    while (bb_status.bb_socket != -1) {
      r = socketRead(&bb_status.bb_socket, buffer, BUFFER_SIZE);
      if (r > 0) {
        printf("Bumblebee status: %*s\n", r, buffer);
        socketClose(&bb_status.bb_socket);
      }
    }
  }

  /* Run given application */
  if (bb_status.runmode == BB_RUN_APP) {
    int ranapp = 0;
    r = snprintf(buffer, BUFFER_SIZE, "Checking availability...");
    socketWrite(&bb_status.bb_socket, buffer, r);
    while (bb_status.bb_socket != -1) {
      r = socketRead(&bb_status.bb_socket, buffer, BUFFER_SIZE);
      if (r > 0) {
        bb_log(LOG_INFO, "Response: %*s\n", r, buffer);
        switch (buffer[0]) {
          case 'N': //No, run normally.
            socketClose(&bb_status.bb_socket);
            if (!bb_config.fallback_start){
              bb_log(LOG_ERR, "Cannot access secondary GPU. Aborting.\n");
            }
            break;
          case 'Y': //Yes, run through vglrun
            bb_log(LOG_INFO, "Running application through vglrun.\n");
            ranapp = 1;
            //run vglclient if any method other than proxy is used
            if (strncmp(bb_config.vgl_compress, "proxy", BUFFER_SIZE) != 0) {
              char * vglclient_args[] = {
                "vglclient",
                "-detach",
                0
              };
              bb_run_fork(vglclient_args);
            }
            char ** vglrun_args = malloc(sizeof (char *) * (9 + argc - optind));
            vglrun_args[0] = "vglrun";
            vglrun_args[1] = "-c";
            vglrun_args[2] = bb_config.vgl_compress;
            vglrun_args[3] = "-d";
            vglrun_args[4] = bb_config.x_display;
            vglrun_args[5] = "-ld";
            vglrun_args[6] = bb_config.ld_path;
            vglrun_args[7] = "--";
            for (r = 0; r < argc - optind; r++) {
              vglrun_args[8 + r] = argv[optind + r];
            }
            vglrun_args[8 + r] = 0;
            bb_run_fork_wait(vglrun_args);
            socketClose(&bb_status.bb_socket);
            break;
          default: //Something went wrong - output and exit.
            bb_log(LOG_ERR, "Problem: %*s\n", r, buffer);
            socketClose(&bb_status.bb_socket);
            break;
        }
      }
    }
    if (!ranapp && bb_config.fallback_start) {
      bb_log(LOG_WARNING, "Running application normally.\n");
      bb_run_exec(argv + optind);
    }
  }

  bb_closelog();
  bb_stop_all(); //stop any started processes that are left
  return (EXIT_SUCCESS);
}
コード例 #29
0
ファイル: client.c プロジェクト: sunfirefox/packages-2
/*
	Make a secure HTTP request to a defined IP and port
	Connection is made in blocking socket mode
	The connection is considered successful if the SSL/TLS session is
	negotiated successfully, a request is sent, and a HTTP response is received.
 */
static int32 httpsClientConnection(sslKeys_t *keys, sslSessionId_t *sid)
{
	int32			rc, transferred, len, complete;
	ssl_t			*ssl;
	unsigned char	*buf;
	httpConn_t		cp;
	SOCKET			fd;
	
	complete = 0;
	memset(&cp, 0x0, sizeof(httpConn_t));
	fd = socketConnect(HTTPS_IP, HTTPS_PORT, &rc);
	if (fd == INVALID_SOCKET || rc != PS_SUCCESS) {
		_psTraceInt("Connect failed: %d.  Exiting\n", rc);
		return PS_PLATFORM_FAIL;
	}
	
	rc = matrixSslNewClientSession(&ssl, keys, sid, 0, certCb, NULL, NULL);
	if (rc != MATRIXSSL_REQUEST_SEND) {
		_psTraceInt("New Client Session Failed: %d.  Exiting\n", rc);
		close(fd);
		return PS_ARG_FAIL;
	}
WRITE_MORE:
	while ((len = matrixSslGetOutdata(ssl, &buf)) > 0) {
		transferred = send(fd, buf, len, 0);
		if (transferred <= 0) {
			goto L_CLOSE_ERR;
		} else {
			/* Indicate that we've written > 0 bytes of data */
			if ((rc = matrixSslSentData(ssl, transferred)) < 0) {
				goto L_CLOSE_ERR;
			}
			if (rc == MATRIXSSL_REQUEST_CLOSE) {
				closeConn(ssl, fd);
				return MATRIXSSL_SUCCESS;
			} 
			if (rc == MATRIXSSL_HANDSHAKE_COMPLETE) {
				/* If we sent the Finished SSL message, initiate the HTTP req */
				/* (This occurs on a resumption handshake) */
				if (httpWriteRequest(ssl) < 0) {
					goto L_CLOSE_ERR;
				}
				goto WRITE_MORE;
			}
			/* SSL_REQUEST_SEND is handled by loop logic */
		}
	}
READ_MORE:
	if ((len = matrixSslGetReadbuf(ssl, &buf)) <= 0) {
		goto L_CLOSE_ERR;
	}
	if ((transferred = recv(fd, buf, len, 0)) < 0) {
		goto L_CLOSE_ERR;
	}
	/*	If EOF, remote socket closed. But we haven't received the HTTP response 
		so we consider it an error in the case of an HTTP client */
	if (transferred == 0) {
		goto L_CLOSE_ERR;
	}
	if ((rc = matrixSslReceivedData(ssl, (int32)transferred, &buf,
									(uint32*)&len)) < 0) {
		goto L_CLOSE_ERR;
	}
	
PROCESS_MORE:
	switch (rc) {
		case MATRIXSSL_HANDSHAKE_COMPLETE:
#ifdef REHANDSHAKE_TEST
/*
			Test rehandshake capabilities of server.  If a successful
			session resmption rehandshake occurs, this client will be last to
			send handshake data and MATRIXSSL_HANDSHAKE_COMPLETE will hit on
			the WRITE_MORE handler and httpWriteRequest will occur there.
			
			NOTE: If the server doesn't support session resumption it is
			possible to fall into an endless rehandshake loop
*/
			if (matrixSslEncodeRehandshake(ssl, NULL, NULL, 0, 0) < 0) {
				goto L_CLOSE_ERR;
			}
#else		
			/* We got the Finished SSL message, initiate the HTTP req */
			if (httpWriteRequest(ssl) < 0) {
				goto L_CLOSE_ERR;
			}
#endif
			goto WRITE_MORE;
		case MATRIXSSL_APP_DATA:
			if ((rc = httpBasicParse(&cp, buf, len)) < 0) {
				closeConn(ssl, fd);
				if (cp.parsebuf) free(cp.parsebuf); cp.parsebuf = NULL;
				cp.parsebuflen = 0;
				return MATRIXSSL_ERROR;
			}
			if (rc == HTTPS_COMPLETE) {
				rc = matrixSslProcessedData(ssl, &buf, (uint32*)&len);
				closeConn(ssl, fd);
				if (cp.parsebuf) free(cp.parsebuf); cp.parsebuf = NULL;
				cp.parsebuflen = 0;
				if (rc < 0) {
					return MATRIXSSL_ERROR;
				} else {
					if (rc > 0) {
						_psTrace("HTTP data parsing not supported, ignoring.\n");
					}
					_psTrace("SUCCESS: Received HTTP Response\n");
					return MATRIXSSL_SUCCESS;
				}
			}
			/* We processed a partial HTTP message */
			if ((rc = matrixSslProcessedData(ssl, &buf, (uint32*)&len)) == 0) {
				goto READ_MORE;
			}
			goto PROCESS_MORE;
		case MATRIXSSL_REQUEST_SEND:
			goto WRITE_MORE;
		case MATRIXSSL_REQUEST_RECV:
			goto READ_MORE;
		case MATRIXSSL_RECEIVED_ALERT:
			/* The first byte of the buffer is the level */
			/* The second byte is the description */
			if (*buf == SSL_ALERT_LEVEL_FATAL) {
				psTraceIntInfo("Fatal alert: %d, closing connection.\n", 
							*(buf + 1));
				goto L_CLOSE_ERR;
			}
			/* Closure alert is normal (and best) way to close */
			if (*(buf + 1) == SSL_ALERT_CLOSE_NOTIFY) {
				closeConn(ssl, fd);
				if (cp.parsebuf) free(cp.parsebuf); cp.parsebuf = NULL;
				cp.parsebuflen = 0;
				return MATRIXSSL_SUCCESS;
			}
			psTraceIntInfo("Warning alert: %d\n", *(buf + 1));
			if ((rc = matrixSslProcessedData(ssl, &buf, (uint32*)&len)) == 0) {
				/* No more data in buffer. Might as well read for more. */
				goto READ_MORE;
			}
			goto PROCESS_MORE;
		default:
			/* If rc <= 0 we fall here */
			goto L_CLOSE_ERR;
	}
	
L_CLOSE_ERR:
	_psTrace("FAIL: No HTTP Response\n");
	matrixSslDeleteSession(ssl);
	close(fd);
	if (cp.parsebuf) free(cp.parsebuf); cp.parsebuf = NULL;
	cp.parsebuflen = 0;
	return MATRIXSSL_ERROR;
}
コード例 #30
0
ファイル: main.c プロジェクト: frankzzcn/M2_SE_RTOS_Project
error_t sslClientTest(void)
{
   error_t error;
   size_t length;
   IpAddr ipAddr;
   static char_t buffer[256];

   //Underlying socket
   Socket *socket = NULL;
   //SSL/TLS context
   TlsContext *tlsContext = NULL;

   //Debug message
   TRACE_INFO("Resolving server name...\r\n");

   //Resolve SSL server name
   error = getHostByName(NULL, APP_SERVER_NAME, &ipAddr, 0);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_INFO("Failed to resolve server name!\r\n");
      //Exit immediately
      return error;
   }

   //Create a new socket to handle the request
   socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
   //Any error to report?
   if(!socket)
   {
      //Debug message
      TRACE_INFO("Failed to open socket!\r\n");
      //Exit immediately
      return ERROR_OPEN_FAILED;
   }

   //Start of exception handling block
   do
   {
      //Debug message
      TRACE_INFO("Connecting to SSL server %s\r\n", ipAddrToString(&ipAddr, NULL));

      //Connect to the SSL server
      error = socketConnect(socket, &ipAddr, APP_SERVER_PORT);
      //Any error to report?
      if(error) break;

      //Initialize SSL/TLS context
      tlsContext = tlsInit();
      //Initialization failed?
      if(!tlsContext)
      {
         //Report an error
         error = ERROR_OUT_OF_MEMORY;
         //Exit immediately
         break;
      }

      //Bind TLS to the relevant socket
      error = tlsSetSocket(tlsContext, socket);
      //Any error to report?
      if(error) break;

      //Select client operation mode
      error = tlsSetConnectionEnd(tlsContext, TLS_CONNECTION_END_CLIENT);
      //Any error to report?
      if(error) break;

      //Set the PRNG algorithm to be used
      error = tlsSetPrng(tlsContext, YARROW_PRNG_ALGO, &yarrowContext);
      //Any error to report?
      if(error) break;

#if (APP_SET_CIPHER_SUITES == ENABLED)
      //Preferred cipher suite list
      error = tlsSetCipherSuites(tlsContext, cipherSuites, arraysize(cipherSuites));
      //Any error to report?
      if(error) break;
#endif

#if (APP_SET_SERVER_NAME == ENABLED)
      //Set the fully qualified domain name of the server
      error = tlsSetServerName(tlsContext, APP_SERVER_NAME);
      //Any error to report?
      if(error) break;
#endif

#if (APP_SET_TRUSTED_CA_LIST == ENABLED)
      //Import the list of trusted CA certificates
      error = tlsSetTrustedCaList(tlsContext, trustedCaList, trustedCaListLength);
      //Any error to report?
      if(error) break;
#endif

#if (APP_SET_CLIENT_CERT == ENABLED)
      //Import the client's certificate
      error = tlsAddCertificate(tlsContext, clientCert,
         clientCertLength, clientPrivateKey, clientPrivateKeyLength);
      //Any error to report?
      if(error) break;
#endif

      //Establish a secure session
      error = tlsConnect(tlsContext);
      //TLS handshake failure?
      if(error) break;

      //Format HTTP request
      sprintf(buffer, "GET %s HTTP/1.0\r\nHost: %s:%u\r\n\r\n",
         APP_REQUEST_URI, APP_SERVER_NAME, APP_SERVER_PORT);

      //Debug message
      TRACE_INFO("\r\n");
      TRACE_INFO("HTTP request:\r\n%s", buffer);

      //Send the request
      error = tlsWrite(tlsContext, buffer, strlen(buffer), 0);
      //Any error to report?
      if(error) break;

      //Debug message
      TRACE_INFO("HTTP response:\r\n");

      //Read the whole response
      while(1)
      {
         //Read data
         error = tlsRead(tlsContext, buffer, sizeof(buffer) - 1, &length, 0);
         //End of stream?
         if(error) break;

         //Properly terminate the string with a NULL character
         buffer[length] = '\0';
         //Debug message
         TRACE_INFO("%s", buffer);
      }

      //Successfull processing
      error = NO_ERROR;

      //End of exception handling block
   } while(0);

   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_INFO("Failed to communicate with SSL server!\r\n");
   }

   //Terminate TLS session
   tlsFree(tlsContext);
   //Close socket
   socketClose(socket);

   //Debug message
   TRACE_INFO("Connection closed...\r\n");

   //Return status code
   return error;
}