예제 #1
0
int		main(int ac, char **av)
{
  t_client	*client;

  client = xmalloc(sizeof(t_client));
  init_client(client);
  register_command(client, "id", cmd_id);
  register_command(client, "map", cmd_map);
  register_command(client, "start", cmd_start);
  register_command(client, "player", cmd_player);
  register_command(client, "coin", cmd_coin);
  register_command(client, "finish", cmd_finish);
  register_command(client, "remove", cmd_remove);
  parse_args(client, ac, av);
  my_connect(client);

  return (0);
}
예제 #2
0
static int NetlibHttpFallbackToDirect(struct NetlibConnection *nlc, struct NetlibUser *nlu, NETLIBOPENCONNECTION *nloc)
{
	NetlibDoClose(nlc, true);

	NetlibLogf(nlu,"Fallback to direct connection");
	NetlibLogf(nlu,"(%p) Connecting to server %s:%d....", nlc, nloc->szHost, nloc->wPort);

	nlc->proxyAuthNeeded = false;
	nlc->proxyType = 0;
	mir_free(nlc->szProxyServer); nlc->szProxyServer = NULL;
	nlc->sinProxy.sin_family = AF_INET;
	nlc->sinProxy.sin_port = htons(nloc->wPort);
	nlc->sinProxy.sin_addr.S_un.S_addr = DnsLookup(nlu, nloc->szHost);
	if (nlc->sinProxy.sin_addr.S_un.S_addr == 0 || my_connect(nlc, nloc) == SOCKET_ERROR) 
	{
		if (nlc->sinProxy.sin_addr.S_un.S_addr)
			NetlibLogf(nlu, "%s %d: %s() failed (%u)", __FILE__, __LINE__, "connect", WSAGetLastError());
		return false;
	}
	return true;
}
예제 #3
0
파일: connect.c 프로젝트: simplegeo/kgio
static VALUE stream_connect(VALUE klass, VALUE addr, int io_wait)
{
	int domain;
	socklen_t addrlen;
	struct sockaddr *sockaddr;

	if (TYPE(addr) == T_STRING) {
		sockaddr = (struct sockaddr *)(RSTRING_PTR(addr));
		addrlen = (socklen_t)RSTRING_LEN(addr);
	} else {
		rb_raise(rb_eTypeError, "invalid address");
	}
	switch (((struct sockaddr_storage *)(sockaddr))->ss_family) {
	case AF_UNIX: domain = PF_UNIX; break;
	case AF_INET: domain = PF_INET; break;
	case AF_INET6: domain = PF_INET6; break;
	default:
		rb_raise(rb_eArgError, "invalid address family");
	}

	return my_connect(klass, io_wait, domain, sockaddr, addrlen);
}
예제 #4
0
static int     		my_client(char *ip, int port)
{
  struct sockaddr_in	s_in;
  struct protoent	*pe;
  int			fd;

  if ((pe = getprotobyname("TCP")) == NULL)
    return (-1);
  if ((fd = my_socket_client(pe)) == -1)
    return (-1);
  s_in.sin_family = AF_INET;
  s_in.sin_port = htons(port);
  s_in.sin_addr.s_addr = inet_addr(ip);
  if (my_connect(fd, s_in) == -1)
    return (-1);
  if (close(fd) == -1)
    {
      printf("Error on : close\n");
      return (-1);
    }
   return (0);
}
예제 #5
0
bool NetlibReconnect(NetlibConnection *nlc)
{
	char buf[4];
	bool opened;  

	switch (WaitUntilReadable(nlc->s, 0, true))
	{
	case SOCKET_ERROR:
		opened = false;
		break;

	case 0:
		opened = true;
		break;

	case 1:
		opened = recv(nlc->s, buf, 1, MSG_PEEK) > 0;
		break;
	}

	if (!opened)
	{
		NetlibDoClose(nlc, true);

		if (Miranda_Terminated()) return false;

		if (nlc->usingHttpGateway)
		{
			nlc->proxyAuthNeeded = true;
			NetlibLogf(nlc->nlu,"(%p) Connecting....", nlc);
			return my_connect(nlc, &nlc->nloc) == 0;
		}
		else
			return NetlibDoConnect(nlc);
	}
	return true;
}
예제 #6
0
int myproxy_ocsp_verify(X509 *cert, X509 *issuer) {
  BIO                   *bio = 0;
  int                   rc, reason, ssl, status;
  char                  *host = 0, *path = 0, *port = 0, *certdir = 0;
  char                  *aiaocspurl = 0, *chosenurl = 0;
  SSL_CTX               *ctx = 0;
  X509_LOOKUP           *lookup = NULL;
  X509_STORE            *store = 0;
  OCSP_CERTID           *id;
  OCSP_REQUEST          *req = 0;
  OCSP_RESPONSE         *resp = 0;
  OCSP_BASICRESP        *basic = 0;
  myproxy_ocspresult_t  result;
  ASN1_GENERALIZEDTIME  *producedAt, *thisUpdate, *nextUpdate;
  globus_result_t       res;

  if (!policy && !responder_url) {
      result = MYPROXY_OCSPRESULT_ERROR_NOTCONFIGURED;
      goto end;
  }

  result = MYPROXY_OCSPRESULT_ERROR_UNKNOWN;

  if (policy && strstr(policy, "aia")) {
      aiaocspurl = myproxy_get_aia_ocsp_uri(cert);
  }

  if (!responder_url && !aiaocspurl) {
      result = MYPROXY_OCSPRESULT_ERROR_NOTCONFIGURED;
      goto end;
  }

  chosenurl = aiaocspurl ? aiaocspurl : responder_url;
  if (!OCSP_parse_url(chosenurl, &host, &port, &path, &ssl)) {
    result = MYPROXY_OCSPRESULT_ERROR_BADOCSPADDRESS;
    goto end;
  }

  myproxy_log("querying OCSP responder at %s", chosenurl);

  if (!(req = OCSP_REQUEST_new())) {
    result = MYPROXY_OCSPRESULT_ERROR_OUTOFMEMORY;
    goto end;
  }

  id = OCSP_cert_to_id(0, cert, issuer);
  if (!id || !OCSP_request_add0_id(req, id)) goto end;
  if (usenonce) OCSP_request_add1_nonce(req, 0, -1);

  /* sign the request */
  if (sign_cert && sign_key &&
      !OCSP_request_sign(req, sign_cert, sign_key, EVP_sha1(), 0, 0)) {
    result = MYPROXY_OCSPRESULT_ERROR_SIGNFAILURE;
    goto end;
  }

  /* setup GSI context */
  store=X509_STORE_new();
  lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
  if (lookup == NULL) {
    result = MYPROXY_OCSPRESULT_ERROR_OUTOFMEMORY;
    goto end;
  }
  res = GLOBUS_GSI_SYSCONFIG_GET_CERT_DIR(&certdir);
  if (res != GLOBUS_SUCCESS) {
    verror_put_string("failed to find GSI CA cert directory");
    globus_error_to_verror(res);
    goto end;
  }
  X509_LOOKUP_add_dir(lookup, certdir, X509_FILETYPE_PEM);
  ctx = SSL_CTX_new(SSLv23_client_method());
  if (ctx == NULL) {
    result = MYPROXY_OCSPRESULT_ERROR_OUTOFMEMORY;
    goto end;
  }
  SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
  SSL_CTX_set_cert_store(ctx, store);
  SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);

  /* establish a connection to the OCSP responder */
  if (!(bio = my_connect(host, atoi(port), ssl, &ctx))) {
    result = MYPROXY_OCSPRESULT_ERROR_CONNECTFAILURE;
    goto end;
  }

  /* send the request and get a response */
  resp = OCSP_sendreq_bio(bio, path, req);
  if ((rc = OCSP_response_status(resp)) != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
    switch (rc) {
      case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
        result = MYPROXY_OCSPRESULT_ERROR_MALFORMEDREQUEST; break;
      case OCSP_RESPONSE_STATUS_INTERNALERROR:
        result = MYPROXY_OCSPRESULT_ERROR_INTERNALERROR;    break;
      case OCSP_RESPONSE_STATUS_TRYLATER:
        result = MYPROXY_OCSPRESULT_ERROR_TRYLATER;         break;
      case OCSP_RESPONSE_STATUS_SIGREQUIRED:
        result = MYPROXY_OCSPRESULT_ERROR_SIGREQUIRED;      break;
      case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
        result = MYPROXY_OCSPRESULT_ERROR_UNAUTHORIZED;     break;
    }
    goto end;
  }

  /* verify the response */
  result = MYPROXY_OCSPRESULT_ERROR_INVALIDRESPONSE;
  if (!(basic = OCSP_response_get1_basic(resp))) goto end;
  if (usenonce && OCSP_check_nonce(req, basic) <= 0) goto end;

  if (!responder_cert ||
      (rc = OCSP_basic_verify(basic, responder_cert, store,
                              OCSP_TRUSTOTHER)) <= 0)
      if ((rc = OCSP_basic_verify(basic, NULL, store, 0)) <= 0) 
          goto end;

  if (!OCSP_resp_find_status(basic, id, &status, &reason, &producedAt,
                             &thisUpdate, &nextUpdate))
    goto end;
  if (!OCSP_check_validity(thisUpdate, nextUpdate, skew, maxage))
    goto end;

  /* All done.  Set the return code based on the status from the response. */
  if (status == V_OCSP_CERTSTATUS_REVOKED) {
    result = MYPROXY_OCSPRESULT_CERTIFICATE_REVOKED;
    myproxy_log("OCSP status revoked!");
  } else {
    result = MYPROXY_OCSPRESULT_CERTIFICATE_VALID;
    myproxy_log("OCSP status valid");
  }

