Exemple #1
0
struct sockaddr *resolve_host(const char *name, int hint)
{
	struct addrinfo *ai = NULL, hints;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = hint;

	if (getaddrinfo(name, NULL, &hints, &ai) == 0 && ai != NULL) {
		char *tmp;

		tmp = xmalloc(ai->ai_addrlen);
		memcpy(tmp, ai->ai_addr, ai->ai_addrlen);

		freeaddrinfo(ai);

		return (struct sockaddr*) tmp;
	}

	/* If hints are optional, try again without them. */
	if (hint_optional && hint != 0) {
		struct sockaddr *res;

		res = resolve_host(name, 0);

		if (res != NULL) {
			debug("warning: %s resolved ignoring hints\n", name);
			return res;
		}
	}

	return NULL;
}
void
print_urls(u_long dst, u_short dport, int win)
{
  char *p, host[128], tmp[128];
  u_long ip;
  
  gethostname(host, sizeof(host));
  ip = resolve_host(host);
  strncpy(host, int_ntoa(ip), sizeof(host));

  /* XXX - "MDTM /\r\n" for Netscape, "CWD /\r\n" for MSIE. i suk. */
  win -= (4 + 2 + 2);
  p = malloc(win + 1);
  memset(p, 'a', win);
  p[win] = '\0';

  portnum2str(tmp, sizeof(tmp), dst, dport);
  
  printf("Netscape / Lynx URL to send client at %s:\n"
	 "ftp://%s/%s%%0a%%0dPORT%%20%s\n",
	 int_ntoa(dst), host, p, tmp);
  printf("MSIE / Wget URL to send client at %s:\n"
	 "ftp://%s/a%s%%0a%%0dPORT%%20%s\n",
	 int_ntoa(dst), host, p, tmp);
  
  free(p);
}
//-------------------------------------------------------------------------------------------------------
//	DATE: January 10 2014
//	AUTHOR: RAMZI CHENNAFI
//	
//	FUNCTION: void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
//	RETURNS: Nothing
//	DESCRIPTION:
//			Deals with menu items and handles messages that are sent by the "OK" buttons.
//	NOTES: 
//			OK buttons cause the respective resolution relevant to that button.
//-------------------------------------------------------------------------------------------------------
void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify){
	switch (id)
	{
	case IDM_ABOUT:
		DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hwnd, About);
		break;
	
	case ID_CLEAR:
		SendMessage(GetDlgItem(hwnd, ID_EDIT_BOX), LB_RESETCONTENT, 0, 0);
		break;

	case IDB_OK_IP:
		resolve_IP(hwnd);
		break;

	case IDB_OK_HST:
		resolve_host(hwnd);
		break;

	case IDB_PRT_OK:
		resolve_port(hwnd);
		break;

	case IDB_SRV_OK:
		resolve_service(hwnd);
		break;

	case IDM_EXIT:
		DestroyWindow(hwnd);
		break;
	}
}
Exemple #4
0
DWORD request_resolve_hosts(Remote *remote, Packet *packet)
{
	Packet *response = packet_create_response(packet);
	Tlv hostname = {0};
	int index = 0;
	int iResult;
	u_short ai_family = packet_get_tlv_value_uint(packet, TLV_TYPE_ADDR_TYPE);

	while( packet_enum_tlv( packet, index++, TLV_TYPE_HOST_NAME, &hostname ) == ERROR_SUCCESS )
	{
		struct in_addr addr = {0};
		struct in6_addr addr6 = {0};
		
		iResult = resolve_host((LPCSTR)hostname.buffer, ai_family, &addr, &addr6);

		if (iResult == NO_ERROR)
		{
			if (ai_family == AF_INET)
			{
				packet_add_tlv_raw(response, TLV_TYPE_IP, &addr, sizeof(struct in_addr));
			} else {
				packet_add_tlv_raw(response, TLV_TYPE_IP, &addr6, sizeof(struct in_addr6));
			}
		}
		else
		{
			dprintf("Unable to resolve_host %s error: %x", hostname.buffer, iResult);		
			packet_add_tlv_raw(response, TLV_TYPE_IP, NULL, 0);
		}
		packet_add_tlv_uint(response, TLV_TYPE_ADDR_TYPE, ai_family);
	}

	packet_transmit_response(NO_ERROR, remote, response);
	return ERROR_SUCCESS;
}
Exemple #5
0
static gboolean
initiate_resolving(gpointer data)
{
	PurpleDnsQueryData *query_data;
	PurpleProxyType proxy_type;

	query_data = data;
	query_data->timeout = 0;

	if (resolve_ip(query_data))
		/* resolve_ip calls purple_dnsquery_resolved */
		return FALSE;

	proxy_type = purple_proxy_info_get_type(
		purple_proxy_get_setup(query_data->account));
	if (proxy_type == PURPLE_PROXY_TOR) {
		purple_dnsquery_failed(query_data,
			_("Aborting DNS lookup in Tor Proxy mode."));
		return FALSE;
	}

	if (purple_dnsquery_ui_resolve(query_data))
		/* The UI is handling the resolve; we're done */
		return FALSE;

	resolve_host(query_data);

	return FALSE;
}
static void
parse_request(rb_helper *helper)
{
	int len;
	static char *parv[MAXPARA + 1];
	int parc;
	while((len = rb_helper_read(helper, readBuf, sizeof(readBuf))) > 0)
	{
		parc = rb_string_to_array(readBuf, parv, MAXPARA);
		switch (*parv[0])
		{
		case 'I':
			if(parc != 4)
				abort();
			resolve_ip(parv);
			break;
		case 'H':
			if(parc != 4)
				abort();
			resolve_host(parv);
			break;
		case 'B':
			if(parc != 4)
				abort();
			set_bind(parv);
			break;
		case 'R':
			restart_resolver();
			report_nameservers();
			break;
		default:
			break;
		}
	}
}
Exemple #7
0
/* ====================================================================
 * This function gets called to create a per-directory configuration
 * record. This will be called for the "default" server environment, and for
 * each directory for which the parser finds any of our directives applicable.
 * If a directory doesn't have any of our directives involved (i.e., they
 * aren't in the .htaccess file, or a <Location>, <Directory>, or related
 * block), this routine will *not* be called - the configuration for the
 * closest ancestor is used.
 *
 * The return value is a pointer to the created module-specific structure.
 * ==================================================================== */
