예제 #1
0
파일: bitmd.c 프로젝트: ddenchev/bit-md
int main(int argc, char **argv) {
    
    // Test argument count
    if (argc != 2) {
        printf("usage: bitmd <file.torrent>");
        exit(0);
    } 
    
    printf("++++ starting bitmd ++++\n");
    printf("++++ parsing ++++ \n%s \n", argv[1]);
    struct Tor *tor = parse_torrent(argv[1]);
    print_tor(tor);
    
    printf("++++ announce ++++ \n");
    
    struct Buffer *tracker_response = (struct Buffer *)malloc_eoe(sizeof(struct Buffer));
    int res;
    while (res != 1) {
        res = announce(tor, tracker_response);
    }
    
    printf("++++ tracker responds ++++ \n");
    print_nchars(tracker_response->cnt, tracker_response->size);
    printf("\n");

    printf("++++ peers found ++++ \n");
    struct Bcont *parsed = b_decode(tracker_response);
    struct Peer *peers = parse_peers(parsed->cnt);
    print_peers(peers);

    printf("+++ connecting to peer ++++ \n");
    connect_to_peer(peers);

    return 0;
}
예제 #2
0
파일: client.c 프로젝트: krunt/projects
int main() {
    int fd;
    if ((fd = connect_to_peer("127.0.0.1", PORT)) == -1)
        return -1;
    struct packet_header header = { 0, htonl(4) };
    if (write(fd, (void *)&header, sizeof(header)) != sizeof(header)
            || write(fd, (void *)"hi!", 4) != 4) {
        return -2;
    }
    return 0;
}
예제 #3
0
파일: network.c 프로젝트: jhosen/elevator
void* listen_udp_broadcast(){

	int sock;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		perror("socket");
		exit(1);
	}

	struct sockaddr_in saSocket;
	memset(&saSocket, 0, sizeof(saSocket));
	saSocket.sin_family      = AF_INET;
	saSocket.sin_addr.s_addr = htonl(INADDR_ANY);
	saSocket.sin_port        = htons(UDP_LISTEN_PORT);

	int opt = 1;
	setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char*)&opt,sizeof(opt));

	if (bind(sock, (struct sockaddr *) &saSocket, sizeof(saSocket)) != 0)
	{
		perror("Bind");
	}
	struct sockaddr_in their_addr; // connector's address information
	int addr_len =  sizeof(their_addr);
	char messager[50];

	while(1) {
		if (recvfrom(sock, messager, 50 , 0, (struct sockaddr *)&their_addr, &addr_len) == -1) {
			perror("recvfrom");
			exit(1);
		}
		// Check if ip is myself or already connected.
		char * peer_ip = inet_ntoa(their_addr.sin_addr);
		struct peer newpeer = peer_object(0, their_addr.sin_addr.s_addr);
		if(!nw_find(newpeer)){
			if( connect_to_peer(their_addr.sin_addr.s_addr)==-1){
//				perror("err: connect_to_peer.");
			}
			else{
                nw_setevent(CONNECTION);
			}
		}
		else{
			NULL;
		}
	}
}
예제 #4
0
// Connect called by client with inbuilt support for retries
bool SocketChannel::Connect(string peer) {
  bool retry = true;
  int attempts = 0;
  int client_fd = 0;
  vector<string> name_port;
  boost::split(name_port, peer, boost::is_any_of(":"));
  int backoff = 1;
  while (retry && (attempts < 5)) {
    retry = false;
    if (client_fd == 0) {
      string peername = name_port.at(0).c_str();;
      string portnumber;
      if (name_port.size() > 1) 
        portnumber = name_port.at(1).c_str();
      
      LOG(INFO) << "Trying to connect with ...["
                << peername <<":"
                << portnumber << "]";
      client_fd = connect_to_peer(peername,
                                  portnumber);
      if (!client_fd) {
        retry = true;
      } else {
        // On success update the local peer's
        // SocketChannel with the connection details
        this->client_fd = client_fd;
        this->peer_name = name_port.at(0);
        this->port_no = atoi(name_port.at(1).c_str());
      }
    }
    attempts++;
    // Retry after 10 secs
    usleep(backoff*1000000);
    backoff = backoff * 2;
  }
  if (retry)
    return false;
  
  return true;
}
예제 #5
0
파일: dc.c 프로젝트: heratgandhi/openssl
static int wait_for_master(struct tcpr_ip4 *state)
{
	int s;
	char buffer[1];
	struct sockaddr_in masteraddr;

	if (!state->address)
		return 0;

	masteraddr.sin_family = AF_INET;
	masteraddr.sin_addr.s_addr = state->address;
	masteraddr.sin_port = htons(masterport);

	s = connect_to_peer(&masteraddr, 0);
	if (s < 0)
		return 1;

	while (recv(s, buffer, sizeof(buffer), 0) > 0) ;

	close(s);
	return 1;
}
예제 #6
0
int main( int argc, char** argv )
{
   // parse command-line options
   boost::program_options::options_description option_config("Allowed options");
   option_config.add_options()("data-dir", boost::program_options::value<std::string>(), "configuration data directory")
                              ("help", "display this help message")
                              ("p2p", "enable p2p mode")
                              ("port", boost::program_options::value<uint16_t>(), "set port to listen on")
                              ("connect-to", boost::program_options::value<std::string>(), "set remote host to connect to")
                              ("server", "enable JSON-RPC server")
                              ("rpcuser", boost::program_options::value<std::string>(), "username for JSON-RPC")
                              ("rpcpassword", boost::program_options::value<std::string>(), "password for JSON-RPC")
                              ("rpcport", boost::program_options::value<uint16_t>(), "port to listen for JSON-RPC connections")
                              ("httpport", boost::program_options::value<uint16_t>(), "port to listen for HTTP JSON-RPC connections")
                              ("trustee-private-key", boost::program_options::value<std::string>(), "act as a trustee using the given private key")
                              ("trustee-address", boost::program_options::value<std::string>(), "trust the given BTS address to generate blocks")
                              ("genesis-json", boost::program_options::value<std::string>(), "generate a genesis block with the given json file (only for testing, only accepted when the blockchain is empty)");

   boost::program_options::positional_options_description positional_config;
   positional_config.add("data-dir", 1);

   boost::program_options::variables_map option_variables;
   try
   {
     boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
       options(option_config).positional(positional_config).run(), option_variables);
     boost::program_options::notify(option_variables);
   }
   catch (boost::program_options::error&)
   {
     std::cerr << "Error parsing command-line options\n\n";
     std::cerr << option_config << "\n";
     return 1;
   }

   if (option_variables.count("help"))
   {
     std::cout << option_config << "\n";
     return 0;
   }
   
   bool p2p_mode = option_variables.count("p2p") != 0;

   try {
      print_banner();
      fc::path datadir = get_data_dir(option_variables);
      ::configure_logging(datadir);

      auto cfg   = load_config(datadir);
      auto chain = load_and_configure_chain_database(datadir, option_variables);
      auto wall  = std::make_shared<bts::wallet::wallet>();
      wall->set_data_directory( datadir );

      auto c = std::make_shared<bts::client::client>(p2p_mode);
      c->set_chain( chain );
      c->set_wallet( wall );

      if (option_variables.count("trustee-private-key"))
      {
         auto key = fc::variant(option_variables["trustee-private-key"].as<std::string>()).as<fc::ecc::private_key>();
         c->run_trustee(key);
      }
      else if( fc::exists( "trustee.key" ) )
      {
         auto key = fc::json::from_file( "trustee.key" ).as<fc::ecc::private_key>();
         c->run_trustee(key);
      }

      bts::rpc::rpc_server_ptr rpc_server = std::make_shared<bts::rpc::rpc_server>();
      rpc_server->set_client(c);


      if( option_variables.count("server") )
      {
        // the user wants us to launch the RPC server.
        // First, override any config parameters they 
        bts::rpc::rpc_server::config rpc_config(cfg.rpc);
        if (option_variables.count("rpcuser"))
          rpc_config.rpc_user = option_variables["rpcuser"].as<std::string>();
        if (option_variables.count("rpcpassword"))
          rpc_config.rpc_password = option_variables["rpcpassword"].as<std::string>();
        // for now, force binding to localhost only
        if (option_variables.count("rpcport"))
          rpc_config.rpc_endpoint = fc::ip::endpoint(fc::ip::address("127.0.0.1"), option_variables["rpcport"].as<uint16_t>());
        if (option_variables.count("httpport"))
          rpc_config.httpd_endpoint = fc::ip::endpoint(fc::ip::address("127.0.0.1"), option_variables["httpport"].as<uint16_t>());
        std::cerr<<"starting json rpc server on "<< std::string( rpc_config.rpc_endpoint ) <<"\n";
        std::cerr<<"starting http json rpc server on "<< std::string( rpc_config.httpd_endpoint ) <<"\n";
        rpc_server->configure(rpc_config);
      }
      
      if (p2p_mode)
      {
        c->configure( datadir );
        if (option_variables.count("port"))
          c->listen_on_port(option_variables["port"].as<uint16_t>());
        c->connect_to_p2p_network();
        if (option_variables.count("connect-to"))
          c->connect_to_peer(option_variables["connect-to"].as<std::string>());
      }
      else
      {
        if (option_variables.count("connect-to"))
          c->add_node(option_variables["connect-to"].as<std::string>());
        else
           c->add_node( "127.0.0.1:4569" );
      }

      auto cli = std::make_shared<bts::cli::cli>( c, rpc_server );
      cli->wait();

   } 
   catch ( const fc::exception& e ) 
   {
      wlog( "${e}", ("e", e.to_detail_string() ) );
   }
   return 0;
}
예제 #7
0
파일: dc.c 프로젝트: heratgandhi/openssl
int main(int argc, char **argv)
{
	struct sockaddr_in pulladdr;
	struct sockaddr_in pushaddr;
	int pullsock;
	int pushsock;
	int err;
	int recovering = 0;
	struct arguments args;
	struct log *log = NULL;
#ifdef TCPR
	int tcprsock;
	struct tcpr_ip4 state;
#endif

	//OpenSSL
	SSL_load_error_strings();
	ERR_load_BIO_strings();
	ERR_load_SSL_strings();
	SSL_library_init();
	OpenSSL_add_all_algorithms();
	/////////

	memset(&args, 0, sizeof(args));
	parse_arguments(&args, argc, argv);

	err = resolve_address(&pulladdr, args.pullhost, args.pullport);
	if (err) {
		fprintf(stderr, "%s:%s: %s\n", args.pullhost, args.pullport,
			gai_strerror(err));
		exit(EXIT_FAILURE);
	}

	err = resolve_address(&pushaddr, args.pushhost, args.pushport);
	if (err) {
		fprintf(stderr, "%s:%s: %s\n", args.pushhost, args.pushport,
			gai_strerror(err));
		exit(EXIT_FAILURE);
	}

	if (!args.port)
		args.port = 10000;

#ifdef TCPR
	printf("Connecting to TCPR.\n");
	tcprsock = connect_to_tcpr(&pulladdr);
	if (tcprsock < 0) {
		perror("Connecting to TCPR");
		exit(EXIT_FAILURE);
	}
	
	pulladdr1 = pulladdr;
	port1 = args.port;
	tcpr_sock = tcprsock;
	
	printf("Waiting for existing master, if any.\n");
	if (get_tcpr_state(&state, tcprsock, &pulladdr, args.port) < 0) {
		perror("Getting TCPR state");
		exit(EXIT_FAILURE);
	}
	
	recovering = wait_for_master(&state);
	if (recovering) {
		printf("Recovering from failed master.\n");
		if (claim_tcpr_state(&state, tcprsock, &pulladdr, args.port) < 0) {
			perror("Claiming TCPR state");
			exit(EXIT_FAILURE);
		}
	} else {
		printf("Creating fresh connection.\n");
	}

	handle_slaves();
#endif /* TCPR */
			
	printf("Connecting to data source.\n");
	pullsock = connect_to_peer(&pulladdr, args.port);
	if (pullsock < 0) {
		perror("Connecting to data source");
		exit(EXIT_FAILURE);
	}

	printf("Connecting to data sink.\n");
	pushsock = connect_to_peer(&pushaddr, 0);
	if (pushsock < 0) {
		perror("Connecting to data sink");
		exit(EXIT_FAILURE);
	}
	
	if (args.logprefix) {
		printf("Opening log.\n");
		log = log_start(args.logprefix, args.logbytes, args.logcount);
	}

#ifdef TCPR
	if (get_tcpr_state(&state, tcprsock, &pulladdr, args.port) < 0) {
		perror("Getting TCPR state");
		exit(EXIT_FAILURE);
	}
#endif

	if (!recovering) {
		printf("Sending ID to data source.\n");
		if (send(pullsock, args.id, strlen(args.id), 0) < 0) {
			perror("Sending session ID");
			exit(EXIT_FAILURE);
		}
	}
	
	get_tcpr_state(&state1, tcpr_sock, &pulladdr1, port1);
	get_tcpr_state(&state, tcpr_sock, &pulladdr, args.port);
	
	//BIO_set_callback(sbio,test_write);
	//BIO_set_callback(sbio1,test_write);
	printf("Copying data from source to sink.\n");
#ifdef TCPR
	if (copy_data(&state, log, pullsock, pushsock, tcprsock) < 0) {
#else
	if (copy_data(log, pullsock, pushsock) < 0) {
#endif
		perror("Copying data");
		exit(EXIT_FAILURE);
	}

	printf("Done.\n");
#ifdef TCPR
	close(tcprsock);
#endif
	close(pullsock);
	close(pushsock);
	return EXIT_SUCCESS;
}
예제 #8
0
파일: main.c 프로젝트: PapaMarky/rpm-ostree
int
main (int argc,
      char **argv)
{
  GError *error;
  GOptionContext *opt_context;
  GIOChannel *channel;
  guint name_owner_id = 0;
  gint ret;

  ret = 1;
  loop = NULL;
  opt_context = NULL;

  #if !GLIB_CHECK_VERSION(2,36,0)
  g_type_init ();
  #endif

  /* See glib/gio/gsocket.c */
  signal (SIGPIPE, SIG_IGN);

  /* avoid gvfs and gsettings: https://bugzilla.gnome.org/show_bug.cgi?id=767183 */
  g_assert (g_setenv ("GIO_USE_VFS", "local", TRUE));
  g_assert (g_setenv ("GSETTINGS_BACKEND", "memory", TRUE));

  opt_context = g_option_context_new ("rpm-ostreed -- rpm-ostree daemon");
  g_option_context_add_main_entries (opt_context, opt_entries, NULL);
  error = NULL;
  if (!g_option_context_parse (opt_context, &argc, &argv, &error))
    {
      g_printerr ("Error parsing options: %s\n", error->message);
      g_error_free (error);
      goto out;
    }

  if (opt_debug)
    {
      g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG | G_LOG_LEVEL_INFO, on_log_debug, NULL);
      g_log_set_always_fatal (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING);

      /* When in debug mode (often testing) we exit when stdin closes */
      channel = g_io_channel_unix_new (0);
      g_io_add_watch (channel, G_IO_HUP, on_stdin_close, NULL);
      g_io_channel_unref (channel);
    }
  else
    {
      /* When not in debug mode, send all logging to syslog */
      g_log_set_default_handler (on_log_handler, NULL);
    }

  g_info ("rpm-ostreed starting");

  loop = g_main_loop_new (NULL, FALSE);

  g_unix_signal_add (SIGINT, on_sigint, NULL);
  g_unix_signal_add (SIGTERM, on_sigint, NULL);

  if (service_dbus_fd == -1)
    {
      GBusType bus_type;

      /* To facilitate testing, use whichever message bus activated
       * this process.  If the process was started directly, assume
       * the system bus. */
      if (g_getenv ("DBUS_STARTER_BUS_TYPE") != NULL)
        bus_type = G_BUS_TYPE_STARTER;
      else if (g_getenv ("RPMOSTREE_USE_SESSION_BUS") != NULL)
        bus_type = G_BUS_TYPE_SESSION;
      else
        bus_type = G_BUS_TYPE_SYSTEM;

      name_owner_id = g_bus_own_name (bus_type,
                                      DBUS_NAME,
                                      G_BUS_NAME_OWNER_FLAGS_NONE,
                                      on_bus_acquired,
                                      on_name_acquired,
                                      on_name_lost,
                                      NULL, (GDestroyNotify) NULL);
    }
  else if (!connect_to_peer (service_dbus_fd))
    {
      ret = 1;
      goto out;
    }

  g_debug ("Entering main event loop");

  g_main_loop_run (loop);

  if (name_owner_id > 0)
    {
      g_bus_unown_name (name_owner_id);
      name_owner_id = 0;
    }

  g_clear_object (&rpm_ostree_daemon);

  ret = 0;

out:
  if (loop != NULL)
    g_main_loop_unref (loop);

  if (opt_context != NULL)
    g_option_context_free (opt_context);

  g_info ("rpm-ostreed exiting");

  return ret;
}
예제 #9
0
int trace_main(char *hostIp, int portNum, char *imsi, int outflag, char *path)
{
	int				fd_stdin, peersock, maxfd, status, readsize;
	int				selStatus;
	fd_set			fdset_Read;
	FILE			*fp = NULL;
	char			buff[128];
	struct timeval	timeout;

	fd_stdin = fileno(stdin);

	peersock = connect_to_peer(hostIp, portNum);
	if(peersock < 0)
		return 1;

	if(outflag){
		fp = open_trace_file(path, imsi);
		if(!fp)
			exit(1);
	}

	timeout.tv_sec = 0;
	timeout.tv_usec = 100;

	while(1){
		FD_ZERO(&fdset_Read);
		FD_SET(fd_stdin, &fdset_Read);
		FD_SET(peersock, &fdset_Read);
		maxfd = (fd_stdin >= peersock)?fd_stdin:peersock;
		maxfd += 1;

		selStatus = select(maxfd, &fdset_Read, NULL, NULL, &timeout);
		if(selStatus < 0){
			fprintf(stderr, "[ERROR] select - %s\n", strerror(errno));
		}else if(selStatus > 0){
			if(FD_ISSET(fd_stdin, &fdset_Read)){
				memset(buff, 0x00, sizeof(buff));
				read_from_fd(fd_stdin, buff, 1);
				if(buff[0] == 'q' || buff[0] == 'Q'){
					close(peersock);
					fclose(fp);
					return 1;
				}
			}
			if(FD_ISSET(peersock, &fdset_Read)){
				status = read_trace(peersock, fp, imsi);
				if(status < 0){
					// try to reconnect to peer.
					peersock = connect_to_peer(hostIp, portNum);
					if(peersock < 0)
						return 1;
				}
			}
		}
#ifdef DEBUG_1
		else{
			printf(".");
		}
#endif
	}

	return 0;

}