end:
  if (result < 0 && result != MYPROXY_OCSPRESULT_ERROR_NOTCONFIGURED) {
      ssl_error_to_verror();
      myproxy_log("OCSP check failed");
      myproxy_log_verror();
  }
  if (bio) BIO_free_all(bio);
  if (host) OPENSSL_free(host);
  if (port) OPENSSL_free(port);
  if (path) OPENSSL_free(path);
  if (req) OCSP_REQUEST_free(req);
  if (resp) OCSP_RESPONSE_free(resp);
  if (basic) OCSP_BASICRESP_free(basic);
  if (ctx) SSL_CTX_free(ctx);   /* this does X509_STORE_free(store) */
  if (certdir) free(certdir);
  if (aiaocspurl) free(aiaocspurl);

  return result;
}
예제 #7
0
bool NetlibDoConnect(NetlibConnection *nlc)
{
	NETLIBOPENCONNECTION *nloc = &nlc->nloc;
	NetlibUser *nlu = nlc->nlu;

	nlc->sinProxy.sin_family = AF_INET;
	mir_free(nlc->szProxyServer); nlc->szProxyServer = NULL;

	bool usingProxy = false, forceHttps = false;
	if (nlu->settings.useProxy)
	{
		if (nlu->settings.proxyType == PROXYTYPE_IE)
		{
			usingProxy = NetlibGetIeProxyConn(nlc, false);
		}
		else
		{
			if (nlu->settings.szProxyServer && nlu->settings.szProxyServer[0])
			{
				nlc->szProxyServer = mir_strdup(nlu->settings.szProxyServer);
				nlc->wProxyPort = nlu->settings.wProxyPort;
				nlc->proxyType = nlu->settings.proxyType;
				usingProxy = true;
			}
		}
	}

retry:
	if (usingProxy) 
	{
		NetlibLogf(nlu,"(%p) Resolving proxy %s:%d for %s:%d ....", nlc, nlc->szProxyServer, nlc->wProxyPort, nloc->szHost, nloc->wPort);
		nlc->sinProxy.sin_port = htons(nlc->wProxyPort);
		nlc->sinProxy.sin_addr.S_un.S_addr = DnsLookup(nlu, nlc->szProxyServer);
		if (nlc->sinProxy.sin_addr.S_un.S_addr == 0) 
		{
			usingProxy = false;
			nlc->proxyType = 0;
		}
	}
	if (!usingProxy)
	{
		NetlibLogf(nlu,"(%p) Connecting to server %s:%d....", nlc, nloc->szHost, nloc->wPort);
		nlc->sinProxy.sin_port = htons(nloc->wPort);
		nlc->sinProxy.sin_addr.S_un.S_addr = DnsLookup(nlu, nloc->szHost);
	}
	else
		NetlibLogf(nlu,"(%p) Connecting to proxy %s:%d for %s:%d ....", nlc, nlc->szProxyServer, nlc->wProxyPort, nloc->szHost, nloc->wPort);

	if (nlc->sinProxy.sin_addr.S_un.S_addr == 0) return false;

	if (my_connect(nlc, nloc) == SOCKET_ERROR) 
	{
		if (usingProxy && (nlc->proxyType == PROXYTYPE_HTTPS || nlc->proxyType == PROXYTYPE_HTTP))
		{
			usingProxy = false;
			if (!NetlibHttpFallbackToDirect(nlc, nlu, nloc))
			{
				NetlibLogf(nlu, "%s %d: %s() failed (%u)", __FILE__, __LINE__, "connect", WSAGetLastError());
				return false;
			}
		}
		else
		{
			if (nlu->settings.useProxy && !usingProxy && nlu->settings.proxyType == PROXYTYPE_IE && !forceHttps)
			{
				forceHttps = true;
				usingProxy = NetlibGetIeProxyConn(nlc, true);
				if (usingProxy) goto retry;
			}
			NetlibLogf(nlu, "%s %d: %s() failed (%u)", __FILE__, __LINE__, "connect", WSAGetLastError());
			return false;
		}
	}

	if (usingProxy && !((nloc->flags & (NLOCF_HTTP | NLOCF_SSL)) == NLOCF_HTTP && 
		(nlc->proxyType == PROXYTYPE_HTTP || nlc->proxyType == PROXYTYPE_HTTPS)))
	{
		if (!WaitUntilWritable(nlc->s, 30000)) return false;

		switch (nlc->proxyType) 
		{
		case PROXYTYPE_SOCKS4:
			if (!NetlibInitSocks4Connection(nlc, nlu, nloc)) return false;
			break;

		case PROXYTYPE_SOCKS5:
			if (!NetlibInitSocks5Connection(nlc, nlu, nloc)) return false;
			break;

		case PROXYTYPE_HTTPS:
			nlc->proxyAuthNeeded = true;
			if (!NetlibInitHttpsConnection(nlc, nlu, nloc))
			{
				usingProxy = false;
				if (!NetlibHttpFallbackToDirect(nlc, nlu, nloc))
					return false;
			}
			break;

		case PROXYTYPE_HTTP:
			nlc->proxyAuthNeeded = true;
			if (!(nlu->user.flags & NUF_HTTPGATEWAY || nloc->flags & NLOCF_HTTPGATEWAY) || nloc->flags & NLOCF_SSL)
			{
				//NLOCF_HTTP not specified and no HTTP gateway available: try HTTPS
				if (!NetlibInitHttpsConnection(nlc, nlu, nloc))
				{
					//can't do HTTPS: try direct
					usingProxy = false;
					if (!NetlibHttpFallbackToDirect(nlc, nlu, nloc))
						return false;
				}
			}
			else 
			{
				if (!NetlibInitHttpConnection(nlc, nlu, nloc)) return false;
			}
			break;

		default:
			SetLastError(ERROR_INVALID_PARAMETER);
			FreePartiallyInitedConnection(nlc);
			return false;
		}
	}
	else if (nloc->flags & NLOCF_HTTPGATEWAY)
	{
		if (!NetlibInitHttpConnection(nlc, nlu, nloc)) return false;
		nlc->usingDirectHttpGateway = true;
	}

	NetlibLogf(nlu,"(%d) Connected to %s:%d", nlc->s, nloc->szHost, nloc->wPort);

	if (NLOCF_SSL & nloc->flags)
	{
		return NetlibStartSsl((WPARAM)nlc, 0) != 0;
	}

	return true;
}
예제 #8
0
bool NetlibDoConnect(NetlibConnection *nlc)
{
	NETLIBOPENCONNECTION *nloc = &nlc->nloc;
	NetlibUser *nlu = nlc->nlu;

	mir_free(nlc->szProxyServer); nlc->szProxyServer = NULL;

	bool usingProxy = false, forceHttps = false;
	if (nlu->settings.useProxy) {
		if (nlu->settings.proxyType == PROXYTYPE_IE)
			usingProxy = NetlibGetIeProxyConn(nlc, false);
		else {
			if (nlu->settings.szProxyServer && nlu->settings.szProxyServer[0]) {
				nlc->szProxyServer = mir_strdup(nlu->settings.szProxyServer);
				nlc->wProxyPort = nlu->settings.wProxyPort;
				nlc->proxyType = nlu->settings.proxyType;
				usingProxy = true;
			}
		}
	}

	while (!my_connect(nlc, nloc)) {
		// Fallback to direct only when using HTTP proxy, as this is what used by companies
		// If other type of proxy used it's an indication of security nutcase, leave him alone
		if (usingProxy && (nlc->proxyType == PROXYTYPE_HTTPS || nlc->proxyType == PROXYTYPE_HTTP)) {
			usingProxy = false;
			nlc->proxyType = 0;
			NetlibLogf(nlu,"Fallback to direct connection");
			continue;
		}
		if (nlu->settings.useProxy && !usingProxy && nlu->settings.proxyType == PROXYTYPE_IE && !forceHttps) {
			forceHttps = true;
			usingProxy = NetlibGetIeProxyConn(nlc, true);
			if (usingProxy) continue;
		}
		NetlibLogf(nlu, "%s %d: %s() failed (%u)", __FILE__, __LINE__, "connect", WSAGetLastError());
		return false;
	}

	if (usingProxy && !((nloc->flags & (NLOCF_HTTP | NLOCF_SSL)) == NLOCF_HTTP && (nlc->proxyType == PROXYTYPE_HTTP || nlc->proxyType == PROXYTYPE_HTTPS))) {
		if (!WaitUntilWritable(nlc->s, 30000))
			return false;

		switch (nlc->proxyType) {
		case PROXYTYPE_SOCKS4:
			if (!NetlibInitSocks4Connection(nlc, nlu, nloc))
				return false;
			break;

		case PROXYTYPE_SOCKS5:
			if (!NetlibInitSocks5Connection(nlc, nlu, nloc))
				return false;
			break;

		case PROXYTYPE_HTTPS:
			nlc->proxyAuthNeeded = true;
			if (!NetlibInitHttpsConnection(nlc, nlu, nloc)) {
				usingProxy = false;
				if (!NetlibHttpFallbackToDirect(nlc, nlu, nloc))
					return false;
			}
			break;

		case PROXYTYPE_HTTP:
			nlc->proxyAuthNeeded = true;
			if (!(nlu->user.flags & NUF_HTTPGATEWAY || nloc->flags & NLOCF_HTTPGATEWAY) || nloc->flags & NLOCF_SSL) {
				//NLOCF_HTTP not specified and no HTTP gateway available: try HTTPS
				if (!NetlibInitHttpsConnection(nlc, nlu, nloc)) {
					//can't do HTTPS: try direct
					usingProxy = false;
					if (!NetlibHttpFallbackToDirect(nlc, nlu, nloc))
						return false;
				}
			}
			else if (!NetlibInitHttpConnection(nlc, nlu, nloc))
				return false;

			break;

		default:
			SetLastError(ERROR_INVALID_PARAMETER);
			FreePartiallyInitedConnection(nlc);
			return false;
		}
	}
	else if (nloc->flags & NLOCF_HTTPGATEWAY) {
		if (!NetlibInitHttpConnection(nlc, nlu, nloc)) return false;
		nlc->usingDirectHttpGateway = true;
	}

	NetlibLogf(nlu, "(%d) Connected to %s:%d", nlc->s, nloc->szHost, nloc->wPort);

	if (NLOCF_SSL & nloc->flags)
		return NetlibStartSsl((WPARAM)nlc, 0) != 0;

	return true;
}
예제 #9
0
파일: check_nrpe.c 프로젝트: abrist/nrpe
int main(int argc, char **argv){
        u_int32_t packet_crc32;
        u_int32_t calculated_crc32;
	int16_t result;
	int rc;
	packet send_packet;
	packet receive_packet;
	int bytes_to_send;
	int bytes_to_recv;

	result=process_arguments(argc,argv);

        if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE){

		if(result!=OK)
			printf("Incorrect command line arguments supplied\n");
                printf("\n");
		printf("NRPE Plugin for Nagios\n");
		printf("Copyright (c) 1999-2008 Ethan Galstad ([email protected])\n");
		printf("Version: %s\n",PROGRAM_VERSION);
		printf("Last Modified: %s\n",MODIFICATION_DATE);
		printf("License: GPL v2 with exemptions (-l for more info)\n");
#ifdef HAVE_SSL
		printf("SSL/TLS Available: Anonymous DH Mode, OpenSSL 0.9.6 or higher required\n");
#endif
		printf("\n");
	        }

	if(result!=OK || show_help==TRUE){

		printf("Usage: check_nrpe -H <host> [ -b <bindaddr> ] [-4] [-6] [-n] [-u] [-p <port>] [-t <timeout>] [-c <command>] [-a <arglist...>]\n");
		printf("\n");
		printf("Options:\n");
		printf(" -n         = Do no use SSL\n");
		printf(" -u         = Make socket timeouts return an UNKNOWN state instead of CRITICAL\n");
		printf(" <host>     = The address of the host running the NRPE daemon\n");
		printf(" <bindaddr> = bind to local address\n");
		printf(" -4         = user ipv4 only\n");
		printf(" -6         = user ipv6 only\n");
		printf(" [port]     = The port on which the daemon is running (default=%d)\n",DEFAULT_SERVER_PORT);
		printf(" [timeout]  = Number of seconds before connection times out (default=%d)\n",DEFAULT_SOCKET_TIMEOUT);
		printf(" [command]  = The name of the command that the remote daemon should run\n");
		printf(" [arglist]  = Optional arguments that should be passed to the command.  Multiple\n");
		printf("              arguments should be separated by a space.  If provided, this must be\n");
		printf("              the last option supplied on the command line.\n");
		printf("\n");
		printf("Note:\n");
		printf("This plugin requires that you have the NRPE daemon running on the remote host.\n");
		printf("You must also have configured the daemon to associate a specific plugin command\n");
		printf("with the [command] option you are specifying here.  Upon receipt of the\n");
		printf("[command] argument, the NRPE daemon will run the appropriate plugin command and\n");
		printf("send the plugin output and return code back to *this* plugin.  This allows you\n");
		printf("to execute plugins on remote hosts and 'fake' the results to make Nagios think\n");
		printf("the plugin is being run locally.\n");
		printf("\n");
	        }

	if(show_license==TRUE)
		display_license();

        if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE)
		exit(STATE_UNKNOWN);


        /* generate the CRC 32 table */
        generate_crc32_table();

