コード例 #1
0
ファイル: msgmem.c プロジェクト: Shirling-VT/VTRST3.5
void read_sock(fd_set *fdset,char *tmp_buf,int tmp_sze) {
  /* reads in a message from a client */         
  int i;
  int byte;

  for (i=0;i<msgmax;i++) 
    if ( (client[i].sock !=-1) && 
         (FD_ISSET(client[i].sock,fdset))) {
         byte=read(client[i].sock,tmp_buf,tmp_sze);
         if (byte ==0) close_sock(i);
         else if ((byte <0) && (errno !=EAGAIN)) close_sock(i);
         else if (byte > 0) {
           if (byte+client[i].in_sze > BUF_SIZE) {
             int delta;
             delta=byte+client[i].in_sze-BUF_SIZE;
             memmove(client[i].in_buf,client[i].in_buf+delta,
                   client[i].in_sze-delta);
             client[i].out_sze=BUF_SIZE-byte;
           } 
           memcpy(client[i].in_buf+client[i].in_sze,tmp_buf,byte);
           client[i].in_sze+=byte;
	 }
    }
}
コード例 #2
0
ファイル: bufferev.c プロジェクト: bcook-r7/mettle
static void
on_connect_timeout(struct ev_loop *loop, struct ev_timer *w, int revents)
{
	struct bufferev *be = (struct bufferev *)w;

	ev_timer_stop(be->loop, &be->connect_timer);

	if (!be->connected) {
		close_sock(be);
		ev_io_stop(be->loop, &be->data_ev);

		if (be->event_cb) {
			be->event_cb(be, BEV_ERROR | BEV_TIMEOUT, be->cb_arg);
		}
	}
}
コード例 #3
0
ファイル: msgmem.c プロジェクト: Shirling-VT/VTRST3.5
int write_sock() {
  int i;
  int byte,cnt=0;
  for (i=0;i<msgmax;i++) 
    if ((client[i].sock !=-1) && (client[i].out_sze !=0)) {   
      byte=write(client[i].sock,client[i].out_buf,client[i].out_sze);
   
      if (byte <0) {
        if (errno==EAGAIN) continue;
        else close_sock(i);
      } else if (byte >0) {
        memmove(client[i].out_buf,client[i].out_buf+byte,
                client[i].out_sze-byte);
        client[i].out_sze-=byte;
        if (client[i].out_sze >0) cnt++; 
      }
    }
    return cnt; /* returns number of clients with outstanding data */
}
コード例 #4
0
ファイル: nub.c プロジェクト: threader/Mac-On-Linux
static void
nub_rcv( int fd, int dummy_events ) 
{
	struct pollfd ufds;
	mol_dgram_t *dg;
	int err, events;

	/* the events parameter can not be trusted since a queued async events can
	 * be stolen by a debugger_nub_poll() call.
	 */
	ufds.fd = fd;
	ufds.events = POLLHUP | POLLIN | POLLERR;
	if( poll(&ufds, 1, 0) <= 0 )
		return;
	events = ufds.revents;
	
	if( events & POLLHUP ) {
		if( sv.hup_count++ > 0 ) {
			sv.hup_count = 0;
			printm("Debugger connection lost\n");
			close_sock();
		}
		return;
	}

	if( events & ~POLLIN ) {
		fprintf(stderr, "nub_rcv events %x\n", events );
		return;
	}

	if( sv.dgram_receiver ) {
		if( (dg=receive_dgram(sv.dgram_receiver, &err)) ) {
			handle_msg(dg);
			free(dg);
		} else if( err ) {
			printm("nub_rcv: an error occured\n");
		}
	} else {
		printm("Unexpected nub_rcv\n");
	}
}
コード例 #5
0
/**
 * ソケット作成
 *
 * @return なし
 */
static int
inet_sock_client(void)
{
    struct sockaddr_in server; /* ソケットアドレス情報構造体 */
    int sockfd = 0;            /* ソケット */
    int retval = 0;            /* 戻り値 */

    dbglog("start");

    /* 初期化 */
    (void)memset(&server, 0, sizeof(struct sockaddr_in));
    server.sin_family = AF_INET;

    if (set_hostname(&server, hostname) < 0)
        return EX_NG;
    if (set_port(&server, port) < 0)
        return EX_NG;

    /* ソケット生成 */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        outlog("sock=%d", sockfd);
        return EX_NG;
    }

    /* コネクト */
    retval = connect(sockfd, (struct sockaddr *)&server,
                     sizeof(struct sockaddr_in));
    if (retval < 0) {
        outlog("connect=%d, sock=%d", retval, sockfd);
        /* ソケットクローズ */
        close_sock(&sockfd);
        return EX_NG;
    }
    return sockfd;
}
コード例 #6
0
ファイル: socket.cpp プロジェクト: tmiw/kite-llvm
 object *socket::close()
 {
     if (socket_val < 0)
     {
         exceptions::SocketError *exc = exceptions::SocketError::Create(
             1,
             new string("Socket already closed.")
         );
         exc->throw_exception();
     }
     
     int ret = close_sock(socket_val);
     if (ret < 0)
     {
         exceptions::SocketError *exc = exceptions::SocketError::Create(
             1,
             new string("Error while closing socket.")
         );
         exc->throw_exception();
     }
     socket_val = -1;
     
     return new boolean(true);
 }
コード例 #7
0
ファイル: resolver.c プロジェクト: avble/natClientEx
/*
 * Destroy DNS resolver instance.
 */
