Example #1
0
session_t *net_init(const char *interface, const uint8_t src_ip_addr[],
                    uint16_t src_port, const uint8_t dst_ip_addr[],
                    uint16_t dst_port, protocol_t protocol, int recv_timeout)
{
    session_t *s = malloc(sizeof(session_t));
    if(s == 0)
        return 0;

    s->session_id = hw_init(interface);
    if(s->session_id == -1)
    {
        free(s);
        return 0;
    }

    if(hw_if_addr(s->session_id, interface, s->src_addr) == -1)
    {
        net_free(s);
        return 0;
    }

    memcpy(s->src_ip, src_ip_addr, IP_ADDR_LEN);
    s->port = src_port;
    s->recv_timeout = recv_timeout;

    switch(protocol)
    {
        case TCP_NOCONNECT:
        case TCP:
            s->protocol = IP_PROTOCOL_TCP;
            break;
        case UDP:
            s->protocol = IP_PROTOCOL_UDP;
            break;
        case ICMP:
            s->protocol = IP_PROTOCOL_ICMP;
            break;
        default:
            net_free(s);
            return 0;
    }

    // Save interface name for further use
    s->interface = malloc(strlen(interface) + 1);
    strcpy(s->interface, interface);

    ndp_initialize(interface, src_ip_addr);

    if(protocol == TCP)
        if(tcp_connect(s, dst_ip_addr, dst_port) == 0)
        {
            net_free(s);
            return 0;
        }

    return s;
}
Example #2
0
gboolean sm_connect(StateMachine * sm, const gchar * host,
		    const gchar * port)
{
	if (sm->ses != NULL)
		net_free(&(sm->ses));

	sm->ses = net_new((NetNotifyFunc) net_event, sm);
	log_message(MSG_INFO, _("Connecting to %s, port %s\n"), host,
		    port);
	if (net_connect(sm->ses, host, port))
		return TRUE;

	net_free(&(sm->ses));
	return FALSE;
}
Example #3
0
void net_done(void) {
    struct net_t *net;

    /* Free list of networks */
    if (net_table) {
        for (hash_table_find_first(net_table, (void **)&net); net;
                hash_table_find_next(net_table, (void **)&net)) {
            /* Dump report for network */
            if (net_report_file) net_dump_report(net, net_report_file);

            /* Dump Visualization data in a 'graphplot'
             * compatible file */
            if (net_visual_file) {
                struct net_graph_t *graph;

                graph = net_visual_calc(net);
                net_dump_visual(graph, net_visual_file);
                net_graph_free(graph);
            }
            /* Free network */
            net_free(net);
        }
        hash_table_free(net_table);
    }

    /* Close report file */
    file_close(net_report_file);

    /* Close visualization file */
    file_close(net_visual_file);
}
Example #4
0
void meta_unregister(void)
{
	if (ses != NULL) {
		log_message(MSG_INFO, _("Unregister from meta-server\n"));
		net_free(&ses);
	}
}
Example #5
0
File: ip.c Project: RoXeon/TCPIPv6
static int ip_to_hw(session_t *session, const uint8_t ip_addr[],
                    uint8_t hw_addr[])
{
    // Multicast addr case:
    if(ip_addr[0] == 0xff)
    {
        static uint8_t multicast_addr[] = { 0x33, 0x33, 0x0, 0x0, 0x0, 0x0 };

        // Multicast mapping: http://tools.ietf.org/html/rfc2464#page-4
        memcpy(multicast_addr + 2, ip_addr + IP_ADDR_LEN - 4, 4);
        memcpy(hw_addr, multicast_addr, ETH_ADDR_LEN);

        return 0;
    }

    // Localhost hardwire:
    if(memcmp(ip_addr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1", IP_ADDR_LEN) == 0 ||
       memcmp(ip_addr, session->src_ip, IP_ADDR_LEN) == 0)
    {
        memcpy(hw_addr, session->src_addr, ETH_ADDR_LEN);
        return 0;
    }

    if(ndp_table_lookup(ip_addr, hw_addr))
        return 0;

    session_t *icmp_session = net_init(session->interface, session->src_ip, 0,
                                       0, 0, ICMP, 1000);

    ndp_neighbor_discover_t ndp;
    size_t recv;
    ndp_solicitate_send(icmp_session, ip_addr);

    while( (recv = ndp_advertisement_recv(icmp_session, &ndp) ) > 0)
    {
        if( netb_l( ndp.reserved ) & 1 << 30)
            break;
    }

    if(!recv)
        return -1;

    ndp_option_t option;
    memcpy(option.buffer, ndp.options, recv - NDP_ND_HEADER_LEN);
    if(option.type != NDP_TARGET_LINK_ADDR_OPT || option.len != 1)
    {
        fprintf(stderr, "Error: unsupported option type for NDP protocol: %d "
                        "with len: %d\n", option.type, option.len);
        return -1;
    }

    net_free(icmp_session);

    memcpy(hw_addr, option.body, ETH_ADDR_LEN);

    ndp_table_insert(ip_addr, hw_addr);

    return 0;
}
Example #6
0
void sm_use_fd(StateMachine * sm, gint fd, gboolean do_ping)
{
	if (sm->ses != NULL)
		net_free(&(sm->ses));

	sm->ses = net_new((NetNotifyFunc) net_event, sm);
	net_use_fd(sm->ses, fd, do_ping);
}
Example #7
0
void sig_handler(int n)
{
    alarm_close();
    connmgr_close();
    net_free(&net);
    log_close();
    exit(0);
}
Example #8
0
/*!\brief Add neurons to a network.
 * \param net Pointer to a neural network.
 * \param layer Integer
 * \param neuron Integer
 * \param number Integer
 * \param range Floating point number
 */
void
net_add_neurons (network_t *net, int layer, int neuron, int number,
                 float range)
{
  int l, nu, nl, new_nu, new_nl, *arglist;
  network_t *new_net, *tmp_net;

  assert (net != NULL);
  assert (0 <= layer && layer < net->no_of_layers);
  assert (0 <= neuron);
  assert (number >= 0);
  assert (range >= 0.0);

  /* special case to conveniently add neurons at the end of the layer */
  if (neuron == -1) {
    neuron = net->layer[layer].no_of_neurons;
  }

  /* allocate memory for the new network */
  arglist = calloc (net->no_of_layers, sizeof (int));
  for (l = 0; l < net->no_of_layers; l++) {
    arglist[l] = net->layer[l].no_of_neurons;
  }
  arglist[layer] += number;
  new_net = net_allocate_l (net->no_of_layers, arglist);
  free (arglist);

  /* the new neuron will be connected with small, random weights */
  net_randomize (net, range);

  /* copy the original network's weights and deltas into the new one */
  for (l = 1; l < net->no_of_layers; l++) {
    for (nu = 0; nu < net->layer[l].no_of_neurons; nu++) {
      new_nu = (l == layer) && (nu >= neuron) ? nu + number : nu;
      for (nl = 0; nl <= net->layer[l - 1].no_of_neurons; nl++) {
        new_nl = (l == layer + 1) && (nl >= neuron) ? nl + number : nl;
        new_net->layer[l].neuron[new_nu].weight[new_nl] =
          net->layer[l].neuron[nu].weight[nl];
        new_net->layer[l].neuron[new_nu].delta[new_nl] =
          net->layer[l].neuron[nu].delta[nl];
      }
    }
  }

  /* copy the original network's constants into the new one */
  new_net->momentum = net->momentum;
  new_net->learning_rate = net->learning_rate;

  /* switch new_net and net, so it is possible to keep the same pointer */
  tmp_net = malloc (sizeof (network_t));
  memcpy (tmp_net, new_net, sizeof (network_t));
  memcpy (new_net, net, sizeof (network_t));
  memcpy (net, tmp_net, sizeof (network_t));
  free (tmp_net);

  /* free allocated memory */
  net_free (new_net);
}
Example #9
0
void meta_start_game(void)
{
#ifdef CLOSE_META_AT_START
	if (ses != NULL) {
		net_printf(ses, "begin\n");
		net_free(&ses);
	}
#endif
}
Example #10
0
void
net_resolve_cb(uv_getaddrinfo_t *rv, int stat, net_ai * ai) {
  net_t * net = (net_t*) rv->data;
  err_t err;
  socketPair_t dest;
  char addr[INET6_ADDRSTRLEN];
  int ret;

  if (stat != 0) {
    err = uv_last_error(net->loop);
    if (net->error_cb) {
      net->error_cb(net, err, (char *) uv_strerror(err));
    } else {
      printf("error(%s:%d) %s", net->hostname, net->port, (char *) uv_strerror(err));
      net_free(net);
    }
    return;
  }

  uv_ip4_name((socketPair_t *) ai->ai_addr, addr, INET6_ADDRSTRLEN);
  dest = uv_ip4_addr(addr, net->port);

  /*
   * create tcp instance.
   */
  uv_tcp_init(net->loop, net->handle);
  ret = uv_tcp_connect(net->conn, net->handle, dest, net_connect_cb);
  if (ret != NET_OK) {
    err = uv_last_error(net->loop);
    if (net->error_cb) {
      net->error_cb(net, err, (char *) uv_strerror(err));
    } else {
      printf("error(%s:%d) %s", net->hostname, net->port, (char *) uv_strerror(err));
      net_free(net);
    }
    return;
  }

  /*
   * free
   */
  uv_freeaddrinfo(ai);
}
Example #11
0
void make_nn(char *path_pattern, char *saved_name)
{
    size_t desc_layers[] = { 400, 210, 52 };
    struct net nwk = net_init(3, desc_layers);
    struct training t = load_pattern(path_pattern);

    train_nn(nwk, t);
    net_save(nwk, saved_name);
    net_free(nwk);
}
Example #12
0
/* Free a state machine
 */
void sm_free(StateMachine * sm)
{
	if (sm->ses != NULL) {
		net_free(&(sm->ses));
		return;
	}
	if (sm->use_count > 0)
		sm->is_dead = TRUE;
	else {
		route_event(sm, SM_FREE);
		g_free(sm);
	}
}
Example #13
0
void
net_connect_cb(uv_connect_t *conn, int stat) {
  net_t * net = (net_t *) conn->data;
  err_t err;
  int read;

  if (stat < 0) {
    err = uv_last_error(net->loop);
    if (net->error_cb) {
      net->error_cb(net, err, (char *) uv_strerror(err));
    } else {
      printf("error(%s:%d) %s", net->hostname, net->port, (char *) uv_strerror(err));
      net_free(net);
    }
    return;
  }

  /*
   * change the `connected` state
   */
  net->connected = 1;

  /*
   * read buffers via uv
   */
  uv_read_start((uv_stream_t *) net->handle, net_alloc, net_read);

  /*
   * call `conn_cb`, the tcp connection has been 
   *  established in user-land.
   */
  if (net->use_ssl == NOT_SSL && net->conn_cb != NULL) {
    net->conn_cb(net);
  }

  /*
   * Handle TLS Partial
   */
  if (net->use_ssl == USE_SSL && tls_connect(net->tls) == NET_OK) {
    read = 0;
    do {
      read = tls_bio_read(net->tls, 0);
      if (read > 0) {
        uv_write_t req;
        uv_buf_t uvbuf = uv_buf_init(net->tls->buf, read);
        uv_write(&req, (uv_stream_t*)net->handle, &uvbuf, 1, NULL);
      }
    } while (read > 0);
  }
}
Example #14
0
void meta_register(const gchar * server, const gchar * port, Game * game)
{
	if (num_redirects > 0)
		log_message(MSG_INFO,
			    _(""
			      "Redirected to meta-server at %s, port %s\n"),
			    server, port);
	else
		log_message(MSG_INFO,
			    _(""
			      "Register with meta-server at %s, port %s\n"),
			    server, port);

	if (ses != NULL)
		net_free(&ses);

	ses = net_new((NetNotifyFunc) meta_event, game);
	if (net_connect(ses, server, port))
		meta_mode = MODE_SIGNON;
	else {
		net_free(&ses);
	}
}
Example #15
0
void sm_close(StateMachine * sm)
{
	net_free(&(sm->ses));
	if (sm->use_cache) {
		/* Purge the cache */
		GList *list = sm->cache;
		sm->cache = NULL;
		sm_set_use_cache(sm, FALSE);
		while (list) {
			gchar *data = list->data;
			list = g_list_remove(list, data);
			g_free(data);
		}
	}
}
Example #16
0
/*!\brief Remove neurons from a network.
 * \param net Pointer to a neural network.
 * \param layer Integer
 * \param neuron Integer
 * \param number Integer
 */
void
net_remove_neurons (network_t *net, int layer, int neuron, int number)
{
  int l, nu, nl, orig_nu, orig_nl, *arglist;
  network_t *new_net, *tmp_net;

  assert (net != NULL);
  assert (0 <= layer && layer < net->no_of_layers);
  assert (0 <= neuron);
  assert (number >= 0);

  /* allocate memory for the new network */
  arglist = calloc (net->no_of_layers, sizeof (int));
  for (l = 0; l < net->no_of_layers; l++) {
    arglist[l] = net->layer[l].no_of_neurons;
  }
  arglist[layer] -= number;
  new_net = net_allocate_l (net->no_of_layers, arglist);
  free (arglist);

  /* copy the original network's weights and deltas into the new one */
  for (l = 1; l < new_net->no_of_layers; l++) {
    for (nu = 0; nu < new_net->layer[l].no_of_neurons; nu++) {
      orig_nu = (l == layer) && (nu >= neuron) ? nu + number : nu;
      for (nl = 0; nl <= new_net->layer[l - 1].no_of_neurons; nl++) {
        orig_nl = (l == layer + 1) && (nl >= neuron) ? nl + number : nl;
        new_net->layer[l].neuron[nu].weight[nl] =
          net->layer[l].neuron[orig_nu].weight[orig_nl];
        new_net->layer[l].neuron[nu].delta[nl] =
          net->layer[l].neuron[orig_nu].delta[orig_nl];
      }
    }
  }

  /* copy the original network's constants into the new one */
  new_net->momentum = net->momentum;
  new_net->learning_rate = net->learning_rate;

  /* switch new_net and net, so it is possible to keep the same pointer */
  tmp_net = malloc (sizeof (network_t));
  memcpy (tmp_net, new_net, sizeof (network_t));
  memcpy (new_net, net, sizeof (network_t));
  memcpy (net, tmp_net, sizeof (network_t));
  free (tmp_net);

  /* free allocated memory */
  net_free (new_net);
}
Example #17
0
/* network event handler, just like the one in meta.c, state.c, etc. */
void admin_net_event(NetEvent event, Session * admin_session, gchar * line)
{
#ifdef PRINT_INFO
	g_print
	    ("admin_event: event = %#x, admin_session = %p, line = %s\n",
	     event, admin_session, line);
#endif

	switch (event) {
	case NET_READ:
		/* there is data to be read */

#ifdef PRINT_INFO
		g_print("admin_event: NET_READ: line = '%s'\n", line);
#endif
		break;

	case NET_CONNECT:
		/* connect() succeeded */

#ifdef PRINT_INFO
		g_print("admin_event: NET_CONNECT\n");
#endif
		break;

	case NET_CONNECT_FAIL:
		/* connect() failed */

#ifdef PRINT_INFO
		g_print
		    ("admin_event: NET_CONNECT_FAIL (falling through to NET_CLOSE...)\n");
#endif

		/* fall through to NET_CLOSE */

	case NET_CLOSE:
		/* connection has been closed */

#ifdef PRINT_INFO
		g_print("admin_event: NET_CLOSE\n");
#endif
		net_free(&admin_session);
		break;

	default:
	}
}
Example #18
0
static DWORD test_do(HWND hwnd)
{
    int s = net_init();

    fd_set rfds;
    struct timeval tv;
    struct sockaddr_in to;
    struct sockaddr_in from;
    int start = time(NULL);
    int ret = 0;

    net_address(&to, config_get("Host"), config_get_int("Port"));
    net_bind("0.0.0.0", 8054);

    net_write_int8(CMD_TESTP2P);
    net_write_int32(start);

    while (time(NULL) < start + 5)
    {
        net_send_noflush(&to);

        FD_ZERO(&rfds);
        FD_SET(s, &rfds);
        tv.tv_sec = 1;
        tv.tv_usec = 0;

        if (select(s + 1, &rfds, NULL, NULL, &tv) > -1)
        {
            if (FD_ISSET(s, &rfds))
            {
                net_recv(&from);

                if (net_read_int8() == CMD_TESTP2P && net_read_int32() == start)
                {
                    ret = 1;
                    break;
                }
            }
        }
    }

    net_free();

    PostMessage(hwnd, WM_USER + 2, ret, 0);
    return 0;
}
Example #19
0
int main(int argc, char *argv[])
{
    srand(time(0));
    log_init("httpsrv.log", 1);
    log_set_level(LOG_LEVEL_DEBUG);
    DEBUG("httpsrv has started.");
    signal(SIGINT, sig_handler);
    alarm_init();
    if(net_create(&net, "8080"))
        return -1;
    connmgr_init(net);
    while(1)
        net_process(net, -1);
    connmgr_close();
    net_free(&net);
    alarm_close();
    log_close();
    return 0;
}
Example #20
0
/*!\brief Overwrite one network with another.
 * \param dest Pointer to a neural network.
 * \param src Pointer to a neural network.
 *
 * The neural network dest becomes a copy of the neural network src.
 * Note that dest must be an allocated neural network and its original
 * contents is discarded (with net_free()).
 */
void
net_overwrite (network_t *dest, const network_t *src)
{
  network_t *new_net, *tmp_net;

  assert (dest != NULL);
  assert (src != NULL);

  new_net = net_copy (src);

  /* switch new_net and dest, so it is possible to keep the same pointer */
  tmp_net = malloc (sizeof (network_t));
  memcpy (tmp_net, new_net, sizeof (network_t));
  memcpy (new_net, dest, sizeof (network_t));
  memcpy (dest, tmp_net, sizeof (network_t));
  free (tmp_net);

  net_free (new_net);
}
Example #21
0
/* =============================================================================
 * main
 * =============================================================================
 */
MAIN(argc, argv)
{
    GOTO_REAL();

    /*
     * Initialization
     */

    parseArgs(argc, (char** const)argv);
    long numThread     = global_params[PARAM_THREAD];
    long numVar        = global_params[PARAM_VAR];
    long numRecord     = global_params[PARAM_RECORD];
    long randomSeed    = global_params[PARAM_SEED];
    long maxNumParent  = global_params[PARAM_NUMBER];
    long percentParent = global_params[PARAM_PERCENT];
    global_insertPenalty = global_params[PARAM_INSERT];
    global_maxNumEdgeLearned = global_params[PARAM_EDGE];
    SIM_GET_NUM_CPU(numThread);
    TM_STARTUP(numThread);
    P_MEMORY_STARTUP(numThread);
    thread_startup(numThread);

    printf("Random seed                = %li\n", randomSeed);
    printf("Number of vars             = %li\n", numVar);
    printf("Number of records          = %li\n", numRecord);
    printf("Max num parents            = %li\n", maxNumParent);
    printf("%% chance of parent         = %li\n", percentParent);
    printf("Insert penalty             = %li\n", global_insertPenalty);
    printf("Max num edge learned / var = %li\n", global_maxNumEdgeLearned);
    printf("Operation quality factor   = %f\n", global_operationQualityFactor);
    fflush(stdout);

    /*
     * Generate data
     */

    printf("Generating data... ");
    fflush(stdout);

    random_t* randomPtr = random_alloc();
    assert(randomPtr);
    random_seed(randomPtr, randomSeed);

    data_t* dataPtr = data_alloc(numVar, numRecord, randomPtr);
    assert(dataPtr);
    net_t* netPtr = data_generate(dataPtr, -1, maxNumParent, percentParent);
    puts("done.");
    fflush(stdout);

    /*
     * Generate adtree
     */

    adtree_t* adtreePtr = adtree_alloc();
    assert(adtreePtr);

    printf("Generating adtree... ");
    fflush(stdout);

    TIMER_T adtreeStartTime;
    TIMER_READ(adtreeStartTime);

    adtree_make(adtreePtr, dataPtr);

    TIMER_T adtreeStopTime;
    TIMER_READ(adtreeStopTime);

    puts("done.");
    fflush(stdout);
    printf("Adtree time = %f\n",
           TIMER_DIFF_SECONDS(adtreeStartTime, adtreeStopTime));
    fflush(stdout);

    /*
     * Score original network
     */

    float actualScore = score(netPtr, adtreePtr);
    net_free(netPtr);

    /*
     * Learn structure of Bayesian network
     */

    learner_t* learnerPtr = learner_alloc(dataPtr, adtreePtr, numThread);
    assert(learnerPtr);
    data_free(dataPtr); /* save memory */

    printf("Learning structure...");
    fflush(stdout);

    TIMER_T learnStartTime;
    TIMER_READ(learnStartTime);
    GOTO_SIM();

    learner_run(learnerPtr);

    GOTO_REAL();
    TIMER_T learnStopTime;
    TIMER_READ(learnStopTime);

    puts("done.");
    fflush(stdout);
    printf("Time = %f\n",
           TIMER_DIFF_SECONDS(learnStartTime, learnStopTime));
    fflush(stdout);

    /*
     * Check solution
     */

    bool_t status = net_isCycle(learnerPtr->netPtr);
    assert(!status);

#ifndef SIMULATOR
    float learnScore = learner_score(learnerPtr);
    printf("Learn score  = %f\n", learnScore);
#endif
    printf("Actual score = %f\n", actualScore);

    /*
     * Clean up
     */

    fflush(stdout);
    random_free(randomPtr);
#ifndef SIMULATOR
    adtree_free(adtreePtr);
#  if 0    
    learner_free(learnerPtr);
#  endif    
#endif

    TM_SHUTDOWN();
    P_MEMORY_SHUTDOWN();

    GOTO_SIM();

    thread_shutdown();

    MAIN_RETURN(0);
}
Example #22
0
static void
testAll (long numVar, long numRecord, long numMaxParent, long percentParent)
{
    random_t* randomPtr = random_alloc();

    puts("Starting...");

    data_t* dataPtr = data_alloc(numVar, numRecord, randomPtr);
    assert(dataPtr);

    puts("Init:");
    net_t* netPtr = data_generate(dataPtr, 0, numMaxParent, percentParent);
    net_free(netPtr);
    printRecords(dataPtr);

    puts("Sort first half from 0:");
    data_sort(dataPtr, 0, numRecord/2, 0);
    printRecords(dataPtr);

    puts("Sort second half from 0:");
    data_sort(dataPtr, numRecord/2, numRecord-numRecord/2, 0);
    printRecords(dataPtr);

    puts("Sort all from mid:");
    data_sort(dataPtr, 0, numRecord, numVar/2);
    printRecords(dataPtr);

    long split = data_findSplit(dataPtr, 0, numRecord, numVar/2);
    printf("Split = %li\n", split);

    long v;
    for (v = 0; v < numVar; v++) {
        data_sort(dataPtr, 0, numRecord, v);
        long s = data_findSplit(dataPtr, 0, numRecord, v);
        if (s < numRecord) {
            assert(dataPtr->records[numVar * s + v] == 1);
        }
        if (s > 0) {
            assert(dataPtr->records[numVar * (s - 1)  + v] == 0);
        }
    }

    memset(dataPtr->records, 0, dataPtr->numVar * dataPtr->numRecord);
    for (v = 0; v < numVar; v++) {
        data_sort(dataPtr, 0, numRecord, v);
        long s = data_findSplit(dataPtr, 0, numRecord, v);
        if (s < numRecord) {
            assert(dataPtr->records[numVar * s + v] == 1);
        }
        if (s > 0) {
            assert(dataPtr->records[numVar * (s - 1)  + v] == 0);
        }
        assert(s == numRecord);
    }

    memset(dataPtr->records, 1, dataPtr->numVar * dataPtr->numRecord);
    for (v = 0; v < numVar; v++) {
        data_sort(dataPtr, 0, numRecord, v);
        long s = data_findSplit(dataPtr, 0, numRecord, v);
        if (s < numRecord) {
            assert(dataPtr->records[numVar * s + v] == 1);
        }
        if (s > 0) {
            assert(dataPtr->records[numVar * (s - 1)  + v] == 0);
        }
        assert(s == 0);
    }

    data_free(dataPtr);
}
Example #23
0
static void *recv_loop(void *data)
{
    session_t *session = net_init(ifname, src_ip_addr, 0, 0, 0, ICMP, -1);
    icmp_packet_t packet;
    ndp_neighbor_discover_t n_discvr;

    while(is_initialized)
    {
        size_t recv = icmp_recv(session, &packet);
        if(!recv)
            continue;

        switch(packet.type)
        {
            case ICMP_TYPE_NEIGHBOR_SOLICITATION:
                memcpy(n_discvr.buffer, packet.body, recv);

                if(memcmp(n_discvr.target_addr, session->src_ip,
                          IP_ADDR_LEN) != 0)
                    continue;

                ndp_option_t opt;
                memcpy(opt.buffer, n_discvr.options, recv + NDP_ND_HEADER_LEN);

                if(opt.type != NDP_SOURCE_LINK_ADDR_OPT || opt.len != 1)
                {
                    fprintf(stderr, "Error: Invalid NDP option type: %d. "
                                    "Expected: %d (NDP_SOURCE_LINK_ADDR_OPT)"
                                    "\n.", opt.type, NDP_SOURCE_LINK_ADDR_OPT);
                    continue;
                }

                ndp_table_insert(session->last_sender_ip, opt.body);

                ndp_neighbor_discover_t ndp_resp;
                ndp_option_t opt_resp;

                memcpy(ndp_resp.target_addr, n_discvr.target_addr, IP_ADDR_LEN);
                // sol & override flag
                ndp_resp.reserved = netb_l( 1 << 30 | 1 << 29 );

                opt_resp.type = NDP_TARGET_LINK_ADDR_OPT;
                opt_resp.len = 1;
                memcpy(opt_resp.body, session->src_addr, ETH_ADDR_LEN);

                size_t opts_len = NDP_OPT_HEADER_LEN + ETH_ADDR_LEN;
                memcpy(ndp_resp.options, opt_resp.buffer, opts_len);

                size_t resp = icmp_send(session, session->last_sender_ip,
                                        ICMP_TYPE_NEIGHBOR_ADVERTISEMENT, 0,
                                        ndp_resp.buffer,
                                        NDP_ND_HEADER_LEN + opts_len);

                if(resp <= 0)
                {
                    fprintf(stderr, "Error: Cannot respond with "
                                    "ICMP_TYPE_NEIGHBOR_ADVERTISEMENT!\n.");
                    continue;
                }

                break;

            case ICMP_TYPE_NEIGHBOR_ADVERTISEMENT:
                memcpy(n_discvr.buffer, packet.body, recv);
                uint8_t zeros[IP_ADDR_LEN] = { 0x0 };

                if(memcmp(zeros, n_discvr.target_addr, IP_ADDR_LEN) == 0)
                    continue; // not sure why it's even possible...

                if(recv <= offsetof(ndp_neighbor_discover_t, options))
                    continue; // If there's no option, ignore

                memcpy(opt.buffer, n_discvr.options, recv + NDP_ND_HEADER_LEN);

                if(opt.type != NDP_TARGET_LINK_ADDR_OPT || opt.len != 1)
                {
                    fprintf(stderr, "Error: Invalid NDP option type: %d. "
                                    "Expected: %d (NDP_TARGET_LINK_ADDR_OPT)"
                                    "\n.", opt.type, NDP_TARGET_LINK_ADDR_OPT);
                    continue;
                }

                ndp_table_insert(n_discvr.target_addr, opt.body);

                break;

            default:
                break; // unsupported ICMP type
        }
    }

    net_free(session);
    return 0;
}
Example #24
0
File: dll.c Project: icharge/cncnet
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    if (fdwReason == DLL_PROCESS_ATTACH)
    {
        const char *cfg_p2p;
        const char *cfg_host;
        int s, cfg_port = 9001;

        #ifdef _DEBUG
        freopen("stdout.txt", "w", stdout);
        setvbuf(stdout, NULL, _IONBF, 0); 
        #endif

        printf("CnCNet git~%s\n", CNCNET_REV);

        s = net_init();
        net_opt_reuse();

        if (getenv("CNCNET_HOST"))
        {
            printf("Going into online mode...\n");

            /* allow CnCNet's wolapi.dll to inject itself */
            if (GetFileAttributes("wolapi.dll") != INVALID_FILE_ATTRIBUTES)
            {
                printf("Loading wolapi.dll for WOL mode\n");
                wolapi_dll = LoadLibrary("wolapi.dll");
            }

            cfg_host = getenv_default("CNCNET_HOST", "server.cncnet.org");
            cfg_port = atoi(getenv_default("CNCNET_PORT", "9001"));
            cfg_p2p = getenv_default("CNCNET_P2P", "false");

            if (STR_TRUE(cfg_p2p))
            {
                printf("Peer-to-peer is enabled\n");
                my_p2p = 1;
            }

            if (cfg_port < 1024 || cfg_port > 65534)
            {
                cfg_port = 9001;
            }

            printf("Broadcasting to %s:%d\n", cfg_host, cfg_port);

            dedicated = 1;
            net_address(&server, cfg_host, cfg_port);

            if (my_p2p)
            {
                net_bind("0.0.0.0", 8054);
            }
        }
        else
        {
            printf("CnCNet: Going into LAN mode...\n");
            net_address(&server, "255.255.255.255", 5000);
            net_opt_broadcast(s);
            net_bind("0.0.0.0", 5000);
        }
    }

    if (fdwReason == DLL_PROCESS_DETACH)
    {
        net_free();

        if (wolapi_dll)
            FreeLibrary(wolapi_dll);
    }

    return TRUE;
}
Example #25
0
static void meta_event(NetEvent event, Game * game, char *line)
{
	switch (event) {
	case NET_READ:
		switch (meta_mode) {
		case MODE_SIGNON:
		case MODE_REDIRECT:
			if (strncmp(line, "goto ", 5) == 0) {
				gchar **split_result;
				const gchar *port;
				meta_mode = MODE_REDIRECT;
				net_free(&ses);
				if (num_redirects++ == 10) {
					log_message(MSG_INFO,
						    _(""
						      "Too many meta-server redirects\n"));
					return;
				}
				split_result = g_strsplit(line, " ", 0);
				g_assert(split_result[0] != NULL);
				g_assert(!strcmp(split_result[0], "goto"));
				if (split_result[1]) {
					port = PIONEERS_DEFAULT_META_PORT;
					if (split_result[2])
						port = split_result[2];
					meta_register(split_result[1],
						      port, game);
				} else {
					log_message(MSG_ERROR,
						    _(""
						      "Bad redirect line: %s\n"),
						    line);
				};
				g_strfreev(split_result);
			}

			meta_server_version_major =
			    meta_server_version_minor = 0;
			if (strncmp(line, "welcome ", 8) == 0) {
				char *p = strstr(line, "version ");
				if (p) {
					p += 8;
					meta_server_version_major =
					    atoi(p);
					p += strspn(p, "0123456789");
					if (*p == '.')
						meta_server_version_minor =
						    atoi(p + 1);
				}
			}
			net_printf(ses, "version %s\n",
				   META_PROTOCOL_VERSION);
			meta_mode = MODE_SERVER_LIST;
			meta_send_details(game);
			break;
		default:
			log_message(MSG_ERROR,
				    _(""
				      "Unknown message from the metaserver: %s\n"),
				    line);
			break;
		}
		break;
	case NET_CLOSE:
		log_message(MSG_ERROR, _("Meta-server kicked us off\n"));
		net_free(&ses);
		break;
	case NET_CONNECT:
	case NET_CONNECT_FAIL:
		break;
	}
}
Example #26
0
void
net_read(uv_stream_t *handle, ssize_t nread, const uv_buf_t buf) {
  net_t * net = (net_t *) handle->data;
  err_t err;

  if (nread < 0) {
    err = uv_last_error(net->loop);
    if (net->error_cb) {
      net->error_cb(net, err, (char *) uv_strerror(err));
    } else {
      printf("error(%s:%d) %s", net->hostname, net->port, (char *) uv_strerror(err));
      net_free(net);
    }
    return;
  }

  /* 
   * BIO Return rule:
   * All these functions return either the amount of data successfully
   * read or written (if the return value is positive) or that no data 
   * was successfully read or written if the result is 0 or -1. If the 
   * return value is -2 then the operation is not implemented in the specific BIO type.
   */
  if (net->use_ssl) {
    net->tls->data = malloc(1);

    tls_bio_write(net->tls, buf.base, nread);
    free(buf.base);

    int read = 0;
    int stat = tls_read(net->tls);
    if (stat == 1) {
      /* 
       * continue: Say hello
       */
      do {
        read = tls_bio_read(net->tls, 0);
        if (read > 0) {
          uv_write_t req;
          uv_buf_t uvbuf = uv_buf_init(net->tls->buf, read);
          uv_write(&req, (uv_stream_t*)net->handle, &uvbuf, 1, NULL);
        }
      } while (read > 0);

    } else if (stat == 0) {
      /*
       * SSL Connection is created
       * Here need to call user-land callback
       */
      uv_read_stop((uv_stream_t*)net->handle);
      if (net->read_cb != NULL) {
        net->read_cb(net, buffer_length(net->tls->buffer),
                          buffer_string(net->tls->buffer));
      }

    } else if (stat == -1) {
      /*
       * Just connection in SSL
       * call `conn_cb`, the ssl connection has been 
       *   established in user-land.
       */
      if (net->conn_cb != NULL) {
        net->conn_cb(net);
      }

    } else {
      /*
       * TODO(Yorkie): HOWTO
       */
    }
    return;
  }

  /*
   * TCP Part, no SSL, just proxy of uv.
   */
  uv_read_stop(handle);
  buf.base[nread] = 0;
  if (net->read_cb != NULL) {
    net->read_cb(net, nread, buf.base);
  }
}
Example #27
0
int
main ()
{
    long numNode = 100;

    puts("Starting tests...");

    bool_t status;

    net_t* netPtr = net_alloc(numNode);
    assert(netPtr);
    bitmap_t* visitedBitmapPtr = bitmap_alloc(numNode);
    assert(visitedBitmapPtr);
    queue_t* workQueuePtr = queue_alloc(-1);
    assert(workQueuePtr);

    assert(!net_isCycle(netPtr));

    long aId = 31;
    long bId = 14;
    long cId = 5;
    long dId = 92;

    net_applyOperation(netPtr, OPERATION_INSERT, aId, bId);
    assert(net_isPath(netPtr, aId, bId, visitedBitmapPtr, workQueuePtr));
    assert(!net_isPath(netPtr, bId, aId, visitedBitmapPtr, workQueuePtr));
    assert(!net_isPath(netPtr, aId, cId, visitedBitmapPtr, workQueuePtr));
    assert(!net_isPath(netPtr, aId, dId, visitedBitmapPtr, workQueuePtr));
    assert(!net_isCycle(netPtr));

    net_applyOperation(netPtr, OPERATION_INSERT, bId, cId);
    net_applyOperation(netPtr, OPERATION_INSERT, aId, cId);
    net_applyOperation(netPtr, OPERATION_INSERT, dId, aId);
    assert(!net_isCycle(netPtr));
    net_applyOperation(netPtr, OPERATION_INSERT, cId, dId);
    assert(net_isCycle(netPtr));
    net_applyOperation(netPtr, OPERATION_REVERSE, cId, dId);
    assert(!net_isCycle(netPtr));
    net_applyOperation(netPtr, OPERATION_REVERSE, dId, cId);
    assert(net_isCycle(netPtr));
    assert(net_isPath(netPtr, aId, dId, visitedBitmapPtr, workQueuePtr));
    net_applyOperation(netPtr, OPERATION_REMOVE, cId, dId);
    assert(!net_isPath(netPtr, aId, dId, visitedBitmapPtr, workQueuePtr));

    bitmap_t* ancestorBitmapPtr = bitmap_alloc(numNode);
    assert(ancestorBitmapPtr);
    status = net_findAncestors(netPtr, cId, ancestorBitmapPtr, workQueuePtr);
    assert(status);
    assert(bitmap_isSet(ancestorBitmapPtr, aId));
    assert(bitmap_isSet(ancestorBitmapPtr, bId));
    assert(bitmap_isSet(ancestorBitmapPtr, dId));
    assert(bitmap_getNumSet(ancestorBitmapPtr) == 3);

    bitmap_t* descendantBitmapPtr = bitmap_alloc(numNode);
    assert(descendantBitmapPtr);
    status = net_findDescendants(netPtr, aId, descendantBitmapPtr, workQueuePtr);
    assert(status);
    assert(bitmap_isSet(descendantBitmapPtr, bId));
    assert(bitmap_isSet(descendantBitmapPtr, cId));
    assert(bitmap_getNumSet(descendantBitmapPtr) == 2);

    bitmap_free(visitedBitmapPtr);
    queue_free(workQueuePtr);
    bitmap_free(ancestorBitmapPtr);
    bitmap_free(descendantBitmapPtr);
    net_free(netPtr);

    random_t* randomPtr = random_alloc();
    assert(randomPtr);
    netPtr = net_alloc(numNode);
    assert(netPtr);
    net_generateRandomEdges(netPtr, 10, 10, randomPtr);
    net_free(netPtr);

    puts("All tests passed.");

    return 0;
}
Example #28
0
/*!\brief Read a network from a file.
 * \param file Pointer to a file descriptor.
 * \return Pointer to the read neural network on success, NULL on failure.
 */