#ifdef HAVE_SSL
	/* initialize SSL */
	if(use_ssl==TRUE){
		SSL_library_init();
		SSLeay_add_ssl_algorithms();
		meth=SSLv23_client_method();
		SSL_load_error_strings();
		if((ctx=SSL_CTX_new(meth))==NULL){
			printf("CHECK_NRPE: Error - could not create SSL context.\n");
			exit(STATE_CRITICAL);
		        }

		/* ADDED 01/19/2004 */
		/* use only TLSv1 protocol */
		SSL_CTX_set_options(ctx,SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
                }
#endif

	/* initialize alarm signal handling */
	signal(SIGALRM,alarm_handler);

	/* set socket timeout */
	alarm(socket_timeout);

	/* try to connect to the host at the given port number */
	if((sd=my_connect(server_name, &hostaddr, server_port, address_family, 
			bind_address)) < 0 ) {
		exit (255);
		}
	else {
		result=STATE_OK;
	}

#ifdef HAVE_SSL
	/* do SSL handshake */
	if(result==STATE_OK && use_ssl==TRUE){
		if((ssl=SSL_new(ctx))!=NULL){
			SSL_CTX_set_cipher_list(ctx,"ADH");
			SSL_set_fd(ssl,sd);
			if((rc=SSL_connect(ssl))!=1){
				printf("CHECK_NRPE: Error - Could not complete SSL handshake.\n");
#ifdef DEBUG
				printf("SSL_connect=%d\n",rc);
				/*
				rc=SSL_get_error(ssl,rc);
				printf("SSL_get_error=%d\n",rc);
				printf("ERR_get_error=%lu\n",ERR_get_error());
				printf("%s\n",ERR_error_string(rc,NULL));
				*/
				ERR_print_errors_fp(stdout);
#endif
				result=STATE_CRITICAL;
			        }
		        }
		else{
			printf("CHECK_NRPE: Error - Could not create SSL connection structure.\n");
			result=STATE_CRITICAL;
		        }

		/* bail if we had errors */
		if(result!=STATE_OK){
			SSL_CTX_free(ctx);
			close(sd);
			exit(result);
		        }
	        }
#endif

	/* we're connected and ready to go */
	if(result==STATE_OK){

		/* clear the packet buffer */
		bzero(&send_packet,sizeof(send_packet));

		/* fill the packet with semi-random data */
		randomize_buffer((char *)&send_packet,sizeof(send_packet));

		/* initialize packet data */
		send_packet.packet_version=(int16_t)htons(NRPE_PACKET_VERSION_2);
		send_packet.packet_type=(int16_t)htons(QUERY_PACKET);
		strncpy(&send_packet.buffer[0],query,MAX_PACKETBUFFER_LENGTH);
		send_packet.buffer[MAX_PACKETBUFFER_LENGTH-1]='\x0';

		/* calculate the crc 32 value of the packet */
		send_packet.crc32_value=(u_int32_t)0L;
		calculated_crc32=calculate_crc32((char *)&send_packet,sizeof(send_packet));
		send_packet.crc32_value=(u_int32_t)htonl(calculated_crc32);


		/***** ENCRYPT REQUEST *****/


		/* send the packet */
		bytes_to_send=sizeof(send_packet);
		if(use_ssl==FALSE)
			rc=sendall(sd,(char *)&send_packet,&bytes_to_send);
#ifdef HAVE_SSL
		else{
			rc=SSL_write(ssl,&send_packet,bytes_to_send);
			if(rc<0)
				rc=-1;
		        }
#endif
		if(rc==-1){
			printf("CHECK_NRPE: Error sending query to host.\n");
			close(sd);
			return STATE_UNKNOWN;
		        }

		/* wait for the response packet */
		bytes_to_recv=sizeof(receive_packet);
		if(use_ssl==FALSE)
			rc=recvall(sd,(char *)&receive_packet,&bytes_to_recv,socket_timeout);
#ifdef HAVE_SSL
		else
			rc=SSL_read(ssl,&receive_packet,bytes_to_recv);
#endif

		/* reset timeout */
		alarm(0);

		/* close the connection */
#ifdef HAVE_SSL
		if(use_ssl==TRUE){
			SSL_shutdown(ssl);
			SSL_free(ssl);
			SSL_CTX_free(ctx);
	                }
#endif
		graceful_close(sd,1000);

		/* recv() error */
		if(rc<0){
			printf("CHECK_NRPE: Error receiving data from daemon.\n");
			return STATE_UNKNOWN;
		        }

		/* server disconnected */
		else if(rc==0){
			printf("CHECK_NRPE: Received 0 bytes from daemon.  Check the remote server logs for error messages.\n");
			return STATE_UNKNOWN;
		        }

		/* receive underflow */
		else if(bytes_to_recv<sizeof(receive_packet)){
			printf("CHECK_NRPE: Receive underflow - only %d bytes received (%d expected).\n",bytes_to_recv,sizeof(receive_packet));
			return STATE_UNKNOWN;
		        }

		
		/***** DECRYPT RESPONSE *****/


		/* check the crc 32 value */
		packet_crc32=ntohl(receive_packet.crc32_value);
		receive_packet.crc32_value=0L;
		calculated_crc32=calculate_crc32((char *)&receive_packet,sizeof(receive_packet));
		if(packet_crc32!=calculated_crc32){
			printf("CHECK_NRPE: Response packet had invalid CRC32.\n");
			close(sd);
			return STATE_UNKNOWN;
                        }
	
		/* check packet version */
		if(ntohs(receive_packet.packet_version)!=NRPE_PACKET_VERSION_2){
			printf("CHECK_NRPE: Invalid packet version received from server.\n");
			close(sd);
			return STATE_UNKNOWN;
			}

		/* check packet type */
		if(ntohs(receive_packet.packet_type)!=RESPONSE_PACKET){
			printf("CHECK_NRPE: Invalid packet type received from server.\n");
			close(sd);
			return STATE_UNKNOWN;
			}

		/* get the return code from the remote plugin */
		result=(int16_t)ntohs(receive_packet.result_code);

		/* print the output returned by the daemon */
		receive_packet.buffer[MAX_PACKETBUFFER_LENGTH-1]='\x0';
		if(!strcmp(receive_packet.buffer,""))
			printf("CHECK_NRPE: No output returned from daemon.\n");
		else
			printf("%s\n",receive_packet.buffer);
	        }

	/* reset the alarm */
	else
		alarm(0);

	return result;
        }