static void *wk_create_dir_config(pool *p, char *dirspec)
{
    wkcfg *cfg;
    char **header;

    /*
     * Allocate the space for our record from the pool supplied.
     */
    cfg = (wkcfg *)ap_pcalloc(p, sizeof(wkcfg));
    /*
     * Now fill in the defaults.  If there are any `parent' configuration
     * records, they'll get merged as part of a separate callback.
     */
    cfg->port = 8086;
    cfg->host = "localhost";
    cfg->addr = resolve_host(cfg->host);
    cfg->retryattempts = 10;
    cfg->retrydelay = 1;
    cfg->passheaders = ap_make_array(p, 1, sizeof(char *));
    /*
     * Pass the "If-Modified-Since" HTTP header through.
     * Servlets may inspect this value and, if the object has not changed,
     * return "Status: 304" and no body.
     */
    header = (char **)ap_push_array(cfg->passheaders);
    *header = "If-Modified-Since";
    return (void *)cfg;
}
Exemple #8
0
int resolve_self(int family, void *result, int length)
{
	char name[HOST_NAME_MAX + 1];
	if (gethostname(name, HOST_NAME_MAX) == -1)
		return -1;

	return resolve_host(name, family, result, length);
}
Exemple #9
0
static int udp_set_url(struct sockaddr_in *addr, const char *hostname, int port)
{
    /* set the destination address */
    if (resolve_host(&addr->sin_addr, hostname) < 0)
        return AVERROR(EIO);
    addr->sin_family = AF_INET;
    addr->sin_port = htons(port);

    return sizeof(struct sockaddr_in);
}
int
main(int argc, char *argv[])
{
  int c, sfd, cfd;
  u_long dst;
  u_short dport, win = WINDOW_LEN;
  struct sockaddr_in sin;

  while ((c = getopt(argc, argv, "w:h?")) != -1) {
    switch (c) {
    case 'w':
      if ((win = atoi(optarg)) == 0)
	usage();
      break;
    default:
      usage();
    }
  }
  argc -= optind;
  argv += optind;
  
  if (argc != 2)
    usage();

  if ((dst = resolve_host(argv[0])) == 0)
    usage();
  
  if ((dport = atoi(argv[1])) == 0)
    usage();

  if ((sfd = init_ftpd(FTPD_PORT, win)) == -1) {
    perror("init_ftpd");
    exit(1);
  }
  print_urls(dst, dport, win);
  
  for (;;) {
    c = sizeof(sin);
    if ((cfd = accept(sfd, (struct sockaddr *)&sin, &c)) == -1) {
      perror("accept");
      exit(1);
    }
    printf("connection from %s\n", inet_ntoa(sin.sin_addr));
      
    if (fork() == 0) {
      close(sfd);
      do_ftpd(cfd);
      close(cfd);
      exit(0);
    }
    close(cfd);
  }
  exit(0);
}
Exemple #11
0
int		main(int ac, char **av)
{
	t_env	env;

	if (ac < 3)
		ft_exit("client: invalid arguments\nclient <host> <port>"
				, EXIT_FAILURE);
	parse_arguments(&env, av);
	resolve_host(&env);
	server_connect(&env);
	run(&env);
}
Exemple #12
0
NetworkSocket::NetworkSocket(const std::string& host, const uint16_t& port, const socket::SOCKET_TYPE stype)
	: socket(stype)
	, host(host)
	, port(port)
{
	std::cout << "creating network socket to host " << this->host << std::endl;
	if(0 != resolve_host(this->host, this->addr))
	{
		std::cout << "Error resolving host " << std::endl;
	}
	this->addr.sin_port = htons(this->port);
}
Exemple #13
0
/* ====================================================================
 * Command handler for the WKServer command.
 * Takes 2 arguments, the host and the port of the AppServer to use.
 * ==================================================================== */