PJ_DEF(pj_status_t) pj_dns_resolver_destroy( pj_dns_resolver *resolver,
					     pj_bool_t notify)
{
    pj_hash_iterator_t it_buf, *it;
    PJ_ASSERT_RETURN(resolver, PJ_EINVAL);

    if (notify) {
	/*
	 * Notify pending queries if requested.
	 */
	it = pj_hash_first(resolver->hquerybyid, &it_buf);
	while (it) {
	    pj_dns_async_query *q = (pj_dns_async_query *)
	    			    pj_hash_this(resolver->hquerybyid, it);
	    pj_dns_async_query *cq;
	    if (q->cb)
		(*q->cb)(q->user_data, PJ_ECANCELLED, NULL);

	    cq = q->child_head.next;
	    while (cq != (pj_dns_async_query*)&q->child_head) {
		if (cq->cb)
		    (*cq->cb)(cq->user_data, PJ_ECANCELLED, NULL);
		cq = cq->next;
	    }
	    it = pj_hash_next(resolver->hquerybyid, it);
	}
    }

    /* Destroy cached entries */
    it = pj_hash_first(resolver->hrescache, &it_buf);
    while (it) {
	struct cached_res *cache;

	cache = (struct cached_res*) pj_hash_this(resolver->hrescache, it);
	pj_hash_set(NULL, resolver->hrescache, &cache->key, 
		    sizeof(cache->key), 0, NULL);
	pj_pool_release(cache->pool);

	it = pj_hash_first(resolver->hrescache, &it_buf);
    }

    if (resolver->own_timer && resolver->timer) {
	pj_timer_heap_destroy(resolver->timer);
	resolver->timer = NULL;
    }

    close_sock(resolver);

    if (resolver->own_ioqueue && resolver->ioqueue) {
	pj_ioqueue_destroy(resolver->ioqueue);
	resolver->ioqueue = NULL;
    }

    if (resolver->mutex) {
	pj_mutex_destroy(resolver->mutex);
	resolver->mutex = NULL;
    }

    if (resolver->pool) {
	pj_pool_t *pool = resolver->pool;
	resolver->pool = NULL;
	pj_pool_release(pool);
    }
    return PJ_SUCCESS;
}
コード例 #8
0
static int winbind_open_pipe_sock(int recursing, int need_priv)
{
#ifdef HAVE_UNIXSOCKET
	static pid_t our_pid;
	struct winbindd_request request;
	struct winbindd_response response;
	ZERO_STRUCT(request);
	ZERO_STRUCT(response);

	if (our_pid != getpid()) {
		close_sock();
		our_pid = getpid();
	}

	if ((need_priv != 0) && (is_privileged == 0)) {
		close_sock();
	}
	
	if (winbindd_fd != -1) {
		return winbindd_fd;
	}

	if (recursing) {
		return -1;
	}

	if ((winbindd_fd = winbind_named_pipe_sock(WINBINDD_SOCKET_DIR)) == -1) {
		return -1;
	}

	is_privileged = 0;

	/* version-check the socket */

	request.flags = WBFLAG_RECURSE;
	if ((winbindd_request_response(WINBINDD_INTERFACE_VERSION, &request, &response) != NSS_STATUS_SUCCESS) || (response.data.interface_version != WINBIND_INTERFACE_VERSION)) {
		close_sock();
		return -1;
	}

	/* try and get priv pipe */

	request.flags = WBFLAG_RECURSE;
	if (winbindd_request_response(WINBINDD_PRIV_PIPE_DIR, &request, &response) == NSS_STATUS_SUCCESS) {
		int fd;
		if ((fd = winbind_named_pipe_sock((char *)response.extra_data.data)) != -1) {
			close(winbindd_fd);
			winbindd_fd = fd;
			is_privileged = 1;
		}
	}

	if ((need_priv != 0) && (is_privileged == 0)) {
		return -1;
	}

	SAFE_FREE(response.extra_data.data);

	return winbindd_fd;
#else
	return -1;
#endif /* HAVE_UNIXSOCKET */
}
コード例 #9
0
ファイル: ping.c プロジェクト: MarkTseng/prozilla-2.0.4
uerr_t tcp_ping(ping_t * ping_data)
{
  int status, noblock, flags;
  extern int h_errno;
  struct timeval start_time;
  struct timeval end_time;
  char ping_buf[TCP_PING_PACKSIZE];
  int bytes_read;
    struct addrinfo hints, *res=NULL;
    char szPort[10];
    int error;

  assert(ping_data->host);
  memset(&hints, 0, sizeof(hints));
  memset(szPort, 0, sizeof(szPort));
  snprintf(szPort, sizeof(szPort), "%d", ping_data->port);
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;

    error = getaddrinfo(ping_data->host, szPort, &hints, &res);
    if (error) {
      return ping_data->err = HOSTERR;
        }
 
 if ((ping_data->sock = socket(res->ai_family, res->ai_socktype, IPPROTO_TCP)) < 1)
  {
    free(res);
    return ping_data->err = CONSOCKERR;
  }

  /* Experimental. */
  flags = fcntl(ping_data->sock, F_GETFL, 0);
  if (flags != -1)
    noblock = fcntl(ping_data->sock, F_SETFL, flags | O_NONBLOCK);
  else
    noblock = -1;

  /* get start time */
  gettimeofday(&start_time, 0);

  status =
      connect(ping_data->sock, res->ai_addr, res->ai_addrlen);

  if ((status == -1) && (noblock != -1) && (errno == EINPROGRESS))
  {
    fd_set writefd;

    FD_ZERO(&writefd);
    FD_SET(ping_data->sock, &writefd);

    status =
	select((ping_data->sock + 1), NULL, &writefd, NULL,
	       &ping_data->timeout);

    /* Do we need to retry if the err is EINTR? */

    if (status > 0)
    {
      socklen_t arglen = sizeof(int);

      if (getsockopt
	  (ping_data->sock, SOL_SOCKET, SO_ERROR, &status, &arglen) < 0)
	status = errno;

      if (status != 0)
	errno = status, status = -1;

      if (errno == EINPROGRESS)
	errno = ETIMEDOUT;
    } else if (status == 0)
      errno = ETIMEDOUT, status = -1;
  }

  if (status < 0)
  {
    close_sock(&ping_data->sock);

    if (errno == ECONNREFUSED)
    {
      free(res);
      return ping_data->err = CONREFUSED;
    } else if (errno == ETIMEDOUT)
    {
      free(res);
      return ping_data->err = PINGTIMEOUT;
    } else
    {
      free(res);
      return ping_data->err = CONERROR;
    }
  } else
  {
    flags = fcntl(ping_data->sock, F_GETFL, 0);

    if (flags != -1)
      fcntl(ping_data->sock, F_SETFL, flags & ~O_NONBLOCK);
  }

  /* setsockopt(*sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&opt,
     (int) sizeof(opt)); */

  free(res);


  /*So far so good connection established */

  bytes_read =
      krecv(ping_data->sock, ping_buf, TCP_PING_PACKSIZE, 0,
	    &ping_data->timeout);
  close_sock(&ping_data->sock);

  proz_debug("bytes read = %d", bytes_read);
  if (bytes_read == -1)
  {
    if (errno == ETIMEDOUT)
      return ping_data->err = PINGTIMEOUT;
    else
      return ping_data->err = READERR;
  }

  if (bytes_read == 0 || bytes_read < TCP_PING_PACKSIZE)
    return ping_data->err = READERR;

  /* the end time */
  gettimeofday(&end_time, 0);
  proz_timeval_subtract(&ping_data->ping_time, &end_time, &start_time);


  /*  standard_ping_milli_secs =(int)((((float)ping_data->ping_time.tv_usec/1000)+(((float)ping_data->ping_time.tv_sec)*1000))*3/(float)bytes_read);

     ping_data->ping_time.tv_sec=standard_ping_milli_secs/1000;
     ping_data->ping_time.tv_usec=standard_ping_milli_secs%1000;
   */

  return ping_data->err = PINGOK;
}
コード例 #10
0
int write_sock(void *buffer, int count, int recursing)
{
	int result, nwritten;
	
	/* Open connection to winbind daemon */
	
 restart:
	
	if (winbind_open_pipe_sock(recursing) == -1) {
		return -1;
	}
	
	/* Write data to socket */
	
	nwritten = 0;
	
	while(nwritten < count) {
		struct timeval tv;
		fd_set r_fds;
		
		/* Catch pipe close on other end by checking if a read()
		   call would not block by calling select(). */

		FD_ZERO(&r_fds);
		FD_SET(winbindd_fd, &r_fds);
		ZERO_STRUCT(tv);
		
		if (select(winbindd_fd + 1, &r_fds, NULL, NULL, &tv) == -1) {
			close_sock();
			return -1;                   /* Select error */
		}
		
		/* Write should be OK if fd not available for reading */
		
		if (!FD_ISSET(winbindd_fd, &r_fds)) {
			
			/* Do the write */
			
			result = write(winbindd_fd,
				       (char *)buffer + nwritten, 
				       count - nwritten);
			
			if ((result == -1) || (result == 0)) {
				
				/* Write failed */
				
				close_sock();
				return -1;
			}
			
			nwritten += result;
			
		} else {
			
			/* Pipe has closed on remote end */
			
			close_sock();
			goto restart;
		}
	}
	
	return nwritten;
}
コード例 #11
0
ファイル: http.c プロジェクト: Raviyanto/new-prozgui
uerr_t ftp_get_url_info_from_http_proxy(connection_t * connection)
{

  uerr_t err;
  int remote_port_len;
  char *user, *passwd, *www_auth = NULL, *proxy_auth =
      NULL, *pragma_no_cache = NULL;

  char *request, *remote_port;
  netrc_entry *netrc_ent;

  memset(&connection->hs, 0, sizeof(connection->hs));

  err = connect_to_server(&connection->data_sock,
			  connection->ftp_proxy->proxy_url.host,
			  connection->ftp_proxy->proxy_url.port,
			  &connection->xfer_timeout);

  if (err != NOCONERROR)
  {
    connection_show_message(connection, _("Error connecting to %s"),
			    connection->ftp_proxy->proxy_url.host);
    return err;
  }

  user = connection->u.user;
  passwd = connection->u.passwd;

  /* Use .netrc if asked to do so. */
  if (connection->use_netrc == TRUE)
  {
    netrc_ent = search_netrc(libprozrtinfo.netrc_list, connection->u.host);

    if (netrc_ent != NULL)
    {
      user = netrc_ent->account;
      passwd = netrc_ent->password;
    }
  }

  user = user ? user : "";
  passwd = passwd ? passwd : "";

  if (strlen(user) || strlen(passwd))
  {
    /* Construct the necessary header. */
    www_auth = get_basic_auth_str(user, passwd, "Authorization");
    proz_debug(_("Authenticating as user %s password %s"), user, passwd);
    proz_debug(_("Authentification string=%s"), www_auth);
  } else
    www_auth = 0;

  if (strlen(connection->ftp_proxy->username)
      || strlen(connection->ftp_proxy->passwd))
    proxy_auth =
	get_basic_auth_str(connection->ftp_proxy->username,
			   connection->ftp_proxy->passwd,
			   "Proxy-Authorization");

  remote_port = (char *) alloca(64);
  remote_port_len = sprintf(remote_port, ":%d", connection->u.port);

  if (http_use_proxy(connection)
      && (connection->http_no_cache || connection->attempts > 0))
  {
    pragma_no_cache = (char *) alloca(21);
    sprintf(pragma_no_cache, "Pragma: no-cache\r\n");
  }

  /*Referrer TAG should not be needed in FTP through HTTP proxy..right */


  request = (char *) alloca(strlen(connection->u.url)
			    + strlen(connection->user_agent)
			    + strlen(connection->u.host) + remote_port_len
			    + (www_auth ? strlen(www_auth) : 0)
			    + (proxy_auth ? strlen(proxy_auth) : 0)
			    + 64
			    +
			    (pragma_no_cache ? strlen(pragma_no_cache) :
			     0));

  sprintf(request,
	  "GET %s HTTP/1.0\r\nUser-Agent: %s\r\nHost: %s%s\r\nAccept: */*\r\n%s%s%s\r\n",
	  connection->u.url, connection->user_agent, connection->u.host,
	  remote_port,
	  www_auth ? www_auth : "", proxy_auth ? proxy_auth : "",
	  pragma_no_cache ? pragma_no_cache : "");

  proz_debug("HTTP request = %s", request);


  err = http_fetch_headers(connection, &connection->hs, request);

  close_sock(&connection->data_sock);

  /*Convert the error code to the equivalent FTP one if possible */

  if (err == HOK)
  {
    connection->main_file_size = connection->hs.contlen;
    if (connection->hs.accept_ranges == 1)
      connection->resume_support = TRUE;
    else if (connection->hs.accept_ranges == -1)
      connection->resume_support = FALSE;
    return FTPOK;
  }


  if (err == HAUTHREQ)
    return FTPLOGREFUSED;
  else if (err == HTTPNSFOD)
    return FTPNSFOD;


  /*  connection->file_type = REGULAR_FILE; */
  return FTPERR;

}
コード例 #12
0
ファイル: http.c プロジェクト: Raviyanto/new-prozgui
/******************************************************************************
 ...
******************************************************************************/
uerr_t proz_http_get_url_info(connection_t * connection)
{
  uerr_t err;
  int remote_port_len;
  char *user, *passwd, *www_auth = NULL, *proxy_auth = NULL,
      *referer = NULL, *location = NULL, *pragma_no_cache = NULL;
  char *request, *remote_port;
  netrc_entry *netrc_ent;

  memset(&connection->hs, 0, sizeof(connection->hs));

  if (http_use_proxy(connection))
  {
    connection_show_message(connection, _("Connecting to %s"),
			    connection->http_proxy->proxy_url.host);

    err = connect_to_server(&connection->data_sock,
			    connection->http_proxy->proxy_url.host,
			    connection->http_proxy->proxy_url.port,
			    &connection->xfer_timeout);
    if (err != NOCONERROR)
    {
      connection_show_message(connection, _("Error connecting to %s"),
			      connection->http_proxy->proxy_url.host);
      return err;
    }
  } else
  {
    connection_show_message(connection, _("Connecting to %s"),
			    connection->u.host);
    err = connect_to_server(&connection->data_sock, connection->u.host,
			    connection->u.port, &connection->xfer_timeout);
    if (err != NOCONERROR)
    {
      connection_show_message(connection, _("Error connecting to %s"),
			      connection->u.host);
      return err;
    }
  }

  user = connection->u.user;
  passwd = connection->u.passwd;

  /* Use .netrc if asked to do so. */
  if (connection->use_netrc == TRUE)
  {
    netrc_ent = search_netrc(libprozrtinfo.netrc_list, connection->u.host);

    if (netrc_ent != NULL)
    {
      user = netrc_ent->account;
      passwd = netrc_ent->password;
    }
  }

  user = user ? user : "";
  passwd = passwd ? passwd : "";

  if (strlen(user) || strlen(passwd))
  {
    /* Construct the necessary header. */
    www_auth = get_basic_auth_str(user, passwd, "Authorization");
    proz_debug(_("Authenticating as user %s password %s"), user, passwd);
    proz_debug(_("Authentification string=%s"), www_auth);
  } else
    www_auth = 0;

  if (http_use_proxy(connection))
  {
    if (strlen(connection->http_proxy->username)
	|| strlen(connection->http_proxy->passwd))
      proxy_auth =
	  get_basic_auth_str(connection->http_proxy->username,
			     connection->http_proxy->passwd,
			     "Proxy-Authorization");
  }

  if (connection->u.port == 80)
  {
    remote_port = NULL;
    remote_port_len = 0;
  } else
  {
    remote_port = (char *) alloca(64);
    remote_port_len = sprintf(remote_port, ":%d", connection->u.port);
  }


  if (connection->u.referer)
  {
    referer = (char *) alloca(13 + strlen(connection->u.referer));
    sprintf(referer, "Referer: %s\r\n", connection->u.referer);
  }

  /* If we go through a proxy the request for the URL is different */
  if (http_use_proxy(connection))
  {
    location = (char *) alloca(strlen(connection->u.url) + 1);
    strcpy(location, connection->u.url);
  } else
  {
    location = (char *) alloca(strlen(connection->u.path) + 1);
    strcpy(location, connection->u.path);
  }

  /*Use no-cache directive for proxy servers? */
  if (http_use_proxy(connection)
      && (connection->http_no_cache || connection->attempts > 0))
  {
    pragma_no_cache = (char *) alloca(21);
    sprintf(pragma_no_cache, "Pragma: no-cache\r\n");
  }

  request = (char *) alloca(strlen(location)
			    + strlen(connection->user_agent)
			    + strlen(connection->u.host) + remote_port_len
			    + (referer ? strlen(referer) : 0)
			    + (www_auth ? strlen(www_auth) : 0)
			    + (proxy_auth ? strlen(proxy_auth) : 0) + 64
			    +
			    (pragma_no_cache ? strlen(pragma_no_cache) :
			     0));

  sprintf(request,
	  "GET %s HTTP/1.0\r\nUser-Agent: %s\r\nHost: %s%s\r\nAccept: */*\r\n%s%s%s%s\r\n",
	  location, connection->user_agent, connection->u.host,
	  remote_port ? remote_port : "",
	  referer ? referer : "",
	  www_auth ? www_auth : "", proxy_auth ? proxy_auth : "",
	  pragma_no_cache ? pragma_no_cache : "");

  proz_debug("HTTP request = %s", request);

  connection_show_message(connection, _("Sending HTTP request"));
  err = http_fetch_headers(connection, &connection->hs, request);

  close_sock(&connection->data_sock);

  if (err == HOK)
  {
    connection->main_file_size = connection->hs.contlen;
    if (connection->hs.accept_ranges == 1)
      connection->resume_support = TRUE;
    else if (connection->hs.accept_ranges == -1)
      connection->resume_support = FALSE;
  }


  connection->file_type = REGULAR_FILE;
  return err;
}
コード例 #13
0
ファイル: vp_local_tcpclient.c プロジェクト: dulton/solotools
static void * __start_local_tcpclient(void * arg)
{
    SAI ser_addr;
    SAI cli_addr;
    int cli_sock = -1;
	struct timeval tout;
	char buf[32] = {0};
	vp_local_client lc;

	char *pSend = NULL;
	char *pRecv = NULL;
	int  nSend = 0;
	int  nRecvBuf = 0;
	int  nRecv = 0;

	if (arg == NULL)
		return NULL;
	memcpy(&lc, arg, sizeof(lc));
	oss_free(&arg);

	puts("-- 1");
    if ((cli_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
	{
		logdbg_out("Start local tcp client: create socket failed!");
		return NULL;
	}

	puts("-- 2");
    if (Setsockopt(cli_sock, SOL_SOCKET, SO_REUSEADDR) < 0)
	{
		logdbg_out("Start local tcp client: set socket reuse failed!");
		close(cli_sock);
		return NULL;
	}

	// set server address
	init_sockaddr(&ser_addr, lc.args.dip, lc.args.dport);

	puts("-- 3");
	// set client address
	if ((lc.args.lip != 0) || (lc.args.lport != 0))
	{
		init_sockaddr(&cli_addr, lc.args.lip, lc.args.lport);
		if (Bind(cli_sock, cli_addr, sizeof(cli_addr)) < 0)
		{
			logdbg_fmt("Start local tcp client: bind socket to %s:%d failed!", inet_ultoa(lc.args.lip, buf), lc.args.lport);
			close(cli_sock);
			return NULL;
		}
	}

	puts("-- 4");
	tout.tv_sec = lc.args.session_tout;  // Seconds Timeout
	tout.tv_usec = 0;  
	if (setsockopt(cli_sock, SOL_SOCKET, SO_RCVTIMEO, &tout,sizeof(struct timeval)) < 0)
	{
		logdbg_out("Start local tcp client: set connect timeout failed!");
		close(cli_sock);
		return NULL;
	}

	puts("-- 5");
	if (Connect(cli_sock, (struct sockaddr*)&ser_addr, sizeof(ser_addr), 5) < 0)
	{
		logdbg_fmt("Start local tcp client: connect %s:%d failed!", inet_ultoa(lc.args.lip, buf), lc.args.lport);
		close(cli_sock);
		return NULL;
	}

	puts("-- 6");
	if (lc.do_connect != NULL)
	{
		if (lc.do_connect(&(lc.args), &pSend, &nSend) <= 0)
		{
			close(cli_sock);
			return NULL;
		}
		if (Send(cli_sock, pSend, nSend, MSG_NOSIGNAL) <= 0)
		{
			close(cli_sock);
			return NULL;
		}
	}
	puts("-- 7");
	// int  (* do_process_recv)(pvp_local_client_args *pclient_args, char **ppreply, int *preply_len);
	nRecvBuf = BUF_SIZE;
	//if (pRecv = (char*)malloc(BUF_SIZE);
	if (oss_malloc(&pRecv, nRecvBuf) < 0)
	{
		logdbg_out("Start local tcp client: malloc receive buffer failed!");
		close(cli_sock);
		return NULL;
	}

	char *pTmp = NULL;
	while (true)
	{
		if (nRecvBuf < BUF_SIZE)
		{
			if ((pTmp = (char*)realloc(pRecv, BUF_SIZE)) == NULL)
			{
				logdbg_out("Start local tcp client: realloc buffer failed!");
				break;
			}
			pRecv = pTmp;
			nRecvBuf = BUF_SIZE;
		}

		if ((nRecv = Recv(cli_sock, pRecv, nRecvBuf, 0)) <= 0)
		{
			if (nRecv < 0)
				logdbg_out("Start local tcp client: receive failed!");
			break;
		}

		if (lc.do_process_recv != NULL)
		{
			if (lc.do_process_recv(&lc.args, &pRecv, &nRecv, &nRecvBuf) < 0)
				break;
		}
	}

    close_sock(&cli_sock);

    return NULL;
}
コード例 #14
0
ファイル: server.c プロジェクト: sluchin/calc
/**
 * 接続受付
 *
 * @param[in] sock ソケット
 * @return なし
 */
void
server_loop(int sock)
{
    int ready = 0;           /* pselect戻り値 */
    pthread_t tid = 0;       /* スレッドID */
    int retval = 0;          /* pthread_create戻り値 */
    fd_set fds, rfds;        /* selectマスク */
    struct timespec timeout; /* タイムアウト値 */
    sigset_t sigmask;        /* シグナルマスク */
    thread_data *dt = NULL;  /* ソケット情報構造体 */

    dbglog("start: sock=%d", sock);

    /* マスクの設定 */
    FD_ZERO(&fds);      /* 初期化 */
    FD_SET(sock, &fds); /* ソケットをマスク */

    /* シグナルマスク取得 */
    sigmask = get_sigmask();

    /* タイムアウト値初期化 */
    (void)memset(&timeout, 0, sizeof(struct timespec));
    /* pselectの場合, constなのでループ前で値を入れる */
    timeout.tv_sec = 1; /* 1秒 */
    timeout.tv_nsec = 0;

    /* ノンブロッキングに設定 */
    if (set_block(sock, NONBLOCK) < 0)
        return;

    do {
        (void)memcpy(&rfds, &fds, sizeof(fd_set)); /* マスクコピー */
        ready = pselect(sock + 1, &rfds,
                        NULL, NULL, &timeout, &sigmask);
        if (ready < 0) {
            if (errno == EINTR) /* 割り込み */
                break;
            outlog("select=%d", ready);
            break;
        } else if (ready) {
            if (FD_ISSET(sock, &rfds)) {

                dt = (thread_data *)malloc(sizeof(thread_data));
                if (!dt) {
                    outlog("malloc: size=%zu", sizeof(thread_data));
                    continue;
                }
                (void)memset(dt, 0, sizeof(thread_data));
                dbglog("dt=%p", dt);

                /* 接続受付 */
                /* addrlenは入出力なのでここで初期化する */
                dt->len = (socklen_t)sizeof(dt->addr);
                dt->sigmask = sigmask;
                dt->sock = accept(sock,
                                  (struct sockaddr *)&dt->addr,
                                  &dt->len);
                if (dt->sock < 0) {
                    outlog("accept: sin_addr=%s sin_port=%d",
                           inet_ntoa(dt->addr.sin_addr),
                           ntohs(dt->addr.sin_port));
                    memfree((void **)&dt, NULL);
                    continue;
                }

                /* スレッド生成 */
                retval = pthread_create(&tid, NULL, server_proc, dt);
                if (retval) { /* エラー(非0) */
                    outlog("pthread_create=%lu", (unsigned long)tid);
                    close_sock(&dt->sock); /* アクセプトクローズ */
                    memfree((void **)&dt, NULL);
                    continue;
                }
                dbglog("pthread_create=%lu, accept=%d", (unsigned long)tid, dt->sock);

                retval = pthread_detach(tid);
                if (retval) /* エラー(非0) */
                    outlog("pthread_detach: tid=%lu", (unsigned long)tid);
            }
        } else { /* タイムアウト */
            continue;
        }
    } while (!g_sig_handled);
}
コード例 #15
0
static int __init init_fbaodv_module(void) {
	char *tmp_str = NULL;
	inet_aton("0.0.0.0", &g_null_ip);

	if (mesh_dev==NULL)
	{
		printk("You need to specify the mesh network device ie:\n");
		printk("    insmod fbaodv_protocol mesh_dev=wlan0    \n");
		return(-1);
	}
	
	strcpy(g_aodv_dev, mesh_dev);
	
	if(aodv_gateway) {
		g_aodv_gateway = (u_int8_t)aodv_gateway;
		printk("\n\nSet as AODV-ST gateway\n");
	} else
	g_aodv_gateway = 0;

	if (network_ip == NULL) {
		printk("You need to specify aodv network ip range, ie: \n");
		printk("network_ip=192.168.0.12/255.255.255.0\n");
		return(-1);
	}
	inet_aton("255.255.255.255",&g_broadcast_ip);
	printk("Miguel Catalan Cid\nImplementation built on top of aodv-st by Krishna Ramachandran, UC Santa Barbara\n");
	printk("---------------------------------------------\n");

	
	/*ROUTING METRICS*/
	if (routing_metric == NULL || strcmp(routing_metric, "HOPS") == 0){
		g_routing_metric = HOPS;
		printk("Hop count routing\n\n");
	}

	else if (strcmp(routing_metric, "ETT") == 0) {
		g_routing_metric = ETT;
		printk("ETT routing: Expected Transmission Time\n\n");
		
		if (nominal_rate && get_nominalrate(nominal_rate))
			g_fixed_rate = nominal_rate;
		
		if (!nominal_rate || g_fixed_rate == 0) {
				g_fixed_rate = 0;
				printk("Nominal rate estimation using packet-pair probe messages: ACTIVE\n\n");
		}
		else
			printk("Nominal rate estimation using packet-pair probe messages: INACTIVE\n\n");

	}
	else if (strcmp(routing_metric, "WCIM") == 0) {
		g_routing_metric = WCIM;
		printk("WCIM routing: Weighted Contention and Interference Model\n\n");
		
		if (nominal_rate && get_nominalrate(nominal_rate))
					g_fixed_rate = nominal_rate;
				
		if (!nominal_rate || g_fixed_rate == 0) {
					g_fixed_rate = 0;
					printk("Nominal rate estimation using packet-pair probe messages: ACTIVE\n\n");
		}
		else
					printk("Nominal rate estimation using packet-pair probe messages: INACTIVE\n\n");


	}

	
	if (network_ip!=NULL)
	{
		tmp_str = strchr(network_ip,'/');
		if (tmp_str)
		{	(*tmp_str)='\0';
			tmp_str++;
			printk("* Network IP - %s/%s\n", network_ip, tmp_str);
			inet_aton(network_ip, &g_mesh_ip);
			inet_aton(tmp_str, &g_mesh_netmask);
		}
	}
		
	
	if (init_packet_queue() < 0) {
			printk("Netlink queue error!!!\n");
			printk("Shutdown complete!\n");
			return(-1);
	}
	
#ifdef BLACKLIST
	if (aodv_blacksize) {
		printk("AODV BLACK LIST:\n");
		int k;
		for (k = 0; k < aodv_blacksize; k++) {
			printk("           %s\n", aodv_blacklist[k]);
			inet_aton(aodv_blacklist[k], &aodv_blacklist_ip[k]);
		}
	}
	if (dtn_blacksize) {
		printk("DTN BLACK LIST:\n");
		int k;
		for (k = 0; k < dtn_blacksize; k++) {
			printk("           %s\n", dtn_blacklist[k]);
			inet_aton(dtn_blacklist[k], &dtn_blacklist_ip[k]);
		}
	}
#endif


	init_aodv_route_table();
	init_task_queue();
	init_timer_queue();
	init_aodv_neigh_list();
	init_aodv_neigh_list_2h();
	init_src_list();
	init_gw_list();
	init_flow_type_table();

	printk("\n*Initialicing mesh device  - %s\n", mesh_dev);	
	if (init_aodv_dev(mesh_dev))
		goto out1;
	

	startup_aodv();


	if (g_aodv_gateway) {
		printk("initiating st_rreq dissemination\n");
		insert_timer_simple(TASK_ST, HELLO_INTERVAL, g_mesh_ip); // start first st_rreq immediately
	}

	//MCC 21/07/2008- UPDATE TIMER ahora en insert_timer
	insert_timer_simple(TASK_HELLO, HELLO_INTERVAL,g_mesh_ip );
	insert_timer_simple(TASK_GW_CLEANUP, ACTIVE_GWROUTE_TIMEOUT, g_mesh_ip);
	insert_timer_simple(TASK_CLEANUP, HELLO_INTERVAL+HELLO_INTERVAL/2, g_mesh_ip);
	update_timer_queue();

	aodv_dir = proc_mkdir("fbaodv",NULL);
	if (aodv_dir == NULL) {
		goto out2;
	}
///*
#ifdef KERNEL2_6_26
	aodv_dir->owner = THIS_MODULE;
#endif

	route_table_proc=create_proc_read_entry("routes", 0, aodv_dir, read_route_table_proc, NULL);
#ifdef KERNEL2_6_26
	route_table_proc->owner=THIS_MODULE;
#endif

	if (route_table_proc == NULL) goto out2;

	neigh_proc=create_proc_read_entry("neigh", 0, aodv_dir, read_neigh_proc, NULL);
	if (neigh_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	neigh_proc->owner=THIS_MODULE;
#endif

	timers_proc=create_proc_read_entry("timers", 0, aodv_dir, read_timer_queue_proc, NULL);
	if (timers_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	timers_proc->owner=THIS_MODULE;
#endif

	reliability_proc=create_proc_read_entry("reliability", 0, aodv_dir, read_rel_list_proc, NULL);
	if (reliability_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	reliability_proc->owner=THIS_MODULE;
#endif

	ett_proc=create_proc_read_entry("bw_estimation", 0, aodv_dir, read_ett_list_proc, NULL);
	if (ett_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	ett_proc->owner=THIS_MODULE;
#endif

	sources_proc=create_proc_read_entry("sources", 0, aodv_dir, read_src_list_proc, NULL);
	if (sources_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	sources_proc->owner=THIS_MODULE;
#endif

	node_load_proc=create_proc_read_entry("node_load", 0, aodv_dir, read_node_load_proc, NULL);
	if (node_load_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	node_load_proc->owner=THIS_MODULE;
#endif

	gw_proc=create_proc_read_entry("gateways", 0, aodv_dir, read_gw_list, NULL);
	if (gw_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	gw_proc->owner=THIS_MODULE;
#endif

	tos_proc=create_proc_read_entry("tos_available", 0, aodv_dir, read_flow_type_table_proc, NULL);
	if (ett_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	ett_proc->owner=THIS_MODULE;
#endif
//*/
	//netfilter stuff
	// input hook
	input_filter.list.next = NULL;
	input_filter.list.prev = NULL;
	input_filter.hook = input_handler;
	input_filter.pf = PF_INET; // IPv4
	input_filter.hooknum = NF_INET_LOCAL_IN;

	//MCC- output hook
	output_filter.list.next = NULL;
	output_filter.list.prev = NULL;
	output_filter.hook = output_handler;
	output_filter.pf = PF_INET; // IPv4
	output_filter.hooknum = NF_INET_POST_ROUTING;

	nf_register_hook(&output_filter);
	nf_register_hook(&input_filter);

	printk("\n\n****FBAODV_PROTO module initialization complete****\n\n");
	return 0;

	out1:
	close_sock();

	del_timer(&aodv_timer);
	printk("Removed timer...\n");

	cleanup_packet_queue();
	printk("Cleaned up AODV Queues...\n");

	if (aodv_route_table != NULL)
	cleanup_aodv_route_table();

	flush_src_list();
	printk("Cleaned up Route and Rule Tables...\n");

	printk("Shutdown complete!\n");

	return(-1);

	out2:

	remove_proc_entry("fbaodv/routes",NULL);
	remove_proc_entry("fbaodv/timers",NULL);
	remove_proc_entry("fbaodv/neigh",NULL);
	remove_proc_entry("fbaodv/reliability", NULL);
	remove_proc_entry("fbaodv/sources", NULL);
	remove_proc_entry("fbaodv/node_load", NULL);

	remove_proc_entry("fbaodv/gateways", NULL);

	remove_proc_entry("fbaodv/user_gateway", NULL);
	remove_proc_entry("fbaodv/gateways_assigned", NULL);
	remove_proc_entry("fbaodv/bw_estimation", NULL);
	remove_proc_entry("fbaodv/tos_available", NULL);
	remove_proc_entry("fbaodv", NULL);

	printk("\n\nShutting down...\n");

	printk("Unregistered NetFilter hooks...\n");

	close_sock();
	printk("Closed sockets...\n");

	del_timer(&aodv_timer);
	printk("Removed timer...\n");

	kill_aodv();
	printk("Killed router thread...\n");

	cleanup_task_queue();
	cleanup_packet_queue();
	printk("Cleaned up AODV Queues...\n");

	cleanup_neigh_routes();
	cleanup_aodv_route_table();
	flush_src_list();
	printk("Cleaned up Route and Rule Tables...\n");

	//Eliminando listas
	delete_aodv_neigh_list();
	delete_aodv_neigh_list_2h();
	delete_gw_list();
	flush_flow_type_table();
	printk("Cleaned up Lists...\n");

	printk("Shutdown complete!\n");

	return(-1);
}
コード例 #16
0
ファイル: jeu.c プロジェクト: ulricheza/Isima
int mode_local_client(SDL_Surface * fenetre)
{
   /*declaration des variables*/
   var_game_t * var;
   void * temp;
   long ready = 1;
   long deb;
   char * adresse_ip;
   pthread_t thread;
   SDL_Event event;

   /*ouverture du module socket sous windows*/
   #ifdef __WIN32__
      WSADATA WSAData;
      WSAStartup(MAKEWORD(2,2), &WSAData);
   #endif


   /*allocation des ressources*/
   init_var(0,&var);

   var->ecran = fenetre;
   SDL_BlitSurface(var->background,NULL,var->ecran,&(var->position_back));
   SDL_Flip(var->ecran);
   do
   {
      
      adresse_ip = read_adress(var);
      /*creation de la socket*/
      var->sock_client=socket(AF_INET, SOCK_STREAM, 0);

      /*configuration de la connexion*/
      var->sin_client.sin_addr.s_addr = inet_addr(adresse_ip);
      var->sin_client.sin_family = AF_INET;
      var->sin_client.sin_port = htons(PORT);
   }while(connect(var->sock_client, (SOCKADDR*) &var->sin_client, sizeof(var->sin_client)) < 0);
   
   SDL_BlitSurface(var->background,NULL,var->ecran,&(var->position_back));
   SDL_Flip(var->ecran);
   message_box(var,"connection effectue");

   
   pthread_create(&thread, NULL,(void *)recept_rdy,var);
   placement_hum(var);

   ready = htonl(1);
   if(send(var->sock_client,&ready,sizeof(long),0) == -1)
   {
      fprintf(var->log_erreur,"Erreur envoie ready\n");
      fclose(var->log_erreur);
      exit(EXIT_FAILURE);
   }

   message_box(var,"placement des bateaux du joueur adverse \n");
   while(pthread_join(thread,&temp) !=0)  
   {
      SDL_PollEvent(&event);
      if(event.type == SDL_QUIT)
         fin(var,1);
      SDL_Delay(20);
   }

   /*reception du jeton de depart*/
   if(recv(var->sock_client, &deb, sizeof(long),0) == -1)
   {
      fprintf(var->log_erreur,"Erreur reception deb\n");
      fclose(var->log_erreur);
      exit(EXIT_FAILURE);
   }
   deb = ntohl(deb);

   affich_score(var,0);
   affich_score(var,1);
   
   while(var->remain_bat_cpu != 0 && var->remain_bat_hum != 0)
   {

      if(deb == 1)
      {
         pthread_create(&thread, NULL,(void *)recept_coord,var);
         /*gestion du rafraichissement SDL pas d'actualité dans cette version*/
         message_box(var,"tir du joueur adverse");
         while(pthread_join(thread,&temp) !=0)  
         {
            SDL_PollEvent(&event);
            if(event.type == SDL_QUIT)
               fin(var,1);
            SDL_Delay(20);
         }
      }

      message_box(var,"A vous de tirer !");
      var->z = tir_humain(var);
      envoi_coord(var);

      pthread_create(&thread, NULL,(void *)recept_rep,var);
      /*gestion du rafraichissement SDL pas d'actualité dans cette version*/
      message_box(var,"reponse joueur adverse");
      while(pthread_join(thread,&temp) !=0)  
      {
         SDL_PollEvent(&event);
         if(event.type == SDL_QUIT)
            fin(var,1);
         SDL_Delay(20);
      }
      
      if(deb != 1)
      {
         pthread_create(&thread, NULL,(void *)recept_coord,var);
         /*gestion du rafraichissement SDL pas d'actualité dans cette version*/
         message_box(var,"tir du joueur adverse \n");
         while(pthread_join(thread,&temp) !=0)  
         {
            SDL_PollEvent(&event);
            if(event.type == SDL_QUIT)
            fin(var,1);
            SDL_Delay(20);
         }
      }
   }
   if(var->remain_bat_cpu == 0)
   {
      message_box(var,"Bravo vous avez gagne(e)");
      FSOUND_PlaySound(FSOUND_FREE,var->gagne);
   }
   else
   {
      message_box(var,"Dommage vous avez perdu(e)");
      FSOUND_PlaySound(FSOUND_FREE,var->perdu);
   }
   
   SDL_Delay(3000);
   message_box(var,"le menu s'affichera dans 5s");
   SDL_Delay(5000);
   
   close_sock(var,0);
   fin(var,0);
   #ifdef __WIN32__
      WSACleanup();
   #endif

   return(EXIT_SUCCESS);
}
コード例 #17
0
/**
 * 終了処理
 *
 * @return なし
 */
void
cut_teardown(void)
{
    close_sock(&ssock);
    close_sock(&csock);
}
コード例 #18
0
static int __init init_fbaodv_module(void) {
	char *tmp_str = NULL;
	inet_aton("0.0.0.0", &g_null_ip);

#ifdef DTN_HELLO
	//inet_aton("192.168.2.2",&dtn_hello_ip);
	inet_aton("127.127.127.127",&dtn_hello_ip);
	//printk("%s",inet_ntoa(dtn_hello_ip));
	longitude = 0;
	latitude = 0;
#endif




	if (mesh_dev==NULL)
	{
		printk("You need to specify the mesh network device ie:\n");
		printk("    insmod fbaodv_protocol mesh_dev=wlan0    \n");
		return(-1);
	}
	
	strcpy(g_aodv_dev, mesh_dev);
	
	if(aodv_gateway) {
		g_aodv_gateway = (u_int8_t)aodv_gateway;
		printk("\n\nSet as AODV-ST gateway\n");
	} else
	g_aodv_gateway = 0;

	if (network_ip == NULL) {
		printk("You need to specify aodv network ip range, ie: \n");
		printk("network_ip=192.168.0.12/255.255.255.0\n");
		return(-1);
	}
	inet_aton("255.255.255.255",&g_broadcast_ip);
	printk("Miguel Catalan Cid\nImplementation built on top of aodv-st by Krishna Ramachandran, UC Santa Barbara\n");
	printk("---------------------------------------------\n");

	
	/*ROUTING METRICS*/
	if (routing_metric == NULL || strcmp(routing_metric, "HOPS") == 0){
		g_routing_metric = HOPS;
		printk("Hop count routing\n\n");
	}
	//delete the metrics of ETT & WCIM
	
	if (network_ip!=NULL)
	{
		tmp_str = strchr(network_ip,'/');
		if (tmp_str)
		{	(*tmp_str)='\0';
			tmp_str++;
			printk("* Network IP - %s/%s\n", network_ip, tmp_str);
			inet_aton(network_ip, &g_mesh_ip);
			inet_aton(tmp_str, &g_mesh_netmask);
		}
	}
		
	
	if (init_packet_queue() < 0) {
			printk("Netlink queue error!!!\n");
			printk("Shutdown complete!\n");
			return(-1);
	}
	
#ifdef BLACKLIST
	if (aodv_blacksize) {
		printk("AODV BLACK LIST:\n");
		int k;
		for (k = 0; k < aodv_blacksize; k++) {
			printk("           %s\n", aodv_blacklist[k]);
			inet_aton(aodv_blacklist[k], &aodv_blacklist_ip[k]);
		}
	}
	if (dtn_blacksize) {
		printk("DTN BLACK LIST:\n");
		int k;
		for (k = 0; k < dtn_blacksize; k++) {
			printk("           %s\n", dtn_blacklist[k]);
			inet_aton(dtn_blacklist[k], &dtn_blacklist_ip[k]);
		}
	}
#endif



	init_aodv_route_table();
#ifdef RECOVERYPATH
        ///////////brk_list//////////////
	init_brk_list();
#endif

	init_task_queue();
	init_timer_queue();
	init_aodv_neigh_list();
	init_aodv_neigh_list_2h();
	init_src_list();
	init_gw_list();
	init_flow_type_table();


	printk("\n*Initialicing mesh device  - %s\n", mesh_dev);	
	extern aodv_dev* net_dev_list;
	net_dev_list = NULL;
	dev_num = 0;
	//if (init_aodv_dev(mesh_dev))
//	if(init_net_dev(mesh_dev))
//		goto out1;
//printk("---------------init adhoc0-------------------\n");

//#ifdef DEBUGC
     //try to get net list when initialling.
	struct net_device *pdev;
	struct list_head *dev_base = &(init_net.dev_base_head);
	//struct list_head *phead;
	struct in_device *ip;
	struct in_ifaddr *ifaddr;
	//int i ;
	list_for_each_entry(pdev,dev_base,dev_list)//list_for_each(phead,&dev_base)
	{
		if( ((pdev->name[0]=='e')&&(pdev->name[1]=='t')&&(pdev->name[2]=='h')) ||
			(strcmp(pdev->name,"adhoc0")==0) )
		{
			char dev_name[IFNAMSIZ];
			strcpy(dev_name,pdev->name);
			if(init_net_dev(dev_name))
				continue;
			dev_num ++;
			printk("------------------------------------\ndev->name:%s\ndev->ifindex:%d\ndev->type:%d\ndev->dev_id:%d\n----------------------------------\n",pdev->name,pdev->ifindex,pdev->type,pdev->dev_id);
			
			
		}

		/*
		//i =0;
		ip = pdev->ip_ptr;
		ifaddr = ip->ifa_list;
		while(ifaddr){
			printk("-------ip:%s---------\n",inet_ntoa(ifaddr->ifa_address));
			ifaddr = ifaddr->ifa_next;
		//	printk("=========iiiiiii:%d========\n",i++);
		}
		//printk("ip:%s\n",inet_ntoa(ip->ifa_list->ifa_address));
		
		if(strcmp(pdev->name,"eth0")==0){
			char eth_dev[8];
			printk("=========iiiiiii========\n");
			strcpy(eth_dev,pdev->name);
			printk("=========istgreii========\n");
			init_eth_dev(eth_dev);
		}
		*/
	}


//#endif
	startup_aodv();

	if (g_aodv_gateway) {
		printk("initiating st_rreq dissemination\n");
		insert_timer_simple(TASK_ST, HELLO_INTERVAL, g_mesh_ip); // start first st_rreq immediately
	}

	//MCC 21/07/2008- UPDATE TIMER ahora en insert_timer
	insert_timer_simple(TASK_HELLO, HELLO_INTERVAL,g_mesh_ip );
	insert_timer_simple(TASK_GW_CLEANUP, ACTIVE_GWROUTE_TIMEOUT, g_mesh_ip);
	insert_timer_simple(TASK_CLEANUP, HELLO_INTERVAL+HELLO_INTERVAL/2, g_mesh_ip);

	update_timer_queue();

	aodv_dir = proc_mkdir("fbaodv",NULL);
	if (aodv_dir == NULL) {
		goto out2;
	}
///*
#ifdef KERNEL2_6_26
	aodv_dir->owner = THIS_MODULE;
#endif

	route_table_proc=create_proc_read_entry("routes", 0, aodv_dir, read_route_table_proc, NULL);
#ifdef KERNEL2_6_26
	route_table_proc->owner=THIS_MODULE;
#endif

	if (route_table_proc == NULL) goto out2;

	neigh_proc=create_proc_read_entry("neigh", 0, aodv_dir, read_neigh_proc, NULL);
	if (neigh_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	neigh_proc->owner=THIS_MODULE;
#endif

	timers_proc=create_proc_read_entry("timers", 0, aodv_dir, read_timer_queue_proc, NULL);
	if (timers_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	timers_proc->owner=THIS_MODULE;
#endif

	reliability_proc=create_proc_read_entry("reliability", 0, aodv_dir, read_rel_list_proc, NULL);
	if (reliability_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	reliability_proc->owner=THIS_MODULE;
#endif

	ett_proc=create_proc_read_entry("bw_estimation", 0, aodv_dir, read_ett_list_proc, NULL);
	if (ett_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	ett_proc->owner=THIS_MODULE;
#endif

	sources_proc=create_proc_read_entry("sources", 0, aodv_dir, read_src_list_proc, NULL);
	if (sources_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	sources_proc->owner=THIS_MODULE;
#endif

	node_load_proc=create_proc_read_entry("node_load", 0, aodv_dir, read_node_load_proc, NULL);
	if (node_load_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	node_load_proc->owner=THIS_MODULE;
#endif

	gw_proc=create_proc_read_entry("gateways", 0, aodv_dir, read_gw_list, NULL);
	if (gw_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	gw_proc->owner=THIS_MODULE;
#endif

	tos_proc=create_proc_read_entry("tos_available", 0, aodv_dir, read_flow_type_table_proc, NULL);
	if (ett_proc == NULL) goto out2;
#ifdef KERNEL2_6_26
	ett_proc->owner=THIS_MODULE;
#endif
//*/
	//netfilter stuff
	// input hook
	input_filter.list.next = NULL;
	input_filter.list.prev = NULL;
	input_filter.hook = input_handler;
	input_filter.pf = PF_INET; // IPv4
	input_filter.hooknum = NF_INET_LOCAL_IN;

	//MCC- output hook
	output_filter.list.next = NULL;
	output_filter.list.prev = NULL;
	output_filter.hook = output_handler;
	output_filter.pf = PF_INET; // IPv4
	output_filter.hooknum = NF_INET_POST_ROUTING;

	nf_register_hook(&output_filter);
	nf_register_hook(&input_filter);

	printk("\n\n****FBAODV_PROTO module initialization complete****\n\n");
	return 0;

	out1:
	close_sock();

	del_timer(&aodv_timer);
	printk("Removed timer...\n");

	cleanup_packet_queue();
	printk("Cleaned up AODV Queues...\n");

	if (aodv_route_table != NULL)
	cleanup_aodv_route_table();

	flush_src_list();
	printk("Cleaned up Route and Rule Tables...\n");

	printk("Shutdown complete!\n");

	return(-1);

	out2:

	remove_proc_entry("fbaodv/routes",NULL);
	remove_proc_entry("fbaodv/timers",NULL);
	remove_proc_entry("fbaodv/neigh",NULL);
	remove_proc_entry("fbaodv/reliability", NULL);
	remove_proc_entry("fbaodv/sources", NULL);
	remove_proc_entry("fbaodv/node_load", NULL);

	remove_proc_entry("fbaodv/gateways", NULL);

	remove_proc_entry("fbaodv/user_gateway", NULL);
	remove_proc_entry("fbaodv/gateways_assigned", NULL);
	remove_proc_entry("fbaodv/bw_estimation", NULL);
	remove_proc_entry("fbaodv/tos_available", NULL);
	remove_proc_entry("fbaodv", NULL);

	printk("\n\nShutting down...\n");

	printk("Unregistered NetFilter hooks...\n");

	close_sock();
	printk("Closed sockets...\n");

	del_timer(&aodv_timer);
	printk("Removed timer...\n");

	kill_aodv();
	printk("Killed router thread...\n");

	cleanup_task_queue();
	cleanup_packet_queue();
	printk("Cleaned up AODV Queues...\n");

	cleanup_neigh_routes();
	cleanup_aodv_route_table();
	flush_src_list();
	printk("Cleaned up Route and Rule Tables...\n");

	//Eliminando listas
	delete_aodv_neigh_list();
	delete_aodv_neigh_list_2h();
	delete_gw_list();
	flush_flow_type_table();
	printk("Cleaned up Lists...\n");

	printk("Shutdown complete!\n");

	return(-1);
}
コード例 #19
0
ファイル: Rsock.c プロジェクト: radfordneal/pqR
void in_Rsockclose(int *sockp)
{
    *sockp = close_sock(*sockp);
}
コード例 #20
0
ファイル: nub.c プロジェクト: threader/Mac-On-Linux
static void
handle_msg( mol_dgram_t *dg )
{
	cmd_entry_t *ce = sv.cmd_root;
	int i, val;
	
	switch( dg->what ) {
	case kMDG_connect:
		printm("Debugger attached\n");
		sv.dbg_attached = 1;
		send_dgram( sv.sock, kMDG_connect );
		send_mregs();
		send_dgram( sv.sock, kMDG_refresh_debugger );

		/* send debugger commands */
		for( ce=sv.cmd_root; ce; ce=ce->next ) {
			int s = strlen( ce->cmdname ) + 1;
			int t = strlen( ce->help ) + 1;
			char *b = malloc( s + t );
			strcpy( b, ce->cmdname );
			strcpy( b+s, ce->help );
			send_dgram_buf2( sv.sock, kMDG_dbg_cmd, b, s+t, s, -1 /*dummy*/ );
			free( b );
		}
		break;

	case kMDG_disconnect:
		sv.dbg_attached = 0;
		close_sock();
		printm("Debugger detached\n");
		break;

	case kMDG_mregs:
		send_mregs();
		break;

	case kMDG_write_mregs:
		receive_mregs( (mac_regs_t*)dg->data );
		break;

	case kMDG_read_dpage: { /* ea, context, data_access */
		char buf[0x2000];

		dg->p0 &= ~0xfff;
		restore_breakpoints();
		for( i=0; i<2; i++ ) {
			char *lvptr;
			if( ea_to_lvptr( dg->p0 + i*0x1000, dg->p1, &lvptr, dg->p2 ) )
				memset( buf+i*0x1000, 0xDE, 0x1000 );
			else
				memcpy( buf+i*0x1000, lvptr, 0x1000 );
		}
		setup_breakpoints();
		send_dgram_buf( sv.sock, kMDG_dpage_data, buf, 0x2000 );
		break;
	}

	case kMDG_in_ppc_mode:	/* flag */
		sv.in_ppc_mode = dg->p0;
		break;

	case kMDG_debug_action: /* action (go, single-step, etc.) */
		debug_action( dg->p0 );
		break;

	case kMDG_add_breakpoint: /* addr, flags, data */
		add_breakpoint( dg->p0, dg->p1, dg->p2 );
		break;

	case kMDG_is_breakpoint: { /* mvptr */ 
		char breakbuf[ BREAK_BUF_SIZE ];
		for(i=0; i<BREAK_BUF_SIZE; i++ ){
			if( !is_breakpoint( dg->p0 + i*4, &breakbuf[i] ) )
				breakbuf[i] = 0;
		}
		send_dgram_buf1( sv.sock, kMDG_is_breakpoint, breakbuf, BREAK_BUF_SIZE, dg->p0 );
		break;
	}
	
	case kMDG_dbg_cmd:
		val = do_dbg_cmd( (remote_cmd_t*)dg->data );
		send_dgram1( sv.sock, kMDG_result, val );
		break;

	default:
		printm("Unknown dbg-message %d received\n", dg->what );
		break;
	}
}
コード例 #21
0
static int read_sock(void *buffer, int count)
{
	int result = 0, nread = 0;
	int total_time = 0, selret;

	if (winbindd_fd == -1) {
		return -1;
	}

	/* Read data from socket */
	while(nread < count) {
		struct timeval tv;
		fd_set r_fds;
		
		/* Catch pipe close on other end by checking if a read()
		   call would not block by calling select(). */

		FD_ZERO(&r_fds);
		FD_SET(winbindd_fd, &r_fds);
		ZERO_STRUCT(tv);
		/* Wait for 5 seconds for a reply. May need to parameterise this... */
		tv.tv_sec = 5;

		if ((selret = select(winbindd_fd + 1, &r_fds, NULL, NULL, &tv)) == -1) {
			close_sock();
			return -1;                   /* Select error */
		}
		
		if (selret == 0) {
			/* Not ready for read yet... */
			if (total_time >= 30) {
				/* Timeout */
				close_sock();
				return -1;
			}
			total_time += 5;
			continue;
		}

		if (FD_ISSET(winbindd_fd, &r_fds)) {
			
			/* Do the Read */
			
			result = read(winbindd_fd, (char *)buffer + nread, 
			      count - nread);
			
			if ((result == -1) || (result == 0)) {
				
				/* Read failed.  I think the only useful thing we
				   can do here is just return -1 and fail since the
				   transaction has failed half way through. */
			
				close_sock();
				return -1;
			}
			
			nread += result;
			
		}
	}
	
	return result;
}
コード例 #22
0
ファイル: jeu2p.c プロジェクト: ulricheza/Isima
int mode_local_serveur()
{
   /*declaration des variables*/
   var_game_t * var;
   void * temp;
   long ready = 1;
   long deb;
   pthread_t thread;


   /*ouverture du module socket sous windows*/
   #ifdef __WIN32__
      WSADATA WSAData;
      WSAStartup(MAKEWORD(2,2), &WSAData);
   #endif


   /*allocation des ressources*/
   init_var(0,&var);

   /*creation de la socket*/
   var->sock_serveur=socket(AF_INET, SOCK_STREAM, 0);

   /*configuration de la connexion*/
   var->sin_serveur.sin_addr.s_addr = htonl(INADDR_ANY);
   var->sin_serveur.sin_family = AF_INET;
   var->sin_serveur.sin_port = htons(PORT);

   if( bind(var->sock_serveur, (SOCKADDR*)&(var->sin_serveur), sizeof(var->sin_serveur)) < 0)
   {
      fprintf(var->log_erreur,"erreur lors du bind serveur \n");
      fclose(var->log_erreur);
      exit(EXIT_FAILURE);
   }

   if(listen(var->sock_serveur,5) == -1)
   {
      fprintf(var->log_erreur,"erreur lors du listen \n");
      fclose(var->log_erreur);
      exit(EXIT_FAILURE);
   }

   deb = rand()%2;


   pthread_create(&thread, NULL,(void *)accept_connect,var);
   /*gestion du rafraichissement SDL pas d'actualité dans cette version*/
   printf("attente de connexion du joueur adverse\n");
   pthread_join(thread,&temp);

   pthread_create(&thread, NULL,(void *)recept_rdy,var);
   printf("-----------------------------------------------------\n");
   printf("placement de vos bateaux\n");
   placement_hum(var);

   ready = htonl(1);
   if(send(var->sock_client,&ready,sizeof(long),0) == -1)
   {
      fprintf(var->log_erreur,"Erreur envoie ready\n");
      fclose(var->log_erreur);
      exit(EXIT_FAILURE);
   }
   printf("attente placement des bateaux du joueur adverse \n");
   pthread_join(thread,&temp);

   deb = htonl(deb);
   if(send(var->sock_client,&deb,sizeof(long),0) == -1)
   {
       fprintf(var->log_erreur,"Erreur envoie deb\n");
       fclose(var->log_erreur);
       exit(EXIT_FAILURE);
   }
   deb = ntohl(deb);
   while(var->remain_bat_cpu != 0 && var->remain_bat_hum != 0)
   {
      clear
      printf("-----------------------------------------------------\n");
      printf("-----------------------------------------------------\n");
      printf("votre matrice cible \n");
      affic_mat(var->mer_cible_hum,0);
      printf("-----------------------------------------------------\n");
      printf("-----------------------------------------------------\n");
      printf("votre matrice home\n");
      affic_mat(var->mer_home_hum,1);
      printf("-----------------------------------------------------\n");
      printf("-----------------------------------------------------\n");

      if(deb == 1)
      {
         printf("A vous de tirer !\n");
         var->z = tir_humain(var);
         envoi_coord(var);

         pthread_create(&thread, NULL,(void *)recept_rep,var);
         /*gestion du rafraichissement SDL pas d'actualité dans cette version*/
         printf("attente reponse joueur adverse\n");
         pthread_join(thread,&temp);

      }

      pthread_create(&thread, NULL,(void *)recept_coord,var);
      /*gestion du rafraichissement SDL pas d'actualité dans cette version*/
      printf("attente du tir du joueur adverse \n");
      pthread_join(thread,&temp);

      if(deb != 1)
      {
         printf("A vous de tirer !\n");
         var->z = tir_humain(var);
         envoi_coord(var);

         pthread_create(&thread, NULL,(void *)recept_rep,var);
         /*gestion du rafraichissement SDL pas d'actualité dans cette version*/
         printf("attente reponse joueur adverse\n");
         pthread_join(thread,&temp);

      }
   }
   if(var->remain_bat_cpu == 0)
      printf("Bravo vous avez gagne!!!\n");
   else
      printf("dommage vous avez perdu \n");

   close_sock(var, 1);

   #ifdef __WIN32__
      WSACleanup();
   #endif

   free(var->mer_home_cpu);
   free(var->mer_home_hum);
   free(var->mer_cible_cpu);
   free(var->mer_cible_hum);
   fclose(var->log_erreur);
   free(var);
   return(1);
}