예제 #10
0
파일: websearch.c 프로젝트: dburger/archive
/*=============================================================================
Function url_content_ok

Purpose: determines if the content at the given URL is ok for processing, that
         is it is text/plain or text/html with no content encoding
          
Parameters:
    *sad (IN) - prepared sockaddr structure
    *url (IN) - the URL we are checking
    *host (IN) - the host we are connecting to
    port (IN) - the port we are connecting to
    *fullpath (IN) - the path to the resource we are requesting from host
        
Returns: 1 if ok to process, 0 otherwise
=============================================================================*/
int url_content_ok(struct sockaddr *sad, char *url, char *host, int port,
                   char *fullpath) {
  int sd, content_ok, done, new_bytes, num_bytes, line, start, end;
  char head_request[MAX_URL + strlen("HEAD  HTTP/1.0\r\n\r\n")];
  char buf[MAX_BUF+1]; /* +1 to let us read MAX_BUF and still null terminate */

  if ((sd=socket(PF_INET, SOCK_STREAM, 0))==-1) {
    printf("unable to create socket\n");
    exit(1);
  }

  if (my_connect(sd,sad,sizeof(*sad),connect_timeout)<0) {
    close(sd);
    if (errno==EINTR)
      printf("connect to %s timed out\n",host);
    else
      printf("unable to connect to %s\n",host);
    return 0;
  }

  sprintf(head_request,"HEAD %s HTTP/1.0\r\n\r\n",fullpath);

#ifdef DEBUG
  printf("  sending request: %s",head_request);
#endif

  if (send_all(sd,head_request,strlen(head_request))<strlen(head_request)) {
    printf("could not send entire HEAD request\n");
    close(sd);
    return 0;
  }

  done = num_bytes = 0;

  /* try to get a buffer of data, we assume HEAD will fit in MAX_BUF bytes */
  do {
    new_bytes = recv(sd,buf+num_bytes,MAX_BUF-num_bytes,0);
    if (new_bytes>0)
      num_bytes+=new_bytes;
    else if (new_bytes==0)
      done = 1;
    else if (new_bytes==-1) {
      printf("problem encountered on recv call\n");
      done = 1;
    }
  } while (num_bytes<MAX_BUF && !done);

  buf[num_bytes] = 0; /* null terminate what was read */
  content_ok = line = start = 0;

  /* process the HEAD buffer */
  while ((end = strcspn(buf+start,"\n"))+start!=num_bytes) {
    buf[start+end] = 0; /* null terminate */
    if (line==0) {
      if (strcasestr(buf+start,"200") == NULL) {
        printf("URL rejected(%s): %s\n",url,buf+start);
        content_ok = 0;
        break;
      }
    } else {
      if (strcasestr(buf+start,"Content-Type:")) {
        if (strcasestr(buf+start,"Content-Type: text/html") ||
            strcasestr(buf+start,"Content-Type: text/plain"))
          content_ok = 1;
        else {
          printf("URL rejected(%s): %s\n",url,buf+start);
          content_ok = 0;
          break;
        }
      }
      if (strcasestr(buf+start,"Content-Encoding:")) {
        printf("URL rejected(%s): %s\n",url,buf+start);
        content_ok = 0;
        break;
      }
    }
    /* some, like www.yahoo.com, send more than HEAD ??? so we break */
    if (strcmp(buf+start,"\r")==0) break;
    start+=end+1; /* position for next search */
    line++;
  }

  close(sd);

  return content_ok;
}
예제 #11
0
파일: websearch.c 프로젝트: dburger/archive
/*=============================================================================
Function process_page

Purpose: to search the given page for matches as specified in the command line
         parameters.
          
Parameters:
    *sad (IN) - prepared sockaddr structure
    *host (IN) - the host we are connecting to
    port (IN) - the port we are connecting to
    *fullpath (IN) - the path to the resource we are requesting from host
    *url - URL for page
    *server_context - server part of URL for relative hyperlinks
    *full_context - server and path part of URL for relative hyperlinks
    depth - search depth of page

Returns: nothing, processes the page giving proper reports and adding links
         to the pages to be spidered if under specified depth
=============================================================================*/
void process_page(struct sockaddr *sad, char *host, char *fullpath, char *url,
                  char *server_context, char *full_context, int depth) {
  int sd, done, line, new_bytes, num_bytes, line_match, page_match, start, end;
  char get_request[MAX_URL + strlen("GET  HTTP/1.0\r\n\r\n")];
  char buf[MAX_BUF+1]; /* +1 to let us read MAX_BUF and still null terminate */

  if ((sd=socket(PF_INET, SOCK_STREAM, 0))==-1) {
    printf("unable to create socket\n");
    exit(1);
  }

  if (my_connect(sd,sad,sizeof(*sad),connect_timeout)<0) {
    close(sd);
    if (errno==EINTR)
      printf("connect to %s timed out\n",host);
    else
      printf("unable to connect to %s\n",host);
    return;
  }

  sprintf(get_request,"GET %s HTTP/1.0\r\n\r\n",fullpath);

#ifdef DEBUG
  printf("  sending request: %s",get_request);
#endif

  if (send_all(sd,get_request,strlen(get_request))<strlen(get_request)) {
    printf("problem sending GET request\n");
    close(sd);
    return;
  }

  done = line = num_bytes = page_match = 0;

  while(!done) {

    /* try to get a full buffer of data */
    do {
      new_bytes = recv(sd,buf+num_bytes,MAX_BUF-num_bytes,0);
      if (new_bytes>0)
        num_bytes+=new_bytes;
      else if (new_bytes==0)
        done = 1;
      else if (new_bytes==-1) {
        printf("problem encountered on recv call\n");
        done = 1;
      }
    } while (num_bytes<MAX_BUF && !done);

    buf[num_bytes] = 0; /* terminate for string processing */
    line = start = 0;

    /* process the buffer of data */
    while ((end = strcspn(buf+start,"\n"))+start!=num_bytes) {
      buf[start+end] = 0; /* null terminate */
      if (case_independent)
        line_match = strcasestr(buf+start,pattern) != NULL;
      else
        line_match = strstr(buf+start,pattern) != NULL;
      if (line_match) page_match = 1;
      if (depth < search_depth)
        process_hrefs(buf+start, server_context, full_context, depth);
      line_report(url,line++,buf+start,line_match);
      start+=end+1; /* position for next search */
    }
    /* calculate bytes left over in buf without /n */
    num_bytes -= start;
    if (done) {
      /* process the last line, in MOST cases this is </html> */
      if (case_independent)
        line_match = strcasestr(buf+start,pattern) != NULL;
      else
        line_match = strstr(buf+start,pattern) != NULL;
      if (line_match) page_match = 1;
      if (depth < search_depth)
        process_hrefs(buf+start, server_context, full_context, depth);
      line_report(url,line++,buf+start,line_match);
    } else if (num_bytes==MAX_BUF) {
      /* full buffer with no \n */
      num_bytes = 0; /* allow full buffer read on next pass */
      line--; /* adjust line counter back to proper line */
    } else if (num_bytes) {
      /* bytes left in buffer with no \n, reposition */
      memmove(buf,buf+start,num_bytes);
    } else {
      /* last byte read was \n */
      num_bytes = 0;
    }

  }

  close(sd);
  url_report(url, page_match);
}
예제 #12
0
void echotester (int sock)
{
	setcntl(sock, F_SETFL, O_NONBLOCK, "O_NONBLOCK");
	
	long long sent = 0, recvd = 0, recvdnow = 0;
	int ptrsend = 0;
	int ptrrecv = 0;
	struct pollfd pollfd = { .fd = sock, .events = POLLIN | POLLOUT, };
	struct timeval tb, ti, te;
	
	gettimeofday(&tb, NULL);
	ti = tb;
	
	while (1)
	{
		int ret = poll(&pollfd, 1, 1000 /*ms*/);
		
		if (ret == -1)
		{
			perror("poll");
			exit(1);
		}

		if (pollfd.revents & POLLIN)
		{
			ssize_t ret = read(sock, bufin, BUFLEN);
			if (ret == -1)
			{
				perror("read");
				exit(1);
			}
			size_t pr = 0;
			while (ret)
			{
				ssize_t size = ret;
				if (size > BUFLEN - ptrrecv)
					size = BUFLEN - ptrrecv;
				if (memcmp(bufin + pr, bufout + ptrrecv, size) != 0)
				{
					fprintf(stderr, "\ndata differ (sent=%Li revcd=%Li ptrsend=%i ptrrecv=%i ret=%i size=%i)\n", sent, recvd, ptrsend, ptrrecv, (int)ret, (int)size);
					
					int i = 0;
					for (i = 0; i < size; i++)
						if (bufin[i + pr] != bufout[i + ptrrecv])
						{
							printf("offset-diff @%Li @0x%Lx\n", i + recvd, i + recvd);
							break;
						}
					int j = i > 16? i - 16: 0;
					int k = i + 16 < size? i + 16: size - 1;
					while (j++ < k)
						printf("@%Lx:R%02x/S%02x ", j + recvd, bufin[j + pr], bufout[j + ptrrecv]);
					printf("\n");
					
					exit(1);
				}
				recvd += size;
				recvdnow += size;
				ptrrecv = (ptrrecv + size) & (BUFLEN - 1);
				ret -= size;
				pr += size;
			}
		}
		
		if (pollfd.revents & POLLOUT)
		{
			ssize_t size = BUFLEN - ptrsend;
			ssize_t ret = write(sock, bufout + ptrsend, size);
			if (ret == -1)
			{
				perror("write");
				exit(1);
			}
			sent += ret;
			ptrsend = (ptrsend + ret) & (BUFLEN - 1);
		}
		
		gettimeofday(&te, NULL);
		if (te.tv_sec - ti.tv_sec > 1)
		{
			printbw(te.tv_sec - tb.tv_sec, te.tv_usec - tb.tv_usec, recvd, "avg:");
			printbw(te.tv_sec - ti.tv_sec, te.tv_usec - ti.tv_usec, recvdnow, "now:");
			printsz(recvd, "size:");
			printf("-----\r"); fflush(stdout);
			ti = te;
			recvdnow = 0;
		}
	}

	my_close(sock);
}