static const char *handle_wkserver(cmd_parms *cmd, void *mconfig,
                                        char *word1, char *word2)
{
    wkcfg* cfg;

    cfg = (wkcfg *)mconfig;

    if (word1 != NULL) cfg->host = word1;
    if (word2 != NULL) cfg->port = atoi(word2);
    cfg->addr = resolve_host(cfg->host); /*Should check for an error here */
    if (cfg->addr == 0)
        log_error("Couldn't resolve hostname for WebKit Server", cmd->server);
    return NULL;
}
Exemple #14
0
int client_socket(struct addrinfo *info, int bindport)
{
  int sockfd;
  struct addrinfo *step, *ownaddr;
  char portstr[10] = {0};
  const int on = 1;

  for (step = info; step != NULL; step = step->ai_next)
  {
    /* Create the socket */
    if ((sockfd = socket(step->ai_family, step->ai_socktype, step->ai_protocol)) == -1)
    {
      perror("socket()");
      continue;
    }

    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    if (bindport > 0) {
      sprintf(portstr, "%d", bindport);
      resolve_host(NULL, portstr, SOCK_DGRAM, 0, &ownaddr);
      if (bind(sockfd, ownaddr->ai_addr, ownaddr->ai_addrlen) == -1) {
        fatal_error("bind()");
      } 
      freeaddrinfo(ownaddr);
    }

    /* Connect to the socket */
    if (connect(sockfd, step->ai_addr, step->ai_addrlen) == -1)
    {
      perror("connect()");
      close(sockfd);
      continue;
    }

    /* Connected */
    break;
  }

  if (step == NULL)
  {
    printf("Could not connect to host.\n");
    return -1;
  }

  freeaddrinfo(info);

  return sockfd;
}
Exemple #15
0
/**
 * If no filename is given to av_open_input_file because you want to
 * get the local port first, then you must call this function to set
 * the remote server address.
 *
 * url syntax: udp://host:port[?option=val...]
 * option: 'multicast=1' : enable multicast 
 *         'ttl=n'       : set the ttl value (for multicast only)
 *         'localport=n' : set the local port
 *         'pkt_size=n'  : set max packet size
 *
 * @param s1 media file context
 * @param uri of the remote server
 * @return zero if no error.
 */