network_t *
net_fscan (FILE *file)
{
  int no_of_layers, l, nu, nl, *arglist, result;
  network_t *net;

  assert (file != NULL);

  /* read network dimensions */
  result = fscanf (file, "%i", &no_of_layers);
  if (result <= 0) {
    return NULL;
  }
  arglist = calloc (no_of_layers, sizeof (int));
  if (arglist == NULL) {
    return NULL;
  }
  for (l = 0; l < no_of_layers; l++) {
    result = fscanf (file, "%i", &arglist[l]);
    if (result <= 0) {
      return NULL;
    }
  }

  /* allocate memory for the network */
  net = net_allocate_l (no_of_layers, arglist);
  free (arglist);
  if (net == NULL) {
    return NULL;
  }

  /* read network constants */
  result = fscanf (file, "%f", &net->momentum);
  if (result <= 0) {
    net_free (net);
    return NULL;
  }
  result = fscanf (file, "%f", &net->learning_rate);
  if (result <= 0) {
    net_free (net);
    return NULL;
  }
  result = fscanf (file, "%f", &net->global_error);
  if (result <= 0) {
    net_free (net);
    return NULL;
  }

  /* read network weights */
  for (l = 1; l < net->no_of_layers; l++) {
    for (nu = 0; nu < net->layer[l].no_of_neurons; nu++) {
      for (nl = 0; nl <= net->layer[l - 1].no_of_neurons; nl++) {
        result = fscanf (file, "%f", &net->layer[l].neuron[nu].weight[nl]);
        if (result <= 0) {
          net_free (net);
          return NULL;
        }
      }
    }
  }

  return net;
}