void echoserver (int sock)
{
	setcntl(sock, F_SETFL, O_NONBLOCK, "O_NONBLOCK");
	
	int ptrsend = 0;
	int ptrrecv = 0;
	size_t inbuf = 0;
	struct pollfd pollfd = { .fd = sock, .events = POLLIN | POLLOUT, };
	
	while (1)
	{
		pollfd.events =  0;
		if (inbuf < BUFLEN) pollfd.events |= POLLIN;
		if (inbuf) pollfd.events |= POLLOUT;
		int ret = poll(&pollfd, 1, 1000 /*ms*/);
		
		if (ret == -1)
		{
			perror("poll");
			exit(1);
		}

		if (pollfd.revents & POLLIN)
		{
			ssize_t maxrecv = BUFLEN - inbuf;
			if (maxrecv > BUFLEN - ptrrecv)
				maxrecv = BUFLEN - ptrrecv;
			ssize_t ret = read(sock, bufin + ptrrecv, maxrecv);
			if (ret == -1)
			{
				perror("read");
				exit(1);
			}
			inbuf += ret;
			ptrrecv = (ptrrecv + ret) & (BUFLEN - 1);
		}
		
		if (pollfd.revents & POLLOUT)
		{
			ssize_t maxsend = inbuf;
			if (maxsend > BUFLEN - ptrsend)
				maxsend = BUFLEN - ptrsend;
			ssize_t ret = write(sock, bufin + ptrsend, maxsend);
			if (ret == -1)
			{
				perror("write");
				exit(1);
			}
			inbuf -= ret;
			ptrsend = (ptrsend + ret) & (BUFLEN - 1);
		}
	}

	my_close(sock);
}