int udp_set_remote_url(URLContext *h, const char *uri)
{
    UDPContext *s = h->priv_data;
    char hostname[256];
    int port;
    
    url_split(NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);

    /* set the destination address */
    if (resolve_host(&s->dest_addr.sin_addr, hostname) < 0)
        return AVERROR_IO;
    s->dest_addr.sin_family = AF_INET;
    s->dest_addr.sin_port = htons(port);
    return 0;
}
Exemple #16
0
// dnsResolveEx in JS context; not available in core JavaScript.
// returns javascript null if not able to resolve.
static JSBool                                  // JS_TRUE or JS_FALSE
dns_resolve_ex(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
               jsval *rval)
{
  char* name = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
  char* out;
  char ipaddr[INET6_ADDRSTRLEN * MAX_IP_RESULTS + MAX_IP_RESULTS] = "";

  out = JS_malloc(cx, strlen(ipaddr) + 1);
  // Return "" on failure.
  if(resolve_host(name, ipaddr, MAX_IP_RESULTS, AF_UNSPEC)) {
    strcpy(out, "");
  }
  strcpy(out, ipaddr);
  JSString *str = JS_NewString(cx, out, strlen(out));
  *rval = STRING_TO_JSVAL(str);
  return JS_TRUE;
}
Exemple #17
0
// dnsResolve in JS context; not available in core JavaScript.
// returns javascript null if not able to resolve.
static JSBool                                  // JS_TRUE or JS_FALSE
dns_resolve(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
  char* name = JS_GetStringBytes(JS_ValueToString(cx, argv[0]));
  char* out;
  char ipaddr[INET6_ADDRSTRLEN] = "";

  // Return null on failure.
  if(resolve_host(name, ipaddr, 1, AF_INET)) {
    *rval = JSVAL_NULL;
    return JS_TRUE;
  }

  out = JS_malloc(cx, strlen(ipaddr) + 1);
  strcpy(out, ipaddr);
  JSString *str = JS_NewString(cx, out, strlen(out));
  *rval = STRING_TO_JSVAL(str);
  return JS_TRUE;
}
Exemple #18
0
/**
 * If no filename is given to av_open_input_file because you want to
 * get the local port first, then you must call this function to set
 * the remote server address.
 *
 * url syntax: udp://host:port[?option=val...]
 * option: 'multicast=1' : enable multicast
 *         'ttl=n'       : set the ttl value (for multicast only)
 *         'localport=n' : set the local port
 *         'pkt_size=n'  : set max packet size
 *         'reuse=1'     : enable reusing the socket
 *
 * @param s1 media file context
 * @param uri of the remote server
 * @return zero if no error.
 */
int udp_set_remote_url(URLContext *h, const char *uri)
{
#ifdef CONFIG_IPV6
    return udp_ipv6_set_remote_url(h, uri);
#else
    UDPContext *s = h->priv_data;
    char hostname[256];
    int port;

    url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);

    /* set the destination address */
    if (resolve_host(&s->dest_addr.sin_addr, hostname) < 0)
        return AVERROR(EIO);
    s->dest_addr.sin_family = AF_INET;
    s->dest_addr.sin_port = htons(port);
    return 0;
#endif
}
Exemple #19
0
/**
 * initialize the sockaddr struct
 */
static gint
addr_init(const gchar *hostname, gint port, struct sockaddr *addr)
{
    gchar host_ip[IPADDR_LEN];
    struct sockaddr_in *addr_in = (struct sockaddr_in*)addr;

    memset(host_ip, 0, sizeof(host_ip));
    if (resolve_host(hostname, host_ip) == HYBRID_ERROR) {
        hybrid_debug_error("connect", "connect terminate due to bad hostname");
        return HYBRID_ERROR;
    }

    memset(addr, 0, sizeof(struct sockaddr_in));
    addr_in->sin_family      = AF_INET;
    addr_in->sin_addr.s_addr = inet_addr(host_ip);
    addr_in->sin_port        = htons(port);

    return HYBRID_OK;
}
Exemple #20
0
wxThread::ExitCode turbotrace::Entry()
{
    tlog(_("Thread starting\n"));

    //Resolve the hostname , get the ip address
    if(!resolve_host(host))
    {
        return false;
    }

    wxMutexGuiEnter();
    parent_frame->set_ip( wxString( inet_ntoa(dest_ip) , wxConvUTF8) );
    wxMutexGuiLeave();

    //Call the outer class function start_sniffer
    start_sniffer();

    return (wxThread::ExitCode)0;
}
Exemple #21
0
/*
 * openlog - open remote syslog server or event logging
 */
void openlog(char *ident, int logstat, int logfac){
  /*
   * Open remote syslog server
   */
  if(strlen(ctl.syslog_server) > 0){ 
    /* Connect to Target server. */
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == SOCKET_ERROR){
      warnx("*** Could not create the socket to send the syslog alert. Error Number: %d.\n", WSAGetLastError());	
    } else {

      sin.sin_port = htons((u_short)ctl.syslog_port);
      sin.sin_family = AF_INET;

      if (!(sin.sin_addr.s_addr = resolve_host(ctl.syslog_server))){
	warnx("*** Could not resolve syslog server's hostname. Error Number: %d.\n", WSAGetLastError());		
	closesocket(sockfd);
      } else {
	outp.syslog_open = TRUE;
	return;
      }
    }
    warnx("*** Remote syslog not working, will now fail over to local event log");
    ctl.syslog_server[0] = '\0';		/* Null string to show are logging locally */
  }
  /*
   * Open local event logging
   */
  if (!util_check_version_winNT()) {
    warnx("*** Local event logging requires WinNT or better");
    return;
  }
  if(ident != NULL){
    strlcpy(LogTag, ident, sizeof(LogTag));
    LogStat = logstat;
    if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
      LogFacility = logfac;

    /* Add the registry key each time openlog is called. */
    AddEventSource(LogTag);
  }
  outp.syslog_open = TRUE;
}
Exemple #22
0
std::string
WSnetio::smsg(std::string strHost,int iPort,std::string strMsg)
{
	std::string tmp;
	SOCKET sock = socket(AF_INET,SOCK_STREAM,0);
	struct sockaddr_in sa;
	sa.sin_family = AF_INET;
	sa.sin_port = htons(iPort);
	sa.sin_addr.s_addr = inet_addr( resolve_host(strHost,0).c_str() );

	connect(sock,(struct sockaddr*)&sa,sizeof(sa));
	send(sock,strMsg.c_str(),strMsg.length()+1,0);

	char *buff = new char[1024];
	memset(buff,0,1024);
	recv(sock,buff,1024,0);
	tmp.append(buff);
	delete buff;
	return tmp;
}
Exemple #23
0
// myIpAddressEx in JS context; not available in core JavaScript.
// returns 127.0.0.1 if not able to determine local ip.
static JSBool                                  // JS_TRUE or JS_FALSE
my_ip_ex(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
  char ipaddr[INET6_ADDRSTRLEN * MAX_IP_RESULTS + MAX_IP_RESULTS];
  char* out;

  if (myip)                  // If my (client's) IP address is already set.
    strcpy(ipaddr, myip);
  else {
    char name[256];
    gethostname(name, sizeof(name));
    if (resolve_host(name, ipaddr, MAX_IP_RESULTS, AF_UNSPEC)) {
      strcpy(ipaddr, "");
    }
  }

  out = JS_malloc(cx, strlen(ipaddr) + 1);
  strcpy(out, ipaddr);
  JSString *str = JS_NewString(cx, out, strlen(out));
  *rval = STRING_TO_JSVAL(str);
  return JS_TRUE;
}
Exemple #24
0
DWORD request_resolve_host(Remote *remote, Packet *packet)
{
	Packet *response = packet_create_response(packet);
	LPCSTR hostname = NULL;
	struct in_addr addr;
	struct in6_addr addr6;
	u_short ai_family = AF_INET;
	int iResult;

	hostname = packet_get_tlv_value_string(packet, TLV_TYPE_HOST_NAME);

	if (!hostname)
	{
		iResult = ERROR_INVALID_PARAMETER;
		dprintf("Hostname not set");
	}
	else
	{
		ai_family = packet_get_tlv_value_uint(packet, TLV_TYPE_ADDR_TYPE);
		iResult = resolve_host(hostname, ai_family, &addr, &addr6);
		if (iResult == NO_ERROR)
		{
			if (ai_family == AF_INET)
			{
				packet_add_tlv_raw(response, TLV_TYPE_IP, &addr, sizeof(struct in_addr));
			} else {
				packet_add_tlv_raw(response, TLV_TYPE_IP, &addr6, sizeof(struct in_addr6));
			}
			packet_add_tlv_uint(response, TLV_TYPE_ADDR_TYPE, ai_family);
		}
		else
		{
			dprintf("Unable to resolve_host %s error: %x", hostname, iResult);
		}
	}

	packet_transmit_response(iResult, remote, response);
	return ERROR_SUCCESS;
}
Exemple #25
0
int token_verify(char* request_token,char* mac)
{
    char buf[MAX_BUF];
    char ip[16];
    s_config *config;
    config = config_get_config();
    int res=resolve_host(config->auth_server,ip);
    if(res<0){
        debug(LOG_INFO,"Resolve auth server[%s] error.",config->auth_server);
  	return -1;      
    }
    ip[15]=0;
    char query[128]={0}; 
    snprintf(query,sizeof(query),"?uid=%d&token=%s&mac=%s",config->uid,request_token,mac);
    res = http_get_request(ip,config->auth_port,config->token_verify_path,query,VERSION,buf,MAX_BUF);
    if(res<0){
        debug(LOG_INFO,"verify token[%s]from auth server[%s] error.",request_token,config->auth_server);
        return -1;
    }
    
    int i;
    char* result=strstr(buf,"\r\n\r\n");
    
    if(result==NULL)
    {
        debug(LOG_INFO,"verify token[%s] from auth server[%s] return null.",request_token,config->auth_server);
        return;
    }
    result=result+4;
    debug(LOG_DEBUG,"verify token[%s] result: %s",request_token,result);
    if(strcmp(result,"1")==0)
    {
       return 1;
    }
    else{
       return 0;
    }
}
Exemple #26
0
int start_server() {
    int lsock, csock, pid, clilen, sopt = 1, i, res;
    struct sockaddr_in serv_addr, cli_addr;
    ws_ctx_t *ws_ctx;
    fd_set myset;
    struct timeval tv;


    /* Initialize buffers */
    lsock = socket(AF_INET, SOCK_STREAM, 0);
    if (lsock < 0) { error("ERROR creating listener socket"); }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(settings.listen_port);

    /* Resolve listen address */
    if (settings.listen_host && (settings.listen_host[0] != '\0')) {
        if (resolve_host(&serv_addr.sin_addr, settings.listen_host) < -1) {
            error("Could not resolve listen address");
	    return 1;
        }
    } else {
        serv_addr.sin_addr.s_addr = INADDR_ANY;
    }

    setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, (char *)&sopt, sizeof(sopt));
    if (bind(lsock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
        error("ERROR on binding listener socket");
	return 1;
    }
    int optval = 1;
    if (setsockopt(lsock, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(int)) < 0) {
      error("Cannot set TCP_NODELAY option on listen address");
      return 1;
    }

    listen(lsock,100);

    signal(SIGPIPE, signal_handler);  // catch pipe

    if (settings.daemon) {
      ;
      //        daemonize(lsock);
    }


    // Reep zombies
    signal(SIGCHLD, SIG_IGN);

    printf("Waiting for connections on %s:%d\n",
            settings.listen_host, settings.listen_port);


    while (websockify_loop) {
        clilen = sizeof(cli_addr);
        pipe_error = 0;
        pid = 0;

	//	if (set_non_blocking(lsock) != 0) {
	//	  return;
	//	}
	// Set Accept socket to non blocking to allow to cancel
	// requests

	while (websockify_loop) {
	  tv.tv_sec = 0;
	  tv.tv_usec = 200000;
	  FD_ZERO(&myset);
	  FD_SET(lsock, &myset);
	  res = select(lsock+1, &myset, NULL, NULL, &tv);
	  /* EINTR */
	  if (res < 0 && errno == EINTR) {
	    continue;
	  }
	  if (res < 0) {
	    perror("select");
	    return 1;
	  }
	  if (res > 0) {
	    break;
	  }
	}
	if (!websockify_loop) {
	  fprintf(stderr, "Ending loop before accept\n");
	  return 0;
	}
	csock = accept(lsock, 
		       (struct sockaddr *) &cli_addr, 
		       &clilen);
	
	fprintf(stderr, "After accept\n");
	if (csock < 0) {
	  error("ERROR on accept");
	  continue;
	}
        handler_msg("got client connection from %s\n",
                    inet_ntoa(cli_addr.sin_addr));

	//	if (set_blocking(lsock) != 0) {
	//	  return;
	//	}

        if (!settings.run_once) {
            handler_msg("forking handler process not supported. Abort\n");
	    abort();
	    //            pid = fork();
        }

        if (pid == 0) {  // handler process
            ws_ctx = do_handshake(csock);
            if (settings.run_once) {
                    // Successful connection, stop listening for new
                    // connections
                    close(lsock);
	    }
            if (ws_ctx == NULL) {
                handler_msg("No connection after handshake\n");
                break;   // Child process exits
            }

            settings.handler(ws_ctx);
            if (pipe_error) {
                handler_emsg("Closing due to SIGPIPE\n");
            }
            break;   // Child process exits
        } else {         // parent process
            settings.handler_id += 1;
        }
    }
    if (pid == 0) {
        if (ws_ctx) {
            ws_socket_free(ws_ctx);
            free_ws_ctx(ws_ctx);
        } else {
            shutdown(csock, SHUT_RDWR);
            close(csock);
        }
        handler_msg("handler exit\n");
    } else {
        handler_msg("websockify exit\n");
    }

    return 0;
}
Exemple #27
0
/* return non zero if error */
static int tcp_open(URLContext *h, const char *uri, int flags)
{
    struct sockaddr_in dest_addr;
    int port, fd = -1;
    TCPContext *s = NULL;
    fd_set wfds;
    int fd_max, ret;
    struct timeval tv;
    socklen_t optlen;
    char hostname[1024],proto[1024],path[1024];

    if(!ff_network_init())
        return AVERROR(EIO);

    url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname),
        &port, path, sizeof(path), uri);
    if (strcmp(proto,"tcp") || port <= 0 || port >= 65536)
        return AVERROR(EINVAL);

    dest_addr.sin_family = AF_INET;
    dest_addr.sin_port = htons(port);
    if (resolve_host(&dest_addr.sin_addr, hostname) < 0)
        return AVERROR(EIO);

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
        return AVERROR(EIO);
    ff_socket_nonblock(fd, 1);

 redo:
    ret = connect(fd, (struct sockaddr *)&dest_addr,
                  sizeof(dest_addr));
    if (ret < 0) {
        if (ff_neterrno() == FF_NETERROR(EINTR))
            goto redo;
        if (ff_neterrno() != FF_NETERROR(EINPROGRESS) &&
            ff_neterrno() != FF_NETERROR(EAGAIN))
            goto fail;

        /* wait until we are connected or until abort */
        for(;;) {
            if (url_interrupt_cb()) {
                ret = AVERROR(EINTR);
                goto fail1;
            }
            fd_max = fd;
            FD_ZERO(&wfds);
            FD_SET(fd, &wfds);
            tv.tv_sec = 0;
            tv.tv_usec = 100 * 1000;
            ret = select(fd_max + 1, NULL, &wfds, NULL, &tv);
            if (ret > 0 && FD_ISSET(fd, &wfds))
                break;
        }

        /* test error */
        optlen = sizeof(ret);
        getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen);
        if (ret != 0)
            goto fail;
    }
    s = av_malloc(sizeof(TCPContext));
    if (!s)
        return AVERROR(ENOMEM);
    h->priv_data = s;
    h->is_streamed = 1;
    s->fd = fd;
    return 0;

 fail:
    ret = AVERROR(EIO);
 fail1:
    if (fd >= 0)
        closesocket(fd);
    return ret;
}
Exemple #28
0
int call_getopt(int argc, char **argv){
	int c=0;
	int i=0;

	int option_index = 0;
	static struct option long_options[] =
	{
		{"serverip",       required_argument,0,'s'},
		{"requestedip",    required_argument,0,'r'},
		{"timeout",        required_argument,0,'t'},
		{"interface",      required_argument,0,'i'},
		{"mac",            required_argument,0,'m'},
		{"unicast",        no_argument,      0,'u'},
		{"verbose",        no_argument,      0,'v'},
		{"version",        no_argument,      0,'V'},
		{"help",           no_argument,      0,'h'},
		{0,0,0,0}
	};

	while(1){
		c=getopt_long(argc,argv,"+hVvt:s:r:t:i:m:u",long_options,&option_index);

		i++;

		if(c==-1||c==EOF||c==1)
			break;

		switch(c){
		case 'w':
		case 'r':
		case 't':
		case 'i':
			i++;
			break;
		default:
			break;
		        }

		switch(c){

		case 's': /* DHCP server address */
			resolve_host(optarg,&dhcp_ip);
			add_requested_server(dhcp_ip);
			break;

		case 'r': /* address we are requested from DHCP servers */
			resolve_host(optarg,&requested_address);
			request_specific_address=TRUE;
			break;

		case 't': /* timeout */

			/*
			if(is_intnonneg(optarg))
			*/
			if(atoi(optarg)>0)
				dhcpoffer_timeout=atoi(optarg);
			/*
			else
				usage("Time interval must be a nonnegative integer\n");
			*/
			break;

		case 'm': /* MAC address */

			if((user_specified_mac=mac_aton(optarg)) == NULL)
				usage("Cannot parse MAC address.\n");
			if(verbose)
				print_hardware_address(user_specified_mac);

			break;

		case 'i': /* interface name */

			strncpy(network_interface_name,optarg,sizeof(network_interface_name)-1);
			network_interface_name[sizeof(network_interface_name)-1]='\x0';

			break;

		case 'u': /* unicast testing */
			unicast=1;
			break;

		case 'V': /* version */
			print_revision(progname, NP_VERSION);
			exit(STATE_OK);

		case 'h': /* help */
			print_help();
			exit(STATE_OK);

		case 'v': /* verbose */
			verbose=1;
			break;

		case '?': /* help */
			usage5 ();
			break;

		default:
			break;
		        }
	        }

	return i;
        }