int main (int argc, char* argv[])
{
	int op;
	const char* host = "localhost";
	int port = 10102;
	int server = 0;
	int i;
	//int nodelay = 0;
	
	while ((op = getopt(argc, argv, "hp:d:fs")) != EOF) switch(op)
	{
		case 'h':
			help();
			return 0;

		case 'p':
			port = atoi(optarg);			
			break;
			
		case 'd':
			host = optarg;
			break;
		
//		case 'f':
//			nodelay = 1;
//			break;

		case 's':
			server = 1;
			break;
		
		default:
			printf("option '%c' not recognized\n", op);
			help();
			return 1;
	}
	
	for (i = 0; i < BUFLEN; i++)
	{
	#if 1
		bufout[i] = random() >> 23;
	#else
		char c = i & 0x0f;
		c += c > 9? 'a' - 10: '0';
		bufout[i] = c;
	#endif
	}

	int sock = my_socket();
	if (server)
	{
		printf("waiting on port %i\n", port);
		my_bind_listen(sock, port);
		int clisock = my_accept(sock);
		echoserver(clisock);
		close(sock);
	}
	else
	{
		printf("remote host:	%s\n"
		       "port:		%i\n",
		       host, port);
	
		my_connect(host, port, sock);
		echotester(sock);
	}
	
	return 0;
}
예제 #13
0
ftpbuf_t*
ftp_open(const char *host, short port)
{
	int			fd = -1;
	ftpbuf_t		*ftp;
	struct sockaddr_in	addr;
	struct hostent		*he;
	int			size;


	/* set up the address */
	if ((he = gethostbyname(host)) == NULL) {
#if 0
		herror("gethostbyname");
#endif
		return NULL;
	}

	memset(&addr, 0, sizeof(addr));
	memcpy(&addr.sin_addr, he->h_addr, he->h_length);
	addr.sin_family = AF_INET;
	addr.sin_port = port ? port : htons(21);


	/* alloc the ftp structure */
	ftp = calloc(1, sizeof(*ftp));
	if (ftp == NULL) {
		perror("calloc");
		return NULL;
	}

	/* connect */
	if ((fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket");
		goto bail;
	}

	if (my_connect(fd, (struct sockaddr*) &addr, sizeof(addr)) == -1) {
		perror("connect");
		goto bail;
	}

	size = sizeof(addr);
	if (getsockname(fd, (struct sockaddr*) &addr, &size) == -1) {
		perror("getsockname");
		goto bail;
	}

	ftp->localaddr = addr.sin_addr;
	ftp->fd = fd;

	if (!ftp_getresp(ftp) || ftp->resp != 220) {
		goto bail;
	}

	return ftp;

bail:
	if (fd != -1)
		closesocket(fd);
	free(ftp);
	return NULL;
}
예제 #14
0
int main( int argc, char **argv ) {
    SSL_CTX *ctx = NULL;
    SSL *session = NULL;

    char *command = "HEAD / HTTP/1.0\r\n\r\n";
    
    int s;
    int status;

    /* We first need to establish what sort of
     * connection we know how to make. We can use one of
     * SSLv23_client_method(), SSLv2_client_method() and
     * SSLv3_client_method().
     */
    SSL_METHOD *meth = SSLv23_client_method();
    if (meth == NULL) { fprintf( stderr, "no method. :(\n" ); exit(1); }

    /* This enables all ciphers in SSLeay, these include:
     *   DES, RC4, IDEA, RC2, Blowfish,
     *   MD2, SHA, DSA.
     * See crypto/c_all.c
     */
    SSLeay_add_all_algorithms();

    /* Initialize the context. This is shared between SSL sessions
     * and can do FH caching.
     */
    ctx = SSL_CTX_new( meth );
    if ( ctx == NULL ) { fprintf( stderr, "no context. :(\n" ); exit(1); }

    /* Set up a callback for each state change so we can see what's
     * going on */
    SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);

    /* Set it up so tha we will connect to *any* site, regardless
     * of their certificate. */
    SSL_CTX_set_verify( ctx, SSL_VERIFY_NONE, my_dumb_callback );

    /* MACRO. Set's CTX options. Not sure. I think this enables bug
     * support hacks. */
    SSL_CTX_set_options(ctx,SSL_OP_ALL);

    /* Finally, we're all set so we can set up the session holder */
    session = SSL_new( ctx );
    if ( session == NULL ) { fprintf( stderr, "no session. :(\n" ); exit(1);}
    
    /* Make connection s.t. s is the appropriate fd */
    s = my_connect( (argc == 2) ? argv[1] : "bozo.mit.edu" , 443 );

    /* Set up the SSL side of the connection */
    SSL_set_fd( session, s );
    status = SSL_connect( session );
    /* Check the results. */
    switch (SSL_get_error(session,status)) {
    case SSL_ERROR_NONE:
	/* Everything worked :-) */
	break;
    case SSL_ERROR_SSL:
	fprintf( stderr, "ssl handshake failure\n" );
	ERR_print_errors_fp(stderr);
	goto byebye;
	break;

	/* These are for NON-BLOCKING I/O only! */
    case SSL_ERROR_WANT_READ:
    case SSL_ERROR_WANT_WRITE:
	fprintf( stderr, "want read/write. Use blocking?\n" );
	goto byebye;	break;
    case SSL_ERROR_WANT_CONNECT:
	fprintf( stderr, "want connect. sleep a while, try again." );
	goto byebye;    break;
	
    case SSL_ERROR_SYSCALL:
	perror("SSL_connect");
	goto byebye;    break;
    case SSL_ERROR_WANT_X509_LOOKUP:
	/* not used! */
	fprintf( stderr, "shouldn't be getting this.\n" );
	break;
    case SSL_ERROR_ZERO_RETURN:
	fprintf( stderr, "connection closed.\n" );
	goto byebye;
    }
    
    /* Send the request */
    SSL_write( session, command, strlen(command) );
    /* wait a second for processing. */
    sleep(1);

    /* read! :) */
    while (1) {
	char readdata[1024];

	status = SSL_read( session, readdata, 1024 );
	if ( status == 0 ) break;
	if ( status <  0 ) { sleep(1); continue; }
	fwrite( readdata, 1, status, stdout );
    }


byebye:
    /* close everything down */
    SSL_shutdown(session);
    close(s);
    
    SSL_free( session ); session = NULL;
    SSL_CTX_free(ctx);
    return 0;
}