Exemple #29
0
int main(int argc, char *argv[]) {
  struct sockaddr_in *sa;

  char buf[1024];
  char *host = "127.0.0.1", *counter = NULL, *timer = NULL;
  uint32_t net_ip;
  long value;
  int port = 8125, sample_rate = 1, performance_test = 0, performance_test_iterations = 10000;

  int opt;
  while ((opt = getopt(argc, argv, "hH:p:c:v:t:s:Pi:")) != -1) {
    switch (opt) {
      case 'h':
        usage(argv);
        return 1;
        break;
      case 'c':
        counter = malloc((strlen(optarg) + 1) * sizeof(char));
        strcpy(counter, optarg);
        break;
      case 't':
        timer = malloc((strlen(optarg) + 1) * sizeof(char));
        strcpy(timer, optarg);
        break;
      case 'p':
        port = atoi(optarg);
        break;
      case 's':
        sample_rate = atoi(optarg);
        break;
      case 'H':
        host = malloc((strlen(optarg) + 1) * sizeof(char));
        strcpy(host, optarg);
        break;
      case 'v':
        value = atol(optarg);
        break;
      case 'P':
        performance_test = 1;
        break;
      case 'i':
        performance_test_iterations = atoi(optarg);
        break;
    }
  }

  /* Sanity checking */
  if ((timer != NULL && counter != NULL) || (counter == NULL && timer == NULL)) {
    usage(argv);
    return 1;
  }

  /* Format message */
  if (timer != NULL) {
    sprintf(buf, "%s:%ld||%d", timer, value, sample_rate);
  } else if (counter != NULL) {
    sprintf(buf, "%s:%ld|c", counter, value);
  }

  /* Send message */
  int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  net_ip = resolve_host(host);
  sa = malloc(sizeof(struct sockaddr_in *));
/*  memset(&sa, 0, sizeof(struct sockaddr_in)); */
  sa->sin_family = AF_INET;
  sa->sin_port = htons(port);
  memcpy(&sa->sin_addr, &net_ip, sizeof(net_ip));
  if (performance_test) {
    double starting_time, ending_time;
    int err = 0;
    int iter;
    starting_time = get_time();
    for (iter=0; iter<performance_test_iterations; iter++) {
      if (!sendto(s, (char*) buf, strlen(buf), 0, (struct sockaddr*) sa, sizeof(struct sockaddr_in))) {
        err++;
      }
    }
    ending_time = get_time();
    printf("10k queries in %f seconds\n", ending_time - starting_time);
    return 0;
  } else {
    if (!sendto(s, (char*) buf, strlen(buf), 0, (struct sockaddr*) sa, sizeof(struct sockaddr_in))) {
      return 1;
    }
  }
  return 0;
}
Exemple #30
0
pj_status_t ConnectionPool::create_connection(int hash_slot)
{
  // Resolve the target host to an IP address.
  pj_sockaddr remote_addr;
  pj_status_t status = resolve_host(&_target.host, _target.port, &remote_addr);

  if (status != PJ_SUCCESS)
  {
    TRC_ERROR("Failed to resolve %.*s to an IP address - %s",
              _target.host.slen, _target.host.ptr,
              PJUtils::pj_status_to_string(status).c_str());
    return status;
  }

  // Call TPMGR to create a new transport connection.
  pjsip_transport* tp;
  pjsip_tpselector tp_sel;
  tp_sel.type = PJSIP_TPSELECTOR_LISTENER;
  tp_sel.u.listener = _tpfactory;
  status = pjsip_tpmgr_acquire_transport(pjsip_endpt_get_tpmgr(_endpt),
                                         (remote_addr.addr.sa_family == pj_AF_INET6()) ?
                                           PJSIP_TRANSPORT_TCP6 : PJSIP_TRANSPORT_TCP,
                                         &remote_addr,
                                         (remote_addr.addr.sa_family == pj_AF_INET6()) ?
                                           sizeof(pj_sockaddr_in6) : sizeof(pj_sockaddr_in),
                                         &tp_sel,
                                         &tp);

  if (status != PJ_SUCCESS)
  {
    return status;
  }

  // TPMGR will have already added a reference to the new transport to stop it
  // being destroyed while we have pointers referencing it.

  TRC_DEBUG("Created transport %s in slot %d (%.*s:%d to %.*s:%d)",
            tp->obj_name,
            hash_slot,
            (int)tp->local_name.host.slen,
            tp->local_name.host.ptr,
            tp->local_name.port,
            (int)tp->remote_name.host.slen,
            tp->remote_name.host.ptr,
            tp->remote_name.port);

  // Register for transport state callbacks.
  pjsip_tp_state_listener_key* key;
  status = pjsip_transport_add_state_listener(tp, &transport_state, (void*)this, &key);

  // Store the new transport in the hash slot, but marked as disconnected.
  pthread_mutex_lock(&_tp_hash_lock);
  _tp_hash[hash_slot].tp = tp;
  _tp_hash[hash_slot].listener_key = key;
  _tp_hash[hash_slot].connected = PJ_FALSE;
  _tp_map[tp] = hash_slot;

  // Don't increment the connection count here, wait until we get confirmation
  // that the transport is connected.

  pthread_mutex_unlock(&_tp_hash_lock);

  return PJ_SUCCESS;
}